> 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-ru/yazykovye-modeli/phi4.md).

# Phi-4

Запустите Phi-4 от Microsoft — небольшую, но мощную языковую модель.

{% hint style="success" %}
Все примеры можно запускать на GPU-серверах, арендованных через [маркетплейс CLORE.AI](https://clore.ai/marketplace).
{% endhint %}

## Аренда на CLORE.AI

1. Перейдите на [маркетплейс CLORE.AI](https://clore.ai/marketplace)
2. Отфильтруйте по типу GPU, объёму VRAM и цене
3. Выберите **On-Demand** (фиксированная ставка) или **Spot** (цена ставки)
4. Настройте свой заказ:
   * Выберите Docker-образ
   * Установите порты (TCP для SSH, HTTP для веб-интерфейсов)
   * При необходимости добавьте переменные окружения
   * Введите команду запуска
5. Выберите способ оплаты: **CLORE**, **BTC**, или **USDT/USDC**
6. Создайте заказ и дождитесь развертывания

### Получите доступ к своему серверу

* Найдите данные для подключения в **Мои заказы**
* Веб-интерфейсы: используйте URL HTTP-порта
* SSH: `ssh -p <port> root@<proxy-address>`

## Что такое Phi-4?

Phi-4 от Microsoft предлагает:

* 14B параметров с отличной производительностью
* Превосходит более крупные модели в бенчмарках
* Сильные рассуждения и математика
* Эффективный вывод

## Варианты модели

| Модель         | Параметры           | VRAM | Специализация   |
| -------------- | ------------------- | ---- | --------------- |
| Phi-4          | 14B                 | 16GB | Общее           |
| Phi-3.5-mini   | 3.8B                | 4 ГБ | Лёгкая          |
| Phi-3.5-MoE    | 42B (6.6B активных) | 16GB | Смесь экспертов |
| Phi-3.5-vision | 4.2B                | 6 ГБ | Зрение          |

## Быстрое развёртывание

**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 vision
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)
print(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)
print(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 Chat"
)

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

## Производительность

| Модель        | GPU      | Токенов/сек |
| ------------- | -------- | ----------- |
| 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 эффективна, но всё равно требует \~8 ГБ для 14B
* При необходимости используйте 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 40 ГБ | \~$0.17          | \~$4.00        | \~$0.70          |
| A100 80 ГБ | \~$0.25          | \~$6.00        | \~$1.00          |

*Цены зависят от провайдера и спроса. Проверьте* [*маркетплейс CLORE.AI*](https://clore.ai/marketplace) *актуальные тарифы.*

**Сэкономьте деньги:**

* Используйте **Spot** рынок для прерываемых задач — примерно треть серверов оценивает spot-цены ниже on-demand (медиана \~13% скидки), остальные совпадают с ними
* Платите **CLORE** токенами
* Сравните цены у разных провайдеров

## Сценарии использования

* Обучение математике
* Помощь с кодом
* Анализ документов (зрение)
* Эффективное развёртывание на периферийных устройствах
* Экономичный вывод

## Дальнейшие шаги

* Qwen2.5 — альтернативная модель
* Gemma 2 — модель Google
* 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-ru/yazykovye-modeli/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.
