> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/phi4.md).

# Phi-4

在 Clore.ai GPU 上运行微软的 Phi-4 小型语言模型

运行微软的 Phi-4——一个小而强大的语言模型。

{% hint style="success" %}
所有示例都可以在通过以下方式租用的 GPU 服务器上运行 [CLORE.AI 市场](https://clore.ai/marketplace).
{% endhint %}

## 在 CLORE.AI 上租用

1. 访问 [CLORE.AI 市场](https://clore.ai/marketplace)
2. 按 GPU 类型、VRAM 和价格筛选
3. 选择 **按需** （固定费率）或 **竞价** （出价）
4. 配置你的订单：
   * 选择 Docker 镜像
   * 设置端口（SSH 用 TCP，Web UI 用 HTTP）
   * 如有需要，添加环境变量
   * 输入启动命令
5. 选择支付方式： **CLORE**, **BTC**，或 **USDT/USDC**
6. 创建订单并等待部署

### 访问你的服务器

* 在以下位置查找连接信息 **我的订单**
* Web 界面：使用 HTTP 端口 URL
* SSH： `ssh -p <port> root@<proxy-address>`

## 什么是 Phi-4？

微软的 Phi-4 提供：

* 140亿参数，性能出色
* 在基准测试中胜过更大的模型
* 强大的推理与数学能力
* 高效推理

## 模型变体

| 模型             | 参数          | 显存   | 特点   |
| -------------- | ----------- | ---- | ---- |
| Phi-4          | 14B         | 16GB | 通用   |
| Phi-3.5-mini   | 38亿         | 4GB  | 轻量级  |
| Phi-3.5-MoE    | 420亿（66亿激活） | 16GB | 专家混合 |
| Phi-3.5-vision | 42亿         | 6GB  | 视觉   |

## 快速部署

**Docker 镜像：**

```
pytorch/pytorch:2.11.0-cuda12.8-cudnn9-runtime
```

**端口：**

```
22/tcp
8000/http
```

**命令：**

```bash
pip install transformers accelerate torch && \
python phi4_server.py
```

## 访问你的服务

部署后，找到你的 `http_pub` URL 在 **我的订单**:

1. 前往 **我的订单** 页面
2. 点击你的订单
3. 找到 `http_pub` URL（例如， `abc123.clorecloud.net`)

使用 `https://YOUR_HTTP_PUB_URL` 替代 `localhost` 在下面的示例中。

## 使用 Ollama

```bash

# 运行 Phi-4
ollama run phi4

# Phi-3.5 mini（更快）
ollama run phi3.5

# Phi-3.5 视觉
ollama run phi3.5-vision
```

## 安装

```bash
pip install transformers accelerate torch
```

## 基础用法

```python
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "microsoft/Phi-4"

tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True
)

messages = [
    {"role": "system", "content": "你是一个乐于助人的 AI 助手。"},
    {"role": "user", "content": "解释 TCP 和 UDP 之间的区别。"}
]

inputs = tokenizer.apply_chat_template(
    messages,
    return_tensors="pt",
    add_generation_prompt=True
).to("cuda")

outputs = model.generate(
    inputs,
    max_new_tokens=512,
    temperature=0.7,
    do_sample=True
)

response = tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)
打印(response)
```

## Phi-3.5-Vision

用于图像理解：

```python
from transformers import AutoModelForCausalLM, AutoProcessor
from PIL import Image
import torch

model_id = "microsoft/Phi-3.5-vision-instruct"

processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16,
    device_map="auto",
    trust_remote_code=True
)

image = Image.open("diagram.png")

messages = [
    {"role": "user", "content": "<|image_1|>\n请详细描述这张图。"}
]

prompt = processor.tokenizer.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)

inputs = processor(prompt, [image], return_tensors="pt").to("cuda")

outputs = model.generate(
    **inputs,
    max_new_tokens=512,
    temperature=0.7
)

response = processor.decode(outputs[0], skip_special_tokens=True)
打印(response)
```

## 数学与推理

```python
messages = [
    {"role": "user", "content": """
逐步求解：
一位农民养了鸡和兔子。
总头数：35
总腿数：94
每种动物各有多少？
"""}
]

# Phi-4 擅长逐步推理
```

## 代码生成

```python
messages = [
    {"role": "user", "content": """
编写一个 Python 二叉搜索树实现，包含：
- 插入
- 搜索
- 删除
- 中序遍历
包含类型提示和文档字符串。
"""}
]
```

## 量化推理

```python
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
import torch

quantization_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_compute_dtype=torch.bfloat16
)

model = AutoModelForCausalLM.from_pretrained(
    "microsoft/Phi-4",
    quantization_config=quantization_config,
    device_map="auto",
    trust_remote_code=True
)
```

## Gradio 界面

```python
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

model_id = "microsoft/Phi-4"
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto", trust_remote_code=True
)

def chat(message, history, system_prompt, temperature):
    messages = [{"role": "system", "content": system_prompt}]
    for h in history:
        messages.append({"role": "user", "content": h[0]})
        messages.append({"role": "assistant", "content": h[1]})
    messages.append({"role": "user", "content": message})

    inputs = tokenizer.apply_chat_template(messages, return_tensors="pt").to("cuda")
    outputs = model.generate(inputs, max_new_tokens=512, temperature=temperature, do_sample=True)

    return tokenizer.decode(outputs[0][inputs.shape[1]:], skip_special_tokens=True)

demo = gr.ChatInterface(
    fn=chat,
    additional_inputs=[
        gr.Textbox(value="你是一个乐于助人的助手。", label="系统"),
        gr.Slider(0.1, 1.5, value=0.7, label="温度")
    ],
    title="Phi-4 聊天"
)

demo.launch(server_name="0.0.0.0", server_port=7860)
```

## 性能

| 模型           | GPU      | 每秒 Token 数 |
| ------------ | -------- | ---------- |
| Phi-3.5-mini | RTX 3060 | \~100      |
| Phi-3.5-mini | RTX 4090 | \~150      |
| Phi-4        | RTX 4090 | \~60       |
| Phi-4        | A100     | \~90       |
| Phi-4（4 位）   | RTX 3090 | \~40       |

## 基准

| 模型            | MMLU  | HumanEval | GSM8K |
| ------------- | ----- | --------- | ----- |
| Phi-4         | 84.8% | 82.6%     | 94.6% |
| GPT-4-Turbo   | 86.4% | 85.4%     | 94.2% |
| Llama-3.1-70B | 83.6% | 80.5%     | 92.1% |

*Phi-4 可与更大得多的模型相媲美，甚至更强*

## 故障排查

### "trust\_remote\_code" 错误

* 在 `trust_remote_code=True` 设为 `from_pretrained()`
* 这是 Phi 模型所必需的

### 重复输出

* 降低温度（0.3-0.6）
* 添加 repetition\_penalty=1.1
* 使用正确的聊天模板

### 内存问题

* Phi-4 很高效，但 14B 仍需要约 8GB
* 如有需要，使用 4 位量化
* 减少上下文长度

### 输出格式错误

* 使用 `apply_chat_template()` 以便正确格式化
* 检查你使用的是 instruct 版本，而不是基础版

## 成本估算

CLORE.AI 市场常见费率（截至 2024 年）：

| GPU       | 小时费率    | 日费率     | 4 小时会话  |
| --------- | ------- | ------- | ------- |
| RTX 3060  | \~$0.03 | \~$0.70 | \~$0.12 |
| RTX 3090  | \~$0.06 | \~$1.50 | \~$0.25 |
| RTX 4090  | \~$0.10 | \~$2.30 | \~$0.40 |
| A100 40GB | \~$0.17 | \~$4.00 | \~$0.70 |
| A100 80GB | \~$0.25 | \~$6.00 | \~$1.00 |

*价格因提供商和需求而异。请查看* [*CLORE.AI 市场*](https://clore.ai/marketplace) *以获取当前费率。*

**节省费用：**

* 使用 **竞价** 可中断工作市场——约三分之一的服务器将现货价格定得低于按需价格（中位数约优惠 13%），其余则与按需价格持平
* 使用 **CLORE** 代币支付
* 比较不同提供商的价格

## 应用场景

* 数学辅导
* 代码辅助
* 文档分析（视觉）
* 高效边缘部署
* 高性价比推理

## 下一步

* Qwen2.5 - 替代模型
* Gemma 2 - 谷歌的模型
* Llama 3.2 - Meta 的模型


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/yu-yan-mo-xing/phi4.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
