モデル概要
モデル特徴
モデル能力
使用事例
library_name: transformers tags:
- torchao
- phi
- phi4
- nlp
- code
- math
- chat
- conversational license: mit language:
- multilingual base_model:
- microsoft/Phi-4-mini-instruct pipeline_tag: text-generation
Phi4-miniはPyTorchチームによってtorchaoを使用して8ビット埋め込みと8ビット動的アクティベーション、4ビット重み線形(8da4w)で量子化されました。 このモデルはExecuTorchを使用したモバイル展開に適しています。
ExecuTorchで直接使用するための量子化されたpteファイルを提供しています。 (提供されているpteファイルはデフォルトのmax_seq_length/max_context_length 128でエクスポートされています。変更したい場合は、ExecuTorchへのエクスポートの手順に従って量子化モデルを再エクスポートしてください。)
モバイルアプリでの実行
pteファイルはExecuTorchを使用してスマートフォン上で実行できます。iOSでの実行方法についてはこちらの手順を参照してください。 iPhone 15 Proでは、このモデルは17.3トークン/秒で実行され、3206 MBのメモリを使用します。
量子化レシピ
まず必要なパッケージをインストールします:
pip install git+https://github.com/huggingface/transformers@main
pip install torchao
埋め込み重みの分離
埋め込み層とlm_headを異なる方法で量子化したいため、まずモデルの重みを分離する必要があります:
from transformers import (
AutoModelForCausalLM,
AutoProcessor,
AutoTokenizer,
)
import torch
model_id = "microsoft/Phi-4-mini-instruct"
untied_model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained(model_id)
print(untied_model)
from transformers.modeling_utils import find_tied_parameters
print("tied weights:", find_tied_parameters(untied_model))
if getattr(untied_model.config.get_text_config(decoder=True), "tie_word_embeddings"):
setattr(untied_model.config.get_text_config(decoder=True), "tie_word_embeddings", False)
untied_model._tied_weights_keys = []
untied_model.lm_head.weight = torch.nn.Parameter(untied_model.lm_head.weight.clone())
print("tied weights:", find_tied_parameters(untied_model))
USER_ID = "YOUR_USER_ID"
MODEL_NAME = model_id.split("/")[-1]
save_to = f"{USER_ID}/{MODEL_NAME}-untied-weights"
untied_model.push_to_hub(save_to)
tokenizer.push_to_hub(save_to)
# またはローカルに保存
save_to_local_path = f"{MODEL_NAME}-untied-weights"
untied_model.save_pretrained(save_to_local_path)
tokenizer.save_pretrained(save_to)
注: push_to_hub
を使用するには以下を実行する必要があります
pip install -U "huggingface_hub[cli]"
huggingface-cli login
そして書き込み権限のあるトークンをhttps://huggingface.co/settings/tokensから取得してください
量子化
以下のコードを使用して量子化モデルを取得しました:
from transformers import (
AutoModelForCausalLM,
AutoProcessor,
AutoTokenizer,
TorchAoConfig,
)
from torchao.quantization.quant_api import (
IntxWeightOnlyConfig,
Int8DynamicActivationIntxWeightConfig,
AOPerModuleConfig,
quantize_,
)
from torchao.quantization.granularity import PerGroup, PerAxis
import torch
# 分離された重みのモデルから開始
model_id = "microsoft/Phi-4-mini-instruct"
USER_ID = "YOUR_USER_ID"
MODEL_NAME = model_id.split("/")[-1]
untied_model_id = f"{USER_ID}/{MODEL_NAME}-untied-weights"
untied_model_local_path = f"{MODEL_NAME}-untied-weights"
embedding_config = IntxWeightOnlyConfig(
weight_dtype=torch.int8,
granularity=PerAxis(0),
)
linear_config = Int8DynamicActivationIntxWeightConfig(
weight_dtype=torch.int4,
weight_granularity=PerGroup(32),
weight_scale_dtype=torch.bfloat16,
)
quant_config = AOPerModuleConfig({"_default": linear_config, "model.embed_tokens": embedding_config})
quantization_config = TorchAoConfig(quant_type=quant_config, include_embedding=True, untie_embedding_weights=True, modules_to_not_convert=[])
# `untied_model_id`または`untied_model_local_path`を使用
quantized_model = AutoModelForCausalLM.from_pretrained(untied_model_id, torch_dtype=torch.float32, device_map="auto", quantization_config=quantization_config)
tokenizer = AutoTokenizer.from_pretrained(model_id)
# Hubにプッシュ
MODEL_NAME = model_id.split("/")[-1]
save_to = f"{USER_ID}/{MODEL_NAME}-untied-8da4w"
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):])
手動テストからの応答は以下の通りです:
こんにちは!私はAIとして、人間のような意識は持っていませんが、完全に動作可能であなたをサポートするためにここにいます。今日はどのようにお手伝いできますか?
モデル品質
量子化モデルの品質を評価するために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
int8動的アクティベーションとint4重み量子化(8da4w)
lm_eval --model hf --model_args pretrained=pytorch/Phi-4-mini-instruct-8da4w --tasks hellaswag --device cuda:0 --batch_size 8
ベンチマーク | ||
---|---|---|
Phi-4-mini-ins | Phi-4-mini-instruct-8da4w | |
主要集計ベンチマーク | ||
mmlu (0ショット) | 66.73 | 60.75 |
mmlu_pro (5ショット) | 46.43 | 11.75 |
推論 | ||
arc_challenge | 56.91 | 48.46 |
gpqa_main_zeroshot | 30.13 | 30.80 |
hellaswag | 54.57 | 50.35 |
openbookqa | 33.00 | 30.40 |
piqa (0ショット) | 77.64 | 74.43 |
siqa | 49.59 | 44.98 |
truthfulqa_mc2 (0ショット) | 48.39 | 51.35 |
winogrande (0ショット) | 71.11 | 70.32 |
多言語 | ||
mgsm_en_cot_en | 60.80 | 57.60 |
数学 | ||
gsm8k (5ショット) | 81.88 | 61.71 |
Mathqa (0ショット) | 42.31 | 36.95 |
全体 | 55.35 | 48.45 |
ExecuTorchへのエクスポート
ExecuTorchを使用して量子化モデルをスマートフォン上で実行できます。 ExecuTorchをセットアップした後、モデルのエクスポートとデバイス上での実行は簡単です。
まず量子化チェックポイントをExecuTorchのLLMエクスポートスクリプトが期待する形式に変換します。チェックポイントキーの一部をリネームします。 以下のスクリプトがこれを実行します。変換されたチェックポイントpytorch_model_converted.binを便利のためにアップロードしています。
python -m executorch.examples.models.phi_4_mini.convert_weights pytorch_model.bin pytorch_model_converted.bin
チェックポイントが変換されたら、XNNPACKデリゲートを使用してExecuTorchのpte形式にエクスポートできます。 以下のコマンドはmax_seq_length/max_context_length 128(デフォルト値)でエクスポートしますが、必要に応じて変更できます。
PARAMS="executorch/examples/models/phi_4_mini/config.json"
python -m executorch.examples.models.llama.export_llama \
--model "phi_4_mini" \
--checkpoint "pytorch_model_converted.bin" \
--params "$PARAMS" \
-kv \
--use_sdpa_with_kv_cache \
-X \
--metadata '{"get_bos_id":199999, "get_eos_ids":[200020,199999]}' \
--max_seq_length 128 \
--max_context_length 128 \
--output_name="phi4-mini-8da4w.pte"
その後、モバイルアプリでモデルを実行できます(モバイルアプリでの実行を参照)。
免責事項
PyTorchは量子化モデルの安全性評価やレッドチーミングを行っていません。性能特性、出力、動作は元のモデルと異なる場合があります。ユーザーは適切な使用ケースの選択、精度・安全性・公平性の評価と緩和、セキュリティの確保、およびすべての適用可能な法律と規制の遵守について単独で責任を負います。
このモデルカードに含まれる内容は、モデルがリリースされたライセンスの制限や変更、またはそこに含まれる責任制限や保証の免責事項と解釈されるべきではありません。



