模型介绍
内容详情
替代品
模型简介
基于Microsoft Phi-4-mini-instruct的量化版本,适用于文本生成任务,支持多语言交互和数学推理。
模型特点
高效量化
采用float8动态激活和权重量化技术,显著降低显存占用
性能优化
在H100上实现15-20%推理速度提升
多任务支持
支持代码生成、数学推理和对话任务
精度保留
量化后模型精度损失极小(基准测试显示总体表现仅下降0.24%)
模型能力
文本生成
数学问题求解
代码生成
多语言对话
逻辑推理
使用案例
教育辅助
数学解题
帮助学生理解代数方程解法
可正确解答2x+3=7类方程
创意生成
食谱建议
生成水果搭配创意食谱
提供香蕉火龙果奶昔等具体方案
技术问答
编程帮助
解释代码逻辑或生成代码片段
库名称: transformers 标签:
- torchao
- phi
- phi4
- nlp
- 代码
- 数学
- 聊天
- 对话式
许可证: mit
语言: - 多语言
基础模型: - microsoft/Phi-4-mini-instruct
管道标签: 文本生成
Phi4-mini模型通过torchao进行float8动态激活和float8权重量化(行级粒度),由PyTorch团队实现。可直接使用,或通过vLLM部署,在H100上实现36%显存降低、15-20%速度提升且几乎不影响精度。
使用vLLM推理
安装vllm nightly版本以获取最新更新:
pip install vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
pip install torchao
代码示例
from vllm import LLM, SamplingParams
# 示例提示词
prompts = [
"你好,我的名字是",
"美国总统是",
"法国首都是",
"AI的未来是",
]
# 创建采样参数对象
sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
if __name__ == '__main__':
# 创建LLM实例
llm = LLM(model="pytorch/Phi-4-mini-instruct-float8dq")
# 生成文本
# 输出是包含提示词、生成文本等信息的RequestOutput对象列表
outputs = llm.generate(prompts, sampling_params)
# 打印输出
print("\n生成结果:\n" + "-" * 60)
for output in outputs:
prompt = output.prompt
generated_text = output.outputs[0].text
print(f"提示词: {prompt!r}")
print(f"输出: {generated_text!r}")
print("-" * 60)
注意:运行代码时请使用VLLM_DISABLE_COMPILE_CACHE=1
禁用编译缓存,例如VLLM_DISABLE_COMPILE_CACHE=1 python example.py
,因vLLM与torchao的编译组合存在已知问题,预计在pytorch 2.8中解决。
服务部署
使用以下命令启动服务:
vllm serve pytorch/Phi-4-mini-instruct-float8dq --tokenizer microsoft/Phi-4-mini-instruct -O3
使用Transformers推理
安装必要包:
pip install git+https://github.com/huggingface/transformers@main
pip install torchao
pip install torch
pip install accelerate
示例:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
torch.random.manual_seed(0)
model_path = "pytorch/Phi-4-mini-instruct-float8dq"
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="auto",
torch_dtype="auto",
trust_remote_code=True,
)
tokenizer = AutoTokenizer.from_pretrained(model_path)
messages = [
{"role": "system", "content": "你是一个乐于助人的AI助手。"},
{"role": "user", "content": "能提供香蕉和火龙果的搭配吃法吗?"},
{"role": "assistant", "content": "当然!以下是香蕉和火龙果的搭配建议:1. 香蕉火龙果奶昔:将香蕉和火龙果与牛奶、蜂蜜一起搅拌。2. 香蕉火龙果沙拉:切片后加柠檬汁和蜂蜜拌匀。"},
{"role": "user", "content": "如何解方程2x + 3 = 7?"},
]
pipe = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
)
generation_args = {
"max_new_tokens": 500,
"return_full_text": False,
"temperature": 0.0,
"do_sample": False,
}
output = pipe(messages, **generation_args)
print(output[0]['generated_text'])
量化方案
安装必要包:
pip install git+https://github.com/huggingface/transformers@main
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
pip install torch
pip install accelerate
使用以下代码获取量化模型:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
model_id = "microsoft/Phi-4-mini-instruct"
from torchao.quantization import Float8DynamicActivationFloat8WeightConfig, PerRow
quant_config = Float8DynamicActivationFloat8WeightConfig(granularity=PerRow())
quantization_config = TorchAoConfig(quant_type=quant_config)
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16, quantization_config=quantization_config)
tokenizer = AutoTokenizer.from_pretrained(model_id)
# 推送至Hub
USER_ID = "您的用户ID"
MODEL_NAME = model_id.split("/")[-1]
save_to = f"{USER_ID}/{MODEL_NAME}-float8dq"
quantized_model.push_to_hub(save_to, safe_serialization=False)
tokenizer.push_to_hub(save_to)
# 手动测试
prompt = "你有意识吗?能和我对话吗?"
messages = [
{
"role": "system",
"content": "",
},
{"role": "user", "content": prompt},
]
templated_prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
print("提示词:", prompt)
print("模板化提示词:", templated_prompt)
inputs = tokenizer(
templated_prompt,
return_tensors="pt",
).to("cuda")
generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
output_text = tokenizer.batch_decode(
generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print("响应:", output_text[0][len(prompt):])
注意:执行push_to_hub
前需运行
pip install -U "huggingface_hub[cli]"
huggingface-cli login
并使用具有写入权限的token(从https://huggingface.co/settings/tokens获取)
模型质量
我们使用lm-evaluation-harness评估量化模型质量。 需从源码安装lm-eval: https://github.com/EleutherAI/lm-evaluation-harness#install
基准测试
lm_eval --model hf --model_args pretrained=microsoft/Phi-4-mini-instruct --tasks hellaswag --device cuda:0 --batch_size 8
float8动态激活+权重量化(float8dq)
lm_eval --model hf --model_args pretrained=pytorch/Phi-4-mini-instruct-float8dq --tasks hellaswag --device cuda:0 --batch_size 8
基准测试 | ||
---|---|---|
Phi-4-mini-ins | Phi-4-mini-instruct-float8dq | |
常用综合基准 | ||
mmlu (0-shot) | 66.73 | 66.61 |
mmlu_pro (5-shot) | 46.43 | 44.58 |
推理能力 | ||
arc_challenge (0-shot) | 56.91 | 56.66 |
gpqa_main_zeroshot | 30.13 | 29.46 |
HellaSwag | 54.57 | 54.55 |
openbookqa | 33.00 | 33.60 |
piqa (0-shot) | 77.64 | 77.48 |
social_iqa | 49.59 | 49.28 |
truthfulqa_mc2 (0-shot) | 48.39 | 48.09 |
winogrande (0-shot) | 71.11 | 72.77 |
多语言能力 | ||
mgsm_en_cot_en | 60.8 | 60.0 |
数学能力 | ||
gsm8k (5-shot) | 81.88 | 80.89 |
mathqa (0-shot) | 42.31 | 42.51 |
总体表现 | 55.35 | 55.11 |
峰值显存占用
结果
测试项 | ||
---|---|---|
Phi-4 mini-Ins | Phi-4-mini-instruct-float8dq | |
峰值显存(GB) | 8.91 | 5.70 (降低36%) |
显存测试代码
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
# 使用"microsoft/Phi-4-mini-instruct"或"pytorch/Phi-4-mini-instruct-float8dq"
model_id = "pytorch/Phi-4-mini-instruct-float8dq"
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained(model_id)
torch.cuda.reset_peak_memory_stats()
prompt = "你有意识吗?能和我对话吗?"
messages = [
{
"role": "system",
"content": "",
},
{"role": "user", "content": prompt},
]
templated_prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
print("提示词:", prompt)
print("模板化提示词:", templated_prompt)
inputs = tokenizer(
templated_prompt,
return_tensors="pt",
).to("cuda")
generated_ids = quantized_model.generate(**inputs, max_new_tokens=128)
output_text = tokenizer.batch_decode(
generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print("响应:", output_text[0][len(prompt):])
mem = torch.cuda.max_memory_reserved() / 1e9
print(f"峰值显存占用: {mem:.02f} GB")
模型性能
结果(H100机器)
测试项 | ||
---|---|---|
Phi-4 mini-Ins | Phi-4-mini-instruct-float8dq | |
延迟 (batch_size=1) | 1.64秒 | 1.41秒 (加速16%) |
延迟 (batch_size=128) | 3.1秒 | 2.72秒 (加速14%) |
服务吞吐 (num_prompts=1) | 1.35 请求/秒 | 1.57 请求/秒 (加速16%) |
服务吞吐 (num_prompts=1000) | 66.68 请求/秒 | 80.53 请求/秒 (加速21%) |
注:延迟测试结果为秒,服务测试结果为每秒请求数。
测试环境
获取vllm源码:
git clone git@github.com:vllm-project/vllm.git
安装vllm
VLLM_USE_PRECOMPILED=1 pip install --editable .
在vllm
根目录下运行测试:
延迟测试
基准测试
python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model microsoft/Phi-4-mini-instruct --batch-size 1
float8dq测试
VLLM_DISABLE_COMPILE_CACHE=1 python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model pytorch/Phi-4-mini-instruct-float8dq --batch-size 1
服务性能测试
我们测试了服务环境下的吞吐量。
下载sharegpt数据集:
wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
其他数据集见:https://github.com/vllm-project/vllm/tree/main/benchmarks
注:可通过--num-prompts
参数调整测试的提示词数量。
基准测试
Phi 2 GGUF
其他
Phi-2是微软开发的一个小型但强大的语言模型,具有27亿参数,专注于高效推理和高质量文本生成。
大型语言模型
支持多种语言
P
TheBloke
41.5M
205
Roberta Large
MIT
基于掩码语言建模目标预训练的大型英语语言模型,采用改进的BERT训练方法
大型语言模型
英语
R
FacebookAI
19.4M
212
Distilbert Base Uncased
Apache-2.0
DistilBERT是BERT基础模型的蒸馏版本,在保持相近性能的同时更轻量高效,适用于序列分类、标记分类等自然语言处理任务。
大型语言模型
英语
D
distilbert
11.1M
669
Llama 3.1 8B Instruct GGUF
Meta Llama 3.1 8B Instruct 是一个多语言大语言模型,针对多语言对话用例进行了优化,在常见的行业基准测试中表现优异。
大型语言模型
英语
L
modularai
9.7M
4
Xlm Roberta Base
MIT
XLM-RoBERTa是基于100种语言的2.5TB过滤CommonCrawl数据预训练的多语言模型,采用掩码语言建模目标进行训练。
大型语言模型
支持多种语言
X
FacebookAI
9.6M
664
Roberta Base
MIT
基于Transformer架构的英语预训练模型,通过掩码语言建模目标在海量文本上训练,支持文本特征提取和下游任务微调
大型语言模型
英语
R
FacebookAI
9.3M
488
Opt 125m
其他
OPT是由Meta AI发布的开放预训练Transformer语言模型套件,参数量从1.25亿到1750亿,旨在对标GPT-3系列性能,同时促进大规模语言模型的开放研究。
大型语言模型
英语
O
facebook
6.3M
198
Llama 3.1 8B Instruct
Llama 3.1是Meta推出的多语言大语言模型系列,包含8B、70B和405B参数规模,支持8种语言和代码生成,优化了多语言对话场景。
大型语言模型
Transformers

支持多种语言
L
meta-llama
5.7M
3,898
T5 Base
Apache-2.0
T5基础版是由Google开发的文本到文本转换Transformer模型,参数规模2.2亿,支持多语言NLP任务。
大型语言模型
支持多种语言
T
google-t5
5.4M
702
Xlm Roberta Large
MIT
XLM-RoBERTa是基于100种语言的2.5TB过滤CommonCrawl数据预训练的多语言模型,采用掩码语言建模目标进行训练。
大型语言模型
支持多种语言
X
FacebookAI
5.3M
431
精选推荐AI模型
Llama 3 Typhoon V1.5x 8b Instruct
专为泰语设计的80亿参数指令模型,性能媲美GPT-3.5-turbo,优化了应用场景、检索增强生成、受限生成和推理任务
大型语言模型
Transformers

支持多种语言
L
scb10x
3,269
16
Cadet Tiny
Openrail
Cadet-Tiny是一个基于SODA数据集训练的超小型对话模型,专为边缘设备推理设计,体积仅为Cosmo-3B模型的2%左右。
对话系统
Transformers

英语
C
ToddGoldfarb
2,691
6
Roberta Base Chinese Extractive Qa
基于RoBERTa架构的中文抽取式问答模型,适用于从给定文本中提取答案的任务。
问答系统
中文
R
uer
2,694
98
AIbase是一个专注于MCP服务的平台,为AI开发者提供高质量的模型上下文协议服务,助力AI应用开发。
简体中文