> 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-de/mlops-and-bereitstellung/mlflow.md).

# MLflow

**MLflow** ist eine Open-Source-Plattform zur Verwaltung des kompletten **Machine-Learning-Lebenszyklus** — von Experimentverfolgung und Modellversionierung bis zu Bereitstellung und Überwachung. Von Tausenden Organisationen weltweit genutzt, bringt MLflow Struktur und Reproduzierbarkeit in ML-Workflows. Führen Sie es in Clore.ais GPU-Cloud aus, um einen zentralen Tracking-Server neben Ihren Trainingsjobs zu erhalten.

***

## Was ist MLflow?

MLflow bietet vier Kernkomponenten:

| Komponente         | Beschreibung                                                                    |
| ------------------ | ------------------------------------------------------------------------------- |
| **Tracking**       | Protokollieren Sie Parameter, Metriken, Artefakte und Code von ML-Läufen        |
| **Projekte**       | Paketieren Sie Code für reproduzierbare Läufe                                   |
| **Modelle**        | Standardmodellformat für die Bereitstellung über verschiedene Frameworks hinweg |
| **Model Registry** | Zentrales Modell-Repository mit Versionierung und Lebenszyklus                  |

**Unterstützte Frameworks (eingebautes Autologging):**

* PyTorch, TensorFlow/Keras
* Scikit-learn, XGBoost, LightGBM
* HuggingFace Transformers
* Spark MLlib, statsmodels, Prophet

***

## Voraussetzungen

| Anforderung | Wert                                                 |
| ----------- | ---------------------------------------------------- |
| GPU-VRAM    | Beliebig (der MLflow-Server selbst ist CPU-gebunden) |
| Speicher    | 20 GB+ (für Artefakte)                               |
| RAM         | 4 GB Minimum für den Server                          |
| Ports       | 22 (SSH), 5000 (MLflow UI)                           |

{% hint style="info" %}
Der MLflow-Tracking-Server ist leichtgewichtig. Sie können ihn auf einer kleinen CPU-Instanz betreiben und Ihre GPU-Trainingsjobs darauf zeigen lassen. Alternativ können Sie ihn zusammen mit Ihrer GPU-Trainingsinstanz platzieren.
{% endhint %}

***

## Schritt 1 — Miete einen Server bei Clore.ai

1. Melden Sie sich an bei [clore.ai](https://clore.ai).
2. Klicken Sie **Marktplatz**.
3. Für einen dedizierten Tracking-Server: nach RAM ≥ 8 GB filtern (GPU optional).
4. Für Co-Location: verwenden Sie Ihre bestehende Trainingsinstanz.
5. Docker-Image festlegen: **`ghcr.io/mlflow/mlflow:latest`**
6. Offene Ports festlegen: `22` (SSH) und `5000` (MLflow UI).
7. Klicken Sie **Mieten**.

***

## Schritt 2 — Starten des MLflow-Tracking-Servers

Das offizielle `ghcr.io/mlflow/mlflow` Image erfordert eine Überschreibung des Startbefehls.

### In der Clore.ai Docker-Konfiguration

Setzen Sie das **Kommando** (oder Entry-Point-Überschreibung) auf:

```bash
bash -c "apt-get update -q && apt-get install -y -q openssh-server && \
    mkdir /var/run/sshd && \
    echo 'root:clore123' | chpasswd && \
    sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config && \
    service ssh start && \
    mlflow server \
        --host 0.0.0.0 \
        --port 5000 \
        --default-artifact-root /mlflow/artifacts \
        --backend-store-uri sqlite:////mlflow/mlflow.db"
```

### Alternative: eigenes Dockerfile

```dockerfile
FROM ghcr.io/mlflow/mlflow:latest

RUN apt-get update && apt-get install -y \
    openssh-server \
    && rm -rf /var/lib/apt/lists/*

# Konfiguriere SSH
RUN mkdir /var/run/sshd && \
    echo 'root:clore123' | chpasswd && \
    sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config

# Zusätzliche Python-Pakete
RUN pip install boto3 psycopg2-binary

RUN mkdir -p /mlflow/artifacts

EXPOSE 22 5000

CMD service ssh start && \
    mlflow server \
        --host 0.0.0.0 \
        --port 5000 \
        --default-artifact-root /mlflow/artifacts \
        --backend-store-uri sqlite:////mlflow/mlflow.db
```

***

## Schritt 3 — Zugriff auf die MLflow-UI

Öffnen Sie Ihren Browser:

```
http://<clore-host>:<public-port-5000>
```

Sie sollten das MLflow-Experiments-Dashboard sehen.

{% hint style="info" %}
Das Standard-SQLite-Backend (`mlflow.db`) speichert alle Run-Metadaten lokal. Für Produktion oder Teamgebrauch wechseln Sie zu PostgreSQL — siehe Erweiterte Konfiguration weiter unten.
{% endhint %}

***

## Schritt 4 — Protokollieren Sie Ihr erstes Experiment

### Verbindung von einem entfernten Trainingsjob herstellen

Auf Ihrer Trainingsmaschine (oder einer anderen Clore.ai-Instanz) setzen Sie die Tracking-URI:

```bash
export MLFLOW_TRACKING_URI=http://<clore-host>:<public-port-5000>
```

### Grundlegendes PyTorch-Experiment-Logging

```python
import mlflow
import mlflow.pytorch
import torch
import torch.nn as nn
import torch.optim as optim

# Verbindung zum MLflow-Server
mlflow.set_tracking_uri("http://<clore-host>:<public-port-5000>")
mlflow.set_experiment("my-first-experiment")

# Definieren Sie ein einfaches Modell
class SimpleNet(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super().__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(hidden_size, output_size)
    
    def forward(self, x):
        return self.fc2(self.relu(self.fc1(x)))

# Training mit MLflow-Tracking
with mlflow.start_run(run_name="training-run-001"):
    # Protokollieren Sie Hyperparameter
    params = {
        "learning_rate": 0.001,
        "batch_size": 64,
        "epochs": 100,
        "hidden_size": 256,
        "optimizer": "adam"
    }
    mlflow.log_params(params)
    
    # Modell initialisieren
    model = SimpleNet(784, 256, 10).cuda()
    optimizer = optim.Adam(model.parameters(), lr=params["learning_rate"])
    criterion = nn.CrossEntropyLoss()
    
    # Trainingsschleife
    for epoch in range(params["epochs"]):
        loss = torch.tensor(0.5 / (epoch + 1))  # Simuliert
        accuracy = 0.7 + epoch * 0.003
        
        # Protokollieren Sie Metriken für jede Epoche
        mlflow.log_metrics({
            "train_loss": loss.item(),
            "train_accuracy": accuracy,
        }, step=epoch)
    
    # Protokollieren Sie das finale Modell
    mlflow.pytorch.log_model(model, "model")
    
    # Protokollieren Sie finale Metriken
    mlflow.log_metric("final_accuracy", accuracy)
    
    print(f"Run logged to MLflow. ID: {mlflow.active_run().info.run_id}")
```

### HuggingFace Transformers Autologging

```python
import mlflow
from transformers import TrainingArguments, Trainer

mlflow.set_tracking_uri("http://<clore-host>:<public-port-5000>")
mlflow.set_experiment("llm-finetuning")

# Aktivieren Sie Autologging — protokolliert automatisch Parameter, Metriken und Modell
mlflow.transformers.autolog()

training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=64,
    learning_rate=2e-5,
    warmup_steps=500,
    weight_decay=0.01,
    logging_dir="./logs",
    logging_steps=10,
    evaluation_strategy="epoch",
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=eval_dataset,
)

with mlflow.start_run():
    trainer.train()
```

***

## Schritt 5 — Scikit-learn mit Autologging

```python
import mlflow
import mlflow.sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_digits

mlflow.set_tracking_uri("http://<clore-host>:<public-port-5000>")
mlflow.set_experiment("sklearn-experiments")

# Autolog alles
mlflow.sklearn.autolog()

X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

with mlflow.start_run(run_name="random-forest-v1"):
    rf = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42)
    rf.fit(X_train, y_train)
    
    score = rf.score(X_test, y_test)
    print(f"Test Accuracy: {score:.4f}")
    # Alle Parameter, Metriken und das Modell werden automatisch protokolliert!
```

***

## Schritt 6 — Model Registry

Registrieren und verwalten Sie Modellversionen über die UI oder API:

```python
import mlflow

client = mlflow.MlflowClient("http://<clore-host>:<public-port-5000>")

# Registrieren Sie ein Modell aus einem Run
run_id = "your-run-id-here"
model_uri = f"runs:/{run_id}/model"

registered = mlflow.register_model(
    model_uri=model_uri,
    name="production-classifier"
)

print(f"Version: {registered.version}")

# Modellphase überführen
client.transition_model_version_stage(
    name="production-classifier",
    version=registered.version,
    stage="Production"
)

# Laden Sie ein Produktionsmodell überall
model = mlflow.pyfunc.load_model(
    model_uri="models:/production-classifier/Production"
)
```

***

## Schritt 7 — Ein Modell bereitstellen

MLflow kann jedes protokollierte Modell als REST-API bereitstellen:

```bash
# Auf der MLflow-Server-Instanz
export MLFLOW_TRACKING_URI=http://localhost:5000

mlflow models serve \
    --model-uri "models:/production-classifier/Production" \
    --host 0.0.0.0 \
    --port 5001 \
    --no-conda
```

Testen Sie das bereitgestellte Modell:

```bash
curl -X POST http://<clore-host>:5001/invocations \
    -H "Content-Type: application/json" \
    -d '{"inputs": [[1.0, 2.0, 3.0, ...]]}'
```

***

## Erweiterte Konfiguration

### PostgreSQL-Backend (Produktion)

```bash
# Starten mit PostgreSQL
mlflow server \
    --host 0.0.0.0 \
    --port 5000 \
    --backend-store-uri postgresql://user:password@db-host/mlflow \
    --default-artifact-root s3://my-bucket/mlflow-artifacts
```

### S3-Artefaktspeicher

```bash
pip install boto3

export AWS_ACCESS_KEY_ID=your_key
export AWS_SECRET_ACCESS_KEY=your_secret

mlflow server \
    --host 0.0.0.0 \
    --port 5000 \
    --default-artifact-root s3://my-mlflow-bucket/artifacts \
    --backend-store-uri sqlite:////mlflow/mlflow.db
```

### Authentifizierung (Enterprise)

```bash
pip install mlflow[auth]

mlflow server \
    --host 0.0.0.0 \
    --port 5000 \
    --app-name basic-auth \
    --backend-store-uri sqlite:////mlflow/mlflow.db \
    --default-artifact-root /mlflow/artifacts
```

***

## Vergleich von Runs in der UI

1. Öffnen Sie die MLflow-UI unter `http://<clore-host>:<port>`
2. Wählen Sie ein Experiment im linken Bereich aus
3. Markieren Sie die Kästchen neben mehreren Runs
4. Klicken Sie **Vergleichen** um Metriken und Parameter nebeneinander anzuzeigen
5. Verwenden Sie die **Diagramme** Registerkarte für visuelle Vergleiche

***

## Fehlerbehebung

### Kann keine Verbindung zum Tracking-Server herstellen

```
mlflow.exceptions.MlflowException: API-Anfrage fehlgeschlagen mit HTTP-Statuscode 503
```

**Lösungen:**

* Prüfen Sie, dass Port 5000 in Clore.ai offen und weitergeleitet ist
* Verifizieren Sie, dass der Server läuft: `ps aux | grep mlflow`
* Testen Sie die Konnektivität: `curl http://<clore-host>:<port>/health`

### Artefakt-Upload schlägt fehl

**Lösung:** Stellen Sie sicher, dass das Artefaktverzeichnis beschreibbar ist:

```bash
chmod 777 /mlflow/artifacts
```

### SQLite-gesperrter Fehler (gleichzeitige Schreibzugriffe)

**Lösung:** Wechseln Sie für Multi-User-Setups zu PostgreSQL:

```bash
pip install psycopg2-binary
```

### Model Registry wird nicht angezeigt

**Lösung:** Vergewissern Sie sich, dass Sie ein `--backend-store-uri` verwenden, das die Registry unterstützt (SQLite oder PostgreSQL — nicht nur ein lokaler Pfad).

***

## Kostenabschätzung

| Instanz    | Anwendungsfall               | Geschätzter Preis | Hinweise                |
| ---------- | ---------------------------- | ----------------- | ----------------------- |
| CPU 4-Kern | Nur Tracking-Server          | \~$0.05/Stunde    | Sehr leichtgewichtig    |
| RTX 3080   | Koinstalliertes Training     | \~$0.10/Stunde    | Training + MLflow       |
| RTX 4090   | Schweres Training + Tracking | \~$0.35/Stunde    | Häufigste Konfiguration |

{% hint style="info" %}
Führen Sie MLflow auf einer günstigen CPU-Instanz aus und lassen Sie alle Ihre GPU-Trainingsjobs darauf zeigen. Auf diese Weise läuft der Tracking-Server kontinuierlich, ohne teure GPU-Credits zu verbrauchen.
{% endhint %}

***

## Nützliche Ressourcen

* [Offizielle MLflow-Dokumentation](https://mlflow.org/docs/latest/index.html)
* [MLflow GitHub](https://github.com/mlflow/mlflow)
* [MLflow Docker Hub](https://github.com/mlflow/mlflow/pkgs/container/mlflow)
* [MLflow Model Registry Guide](https://mlflow.org/docs/latest/model-registry.html)
* [MLflow Tracking API-Referenz](https://mlflow.org/docs/latest/python_api/mlflow.html)

***

## Clore.ai GPU-Empfehlungen

| Anwendungsfall            | Empfohlene GPU  | Geschätzte Kosten auf Clore.ai |
| ------------------------- | --------------- | ------------------------------ |
| Entwicklung/Tests         | RTX 3090 (24GB) | \~$0.12/gpu/hr                 |
| Produktions-Training      | RTX 4090 (24GB) | \~$0.70/gpu/hr                 |
| Großangelegte Experimente | A100 80GB       | \~$1.20/gpu/hr                 |

> 💡 Alle Beispiele in diesem Leitfaden können bereitgestellt werden auf [Clore.ai](https://clore.ai/marketplace) GPU-Servern. Durchsuchen Sie verfügbare GPUs und mieten Sie stundenweise — keine Verpflichtungen, voller Root-Zugriff.


---

# 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:

```
GET https://docs.clore.ai/guides/guides_v2-de/mlops-and-bereitstellung/mlflow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
