Downloads · 30 days
239
1% of all-time downloads
pytorch/Phi-4-mini-instruct-FP8
Phi-4-mini-instruct-FP8 is a text generation model from pytorch. Use it when you need the model to write or continue text. It is set up for transformers. The card lists the license as mit.
Phi4-mini model quantized with torchao float8 dynamic activation and float8 weight quantization (per row granularity), by PyTorch team. Use it directly, or serve using vLLM with 36% VRAM reduction (5.70 GB needed), 1.…
Downloads · 30 days
239
1% of all-time downloads
All-time downloads
25K
Public
Repo size
13.4 GB
Likes
1
Public
Click a slice to open those files.
.bin4.5 GB · 100%
From the Hugging Face model README
Phi4-mini model quantized with torchao float8 dynamic activation and float8 weight quantization (per row granularity), by PyTorch team. Use it directly, or serve using vLLM with 36% VRAM reduction (5.70 GB needed), 1.15x-1.2x speedup and little to no accuracy impact on H100.
Install vllm nightly to get some recent changes:
pip install vllm --pre --extra-index-url https://wheels.vllm.ai/nightly
pip install --pre torchao torch --index-url https://download.pytorch.org/whl/nightly/cu126
To use fbgemm kernels:
pip install --pre fbgemm-gpu-genai --index-url https://download.pytorch.org/whl/nightly/cu126
from vllm import LLM, SamplingParams
# Sample prompts.
prompts = [
"Hello, my name is",
"The president of the United States is",
"The capital of France is",
"The future of AI is",
]
# Create a sampling params object.
sampling_params = SamplingParams(temperature=0.8, top_p=0.95)
if __name__ == '__main__':
# Create an LLM.
llm = LLM(model="pytorch/Phi-4-mini-instruct-FP8")
# Generate texts from the prompts.
# The output is a list of RequestOutput objects
# that contain the prompt, generated text, and other information.
outputs = llm.generate(prompts, sampling_params)
# Print the outputs.
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)
Note: please use VLLM_DISABLE_COMPILE_CACHE=1 to disable compile cache when running this code, e.g. VLLM_DISABLE_COMPILE_CACHE=1 python example.py, since there are some issues with the composability of compile in vLLM and torchao,
this is expected be resolved in pytorch 2.8.
Then we can serve with the following command:
vllm serve pytorch/Phi-4-mini-instruct-FP8 --tokenizer microsoft/Phi-4-mini-instruct -O3
Install the required packages:
# for compatibility with modeling file in checkpoint
pip install transformers==4.53.0
pip install --pre torchao torch --index-url https://download.pytorch.org/whl/nightly/cu126
pip install accelerate
To use fbgemm kernels:
pip install --pre fbgemm-gpu-genai --index-url https://download.pytorch.org/whl/nightly/cu126
Example:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
torch.random.manual_seed(0)
model_path = "pytorch/Phi-4-mini-instruct-FP8"
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'])
Install the required packages:
# for compatibility with modeling file in checkpoint
pip install transformers==4.53.0
pip install --pre torchao --index-url https://download.pytorch.org/whl/nightly/cu126
pip install torch
pip install accelerate
Use the following code to get the quantized model:
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)
# Push to hub
USER_ID = "YOUR_USER_ID"
MODEL_NAME = model_id.split("/")[-1]
save_to = f"{USER_ID}/{MODEL_NAME}-FP8"
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):])
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
We rely on lm-evaluation-harness to evaluate the quality of the quantized model.
| Benchmark | ||
|---|---|---|
| Phi-4-mini-ins | Phi-4-mini-instruct-FP8 | |
| Popular aggregated benchmark | ||
| mmlu (0-shot) | 66.73 | 66.61 |
| mmlu_pro (5-shot) | 46.43 | 44.58 |
| Reasoning | ||
| 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 |
| Multilingual | ||
| mgsm_en_cot_en | 60.8 | 60.0 |
| Math | ||
| gsm8k (5-shot) | 81.88 | 80.89 |
| mathqa (0-shot) | 42.31 | 42.51 |
| Overall | 55.35 | 55.11 |
Need to install lm-eval from source: 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
lm_eval --model hf --model_args pretrained=pytorch/Phi-4-mini-instruct-FP8 --tasks hellaswag --device cuda:0 --batch_size 8
</details>
| Benchmark | ||
|---|---|---|
| Phi-4 mini-Ins | Phi-4-mini-instruct-FP8 | |
| Peak Memory (GB) | 8.91 | 5.70 (36% reduction) |
We can use the following code to get a sense of peak memory usage during inference:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig
# use "microsoft/Phi-4-mini-instruct" or "pytorch/Phi-4-mini-instruct-FP8"
model_id = "pytorch/Phi-4-mini-instruct-FP8"
quantized_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cuda:0", 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")
</details>
| Benchmark | ||
|---|---|---|
| Phi-4 mini-Ins | Phi-4-mini-instruct-FP8 | |
| latency (batch_size=1) | 1.61s | 1.25s (1.29x speedup) |
| latency (batch_size=256) | 5.16s | 4.89s (1.05x speedup) |
Note the result of latency (benchmark_latency) is in seconds, and serving (benchmark_serving) is in number of requests per second.
<details> <summary> Reproduce Model Performance Results </summary>Get vllm source code:
git clone [email protected]:vllm-project/vllm.git
Install vllm
VLLM_USE_PRECOMPILED=1 pip install --editable .
To use fbgemm kernels:
pip install fbgemm-gpu-genai
Run the benchmarks under vllm root folder:
vllm bench latency --input-len 256 --output-len 256 --model microsoft/Phi-4-mini-instruct --batch-size 1
VLLM_DISABLE_COMPILE_CACHE=1 vllm bench latency --input-len 256 --output-len 256 --model pytorch/Phi-4-mini-instruct-FP8 --batch-size 1
</details>
The model's quantization is powered by TorchAO, a framework presented in the paper TorchAO: PyTorch-Native Training-to-Serving Model Optimization.
Abstract: We present TorchAO, a PyTorch-native model optimization framework leveraging quantization and sparsity to provide an end-to-end, training-to-serving workflow for AI models. TorchAO supports a variety of popular model optimization techniques, including FP8 quantized training, quantization-aware training (QAT), post-training quantization (PTQ), and 2:4 sparsity, and leverages a novel tensor subclass abstraction to represent a variety of widely-used, backend agnostic low precision data types, including INT4, INT8, FP8, MXFP4, MXFP6, and MXFP8. TorchAO integrates closely with the broader ecosystem at each step of the model optimization pipeline, from pre-training (TorchTitan) to fine-tuning (TorchTune, Axolotl) to serving (HuggingFace, vLLM, SGLang, ExecuTorch), connecting an otherwise fragmented space in a single, unified workflow. TorchAO has enabled recent launches of the quantized Llama 3.2 1B/3B and LlamaGuard3-8B models and is open-source at this https URL .
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.