🚀 Transformers Library
This library provides a quantized version of Phi4-mini, suitable for mobile deployment with ExecuTorch. It offers quantization recipes, running instructions on mobile apps, and model quality evaluations.
🚀 Quick Start
Phi4-mini is quantized by the PyTorch team using torchao with 8-bit embeddings and 8-bit dynamic activations with 4-bit weight linears (8da4w). The model is suitable for mobile deployment with ExecuTorch.
We provide the quantized pte for direct use in ExecuTorch.
(The provided pte file is exported with the default max_seq_length/max_context_length of 128; if you wish to change this, re-export the quantized model following the instructions in Exporting to ExecuTorch.)
✨ Features
- Quantized model suitable for mobile deployment with ExecuTorch.
- Provides quantization recipes and running instructions on mobile apps.
- Evaluates the quality of the quantized model.
📦 Installation
First need to install the required packages:
pip install git+https://github.com/huggingface/transformers@main
pip install torchao
💻 Usage Examples
Running in a mobile app
The pte file can be run with ExecuTorch on a mobile phone. See the instructions for doing this in iOS.
On iPhone 15 Pro, the model runs at 17.3 tokens/sec and uses 3206 Mb of memory.

Quantization Recipe
Untie Embedding Weights
We want to quantize the embedding and lm_head differently. Since those layers are tied, we first need to untie the model:
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)
Note: to push_to_hub
you need to run
pip install -U "huggingface_hub[cli]"
huggingface-cli login
and use a token with write access, from https://huggingface.co/settings/tokens
Quantization
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"
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=[])
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)
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):])
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 Evaluation
We rely on 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 8
int8 dynamic activation and int4 weight quantization (8da4w)
lm_eval --model hf --model_args pretrained=pytorch/Phi-4-mini-instruct-8da4w --tasks hellaswag --device cuda:0 --batch_size 8
Benchmark |
Phi-4-mini-ins |
Phi-4-mini-instruct-8da4w |
Popular aggregated benchmark |
|
|
mmlu (0 shot) |
66.73 |
60.75 |
mmlu_pro (5-shot) |
46.43 |
11.75 |
Reasoning |
|
|
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-shot) |
77.64 |
74.43 |
siqa |
49.59 |
44.98 |
truthfulqa_mc2 (0-shot) |
48.39 |
51.35 |
winogrande (0-shot) |
71.11 |
70.32 |
Multilingual |
|
|
mgsm_en_cot_en |
60.80 |
57.60 |
Math |
|
|
gsm8k (5-shot) |
81.88 |
61.71 |
Mathqa (0-shot) |
42.31 |
36.95 |
Overall |
55.35 |
48.45 |
Exporting to ExecuTorch
We can run the quantized model on a mobile phone using ExecuTorch.
Once ExecuTorch is set-up, exporting and running the model on device is a breeze.
We first convert the quantized checkpoint to one ExecuTorch's LLM export script expects by renaming some of the checkpoint keys.
The following script does this for you. We have uploaded the converted checkpoint pytorch_model_converted.bin for convenience.
python -m executorch.examples.models.phi_4_mini.convert_weights pytorch_model.bin pytorch_model_converted.bin
Once the checkpoint is converted, we can export to ExecuTorch's pte format with the XNNPACK delegate.
The below command exports with a max_seq_length/max_context_length of 128, the default value, but it can be changed as desired.
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"
After that you can run the model in a mobile app (see Running in a mobile app).
📄 License
This project is licensed under the MIT license.