# Phi-4

Führen Sie Microsofts Phi-4 aus - ein kleines, aber leistungsstarkes Sprachmodell.

{% hint style="success" %}
Alle Beispiele können auf GPU-Servern ausgeführt werden, die über [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Mieten auf CLORE.AI

1. Besuchen Sie [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Nach GPU-Typ, VRAM und Preis filtern
3. Wählen **On-Demand** (Festpreis) oder **Spot** (Gebotspreis)
4. Konfigurieren Sie Ihre Bestellung:
   * Docker-Image auswählen
   * Ports festlegen (TCP für SSH, HTTP für Web-UIs)
   * Umgebungsvariablen bei Bedarf hinzufügen
   * Startbefehl eingeben
5. Zahlung auswählen: **CLORE**, **BTC**, oder **USDT/USDC**
6. Bestellung erstellen und auf Bereitstellung warten

### Zugriff auf Ihren Server

* Verbindungsdetails finden Sie in **Meine Bestellungen**
* Webschnittstellen: Verwenden Sie die HTTP-Port-URL
* SSH: `ssh -p <port> root@<proxy-address>`

## Was ist Phi-4?

Phi-4 von Microsoft bietet:

* 14B Parameter mit ausgezeichneter Leistung
* Übertrifft größere Modelle in Benchmarks
* Starke Schlussfolgerungs- und Mathematikfähigkeiten
* Effiziente Inferenz

## Modellvarianten

| Modell         | Parameter        | VRAM | Spezialgebiet      |
| -------------- | ---------------- | ---- | ------------------ |
| Phi-4          | 14B              | 16GB | Allgemein          |
| Phi-3.5-mini   | 3,8B             | 4GB  | Leichtgewichtig    |
| Phi-3.5-MoE    | 42B (6,6B aktiv) | 16GB | Mixture of Experts |
| Phi-3.5-vision | 4,2B             | 6GB  | Vision             |

## Schnelle Bereitstellung

**Docker-Image:**

```
pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime
```

**Ports:**

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

**Befehl:**

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

## Zugriff auf Ihren Dienst

Nach der Bereitstellung finden Sie Ihre `http_pub` URL in **Meine Bestellungen**:

1. Gehen Sie zur **Meine Bestellungen** Seite
2. Klicken Sie auf Ihre Bestellung
3. Finden Sie die `http_pub` URL (z. B., `abc123.clorecloud.net`)

Verwenden Sie `https://IHRE_HTTP_PUB_URL` anstelle von `localhost` in den Beispielen unten.

## Verwendung von Ollama

```bash

# Phi-4 ausführen
ollama run phi4

# Phi-3.5 mini (schneller)
ollama run phi3.5

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

## Installation

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

## Grundlegende Verwendung

```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": "You are a helpful AI assistant."},
    {"role": "user", "content": "Explain the difference between TCP and 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

Für Bildverständnis:

```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|>\nDescribe this diagram in detail."}
]

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)
```

## Mathematik und Schlussfolgern

```python
messages = [
    {"role": "user", "content": """
Löse Schritt für Schritt:
Ein Bauer hat Hühner und Kaninchen.
Gesamtanzahl der Köpfe: 35
Gesamtanzahl der Beine: 94
Wie viele von jedem Tier?
"""}
]

# Phi-4 glänzt bei schrittweisem Denken
```

## Codegenerierung

```python
messages = [
    {"role": "user", "content": """
Schreiben Sie eine Python-Implementierung eines binären Suchbaums mit:
- Einfügen
- Suche
- Löschen
- Inorder-Traversierung
Fügen Sie Typangaben und Docstrings hinzu.
"""}
]
```

## Quantisierte Inferenz

```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-Oberfläche

```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="You are a helpful assistant.", label="System"),
        gr.Slider(0.1, 1.5, value=0.7, label="Temperature")
    ],
    title="Phi-4 Chat"
)

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

## Leistung

| Modell        | GPU      | Tokens/sec |
| ------------- | -------- | ---------- |
| 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-Bit) | RTX 3090 | \~40       |

## Benchmarks

| Modell        | 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 erreicht oder übertrifft deutlich größere Modelle*

## Fehlerbehebung

### "trust\_remote\_code" Fehler

* Hinzufügen `trust_remote_code=True` auf `from_pretrained()`
* Dies ist für Phi-Modelle erforderlich

### Wiederholende Ausgaben

* Niedrigere Temperatur (0,3-0,6)
* Fügen Sie repetition\_penalty=1.1 hinzu
* Verwenden Sie die richtige Chat-Vorlage

### Speicherprobleme

* Phi-4 ist effizient, benötigt aber trotzdem \~8 GB für 14B
* Verwenden Sie bei Bedarf 4-Bit-Quantisierung
* Reduzieren Sie die Kontextlänge

### Falsches Ausgabeformat

* Verwenden Sie `apply_chat_template()` für richtige Formatierung
* Überprüfen Sie, ob Sie die Instruct-Version verwenden, nicht die Basisversion

## Kostenabschätzung

Typische CLORE.AI-Marktplatztarife (Stand 2024):

| GPU       | Stundensatz | Tagessatz | 4-Stunden-Sitzung |
| --------- | ----------- | --------- | ----------------- |
| 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           |

*Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *auf aktuelle Preise.*

**Geld sparen:**

* Verwenden Sie **Spot** Markt für flexible Workloads (oft 30–50% günstiger)
* Bezahlen mit **CLORE** Token
* Preise bei verschiedenen Anbietern vergleichen

## Anwendungsfälle

* Mathematik-Nachhilfe
* Code-Unterstützung
* Dokumentenanalyse (Vision)
* Effiziente Edge-Bereitstellung
* Kosteneffiziente Inferenz

## Nächste Schritte

* Qwen2.5 - alternatives Modell
* Gemma 2 - Googles Modell
* Llama 3.2 - Metas Modell
