> 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-fr/modeles-de-langage/exllamav2-fast.md).

# ExLlamaV2

Exécutez les LLMs à pleine vitesse avec ExLlamaV2.

{% hint style="success" %}
Tous les exemples peuvent être exécutés sur des serveurs GPU loués via [CLORE.AI Marketplace](https://clore.ai/marketplace).
{% endhint %}

## Location sur CLORE.AI

1. Visitez [CLORE.AI Marketplace](https://clore.ai/marketplace)
2. Filtrer par type de GPU, VRAM et prix
3. Choisir **À la demande** (tarif fixe) ou **Spot** (prix d'enchère)
4. Configurez votre commande :
   * Sélectionnez l'image Docker
   * Définissez les ports (TCP pour SSH, HTTP pour les interfaces web)
   * Ajoutez des variables d'environnement si nécessaire
   * Entrez la commande de démarrage
5. Sélectionnez le paiement : **CLORE**, **BTC**, ou **USDT/USDC**
6. Créez la commande et attendez le déploiement

### Accédez à votre serveur

* Trouvez les détails de connexion dans **Mes commandes**
* Interfaces Web : utilisez l'URL du port HTTP
* SSH : `ssh -p <port> root@<adresse-proxy>`

## Qu'est-ce qu'ExLlamaV2 ?

ExLlamaV2 est le moteur d'inférence le plus rapide pour les grands modèles de langage :

* 2 à 3 fois plus rapide que les autres moteurs
* Excellente quantification (EXL2)
* Faible utilisation de VRAM
* Prend en charge le décodage spéculatif

## Exigences

| Taille du modèle | VRAM min | Recommandé |
| ---------------- | -------- | ---------- |
| 7B               | 6 Go     | RTX 3060   |
| 13B              | 10Go     | RTX 3090   |
| 34B              | 20Go     | RTX 4090   |
| 70B              | 40Go     | A100       |

## Déploiement rapide

**Image Docker :**

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

**Ports :**

```
22/tcp
8080/http
```

**Commande :**

```bash
pip install exllamav2 && \
huggingface-cli download turboderp/Llama2-7B-exl2 --local-dir ./model && \
python -m exllamav2.server --model_dir ./model --host 0.0.0.0 --port 8080
```

## Accéder à votre service

Après le déploiement, trouvez votre `http_pub` URL dans **Mes commandes**:

1. Aller à la **Mes commandes** page
2. Cliquez sur votre commande
3. Trouvez l' `http_pub` URL (par ex., `abc123.clorecloud.net`)

Utilisez `https://VOTRE_HTTP_PUB_URL` au lieu de `localhost` dans les exemples ci-dessous.

## Installation

```bash

# Installer depuis PyPI
pip install exllamav2

# Ou depuis la source (dernières fonctionnalités)
git clone https://github.com/turboderp/exllamav2
cd exllamav2
pip install .
```

## Télécharger des modèles

### Modèles quantifiés EXL2

```bash

# Llama 3.1 8B (4.0 bpw)
huggingface-cli download turboderp/Llama2-7B-exl2 \
    --revision 4.0bpw \
    --local-dir ./llama2-7b-exl2

# Llama 3.1 8B (4.0 bpw)
huggingface-cli download turboderp/Llama2-13B-exl2 \
    --revision 4.0bpw \
    --local-dir ./llama2-13b-exl2

# Mistral 7B (4.0 bpw)
huggingface-cli download turboderp/Mistral-7B-instruct-exl2 \
    --revision 4.0bpw \
    --local-dir ./mistral-7b-exl2

# Mixtral 8x7B
huggingface-cli download turboderp/Mixtral-8x7B-instruct-exl2 \
    --revision 4.0bpw \
    --local-dir ./mixtral-exl2
```

### Bits par poids (bpw)

| BPW | Qualité        | VRAM (7B) |
| --- | -------------- | --------- |
| 2.0 | Faible         | \~3 Go    |
| 3.0 | Bon            | \~4 Go    |
| 4.0 | Excellent      | \~5 Go    |
| 5.0 | Excellent      | \~6 Go    |
| 6.0 | Proche du FP16 | \~7 Go    |

## API Python

### Génération basique

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config, ExLlamaV2Cache, ExLlamaV2Tokenizer
from exllamav2.generator import ExLlamaV2StreamingGenerator, ExLlamaV2Sampler

# Charger le modèle
config = ExLlamaV2Config()
config.model_dir = "./llama2-7b-exl2"
config.prepare()

model = ExLlamaV2(config)
model.load()

tokenizer = ExLlamaV2Tokenizer(config)
cache = ExLlamaV2Cache(model, lazy=True)

# Créer le générateur
generator = ExLlamaV2StreamingGenerator(model, cache, tokenizer)

# Définir les paramètres d'échantillonnage
settings = ExLlamaV2Sampler.Settings()
settings.temperature = 0.7
settings.top_k = 50
settings.top_p = 0.9

# Générer
prompt = "L'avenir de l'intelligence artificielle est"
output = generator.generate_simple(prompt, settings, num_tokens=200)
print(output)
```

### Génération en streaming

```python
from exllamav2.generator import ExLlamaV2StreamingGenerator

generator = ExLlamaV2StreamingGenerator(model, cache, tokenizer)

prompt = "Écris une courte histoire sur un robot :"
input_ids = tokenizer.encode(prompt)

generator.set_stop_conditions([tokenizer.eos_token_id])
generator.begin_stream(input_ids, settings)

while True:
    chunk, eos, _ = generator.stream()
    if eos:
        break
    print(chunk, end="", flush=True)
```

### Format de chat

```python
def format_chat(messages):
    text = ""
    for msg in messages:
        role = msg["role"]
        content = msg["content"]
        if role == "system":
            text += f"[INST] <<SYS>>\n{content}\n<</SYS>>\n\n"
        elif role == "user":
            text += f"{content} [/INST]"
        elif role == "assistant":
            text += f" {content}</s><s>[INST] "
    return text

messages = [
    {"role": "system", "content": "Vous êtes un assistant serviable."},
    {"role": "user", "content": "What is Python?"}
]

prompt = format_chat(messages)
output = generator.generate_simple(prompt, settings, num_tokens=300)
```

## Mode Serveur

### Démarrer le serveur

```bash
python -m exllamav2.server \
    --model_dir ./llama2-7b-exl2 \
    --host 0.0.0.0 \
    --port 8080 \
    --max_seq_len 4096 \
    --cache_size 4096
```

### Utilisation de l'API

```python
import requests

response = requests.post(
    "http://localhost:8080/v1/completions",
    json={
        "prompt": "Bonjour, comment ça va ?",
        "max_tokens": 100,
        "temperature": 0.7
    }
)

print(response.json()["choices"][0]["text"])
```

### Complétions de chat

```python
import openai

client = openai.OpenAI(
    base_url="http://localhost:8080/v1",
    api_key="non-nécessaire"
)

response = client.chat.completions.create(
    model="llama2-7b",
    messages=[{"role": "user", "content": "Bonjour !"}],
    temperature=0.7
)

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

## TabbyAPI (Serveur recommandé)

TabbyAPI fournit un serveur ExLlamaV2 riche en fonctionnalités :

```bash

# Cloner TabbyAPI
git clone https://github.com/theroyallab/tabbyAPI
cd tabbyAPI

# Installer
pip install -r requirements.txt

# Configurer

# Éditez config.yml avec le chemin de votre modèle

# Exécuter
python main.py
```

### Fonctionnalités de TabbyAPI

* API compatible OpenAI
* Prise en charge de plusieurs modèles
* Hot-swapping LoRA
* Streaming
* Appel de fonctions
* API d'administration

## Décodage spéculatif

Utilisez un modèle plus petit pour accélérer la génération :

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config, ExLlamaV2Cache

# Charger le modèle principal (13B)
main_config = ExLlamaV2Config()
main_config.model_dir = "./llama2-13b-exl2"
main_config.prepare()
main_model = ExLlamaV2(main_config)
main_model.load()

# Charger le modèle de brouillon (7B)
draft_config = ExLlamaV2Config()
draft_config.model_dir = "./llama2-7b-exl2"
draft_config.prepare()
draft_model = ExLlamaV2(draft_config)
draft_model.load()

# Créer le générateur spéculatif
from exllamav2.generator import ExLlamaV2DraftGenerator

generator = ExLlamaV2DraftGenerator(
    main_model, draft_model,
    cache_main, cache_draft,
    tokenizer
)

# Générer (plus rapide avec la spéculation)
output = generator.generate_simple(prompt, settings, num_tokens=500)
```

## Quantifiez vos propres modèles

### Convertir en EXL2

```python
from exllamav2 import ExLlamaV2, ExLlamaV2Config
from exllamav2.conversion import convert_model

# Source : modèle HuggingFace

# Cible : quantifié EXL2

convert_model(
    input_dir="./llama-3.1-8b-hf",
    output_dir="./llama-3.1-8b-exl2-4bpw",
    cal_dataset="wikitext",  # Jeu de données de calibration
    bits=4.0,  # Bits par poids
    head_bits=6,  # Précision supérieure pour l'attention
)
```

### Ligne de commande

```bash
python convert.py \
    -i ./llama-3.1-8b-hf \
    -o ./llama-3.1-8b-exl2 \
    -cf ./llama-3.1-8b-exl2 \
    -b 4.0 \
    -hb 6
```

## Gestion de la mémoire

### Allocation du cache

```python

# Taille de cache fixe
cache = ExLlamaV2Cache(model, max_seq_len=4096)

# Cache dynamique
cache = ExLlamaV2Cache(model, lazy=True)
cache.current_seq_len = 0  # Croît selon les besoins
```

### Multi-GPU

```python
config = ExLlamaV2Config()
config.model_dir = "./large-model"

# Répartir entre les GPUs
config.set_auto_split([0.5, 0.5])  # 50 % par GPU

model = ExLlamaV2(config)
model.load()
```

## Comparaison des performances

| Modèle       | Moteur    | GPU      | Tokens/sec |
| ------------ | --------- | -------- | ---------- |
| Llama 3.1 8B | ExLlamaV2 | RTX 3090 | \~150      |
| Llama 3.1 8B | llama.cpp | RTX 3090 | \~100      |
| Llama 3.1 8B | vLLM      | RTX 3090 | \~120      |
| Llama 3.1 8B | ExLlamaV2 | RTX 3090 | \~90       |
| Mixtral 8x7B | ExLlamaV2 | A100     | \~70       |

## Paramètres avancés

### Paramètres d'échantillonnage

```python
settings = ExLlamaV2Sampler.Settings()
settings.temperature = 0.7
settings.top_k = 50
settings.top_p = 0.9
settings.token_repetition_penalty = 1.1
settings.token_frequency_penalty = 0.0
settings.token_presence_penalty = 0.0
settings.mirostat = False
settings.mirostat_tau = 5.0
settings.mirostat_eta = 0.1
```

### Génération par lot

```python
prompts = [
    "Le sens de la vie est",
    "L'intelligence artificielle va",
    "Le changement climatique est"
]

outputs = []
for prompt in prompts:
    output = generator.generate_simple(prompt, settings, num_tokens=100)
    outputs.append(output)
```

## Dépannage

### CUDA Out of Memory

```python

# Utiliser un cache plus petit
cache = ExLlamaV2Cache(model, max_seq_len=2048)

# Ou modèle avec bpw inférieur (3.0 au lieu de 4.0)
```

### Chargement lent

```python

# Activer le chargement rapide
config.fasttensors = True
```

### Modèle introuvable

```bash

# Vérifiez que les fichiers du modèle existent
ls ./model/

# Devrait contenir : config.json, *.safetensors, tokenizer.json
```

## Intégration avec LangChain

```python
from langchain.llms.base import LLM
from typing import Optional, List

class ExLlamaV2LLM(LLM):
    model: ExLlamaV2
    tokenizer: ExLlamaV2Tokenizer
    generator: ExLlamaV2StreamingGenerator
    settings: ExLlamaV2Sampler.Settings

    @property
    def _llm_type(self) -> str:
        return "exllamav2"

    def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
        return self.generator.generate_simple(prompt, self.settings, num_tokens=500)

# Utilisation
llm = ExLlamaV2LLM(model=model, tokenizer=tokenizer, generator=generator, settings=settings)
result = llm("Qu'est-ce que l'informatique quantique ?")
```

## Estimation des coûts

Tarifs typiques du marché CLORE.AI (à partir de 2024) :

| GPU       | Tarif horaire | Tarif journalier | Session de 4 heures |
| --------- | ------------- | ---------------- | ------------------- |
| 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             |

*Les prix varient selon le fournisseur et la demande. Vérifiez* [*CLORE.AI Marketplace*](https://clore.ai/marketplace) *pour les tarifs actuels.*

**Économisez de l'argent :**

* Utilisez **Spot** market pour les charges de travail flexibles (souvent 30-50 % moins cher)
* Payer avec **CLORE** jetons
* Comparer les prix entre différents fournisseurs

## Prochaines étapes

* vLLM Inference - Service à haut débit
* [Serveur llama.cpp](/guides/guides_v2-fr/modeles-de-langage/llamacpp-server.md) - Multi-plateforme
* [Text Generation WebUI](/guides/guides_v2-fr/modeles-de-langage/text-generation-webui.md) - Interface web


---

# 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-fr/modeles-de-langage/exllamav2-fast.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.
