在这篇博客中,我们将演示如何使用 Python 和 Hugging Face Transformers 快速测试 microsoft/Phi-4-mini-instruct 模型。
该模型非常适合处理 快速且高效的自然语言任务,尤其适用于 计算资源有限 或对 低延迟推理 有要求的场景。
Phi-4-mini-instruct 是微软开发的小型语言模型,专为指令跟随优化。适用场景包括:
下面是一个最小化的 Python 脚本,用于:
请确保安装以下依赖:
pip install transformers torch
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# 检查是否有 GPU
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# 加载模型和 tokenizer
model_id = "microsoft/Phi-4-mini-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
trust_remote_code=True
).to(device)
# 构建对话
messages = [
{"role": "system", "content": "You are a helpful AI assistant."},
{"role": "user", "content": "用简单的语言解释监督学习和非监督学习的区别。"}
]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
# 编码并转移到设备
inputs = tokenizer(prompt, return_tensors="pt").to(device)
# 生成回复
output_ids = model.generate(
**inputs,
max_new_tokens=900,
do_sample=False,
temperature=0.0
)
# 解码并打印输出
response = tokenizer.decode(output_ids[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True)
print("生成的回复:")
print(response)
没有本地 GPU?你可以在 NiceGPU.com 上运行上述代码,这是一个基于云端 GPU 的 Jupyter Notebook 平台。
NiceGPU 由 Newegg 推出,支持学生和开源开发者的 AI 项目,免费或低价提供 GPU 资源。
模型可能会生成如下回复:
生成的回复:
Supervised learning is like having a teacher who shows you examples of the answers and then asks you to predict the answers for new questions. You learn from the examples provided, and your goal is to get the answers right. Unsupervised learning, on the other hand, is like exploring a new place without a map. You look at the data and try to find patterns or groupings on your own, without any guidance on what you're looking for.
Phi-4-Mini-Instruct 是一个高效的轻量模型。无论你是在开发嵌入式助手、在本地实验 LLM,还是希望以低成本部署智能服务,它都是一个出色的起点。
🔗 在线体验模型: https://huggingface.co/microsoft/phi-4-mini-instruct
🚀 免费运行模型: https://nicegpu.com