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

# LMDeploy

**Boîte à outils de déploiement LLM efficace par Shanghai AI Lab** — inférence, quantification et service de niveau production pour les grands modèles de langage avec batchs continus et PagedAttention.

> 🏛️ Développé par **OpenMMLab / Shanghai AI Lab** | Licence Apache-2.0 | 4 000+ étoiles GitHub

***

## Qu'est-ce que LMDeploy ?

LMDeploy est une boîte à outils complète pour compresser, déployer et servir des grands modèles de langage en production. Construit par la même équipe derrière OpenMMLab (MMDetection, MMSeg), il apporte des optimisations de niveau recherche au déploiement pratique :

* **Moteur TurboMind** — backend d'inférence C++ haute performance avec optimisations CUDA
* **Moteur PyTorch** — moteur flexible basé en Python pour une large compatibilité des modèles
* **Batching continu** — maximise l'utilisation du GPU à travers les requêtes concurrentes
* **PagedAttention** — gestion efficace du cache KV (similaire à vLLM)
* **Quantification 4-bit / 8-bit** — prise en charge d'AWQ et de SmoothQuant
* **Modèles Vision-Langage** — prise en charge d'InternVL, LLaVA, Qwen-VL

Comparé à vLLM, le moteur TurboMind de LMDeploy offre environ 1,36× plus de débit sur Llama 3 8B à batch=32, et sa quantification AWQ est de première classe — pas un simple ajout. Pour les VLMs (surtout InternVL2), LMDeploy est la pile de déploiement de référence.

### Pourquoi LMDeploy ?

| Fonctionnalité                  | LMDeploy | vLLM   | TGI    |
| ------------------------------- | -------- | ------ | ------ |
| Batching continu                | ✅        | ✅      | ✅      |
| Quantification AWQ              | ✅        | ✅      | ❌      |
| Décodage spéculatif             | ✅        | ✅      | ✅      |
| Vision-Langage                  | ✅        | Limité | Limité |
| API OpenAI                      | ✅        | ✅      | ✅      |
| TurboMind (moteur personnalisé) | ✅        | ❌      | ❌      |

***

## Démarrage rapide sur Clore.ai

### Étape 1 : Choisir un serveur GPU

Sur [clore.ai](https://clore.ai) place de marché :

* **Minimum :** GPU NVIDIA avec 8 Go de VRAM (pour modèles 7B)
* **Recommandé :** RTX 3090/4090 (24GB) ou A100 (40/80GB)
* **CUDA :** 11.8 ou 12.x requis

### Étape 2 : Déployer LMDeploy Docker

```
Image Docker : openmmlab/lmdeploy
```

**Mappages de ports :**

| Port du conteneur | Usage                |
| ----------------- | -------------------- |
| `22`              | Accès SSH            |
| `23333`           | Serveur API LMDeploy |

**Variables d'environnement :**

```
HUGGING_FACE_HUB_TOKEN=your_hf_token_here  # Pour les modèles restreints
```

### Étape 3 : SSH et vérification

```bash
ssh root@<clore-node-ip> -p <ssh-port>

# Vérifier l'installation
python -c "import lmdeploy; print(lmdeploy.__version__)"
lmdeploy --help
```

***

## Démarrage du serveur API

### Serveur compatible OpenAI (recommandé)

```bash
# Servir Llama 3 8B avec le moteur TurboMind
lmdeploy serve api_server \
  meta-llama/Meta-Llama-3-8B-Instruct \
  --server-port 23333 \
  --server-name 0.0.0.0 \
  --model-name llama3-8b

# Avec sélection explicite du moteur
lmdeploy serve api_server \
  meta-llama/Meta-Llama-3-8B-Instruct \
  --backend turbomind \
  --server-port 23333 \
  --server-name 0.0.0.0 \
  --tp 1 \
  --max-batch-size 128 \
  --cache-max-entry-count 0.8
```

### Moteur PyTorch (compatibilité plus large)

```bash
# Utiliser le moteur PyTorch pour les modèles non pris en charge par TurboMind
lmdeploy serve api_server \
  mistralai/Mistral-7B-Instruct-v0.2 \
  --backend pytorch \
  --server-port 23333 \
  --server-name 0.0.0.0
```

### Sortie du démarrage du serveur

```
[2024-01-01 12:00:00,000] INFO: Chargement du modèle : meta-llama/Meta-Llama-3-8B-Instruct
[2024-01-01 12:00:20,000] INFO: Moteur TurboMind initialisé
[2024-01-01 12:00:20,000] INFO: Serveur démarré à http://0.0.0.0:23333
[2024-01-01 12:00:20,000] INFO: Docs API : http://0.0.0.0:23333/docs
```

{% hint style="success" %}
Une fois démarré, LMDeploy expose des docs API interactives à `http://<votre-ip>:23333/docs` — utile pour tester les endpoints directement depuis le navigateur.
{% endhint %}

***

## Modèles pris en charge

### Modèles de texte

```bash
# Llama 3
meta-llama/Meta-Llama-3-8B-Instruct
meta-llama/Meta-Llama-3-70B-Instruct

# Mistral / Mixtral
mistralai/Mistral-7B-Instruct-v0.2
mistralai/Mixtral-8x7B-Instruct-v0.1

# Qwen
Qwen/Qwen2-7B-Instruct
Qwen/Qwen2-72B-Instruct

# InternLM
internlm/internlm2-chat-7b
internlm/internlm2-chat-20b

# Yi
01-ai/Yi-1.5-9B-Chat
01-ai/Yi-1.5-34B-Chat

# Gemma
google/gemma-7b-it
google/gemma-2b-it
```

### Modèles Vision-Langage

```bash
# InternVL (VLM recommandé)
OpenGVLab/InternVL2-8B
OpenGVLab/InternVL2-26B

# LLaVA
llava-hf/llava-1.5-7b-hf

# Qwen-VL
Qwen/Qwen-VL-Chat
```

***

## Quantification

### Quantification AWQ 4-bit

L'AWQ de LMDeploy (Activation-aware Weight Quantization) produit une excellente qualité en 4 bits :

```bash
# Quantifier un modèle en AWQ 4-bit
lmdeploy lite auto_awq \
  meta-llama/Meta-Llama-3-8B-Instruct \
  --calib-dataset ptb \
  --calib-samples 128 \
  --calib-seqlen 2048 \
  --w-bits 4 \
  --w-group-size 128 \
  --work-dir ./quantized/llama3-8b-awq

# Servir le modèle quantifié
lmdeploy serve api_server \
  ./quantized/llama3-8b-awq \
  --server-port 23333 \
  --server-name 0.0.0.0
```

### SmoothQuant W8A8

Quantification 8-bit des poids et des activations (mieux pour les déploiements sensibles au débit) :

```bash
lmdeploy lite smooth_quant \
  meta-llama/Meta-Llama-3-8B-Instruct \
  --work-dir ./quantized/llama3-8b-sq \
  --calib-dataset ptb \
  --calib-samples 512
```

### Impact de la quantification

| Quantification   | VRAM (7B) | Perte de qualité | Gain de débit |
| ---------------- | --------- | ---------------- | ------------- |
| Aucun (bf16)     | \~14GB    | Aucune           | Référence     |
| SmoothQuant W8A8 | \~8GB     | Minimale         | +20%          |
| AWQ W4A16        | \~4GB     | Faible           | +15%          |
| GPTQ W4A16       | \~4GB     | Faible           | +10%          |

{% hint style="info" %}
**Recommandation AWQ :** Pour la plupart des cas d'utilisation, AWQ 4-bit est le meilleur compromis entre qualité et économies de VRAM. Utilisez `--w-group-size 128` pour une meilleure qualité avec une utilisation mémoire légèrement plus élevée.
{% endhint %}

***

## Exemples d'utilisation de l'API

### Client Python

```python
from openai import OpenAI

client = OpenAI(
    base_url="http://<clore-node-ip>:<api-port>/v1",
    api_key="none"
)

# Complétion de chat
response = client.chat.completions.create(
    model="llama3-8b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Summarize the history of AI in 3 sentences."}
    ],
    temperature=0.7,
    max_tokens=512
)
print(response.choices[0].message.content)
```

### Streaming

```python
stream = client.chat.completions.create(
    model="llama3-8b",
    messages=[{"role": "user", "content": "Write a poem about space."}],
    stream=True
)

for chunk in stream:
    delta = chunk.choices[0].delta
    if delta.content:
        print(delta.content, end="", flush=True)
print()
```

### Client Python natif LMDeploy

```python
from lmdeploy import pipeline, TurbomindEngineConfig

# Pipeline direct (pas de serveur requis)
pipe = pipeline(
    'meta-llama/Meta-Llama-3-8B-Instruct',
    backend_config=TurbomindEngineConfig(max_batch_size=16)
)

# Inférence unique
response = pipe("What is the capital of France?")
print(response.text)

# Inférence par lot
responses = pipe([
    "Explain gravity",
    "What is DNA?",
    "How does Bitcoin work?"
])
for r in responses:
    print(r.text)
    print("---")
```

### Modèle Vision-Langage

```python
from lmdeploy import pipeline
from lmdeploy.vl import load_image

pipe = pipeline('OpenGVLab/InternVL2-8B')

image = load_image('https://example.com/photo.jpg')
response = pipe(('Describe this image in detail', image))
print(response.text)
```

***

## Déploiement Multi-GPU

### Parallélisme de tenseurs

```bash
# Distribuer un modèle 70B sur 4 GPU
lmdeploy serve api_server \
  meta-llama/Meta-Llama-3-70B-Instruct \
  --backend turbomind \
  --server-port 23333 \
  --server-name 0.0.0.0 \
  --tp 4 \
  --max-batch-size 64
```

```python
from lmdeploy import pipeline, TurbomindEngineConfig

pipe = pipeline(
    'meta-llama/Meta-Llama-3-70B-Instruct',
    backend_config=TurbomindEngineConfig(tp=4)
)
```

***

## Configuration avancée

### Configuration du moteur TurboMind

```python
from lmdeploy import pipeline, TurbomindEngineConfig

engine_config = TurbomindEngineConfig(
    max_batch_size=64,          # Requêtes concurrentes maximales
    cache_max_entry_count=0.8,  # Ratio du cache KV (0.0-1.0)
    quant_policy=0,             # 0=pas de quant, 4=cache KV 4bit, 8=cache KV 8bit
    rope_scaling_factor=1.0,    # Pour contexte étendu
    num_tokens_per_iter=4096,   # Taille du chunk de préremplissage
    max_prefill_token_num=8192, # Longueur maximale de préremplissage
)

pipe = pipeline('meta-llama/Meta-Llama-3-8B-Instruct', backend_config=engine_config)
```

### Configuration de génération

```python
from lmdeploy import GenerationConfig

gen_config = GenerationConfig(
    temperature=0.7,
    top_p=0.9,
    top_k=40,
    repetition_penalty=1.1,
    max_new_tokens=1024,
    stop_words=['<|eot_id|>', '<|end_of_text|>'],
)

response = pipe("Hello, world!", gen_config=gen_config)
```

***

## Surveillance & métriques

### Vérifier la santé du serveur

```bash
# Endpoint de vérification de santé
curl http://localhost:23333/health

# Lister les modèles disponibles
curl http://localhost:23333/v1/models

# Statistiques du serveur
curl http://localhost:23333/stats
```

### Surveillance GPU

```bash
# Statistiques GPU en temps réel
watch -n 1 'nvidia-smi --query-gpu=name,memory.used,memory.free,utilization.gpu --format=csv'
```

***

## Exemple Docker Compose

```yaml
version: '3.8'
services:
  lmdeploy:
    image: openmmlab/lmdeploy:latest
    runtime: nvidia
    environment:
      - NVIDIA_VISIBLE_DEVICES=all
      - HUGGING_FACE_HUB_TOKEN=${HF_TOKEN}
    ports:
      - "23333:23333"
      - "22:22"
    volumes:
      - hf-cache:/root/.cache/huggingface
      - ./models:/models
    command: >
      lmdeploy serve api_server
      meta-llama/Meta-Llama-3-8B-Instruct
      --server-port 23333
      --server-name 0.0.0.0
      --model-name llama3-8b
      --max-batch-size 64
    restart: unless-stopped
    shm_size: '2g'

volumes:
  hf-cache:
```

***

## Benchmarking

```bash
# Outil de benchmark intégré
lmdeploy benchmark \
  meta-llama/Meta-Llama-3-8B-Instruct \
  --backend turbomind \
  --concurrency 1 4 8 16 32 \
  --num-prompts 1000 \
  --prompt-len 128 \
  --output-len 256
```

Sortie d'exemple (RTX 4090, TurboMind, bf16) :

```
concurrency=1:  throughput=42.3 tokens/s, latency_p50=23ms
concurrency=8:  throughput=287.1 tokens/s, latency_p50=156ms
concurrency=32: throughput=412.6 tokens/s, latency_p50=621ms
```

Sur A100 80GB, attendez-vous à \~2.2× plus de débit vs RTX 4090 à forte concurrence en raison de la bande passante mémoire HBM2e (2 TB/s vs 1 TB/s).

***

## Recommandations GPU Clore.ai

Choisissez en fonction de la taille du modèle cible et de la charge de service :

| Cas d’utilisation             | GPU           | VRAM  | Pourquoi                                                           |
| ----------------------------- | ------------- | ----- | ------------------------------------------------------------------ |
| Modèles 7–13B, dev/staging    | **RTX 3090**  | 24 Go | Meilleur ratio $/VRAM ; gère 7B bf16 ou 13B AWQ                    |
| Modèles 7–13B, production     | **RTX 4090**  | 24 Go | \~40% plus rapide que 3090 à VRAM égale ; 412 tok/s sur Llama 3 8B |
| Modèles 70B, service d'équipe | **A100 40GB** | 40 Go | Compatibilité 70B AWQ ; mémoire ECC pour la fiabilité              |
| Modèles 70B, haut débit       | **A100 80GB** | 80 Go | Compatibilité 70B bf16 ; 2× débit vs A100 40GB à batch=32          |

**Choix économique :** RTX 3090 + AWQ 4-bit — sert Llama 3 8B à \~280 tok/s batch=8, couvre la plupart des cas d'utilisation d'API.

**Choix vitesse :** RTX 4090 — le plus rapide par dollar pour les modèles 7–13B ; TurboMind exploite chaque GB/s de sa bande passante de 1 TB/s.

**Choix production :** A100 80GB — exécute Qwen2-72B ou Llama 3 70B en bf16 complet sans compromis de qualité liés à la quantification ; s'intègre facilement dans un service GPU multi-instance.

***

## Dépannage

### Modèle ne se charge pas

```bash
# Vérifier que le token HuggingFace est défini
echo $HUGGING_FACE_HUB_TOKEN

# Télécharger manuellement le modèle
pip install huggingface_hub
huggingface-cli download meta-llama/Meta-Llama-3-8B-Instruct --local-dir ./llama3-8b

# Utiliser le chemin local à la place
lmdeploy serve api_server ./llama3-8b --server-port 23333
```

### CUDA : mémoire insuffisante

```bash
# Réduire l'allocation du cache KV
lmdeploy serve api_server MODEL \
  --cache-max-entry-count 0.5  # Réduire depuis 0.8

# Utiliser le cache KV quantifié
lmdeploy serve api_server MODEL \
  --quant-policy 8  # cache KV 8-bit
```

### Port déjà utilisé

```bash
# Vérifier ce qui utilise le port 23333
ss -tlnp | grep 23333
fuser 23333/tcp

# Tuer le processus existant
kill -9 $(fuser 23333/tcp)
```

{% hint style="warning" %}
**Mode réseau Docker :** Lors de l'exécution dans Docker, assurez-vous que le conteneur utilise `--network host` ou un mappage de ports approprié (`-p 23333:23333`) afin que l'API soit joignable depuis l'extérieur.
{% endhint %}

***

## Recommandations GPU Clore.ai

Le moteur TurboMind de LMDeploy et la quantification W4A16 offrent un débit de premier ordre — surtout sur les GPU Ampere/Hopper.

| GPU         | VRAM  | Prix Clore.ai | Débit Llama 3 8B                       | Llama 3 70B Q4     |
| ----------- | ----- | ------------- | -------------------------------------- | ------------------ |
| RTX 3090    | 24 Go | \~0,12 $/h    | \~120 tok/s (fp16)                     | ❌ Trop grand       |
| RTX 4090    | 24 Go | \~0,70 $/h    | \~200 tok/s (fp16)                     | ❌ Trop grand       |
| A100 40GB   | 40 Go | \~1,20 $/h    | \~160 tok/s (fp16)                     | \~55 tok/s (W4A16) |
| A100 80GB   | 80 Go | \~2,00 $/h    | \~175 tok/s (fp16)                     | \~80 tok/s (fp16)  |
| 2× RTX 4090 | 48 GB | \~$1.40/hr    | \~380 tok/s (parallélisme de tenseurs) | \~60 tok/s         |

{% hint style="info" %}
**RTX 3090 à \~0,12 $/hr** est le meilleur choix pour les modèles 7B–13B. Le moteur TurboMind de LMDeploy extrait un débit proche du maximum des GPU grand public. Un seul RTX 3090 servant Llama 3 8B gère 120 tok/s — suffisant pour des APIs en production avec 10–20 utilisateurs concurrents.

Pour les modèles 70B : A100 40GB (\~0,20 $/hr) avec quantification W4A16 fournit \~55 tok/s — plus rentable que deux RTX 4090.
{% endhint %}

***

## Ressources

* 📦 **Docker Hub :** [hub.docker.com/r/openmmlab/lmdeploy](https://hub.docker.com/r/openmmlab/lmdeploy)
* 🐙 **GitHub :** [github.com/InternLM/lmdeploy](https://github.com/InternLM/lmdeploy)
* 📚 **Documentation :** [lmdeploy.readthedocs.io](https://lmdeploy.readthedocs.io)
* 💬 **Discord :** [discord.gg/xa29JuW84p](https://discord.gg/xa29JuW84p)
* 🤗 **Modèles pré-quantifiés :** [huggingface.co/lmdeploy](https://huggingface.co/lmdeploy)


---

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