> 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 efficace de déploiement de LLM par Shanghai AI Lab** — inférence, quantification et service de niveau production pour les grands modèles de langage avec regroupement continu et PagedAttention.

> 🏛️ Développé par **OpenMMLab / Shanghai AI Lab** | Licence Apache-2.0 | plus de 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. Développé par la même équipe qu'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é sur Python pour une large compatibilité des modèles
* **Lotissement continu** — maximise l'utilisation du GPU sur les requêtes simultanées
* **PagedAttention** — gestion efficace du cache KV (similaire à vLLM)
* **Quantification 4 bits / 8 bits** — prise en charge d'AWQ et de SmoothQuant
* **Modèles vision-langage** — prise en charge d'InternVL, LLaVA et Qwen-VL

Par rapport à vLLM, le moteur TurboMind de LMDeploy offre un débit environ 1,36× supérieur sur Llama 3 8B à batch=32, et sa quantification AWQ est une fonctionnalité de premier plan — pas une réflexion après coup. Pour les VLM (surtout InternVL2), LMDeploy est la pile de déploiement de référence.

### Pourquoi LMDeploy ?

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

***

## Démarrage rapide sur Clore.ai

### Étape 1 : sélectionner un serveur GPU

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

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

### Étape 2 : déployer le Docker LMDeploy

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

**Mappages de ports :**

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

**Variables d'environnement :**

```
HUGGING_FACE_HUB_TOKEN=your_hf_token_here  # Pour les modèles protégés
```

### Étape 3 : se connecter en SSH et vérifier

```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 de 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é sur http://0.0.0.0:23333
[2024-01-01 12:00:20,000] INFO: Documentation API : http://0.0.0.0:23333/docs
```

{% hint style="success" %}
Une fois démarré, LMDeploy expose une documentation API interactive à `http://<your-ip>:23333/docs` — utile pour tester les points de terminaison directement depuis le navigateur.
{% endhint %}

***

## Modèles pris en charge

### Modèles textuels

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

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

```bash
# Quantifier un modèle en AWQ 4 bits
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 des poids et activations sur 8 bits (mieux pour les déploiements où le débit est critique) :

```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 |
| ---------------- | --------- | ---------------- | ------------- |
| Aucune (bf16)    | \~14 Go   | Aucune           | Référence     |
| SmoothQuant W8A8 | \~8 Go    | Minime           | +20%          |
| AWQ W4A16        | \~4 Go    | Faible           | +15%          |
| GPTQ W4A16       | \~4 Go    | Faible           | +10%          |

{% hint style="info" %}
**Recommandation AWQ :** Pour la plupart des cas d'usage, l'AWQ 4 bits offre le meilleur équilibre entre qualité et économie de VRAM. Utilisez `--w-group-size 128` pour une meilleure qualité avec une consommation 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": "Vous êtes un assistant utile."},
        {"role": "user", "content": "Résume l'histoire de l'IA en 3 phrases."}
    ],
    temperature=0.7,
    max_tokens=512
)
print(response.choices[0].message.content)
```

### Flux continu

```python
stream = client.chat.completions.create(
    model="llama3-8b",
    messages=[{"role": "user", "content": "Écris un poème sur l'espace."}],
    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 (aucun serveur nécessaire)
pipe = pipeline(
    'meta-llama/Meta-Llama-3-8B-Instruct',
    backend_config=TurbomindEngineConfig(max_batch_size=16)
)

# Inférence unique
response = pipe("Quelle est la capitale de la France ?")
print(response.text)

# Inférence par lot
responses = pipe([
    "Explique la gravité",
    "Qu'est-ce que l'ADN ?",
    "Comment fonctionne Bitcoin ?"
])
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(('Décris cette image en détail', image))
print(response.text)
```

***

## Déploiement multi-GPU

### Parallélisme de tenseur

```bash
# Répartir 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,          # Nombre maximal de requêtes simultanées
    cache_max_entry_count=0.8,  # Ratio du cache KV (0,0-1,0)
    quant_policy=0,             # 0=pas de quantification, 4=cache KV 4 bits, 8=cache KV 8 bits
    rope_scaling_factor=1.0,    # Pour un contexte étendu
    num_tokens_per_iter=4096,   # Taille du segment 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("Bonjour le monde !", gen_config=gen_config)
```

***

## Surveillance et métriques

### Vérifier l'état du serveur

```bash
# Point de terminaison de vérification de l'état
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 du 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 de 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:
```

***

## Benchmark

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

Exemple de sortie (RTX 4090, TurboMind, bf16) :

```
concurrency=1:  débit=42.3 tokens/s, latence_p50=23ms
concurrency=8:  débit=287.1 tokens/s, latence_p50=156ms
concurrency=32: débit=412.6 tokens/s, latence_p50=621ms
```

Sur une A100 80 Go, attendez-vous à un débit environ 2,2× plus élevé qu'une RTX 4090 à forte concurrence grâce à la bande passante mémoire HBM2e (2 To/s contre 1 To/s).

***

## Recommandations GPU Clore.ai

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

| Cas d’utilisation                          | GPU            | VRAM  | Pourquoi                                                                  |
| ------------------------------------------ | -------------- | ----- | ------------------------------------------------------------------------- |
| Modèles 7–13B, développement/préproduction | **RTX 3090**   | 24 Go | Meilleur rapport $/VRAM ; gère 7B bf16 ou 13B AWQ                         |
| Modèles 7–13B, production                  | **RTX 4090**   | 24 Go | \~40 % plus rapide qu'une 3090 à VRAM égale ; 412 tok/s sur Llama 3 8B    |
| Modèles 70B, service d'équipe              | **A100 40 Go** | 40 Go | Prend en charge 70B AWQ ; mémoire ECC pour la fiabilité                   |
| Modèles 70B, débit élevé                   | **A100 80 Go** | 80 Go | Prend en charge 70B bf16 ; débit 2× supérieur à une A100 40 Go à batch=32 |

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

**Choix vitesse :** RTX 4090 — le meilleur rapport vitesse/prix pour les modèles 7–13B ; TurboMind exploite chaque Go/s de sa bande passante de 1 To/s.

**Choix production :** A100 80 Go — exécutez Qwen2-72B ou Llama 3 70B en bf16 complet sans compromis sur la qualité de la quantification ; s'intègre facilement au service GPU multi-instances.

***

## Dépannage

### Le modèle ne se charge pas

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

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

# Utiliser plutôt le chemin local
lmdeploy serve api_server ./llama3-8b --server-port 23333
```

### Mémoire CUDA 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 un cache KV quantifié
lmdeploy serve api_server MODEL \\
  --quant-policy 8  # Cache KV 8 bits
```

### 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 accessible depuis l'extérieur.
{% endhint %}

***

## Recommandations GPU Clore.ai

Le moteur TurboMind de LMDeploy et la quantification W4A16 offrent un débit parmi les meilleurs du secteur — surtout sur les GPU Ampere/Hopper.

| GPU         | VRAM  | Prix Clore.ai                             | Débit de Llama 3 8B                  | Llama 3 70B Q4     |
| ----------- | ----- | ----------------------------------------- | ------------------------------------ | ------------------ |
| RTX 3090    | 24 Go | 0,07–0,21 $/h                             | \~120 tok/s (fp16)                   | ❌ Trop grand       |
| RTX 4090    | 24 Go | 0,14–0,42 $/h                             | \~200 tok/s (fp16)                   | ❌ Trop grand       |
| A100 40 Go  | 40 Go | [bare metal](https://clore.ai/bare-metal) | \~160 tok/s (fp16)                   | \~55 tok/s (W4A16) |
| A100 80 Go  | 80 Go | [bare metal](https://clore.ai/bare-metal) | \~175 tok/s (fp16)                   | \~80 tok/s (fp16)  |
| 2× RTX 4090 | 48 Go | 0,28–0,84 $/h                             | \~380 tok/s (parallélisme tensoriel) | \~60 tok/s         |

{% hint style="info" %}
**RTX 3090 à 0,07–0,21 $/h** est le meilleur choix pour les modèles 7B–13B. Le moteur TurboMind de LMDeploy extrait un débit presque maximal des GPU grand public. Une seule RTX 3090 servant Llama 3 8B gère 120 tok/s — suffisant pour des API de production avec 10 à 20 utilisateurs simultanés.

Pour les modèles 70B : A100 40 Go ([bare metal](https://clore.ai/bare-metal)) avec quantification W4A16 offre \~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, and the optional `goal` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-fr/modeles-de-langage/lmdeploy.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.
