> 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/sprachmodelle/codellama.md).

# CodeLlama

Code mit CodeLlama generieren, vervollständigen und erklären auf Clore.ai

{% hint style="info" %}
**Neuere Alternativen!** Für Programmieraufgaben sollten Sie erwägen [**Qwen2.5-Coder**](/guides/guides_v2-de/sprachmodelle/qwen25.md) (32B, State-of-the-Art-Codegenerierung) oder [**DeepSeek-R1**](/guides/guides_v2-de/sprachmodelle/deepseek-r1.md) (Schlussfolgerung + Programmierung). CodeLlama ist für leichtgewichtige Bereitstellungen weiterhin nützlich.
{% endhint %}

Code generieren, vervollständigen und erklären mit Metas CodeLlama.

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

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

## Modellvarianten

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

### Varianten

* **Basis**: Code-Vervollständigung
* **Instrukt**: Anweisungen befolgen
* **Python**: Auf Python spezialisiert

## Schnell bereitstellen

**Docker-Image:**

```
pytorch/pytorch:2.11.0-cuda12.8-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
```

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

## Installation

### Mit Ollama

```bash

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

# CodeLlama ausführen
ollama run codellama

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

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

## Instruktionsmodell

Für folgende 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ügung
prefix = """def calculate_area(shape, dimensions):
    if shape == "circle":
        radius = dimensions[0]
"""

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

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

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

## Auf 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 Benutzerauthentifizierung"}
    ],
    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="Anweisung", lines=5, placeholder="Schreibe eine Python-Funktion, die..."),
        gr.Slider(0.1, 1.0, value=0.2, label="Temperatur"),
        gr.Slider(100, 2000, value=500, step=100, label="Maximale Token")
    ],
    outputs=gr.Code(language="python", label="Generierter Code"),
    title="CodeLlama-Codegenerator"
)

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 Dekorator zur Zeitmessung der Funktionsausführung",
    "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())
```

## Mit Continue (VSCode) verwenden

Continue-Erweiterung konfigurieren:

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

## Leistung

| Modell        | GPU      | Tokens/Sek. |
| ------------- | -------- | ----------- |
| 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)
* Instruktionsvariante verwenden
* Größeres Modell, wenn möglich

### Unvollständige Ausgabe

* max\_new\_tokens erhöhen
* Kontextlänge prüfen

### Langsame Generierung

* vLLM verwenden
* Modell quantisieren
* Kleinere Variante verwenden

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

## Nächste Schritte

* Open Interpreter - Code ausführen
* vLLM Inference - Produktionsbereitstellung
* Mistral/Mixtral - Alternative Modelle


---

# 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/sprachmodelle/codellama.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.
