Phi 4 Mini Instruct Float8dq
模型概述
基於Microsoft Phi-4-mini-instruct的量化版本,適用於文本生成任務,支持多語言交互和數學推理。
模型特點
高效量化
採用float8動態激活和權重量化技術,顯著降低顯存佔用
性能優化
在H100上實現15-20%推理速度提升
多任務支持
支持代碼生成、數學推理和對話任務
精度保留
量化後模型精度損失極小(基準測試顯示總體表現僅下降0.24%)
模型能力
文本生成
數學問題求解
代碼生成
多語言對話
邏輯推理
使用案例
教育輔助
數學解題
幫助學生理解代數方程解法
可正確解答2x+3=7類方程
創意生成
食譜建議
生成水果搭配創意食譜
提供香蕉火龍果奶昔等具體方案
技術問答
編程幫助
解釋代碼邏輯或生成代碼片段
🚀 [Phi4-mini-instruct-float8dq模型]
[Phi4-mini-instruct-float8dq模型由PyTorch團隊使用torchao進行float8動態激活和float8權重量化(每行粒度)。可直接使用該模型,或藉助vLLM進行服務部署,在H100上可減少36%的顯存使用,提速15 - 20%,且幾乎不影響準確性。]
🚀 快速開始
本項目提供了使用vLLM和Transformers進行推理、模型量化、模型評估等功能。下面將為你詳細介紹各部分的使用方法。
✨ 主要特性
- 使用torchao對Phi4-mini模型進行float8動態激活和float8權重量化(每行粒度)。
- 可直接使用量化後的模型,也可藉助vLLM進行服務部署,在H100上可減少36%的顯存使用,提速15 - 20%,且幾乎不影響準確性。
📦 安裝指南
安裝vLLM nightly版本
pip install vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
pip install torchao
推理和量化所需的其他依賴
pip install git+https://github.com/huggingface/transformers@main
pip install torch
pip install accelerate
量化安裝
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
模型評估所需依賴
需從源碼安裝lm-eval
:
git clone https://github.com/EleutherAI/lm-evaluation-harness.git
cd lm-evaluation-harness
pip install -e .
推送到Hugging Face Hub所需依賴
pip install -U "huggingface_hub[cli]"
vLLM基準測試所需依賴
git clone git@github.com:vllm-project/vllm.git
VLLM_USE_PRECOMPILED=1 pip install --editable .
下載ShareGPT數據集
wget https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered/resolve/main/ShareGPT_V3_unfiltered_cleaned_split.json
💻 使用示例
基礎用法
使用vLLM進行推理
# 安裝vllm nightly版本以獲取最新更改
pip install vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
pip install torchao
from vllm import LLM, SamplingParams
# 示例提示
prompts = [
"Hello, my name is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
# 創建採樣參數對象
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("\nGenerated Outputs:\n" + "-" * 60)
for output in outputs:
prompt = output.prompt
generated_text = output.outputs[0].text
print(f"Prompt: {prompt!r}")
print(f"Output: {generated_text!r}")
print("-" * 60)
使用Transformers進行推理
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": "You are a helpful AI assistant."},
{"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
{"role": "assistant", "content": "Sure! Here are some ways to eat bananas and dragonfruits together: 1. Banana and dragonfruit smoothie: Blend bananas and dragonfruits together with some milk and honey. 2. Banana and dragonfruit salad: Mix sliced bananas and dragonfruits together with some lemon juice and honey."},
{"role": "user", "content": "What about solving an 2x + 3 = 7 equation?"},
]
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'])
模型量化
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 = "YOUR_USER_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 = "Hey, are you conscious? Can you talk to me?"
messages = [
{
"role": "system",
"content": "",
},
{"role": "user", "content": prompt},
]
templated_prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
print("Prompt:", prompt)
print("Templated prompt:", 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("Response:", output_text[0][len(prompt):])
高級用法
使用vLLM進行服務部署
vllm serve pytorch/Phi-4-mini-instruct-float8dq --tokenizer microsoft/Phi-4-mini-instruct -O3
模型評估
# 基準模型評估
lm_eval --model hf --model_args pretrained=microsoft/Phi-4-mini-instruct --tasks hellaswag --device cuda:0 --batch_size 8
# 量化模型評估
lm_eval --model hf --model_args pretrained=pytorch/Phi-4-mini-instruct-float8dq --tasks hellaswag --device cuda:0 --batch_size 8
峰值內存使用測試
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 = "Hey, are you conscious? Can you talk to me?"
messages = [
{
"role": "system",
"content": "",
},
{"role": "user", "content": prompt},
]
templated_prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
print("Prompt:", prompt)
print("Templated prompt:", 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("Response:", output_text[0][len(prompt):])
mem = torch.cuda.max_memory_reserved() / 1e9
print(f"Peak Memory Usage: {mem:.02f} GB")
模型性能基準測試
# 獲取vllm源碼
git clone git@github.com:vllm-project/vllm.git
VLLM_USE_PRECOMPILED=1 pip install --editable .
# 延遲基準測試 - 基準模型
python benchmarks/benchmark_latency.py --input-len 256 --output-len 256 --model microsoft/Phi-4-mini-instruct --batch-size 1
# 延遲基準測試 - 量化模型
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
# 服務基準測試 - 基準模型
vllm serve microsoft/Phi-4-mini-instruct --tokenizer microsoft/Phi-4-mini-instruct -O3
python benchmarks/benchmark_serving.py --backend vllm --dataset-name sharegpt --tokenizer microsoft/Phi-4-mini-instruct --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json --model microsoft/Phi-4-mini-instruct --num-prompts 1
# 服務基準測試 - 量化模型
VLLM_DISABLE_COMPILE_CACHE=1 vllm serve pytorch/Phi-4-mini-instruct-float8dq --tokenizer microsoft/Phi-4-mini-instruct -O3
python benchmarks/benchmark_serving.py --backend vllm --dataset-name sharegpt --tokenizer microsoft/Phi-4-mini-instruct --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json --model pytorch/Phi-4-mini-instruct-float8dq --num-prompts 1
📚 詳細文檔
模型質量評估
我們使用lm-evaluation-harness對量化模型的質量進行評估。以下是基準模型和量化模型在不同基準測試中的表現:
基準測試 | 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% 減少) |
模型性能
以下是基準模型和量化模型在H100機器上的性能表現:
基準測試 | Phi-4 mini-Ins | Phi-4-mini-instruct-float8dq |
---|---|---|
延遲 (batch_size=1) | 1.64s | 1.41s (16% 提速) |
延遲 (batch_size=128) | 3.1s | 2.72s (14% 提速) |
服務 (num_prompts=1) | 1.35 req/s | 1.57 req/s (16% 提速) |
服務 (num_prompts=1000) | 66.68 req/s | 80.53 req/s (21% 提速) |
注意事項
- 使用
VLLM_DISABLE_COMPILE_CACHE=1
來禁用編譯緩存,因為vLLM和torchao的編譯組合存在一些問題,預計在PyTorch 2.8中解決。 - 要將模型推送到Hugging Face Hub,需要運行
huggingface-cli login
並使用具有寫入權限的令牌。
📄 許可證
本項目使用MIT許可證。
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
1
基於transformers庫的預訓練模型,適用於多種NLP任務
大型語言模型
Transformers

1
unslothai
6.2M
1
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
精選推薦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