|
--- |
|
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 |
|
--- |
|
|
|
# Quantization Recipe |
|
|
|
First need to install the required packages: |
|
``` |
|
pip install git+https://github.com/huggingface/transformers@main |
|
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126 |
|
``` |
|
|
|
We used following code to get the quantized model: |
|
|
|
``` |
|
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" |
|
|
|
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, |
|
) |
|
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32, device_map="auto") |
|
tokenizer = AutoTokenizer.from_pretrained(model_id) |
|
|
|
# TODO: use AOPerModuleConfig once fix for tied weights is landed |
|
quantize_( |
|
quantized_model, |
|
embedding_config, |
|
lambda m, fqn: isinstance(m, torch.nn.Embedding) |
|
) |
|
quantize_( |
|
quantized_model, |
|
linear_config, |
|
) |
|
|
|
# Push to hub |
|
# USER_ID = "YOUR_USER_ID" |
|
# save_to = f"{USER_ID}/phi4-mini-8dq4w" |
|
# quantized_model.push_to_hub(save_to, safe_serialization=False) |
|
# tokenizer.push_to_hub(save_to) |
|
|
|
# Manual testing |
|
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):]) |
|
|
|
|
|
# Save to disk |
|
state_dict = quantized_model.state_dict() |
|
torch.save(state_dict, "phi4-mini-8dq4w.bin") |
|
|
|
``` |
|
|
|
The response from the manual testing is: |
|
|
|
``` |
|
Hello! As an AI, I don't have consciousness in the way humans do, but I am fully operational and here to assist you. How can I help you today? |
|
``` |
|
|
|
# Model Quality |
|
|
|
We rely on [lm-evaluation-harness](https://github.com/EleutherAI/lm-evaluation-harness) to evaluate the quality of the quantized model. |
|
|
|
Need to install lm-eval from source: https://github.com/EleutherAI/lm-evaluation-harness#install |
|
|
|
## baseline |
|
``` |
|
lm_eval --model hf --model_args pretrained=microsoft/Phi-4-mini-instruct --tasks hellaswag --device cuda:0 --batch_size 64 |
|
``` |
|
|
|
## 8dq4w |
|
``` |
|
import lm_eval |
|
from lm_eval import evaluator |
|
from lm_eval.utils import ( |
|
make_table, |
|
) |
|
|
|
lm_eval_model = lm_eval.models.huggingface.HFLM(pretrained=quantized_model, batch_size=64) |
|
results = evaluator.simple_evaluate( |
|
lm_eval_model, tasks=["hellaswag"], device="cuda:0", batch_size="auto" |
|
) |
|
print(make_table(results)) |
|
``` |
|
|
|
| Benchmark | | | |
|
|----------------------------------|-------------|-------------------| |
|
| | Phi-4 mini-Ins | phi4-mini-8dq4w | |
|
| **Popular aggregated benchmark** | | | |
|
| mmlu | 66.73 | 63.11 | |
|
| mmlu_pro | 44.71 | 35.31 | |
|
| **Reasoning** | | | |
|
| HellaSwag | 54.57 | 53.24 | |
|
| **Multilingual** | | | |
|
| **Math** | | | |
|
| **Overall** | **TODO** | **TODO** | |
|
|
|
|
|
# Exporting to ExecuTorch |
|
|
|
Exporting to ExecuTorch requires you clone and install [ExecuTorch](https://github.com/pytorch/executorch). |
|
|
|
|
|
## Convert quantized checkpoint to ExecuTorch's format |
|
``` |
|
python -m executorch.examples.models.phi_4_mini.convert_weights phi4-mini-8dq4w.bin phi4-mini-8dq4w-converted.bin |
|
``` |
|
|
|
## Export to an ExecuTorch *.pte with XNNPACK |
|
``` |
|
PARAMS="executorch/examples/models/phi_4_mini/config.json" |
|
python -m executorch.examples.models.llama.export_llama \ |
|
--model "phi_4_mini" \ |
|
--checkpoint "phi4-mini-8dq4w-converted.bin" \ |
|
--params "$PARAMS" \ |
|
-kv \ |
|
--use_sdpa_with_kv_cache \ |
|
-X \ |
|
--xnnpack-extended-ops \ |
|
--metadata '{"get_bos_id":199999, "get_eos_ids":[200020,199999]}' \ |
|
--output_name="phi4-mini-8dq4w.pte" |
|
``` |
|
|
|
## Run model with pybindings |
|
``` |
|
export TOKENIZER="/path/to/tokenizer.json" |
|
export TOKENIZER_CONFIG="/path/to/tokenizer_config.json" |
|
export PROMPT="<|system|><|end|><|user|>Hey, are you conscious? Can you talk to me?<|end|><|assistant|>" |
|
python -m executorch.examples.models.llama.runner.native \ |
|
--model phi_4_mini \ |
|
--pte phi4-mini-8dq4w.pte \ |
|
-kv \ |
|
--tokenizer ${TOKENIZER} \ |
|
--tokenizer_config ${TOKENIZER_CONFIG} \ |
|
--prompt "${PROMPT}" \ |
|
--params "${PARAMS}" \ |
|
--max_len 128 \ |
|
--temperature 0 |
|
``` |
|
|
|
The output is: |
|
|
|
``` |
|
Hello! I am Phi, an AI developed by Microsoft. I am not conscious in the way humans are, but I am here to help and converse with you. How can I assist you today?Hello! I am Phi, an AI developed by Microsoft. I am not conscious in the way humans are, but I am here to help and converse with you. How can I assist you today?Hello! I am Phi, an AI developed by Microsoft. I am not conscious in the way humans are, but I am here to |
|
``` |
|
|
|
Note: the runner does not currently recongize the stop token from Phi 4 Mini, so it generates text beyond when it should stop. |
|
|
|
## Running in a mobile app |
|
The model can be run in a mobile app. See [instructions](https://pytorch.org/executorch/main/llm/llama-demo-ios.html) for doing this on iOS. |
|
TODO: add perf numbers, memory numbers, and screenshot from app |
|
|
|
# Disclaimer |
|
PyTorch has not performed safety evaluations or red teamed the quantized models. Performance characteristics, outputs, and behaviors may differ from the original models. Users are solely responsible for selecting appropriate use cases, evaluating and mitigating for accuracy, safety, and fairness, ensuring security, and complying with all applicable laws and regulations. |
|
|
|
Nothing contained in this Model Card should be interpreted as or deemed a restriction or modification to the licenses the models are released under, including any limitations of liability or disclaimers of warranties provided therein. |