Aller au contenu

Déployer un serveur d'inférence vLLM sur Ubuntu 22.04 (prêt pour la production)

Monter un serveur vLLM GPU durci sur Ubuntu 22.04 avec CUDA 12.x, venv Python, systemd, modèle Hugging Face et API compatible OpenAI derrière nginx + Let's Encrypt.

On vous demande de faire tourner une vraie couche d’inférence de production — utilisateurs concurrents, longs contextes, p95 prévisible. Vous installez vLLM avec pip install vllm, lancez le serveur compatible OpenAI, le premier benchmark est superbe, vous remettez ça à l’équipe. Six mois plus tard, le GPU est en OOM tous les lundis matin parce que --max-model-len a pris une valeur par défaut au-delà du budget de cache KV disponible, le serveur redémarre toutes les six heures parce que l’unit systemd n’a pas de Restart=on-failure, l’API est sur 0.0.0.0:8000 sans clé, et le cache de modèles est coincé sur le disque OS où le prochain df -h va remplir la partition.

Ce qui se passe

Un déploiement vLLM réellement prêt pour la production demande beaucoup plus que le pip install. PagedAttention plus le tensor parallelism sont les raisons pour lesquelles vLLM débite 5 à 10 fois plus qu’Ollama sur le même matériel, mais ça veut aussi dire que l’opérateur doit dimensionner trois choses dès le départ : --max-model-len pour la plus longue combinaison prompt+complétion que vous comptez servir, --gpu-memory-utilization pour laisser de la marge pour les activations et les requêtes concurrentes, et --tensor-parallel-size pour correspondre au nombre de GPU sur lesquels le modèle est sharded. Un modèle 7B en fp16 demande environ 14 Go de VRAM pour les poids plus 4 à 8 Go pour le cache KV à 8k de contexte avec une taille de lot raisonnable ; un 70B en fp16 demande environ 140 Go et oblige à faire du tensor-parallel sur 2x A100 80 Go ou 4x A100 40 Go. L’API compatible OpenAI doit binder sur 127.0.0.1 derrière nginx avec une clé d’API, le cache de modèles Hugging Face doit vivre sur /var/lib/vllm sur le volume de données, et l’unit systemd doit redémarrer sur échec avec LimitNOFILE=64000 pour que le pool de workers asyncio puisse monter en charge.

Comment vérifier

Après installation, les écouteurs doivent ressembler à ça :

ss -lntp | grep -E ':(443|8000)\b'
# 0.0.0.0:443     nginx
# 127.0.0.1:8000  vllm (uvicorn)

Le port vLLM doit être 127.0.0.1, jamais 0.0.0.0. La mémoire GPU doit afficher le modèle chargé avec une marge raisonnable :

nvidia-smi --query-gpu=name,memory.used,memory.total,utilization.gpu --format=csv

Aller-retour bout-en-bout via l’endpoint compatible OpenAI :

curl -fsS -X POST https://llm.example.com/v1/chat/completions \
  -H "Authorization: Bearer ${VLLM_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"model":"meta-llama/Llama-3.1-8B-Instruct","messages":[{"role":"user","content":"reply OK"}],"max_tokens":4}' \
  | jq -r '.choices[0].message.content'

Si la réponse est OK et que nvidia-smi montre le worker vllm qui tient une VRAM stable, le runtime est en service. Si l’utilisation mémoire grimpe d’une requête à l’autre sans se stabiliser, votre --gpu-memory-utilization est trop agressif et le prochain prompt à long contexte va OOM.

Le correctif

Enregistrez le script ci-dessous sous /root/setup-vllm-ubuntu22.sh, puis exécutez-le. Il déroule l’installation complète sur une VM Ubuntu 22.04 fraîche : mise à jour de base, ajustement noyau, limites de fichiers, UFW, durcissement SSH, unattended-upgrades, pilote NVIDIA 535 + toolkit CUDA 12.4 si un GPU est présent (bascule CPU avec avertissement sinon), un venv Python 3.11 dans /opt/vllm/venv avec vLLM et ses wheels CUDA installés, /var/lib/vllm comme cache Hugging Face, un utilisateur système vllm dédié, une unit systemd qui exécute vllm serve avec des boutons --max-model-len / --tensor-parallel-size / --gpu-memory-utilization commentés pour que l’opérateur puisse ajuster, nginx qui termine TLS avec vérification de clé d’API et Let’s Encrypt, et la vérification des écouteurs.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 vLLM clean VM installer
### Installs NVIDIA driver + CUDA 12.4 if a GPU is present, CPU fallback otherwise
### Binds vLLM on 127.0.0.1 only; nginx terminates TLS and enforces API key
### Operator must set VLLM_MODEL and tune --max-model-len / --tensor-parallel-size
### No local backups; assumes VM-level backup. Model weights re-pullable from Hugging Face.
### Reboot remains manual

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${VLLM_DOMAIN:?Set VLLM_DOMAIN=llm.example.com}"
: "${VLLM_EMAIL:?Set VLLM_EMAIL=ops@example.com for Let's Encrypt}"
VLLM_API_KEY="${VLLM_API_KEY:-$(openssl rand -hex 32)}"
VLLM_MODEL="${VLLM_MODEL:-meta-llama/Llama-3.1-8B-Instruct}"
VLLM_MAX_MODEL_LEN="${VLLM_MAX_MODEL_LEN:-8192}"
VLLM_TP_SIZE="${VLLM_TP_SIZE:-1}"
VLLM_GPU_MEM_UTIL="${VLLM_GPU_MEM_UTIL:-0.90}"
VLLM_DTYPE="${VLLM_DTYPE:-auto}"
VLLM_HF_TOKEN="${VLLM_HF_TOKEN:-}"
VLLM_HOME="/opt/vllm"
VLLM_CACHE="/var/lib/vllm"

echo
echo "========================================"
echo "vLLM Ubuntu 22.04 Setup"
echo "========================================"
echo

echo "==> Updating base OS"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade

echo "==> Installing base packages"
apt-get -y install \
  vim curl wget ca-certificates gnupg2 \
  chrony fail2ban unattended-upgrades \
  ufw lsof tcpdump dnsutils tar gzip \
  iproute2 net-tools openssl jq pciutils \
  build-essential git \
  software-properties-common

echo "==> Enabling time sync"
systemctl enable --now chrony
timedatectl set-ntp true

echo "==> Detecting NVIDIA GPU"
HAS_GPU=0
if lspci | grep -qi 'nvidia'; then
  HAS_GPU=1
  echo "NVIDIA GPU detected."
else
  echo "WARNING: no NVIDIA GPU detected. vLLM will run in CPU mode (very slow, only suitable for smoke tests)."
fi

if [[ $HAS_GPU -eq 1 ]]; then
  echo "==> Installing NVIDIA driver 535 and CUDA 12.4 toolkit"
  apt-get -y install ubuntu-drivers-common
  ubuntu-drivers autoinstall || apt-get -y install nvidia-driver-535

  wget -qO /tmp/cuda-keyring.deb \
    https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb
  dpkg -i /tmp/cuda-keyring.deb
  apt-get update
  apt-get -y install cuda-toolkit-12-4

  if ! grep -q '/usr/local/cuda/bin' /etc/profile.d/cuda.sh 2>/dev/null; then
    cat > /etc/profile.d/cuda.sh <<'CUDAENV'
export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
CUDAENV
  fi
fi

echo "==> Applying kernel/network tuning"
cat > /etc/sysctl.d/99-vllm.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr

net.core.somaxconn = 4096
net.core.netdev_max_backlog = 250000
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10240 65535

net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
vm.swappiness = 10
vm.overcommit_memory = 1
SYSCTL

modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

echo "==> Setting file limits"
cat > /etc/security/limits.d/99-vllm.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
root soft nofile 64000
root hard nofile 64000
LIMITS

echo "==> Configuring UFW"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

echo "==> Hardening SSH while keeping root SSH key login enabled"
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)

set_sshd_option() {
  local key="$1"
  local value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}

set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option KbdInteractiveAuthentication no
set_sshd_option ChallengeResponseAuthentication no
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
set_sshd_option MaxAuthTries 4

sshd -t
systemctl restart ssh

echo "==> Configuring fail2ban"
mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN

systemctl enable --now fail2ban

echo "==> Configuring unattended-upgrades"
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";
AUTOUPG

echo "==> Installing Python 3.11"
add-apt-repository -y ppa:deadsnakes/ppa
apt-get update
apt-get -y install python3.11 python3.11-venv python3.11-dev

echo "==> Creating vllm system user"
if ! id vllm >/dev/null 2>&1; then
  useradd --system --create-home --home-dir "${VLLM_HOME}" --shell /usr/sbin/nologin vllm
fi

echo "==> Preparing model cache on data volume"
mkdir -p "${VLLM_CACHE}"
chown -R vllm:vllm "${VLLM_CACHE}" "${VLLM_HOME}"
chmod 750 "${VLLM_CACHE}"

echo "==> Creating Python venv and installing vLLM"
sudo -u vllm python3.11 -m venv "${VLLM_HOME}/venv"
sudo -u vllm "${VLLM_HOME}/venv/bin/pip" install --upgrade pip wheel setuptools
sudo -u vllm "${VLLM_HOME}/venv/bin/pip" install vllm

echo "==> Writing environment file"
cat > /etc/default/vllm <<VLLMENV
# vLLM runtime environment
# Tune these for the model and the GPU:
#   VLLM_MODEL            - Hugging Face model id
#   VLLM_MAX_MODEL_LEN    - max prompt+completion tokens (drives KV cache size)
#   VLLM_TP_SIZE          - tensor-parallel-size (set to number of GPUs)
#   VLLM_GPU_MEM_UTIL     - fraction of VRAM vLLM may use (0.85-0.92 typical)
#   VLLM_DTYPE            - auto | float16 | bfloat16 | float32
VLLM_MODEL=${VLLM_MODEL}
VLLM_MAX_MODEL_LEN=${VLLM_MAX_MODEL_LEN}
VLLM_TP_SIZE=${VLLM_TP_SIZE}
VLLM_GPU_MEM_UTIL=${VLLM_GPU_MEM_UTIL}
VLLM_DTYPE=${VLLM_DTYPE}
VLLM_API_KEY=${VLLM_API_KEY}
HF_HOME=${VLLM_CACHE}
HF_HUB_CACHE=${VLLM_CACHE}
HUGGING_FACE_HUB_TOKEN=${VLLM_HF_TOKEN}
VLLMENV

chmod 600 /etc/default/vllm
chown root:vllm /etc/default/vllm
chmod 640 /etc/default/vllm

echo "==> Writing systemd unit for vLLM"
cat > /etc/systemd/system/vllm.service <<'VLLM_UNIT'
[Unit]
Description=vLLM OpenAI-compatible inference server
After=network.target
Wants=network-online.target

[Service]
Type=simple
User=vllm
Group=vllm
EnvironmentFile=/etc/default/vllm
WorkingDirectory=/opt/vllm
ExecStart=/opt/vllm/venv/bin/vllm serve ${VLLM_MODEL} \
  --host 127.0.0.1 \
  --port 8000 \
  --api-key ${VLLM_API_KEY} \
  --max-model-len ${VLLM_MAX_MODEL_LEN} \
  --tensor-parallel-size ${VLLM_TP_SIZE} \
  --gpu-memory-utilization ${VLLM_GPU_MEM_UTIL} \
  --dtype ${VLLM_DTYPE} \
  --disable-log-requests
Restart=on-failure
RestartSec=10
TimeoutStartSec=600
LimitNOFILE=64000

[Install]
WantedBy=multi-user.target
VLLM_UNIT

systemctl daemon-reload
systemctl enable vllm

echo "==> Starting vLLM (first run will download model weights; this can take 10-30 minutes)"
systemctl start vllm

echo "==> Waiting for vLLM on 127.0.0.1:8000 (long timeout for first model download)"
for i in {1..180}; do
  if ss -lntp | grep -q '127.0.0.1:8000'; then
    break
  fi
  sleep 10
done

if ! ss -lntp | grep -q '127.0.0.1:8000'; then
  echo "vLLM failed to listen on 127.0.0.1:8000 within 30 minutes"
  systemctl status vllm --no-pager -l || true
  journalctl -u vllm -n 300 --no-pager || true
  exit 1
fi

echo "==> Installing nginx and certbot"
apt-get -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/conf.d/vllm-ratelimit.conf <<'RATELIMIT'
limit_req_zone $binary_remote_addr zone=vllm_rl:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=vllm_conn:10m;
RATELIMIT

cat > /etc/nginx/sites-available/vllm <<NGINX
upstream vllm_backend {
    server 127.0.0.1:8000;
    keepalive 32;
}

server {
    listen 80;
    listen [::]:80;
    server_name ${VLLM_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name ${VLLM_DOMAIN};

    client_max_body_size 32M;
    proxy_read_timeout   600s;
    proxy_send_timeout   600s;
    proxy_connect_timeout 60s;
    proxy_buffering      off;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options SAMEORIGIN always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;

    limit_req zone=vllm_rl burst=20 nodelay;
    limit_conn vllm_conn 8;

    location / {
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_http_version 1.1;
        proxy_pass http://vllm_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/vllm /etc/nginx/sites-enabled/vllm
rm -f /etc/nginx/sites-enabled/default

nginx -t
systemctl enable --now nginx
systemctl reload nginx

echo "==> Requesting Let's Encrypt certificate"
certbot --nginx --non-interactive --agree-tos \
  -m "${VLLM_EMAIL}" -d "${VLLM_DOMAIN}" --redirect

systemctl enable --now certbot.timer

echo "==> Waiting for HTTPS listener"
for i in {1..30}; do
  if ss -lntp | grep -q ':443'; then
    break
  fi
  sleep 1
done

echo "==> First chat completion smoke test"
curl -fsS -X POST "https://${VLLM_DOMAIN}/v1/chat/completions" \
  -H "Authorization: Bearer ${VLLM_API_KEY}" \
  -H "Content-Type: application/json" \
  -d "{\"model\":\"${VLLM_MODEL}\",\"messages\":[{\"role\":\"user\",\"content\":\"reply with the single word OK\"}],\"max_tokens\":4}" \
  | jq -r '.choices[0].message.content' || true

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo

if [[ $HAS_GPU -eq 1 ]] && command -v nvidia-smi >/dev/null 2>&1; then
  echo "GPU:"
  nvidia-smi --query-gpu=name,memory.total,memory.free,utilization.gpu,driver_version --format=csv,noheader || true
else
  echo "GPU: none detected. CPU-only mode."
fi

echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|8000)\b' || true

echo
echo "Services:"
systemctl is-active vllm nginx fail2ban chrony || true

echo
echo "Model served:"
echo "${VLLM_MODEL}"
echo "  --max-model-len ${VLLM_MAX_MODEL_LEN}"
echo "  --tensor-parallel-size ${VLLM_TP_SIZE}"
echo "  --gpu-memory-utilization ${VLLM_GPU_MEM_UTIL}"

echo
echo "API URL:"
echo "https://${VLLM_DOMAIN}/v1/chat/completions"
echo
echo "API key (Authorization: Bearer ...):"
echo "${VLLM_API_KEY}"
echo
echo "Tuning lives in /etc/default/vllm. To change the model or context length, edit that file then 'systemctl restart vllm'."

echo
echo "Final step:"
echo "Reboot once so the NVIDIA driver loads cleanly, then watch 'journalctl -u vllm -f' on the first real workload to confirm KV cache fits."

Rendez-le exécutable et lancez-le :

chmod 700 /root/setup-vllm-ubuntu22.sh
VLLM_DOMAIN=llm.example.com VLLM_EMAIL=ops@example.com \
  VLLM_MODEL=meta-llama/Llama-3.1-8B-Instruct \
  VLLM_HF_TOKEN=hf_xxx \
  /root/setup-vllm-ubuntu22.sh

Le premier démarrage télécharge le modèle dans /var/lib/vllm — pour un 8B fp16 attendez-vous à environ 16 Go, pour un 70B environ 140 Go. L’unit systemd lit tout depuis /etc/default/vllm ; pour changer de modèle ou de longueur de contexte, éditez ce fichier puis systemctl restart vllm. Suivez la mémoire GPU, l’utilisation GPU et la latence des requêtes avec dcgm_exporter ou nvidia_gpu_exporter pour que le même tableau de bord qui attrape un voisin bruyant attrape une régression de cache KV.

Faites tourner le vLLM de production dans un environnement infogéré par Stack Harbor avec monitoring GPU-aware, cadence de mise à jour des modèles et escalade Sev-1 en place : Environnements infogérés. L’angle runtime infogéré (vLLM comme endpoint PaaS que vos applications consomment) est couvert dans Cloud PaaS.