# CodeLlama

{% hint style="info" %}
**Neuere Alternativen!** Für Programmieraufgaben in Betracht ziehen [**Qwen2.5-Coder**](https://docs.clore.ai/guides/guides_v2-de/sprachmodelle/qwen25) (32B, hochmoderne Code-Generierung) oder [**DeepSeek-R1**](https://docs.clore.ai/guides/guides_v2-de/sprachmodelle/deepseek-r1) (Schlussfolgern + Codieren). CodeLlama ist weiterhin nützlich für leichte Bereitstellungen.
{% endhint %}

Erzeuge, vervollständige und erkläre Code mit Metas CodeLlama.

{% 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>`

## Modellvarianten

| Modell        | Größe | VRAM  | Am besten geeignet für     |
| ------------- | ----- | ----- | -------------------------- |
| CodeLlama-7B  | 7B    | 8GB   | Schnelle Vervollständigung |
| CodeLlama-13B | 13B   | 16GB  | Ausgeglichen               |
| CodeLlama-34B | 34B   | 40GB  | Beste Qualität             |
| CodeLlama-70B | 70B   | 80GB+ | Maximale Qualität          |

### Varianten

* **Basis**: Code-Vervollständigung
* **Instruct**: Befehlen folgen
* **Python**: Python-spezialisiert

## Schnelle Bereitstellung

**Docker-Image:**

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

**Ports:**

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

**Befehl:**

```bash
pip install vllm && \
python -m vllm.entrypoints.openai.api_server \
    --model codellama/CodeLlama-7b-Instruct-hf \
    --port 8000
```

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

## Installation

### Verwendung von Ollama

```bash

# Ollama installieren
curl -fsSL https://ollama.com/install.sh | sh

# CodeLlama starten
ollama run codellama

# Python-Variante ausführen
ollama run codellama:python
```

### Verwendung von Transformers

```bash
pip install transformers accelerate
```

## Code-Vervollständigung

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

model_id = "codellama/CodeLlama-7b-hf"

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

# Code-Vervollständigung
code = """
def fibonacci(n):
    '''Berechne die n-te Fibonacci-Zahl'''
"""

inputs = tokenizer(code, return_tensors="pt").to("cuda")

outputs = model.generate(
    **inputs,
    max_new_tokens=200,
    temperature=0.2,
    do_sample=True
)

print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```

## Instruct-Modell

Zum Befolgen von Programmieranweisungen:

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

model_id = "codellama/CodeLlama-7b-Instruct-hf"

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

prompt = """[INST] Schreibe eine Python-Funktion, die:
1. Eine Liste von Zahlen entgegennimmt
2. Duplikate entfernt
3. In absteigender Reihenfolge sortiert
4. Die 5 obersten Elemente zurückgibt
[/INST]"""

inputs = tokenizer(prompt, return_tensors="pt").to("cuda")

outputs = model.generate(
    **inputs,
    max_new_tokens=500,
    temperature=0.2
)

print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```

## Fill-in-the-Middle (FIM)

```python

# CodeLlama unterstützt FIM für Code-Einfügungen
prefix = """def calculate_area(shape, dimensions):
    if shape == "circle":
        radius = dimensions[0]
"""

suffix = """
    elif shape == "rectangle":
        length, width = dimensions
        return length * width
    return None
"""

# Verwende spezielle Tokens für FIM
prompt = f"<PRE> {prefix} <SUF>{suffix} <MID>"

inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens=100)
```

## Python-spezialisiertes Modell

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

model_id = "codellama/CodeLlama-7b-Python-hf"

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

# Python-spezifische Vervollständigung
code = """
import pandas as pd
import numpy as np

def analyze_sales_data(df):
    '''Analysiere Verkaufsdaten und gib wichtige Kennzahlen zurück'''
"""

inputs = tokenizer(code, return_tensors="pt").to("cuda")
outputs = model.generate(**inputs, max_new_tokens=300)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
```

## vLLM-Server

```bash
python -m vllm.entrypoints.openai.api_server \
    --model codellama/CodeLlama-13b-Instruct-hf \
    --dtype float16 \
    --max-model-len 8192
```

### API-Nutzung

```python
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="x")

response = client.chat.completions.create(
    model="codellama/CodeLlama-13b-Instruct-hf",
    messages=[
        {"role": "user", "content": "Schreibe einen FastAPI-Endpunkt für die Benutzer-Authentifizierung"}
    ],
    temperature=0.2,
    max_tokens=1000
)

print(response.choices[0].message.content)
```

## Code-Erklärung

```python
code_to_explain = """
def quicksort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)
"""

prompt = f"[INST] Erkläre diesen Code Schritt für Schritt:\n\n{code_to_explain}\n[/INST]"
```

## Fehlerbehebung

```python
buggy_code = """
def reverse_string(s):
    result = ""
    for i in range(len(s)):
        result += s[i]
    return result
"""

prompt = f"""[INST] Finde und behebe den Fehler in diesem Code. Die Funktion sollte einen String umkehren:

{buggy_code}
[/INST]"""
```

## Code-Übersetzung

```python
python_code = """
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)
"""

prompt = f"""[INST] Konvertiere diesen Python-Code in JavaScript:

{python_code}
[/INST]"""
```

## Gradio-Oberfläche

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

model_id = "codellama/CodeLlama-7b-Instruct-hf"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

def generate_code(instruction, temperature, max_tokens):
    prompt = f"[INST] {instruction} [/INST]"
    inputs = tokenizer(prompt, return_tensors="pt").to("cuda")

    outputs = model.generate(
        **inputs,
        max_new_tokens=max_tokens,
        temperature=temperature,
        do_sample=True
    )

    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return response.split("[/INST]")[-1].strip()

demo = gr.Interface(
    fn=generate_code,
    inputs=[
        gr.Textbox(label="Instruction", lines=5, placeholder="Schreibe eine Python-Funktion, die..."),
        gr.Slider(0.1, 1.0, value=0.2, label="Temperature"),
        gr.Slider(100, 2000, value=500, step=100, label="Maximale Token")
    ],
    outputs=gr.Code(language="python", label="Generierter Code"),
    title="CodeLlama Code Generator"
)

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

## Batch-Verarbeitung

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

model_id = "codellama/CodeLlama-7b-Instruct-hf"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.float16,
    device_map="auto"
)

tasks = [
    "Schreibe eine Funktion zur Validierung von E-Mail-Adressen",
    "Erstelle eine Klasse zur Verwaltung eines Warenkorbs",
    "Schreibe eine Funktion, um JSON von einer URL zu parsen",
    "Erstelle einen Decorator zur Messung der Ausführungsdauer einer Funktion",
    "Schreibe eine Funktion zur Generierung zufälliger Passwörter"
]

for task in tasks:
    prompt = f"[INST] {task} [/INST]"
    inputs = tokenizer(prompt, return_tensors="pt").to("cuda")

    outputs = model.generate(
        **inputs,
        max_new_tokens=500,
        temperature=0.2
    )

    result = tokenizer.decode(outputs[0], skip_special_tokens=True)
    print(f"\n=== {task} ===")
    print(result.split("[/INST]")[-1].strip())
```

## Verwendung mit Continue (VSCode)

Konfiguriere die Continue-Erweiterung:

```json
{
  "models": [
    {
      "title": "CodeLlama",
      "provider": "ollama",
      "model": "codellama:7b-instruct"
    }
  ],
  "tabAutocompleteModel": {
    "title": "CodeLlama",
    "provider": "ollama",
    "model": "codellama:7b-code"
  }
}
```

## Leistung

| Modell        | GPU      | Tokens/sec |
| ------------- | -------- | ---------- |
| CodeLlama-7B  | RTX 3090 | \~90       |
| CodeLlama-7B  | RTX 4090 | \~130      |
| CodeLlama-13B | RTX 4090 | \~70       |
| CodeLlama-34B | A100     | \~50       |

## Fehlerbehebung

### Schlechte Codequalität

* Niedrigere Temperatur (0.1-0.3)
* Verwende die Instruct-Variante
* Größeres Modell, falls möglich

### Unvollständige Ausgabe

* Erhöhe max\_new\_tokens
* Prüfe Kontextlänge

### Langsame Generierung

* Verwende vLLM
* Modell quantisieren
* Verwende kleinere Variante

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

## Nächste Schritte

* Open Interpreter - Code ausführen
* vLLM-Inferenz - Produktionseinsatz
* Mistral/Mixtral - Alternative Modelle
