> 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/training/jupyter-ml-training.md).

# Jupyter-ML-Training

Richte JupyterLab mit GPU-Unterstützung für ML-Training auf Clore.ai ein

Richte JupyterLab mit GPU-Unterstützung für Machine-Learning-Experimente und Modelltraining ein.

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

## Serveranforderungen

| Parameter | Minimum     | Empfohlen |
| --------- | ----------- | --------- |
| RAM       | 16 GB       | 32 GB+    |
| VRAM      | 8 GB        | 16GB+     |
| Netzwerk  | 200Mbps     | 500Mbps+  |
| Startzeit | 2–3 Minuten | -         |

{% hint style="info" %}
JupyterLab selbst ist leichtgewichtig. Wähle GPU und RAM basierend auf den Anforderungen deiner Trainingslast.
{% endhint %}

## Schnell bereitstellen

**Docker-Image:**

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

**Ports:**

```
22/tcp
8888/http
6006/http
```

**Umgebung:**

```
JUPYTER_TOKEN=dein_sicheres_token_hier
```

**Befehl:**

```bash
pip install jupyterlab tensorboard && \\
jupyter lab --ip=0.0.0.0 --port=8888 --allow-root --NotebookApp.token='your_secure_token_here'
```

## Auf deinen Dienst zugreifen

Nach der Bereitstellung findest du deine `http_pub` URL in **Meine Bestellungen**:

1. Gehe zu **Meine Bestellungen** Seite
2. Klicke auf deine Bestellung
3. Finde die `http_pub` URL (z. B. `abc123.clorecloud.net`)

Verwende `https://YOUR_HTTP_PUB_URL` anstelle von `localhost` in den folgenden Beispielen.

### Prüfen, ob es funktioniert

```bash
# Prüfen, ob JupyterLab erreichbar ist
curl https://your-http-pub.clorecloud.net/

# Mit Token aufrufen
# https://your-http-pub.clorecloud.net/?token=dein_sicheres_token_hier
```

{% hint style="warning" %}
Wenn du HTTP 502 erhältst, warte 2–3 Minuten - der Dienst installiert Abhängigkeiten.
{% endhint %}

## Mieten auf CLORE.AI

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

### Greife auf deinen Server zu

* Verbindungsdetails finden in **Meine Bestellungen**
* Web-Oberflächen: Verwende die HTTP-Port-URL
* SSH: `ssh -p <port> root@<proxy-address>`

## Jupyter aufrufen

1. Auf die Bereitstellung warten
2. Zuordnung von Port 8888 finden
3. Öffnen: `http://<proxy>:<port>?token=dein_sicheres_token_hier`

## Vorkonfiguriertes ML-Image

Für vollständige ML-Umgebung:

**Image:**

```
quay.io/jupyter/pytorch-notebook:cuda12-pytorch-2.11.0
```

Oder benutzerdefiniert erstellen:

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

RUN pip install --no-cache-dir \
    jupyterlab \\
    numpy pandas matplotlib seaborn \\
    scikit-learn \\
    transformers datasets accelerate \\
    tensorboard wandb \\
    opencv-python pillow \\
    tqdm rich

EXPOSE 8888 6006

CMD ["jupyter", "lab", "--ip=0.0.0.0", "--allow-root"]
```

## Wichtige Bibliotheken

### In Jupyter installieren

```python
!pip install transformers datasets accelerate bitsandbytes
!pip install wandb tensorboard
!pip install scikit-learn xgboost lightgbm
!pip install opencv-python albumentations
```

### requirements.txt erstellen

```

# ML-Frameworks
torch>=2.1.0
torchvision
torchaudio

# NLP
transformers>=4.36.0
datasets
tokenizers
sentencepiece

# Training
accelerate
bitsandbytes
peft
trl

# Überwachung
wandb
tensorboard

# Daten
numpy
pandas
matplotlib
seaborn
scikit-learn

# Computer Vision
opencv-python
pillow
albumentations
```

## Trainingsbeispiele

### PyTorch-Bildklassifizierung

```python
import torch
import torch.nn as nn
import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader

# GPU prüfen
print(f"GPU: {torch.cuda.get_device_name(0)}")
print(f"Speicher: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f} GB")

# Daten laden
transform = transforms.Compose([
    transforms.Resize(224),
    transforms.ToTensor(),
    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])

train_data = torchvision.datasets.CIFAR10(
    root='./data', train=True, download=True, transform=transform
)
train_loader = DataLoader(train_data, batch_size=64, shuffle=True, num_workers=4)

# Modell
model = torchvision.models.resnet18(pretrained=True)
model.fc = nn.Linear(512, 10)
model = model.cuda()

# Training
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
criterion = nn.CrossEntropyLoss()

for epoch in range(10):
    model.train()
    for images, labels in train_loader:
        images, labels = images.cuda(), labels.cuda()

        optimizer.zero_grad()
        outputs = model(images)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

    print(f"Epoche {epoch+1}, Verlust: {loss.item():.4f}")

# Modell speichern
torch.save(model.state_dict(), 'model.pth')
```

### HuggingFace-Textklassifizierung

```python
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import TrainingArguments, Trainer
from datasets import load_dataset
import numpy as np

# Datensatz laden
dataset = load_dataset("imdb")

# Modell laden
model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)

# Tokenisieren
def tokenize(examples):
    return tokenizer(examples["text"], padding="max_length", truncation=True)

tokenized = dataset.map(tokenize, batched=True)

# Training
training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=16,
    per_device_eval_batch_size=64,
    warmup_steps=500,
    weight_decay=0.01,
    logging_dir="./logs",
    logging_steps=100,
    evaluation_strategy="epoch",
    save_strategy="epoch",
    load_best_model_at_end=True,
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized["train"],
    eval_dataset=tokenized["test"],
)

trainer.train()
trainer.save_model("./best_model")
```

### LLM-Feinabstimmung mit LoRA

```python
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from datasets import load_dataset
from trl import SFTTrainer
import torch

# Modell mit 4-Bit-Quantisierung laden
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.float16,
)

model = AutoModelForCausalLM.from_pretrained(
    "mistralai/Mistral-7B-v0.1",
    quantization_config=bnb_config,
    device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")
tokenizer.pad_token = tokenizer.eos_token

# LoRA konfigurieren
lora_config = LoraConfig(
    r=16,
    lora_alpha=32,
    target_modules=["q_proj", "v_proj"],
    lora_dropout=0.05,
    bias="none",
    task_type="CAUSAL_LM"
)

model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, lora_config)

# Datensatz laden
dataset = load_dataset("timdettmers/openassistant-guanaco")

# Trainieren
trainer = SFTTrainer(
    model=model,
    train_dataset=dataset["train"],
    dataset_text_field="text",
    max_seq_length=512,
    tokenizer=tokenizer,
    args=TrainingArguments(
        output_dir="./lora_output",
        num_train_epochs=1,
        per_device_train_batch_size=4,
        gradient_accumulation_steps=4,
        learning_rate=2e-4,
        fp16=True,
        logging_steps=10,
        save_steps=100,
    ),
)

trainer.train()
trainer.save_model("./final_lora")
```

## TensorBoard-Integration

### TensorBoard starten

```python
%load_ext tensorboard
%tensorboard --logdir ./logs --port 6006 --bind_all
```

Oder über das Terminal:

```bash
tensorboard --logdir ./logs --port 6006 --bind_all &
```

### Trainingsmetriken protokollieren

```python
from torch.utils.tensorboard import SummaryWriter

writer = SummaryWriter('./logs')

for epoch in range(epochs):
    # ... Trainingsschleife ...
    writer.add_scalar('Loss/train', train_loss, epoch)
    writer.add_scalar('Loss/val', val_loss, epoch)
    writer.add_scalar('Accuracy/val', accuracy, epoch)

writer.close()
```

## Weights-&-Biases-Integration

```python
import wandb

wandb.init(project="my-project", name="experiment-1")

# Metriken protokollieren
wandb.log({"loss": loss, "accuracy": acc})

# Modell protokollieren
wandb.save("model.pth")

# Beenden
wandb.finish()
```

## Datenverwaltung

### Datensätze herunterladen

```python

# HuggingFace-Datensätze
from datasets import load_dataset
dataset = load_dataset("squad")

# Kaggle-Datensätze
!pip install kaggle
!kaggle datasets download -d username/dataset-name

# Direkt herunterladen
!wget https://example.com/data.zip
!unzip data.zip
```

### Cloud-Speicher einbinden

```python

# S3
!pip install boto3
import boto3
s3 = boto3.client('s3')
s3.download_file('bucket', 'key', 'local_path')

# Google Cloud
!pip install google-cloud-storage
from google.cloud import storage
client = storage.Client()
bucket = client.bucket('my-bucket')
blob = bucket.blob('data.zip')
blob.download_to_filename('data.zip')
```

## Arbeit speichern

### Auf externem Speicher speichern

```python

# Modell in S3 speichern
import boto3
s3 = boto3.client('s3',
    aws_access_key_id='YOUR_KEY',
    aws_secret_access_key='YOUR_SECRET'
)
s3.upload_file('model.pth', 'my-bucket', 'models/model.pth')
```

### Vor dem Beenden der Sitzung

```bash

# Wichtige Dateien herunterladen
scp -P <port> root@<host>:/workspace/model.pth ./
scp -P <port> -r root@<host>:/workspace/results/ ./results/
```

## Multi-GPU-Training

```python
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel

# GPUs prüfen
print(f"Verfügbare GPUs: {torch.cuda.device_count()}")

# DataParallel (einfach)
model = nn.DataParallel(model)

# DistributedDataParallel (besser)

# Starten mit: torchrun --nproc_per_node=4 train.py
dist.init_process_group("nccl")
model = DistributedDataParallel(model)
```

## Leistungstipps

### Speicheroptimierung

```python

# Gradient-Checkpointing
model.gradient_checkpointing_enable()

# Gemischte Präzision
from torch.cuda.amp import autocast, GradScaler
scaler = GradScaler()

with autocast():
    output = model(input)
    loss = criterion(output, target)

scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
```

### Datenladen

```python

# Schnelleres Datenladen
loader = DataLoader(
    dataset,
    batch_size=64,
    num_workers=8,      # Mehrere Worker verwenden
    pin_memory=True,    # Schnellere GPU-Übertragung
    prefetch_factor=2   # Batches vorab laden
)
```

## Fehlerbehebung

## Kostenschätzung

Übliche CLORE.AI-Marktplatzpreise (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           |

*Die Preise variieren je nach Anbieter und Nachfrage. Prüfen Sie* [*CLORE.AI-Marktplatz*](https://clore.ai/marketplace) *für aktuelle Preise.*

**Geld sparen:**

* Nutzen Sie den **Spot** Markt für unterbrechbare Arbeit — etwa ein Drittel der Server bietet Spot-Preise unter dem On-Demand-Preis (Median ca. 13 % Rabatt), der Rest ist gleichauf
* Bezahlen Sie mit **CLORE** Tokens
* Vergleichen Sie Preise zwischen verschiedenen Anbietern


---

# 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-de/training/jupyter-ml-training.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.
