> ## Documentation Index
> Fetch the complete documentation index at: https://ai-infra.lkad.net/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 实验环境与练习

> 一组循序渐进的动手实验，覆盖驱动安装、vLLM 部署、显存调优、压测、K8s GPU 调度、监控告警、弹性伸缩与故障演练。

本页提供 10 组实验，按由浅到深的顺序排列。实验环境有三种方案：单张消费级或云上按量 GPU（如一张 24 GB 卡）、云上 8 卡机按小时租用，以及没有 GPU 时可以做的替代方案（kind 集群练 K8s 调度对象、用 fake GPU 或 CPU 版 vLLM 练接口）。每个实验都写明目标、环境要求、具体步骤、预期结果和思考题。建议在做完每个实验后把关键命令和输出保存到个人笔记里，以便后续值班时快速查阅。

## 环境准备说明

| 环境方案 | 适用实验 | 备注 |
| - | - | - |
| 单卡 24 GB GPU（如 RTX 4090 / A10 / L4） | 实验 1-6、8-9 | 可跑 Qwen2.5-7B / Llama-3-8B 级别模型 |
| 云上 8 卡机按小时租用 | 实验 7-10 | 多卡 TP、nccl-tests、调度演练 |
| 无 GPU，kind + Mokka / fake GPU | 实验 5-8（部分） | 练 K8s 调度与对象配置，不跑真实推理 |
| 无 GPU，CPU 版 vLLM | 实验 2-4（简化版） | 可验证 API 接口与参数行为，速度极慢 |

CPU 版 vLLM 安装命令（参考官方文档，以实际版本为准）：

```bash theme={null}
pip install vllm --extra-index-url https://download.pytorch.org/whl/cpu
```

Mokka fake GPU 在 kind 上的快速启动（验证 K8s 调度用）：

```bash theme={null}
kind create cluster --name mokka
helm install nvml-mock oci://ghcr.io/nvidia/k8s-test-infra/chart/nvml-mock \
  --version 0.5.1 --namespace mokka --create-namespace
```

部署 NVIDIA device plugin 指向 mock 驱动后，节点会报告 `nvidia.com/gpu` 资源，此时可练习 YAML 编写与调度，但无法执行 CUDA 运算。

***

## 实验 1：安装驱动与 container toolkit，跑通 nvidia-smi 容器

### 目标

确认宿主机驱动、nvidia-container-toolkit 和容器运行时 CDI 配置正确，使 GPU 容器内可见。

### 环境

单卡 GPU 物理机或云实例，Ubuntu 22.04，已安装 NVIDIA 驱动（如 535 或 550 系列）。

### 步骤

1. 宿主机检查驱动：

```bash theme={null}
nvidia-smi
# 预期输出：显示 GPU 型号、驱动版本、CUDA 版本，GPU 温度与功耗
```

2. 安装 nvidia-container-toolkit：

```bash theme={null}
curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | \
  sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg

curl -s -L https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list | \
  sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \
  sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list

sudo apt-get update
sudo apt-get install -y nvidia-container-toolkit
sudo nvidia-ctk runtime configure --runtime=docker
sudo systemctl restart docker
```

3. 运行带 GPU 的容器：

```bash theme={null}
docker run --rm --gpus all nvidia/cuda:12.4.0-base-ubuntu22.04 nvidia-smi
# 预期输出与宿主机 nvidia-smi 信息一致
```

4. 验证 CDI 模式（containerd 1.7+ 推荐）：

```bash theme={null}
sudo nvidia-ctk cdi generate --output=/etc/cdi/nvidia.yaml
sudo grep nvidia.com/gpu /etc/cdi/nvidia.yaml | head -3
```

### 预期结果

* 宿主机 `nvidia-smi` 正常输出。
* Docker 容器内 `nvidia-smi` 与宿主机信息显示同一 GPU。
* CDI 配置文件生成成功，可被 containerd 消费。

### 思考题

1. 如果容器内 `nvidia-smi` 报错 "Failed to initialize NVML"，可能的根因有哪些？
2. nvidia-container-toolkit 的 legacy 模式与 cdi 模式在 K8s 中注册设备的方式有何不同？

***

## 实验 2：vLLM 单卡部署 Qwen2.5-7B-Instruct 并用 curl 调用

### 目标

在单卡上启动 vLLM OpenAI 兼容服务，验证模型加载与 chat completions 接口。

### 环境

单卡 GPU，显存大于等于 16 GB。模型选用 Qwen2.5-7B-Instruct（fp16 约 14 GB 权重）。

### 步骤

1. 安装 vLLM（以所用版本为准）：

```bash theme={null}
pip install vllm
```

2. 启动服务：

```bash theme={null}
vllm serve Qwen/Qwen2.5-7B-Instruct \
  --host 0.0.0.0 \
  --port 8080 \
  --gpu-memory-utilization 0.90 \
  --max-model-len 8192 \
  --max-num-seqs 256
```

启动参数的具体名称与默认值以当前版本 `vllm serve --help` 输出为准。例如新版可能调整参数名或增加新的优化级别选项。

3. 观察启动日志，确认以下关键行：

```text theme={null}
INFO  GPU KV cache size: X tokens
INFO  Maximum concurrency for Y tokens per request: Zx
```

4. 用 curl 调用 chat completions：

```bash theme={null}
curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Qwen/Qwen2.5-7B-Instruct",
    "messages": [{"role": "user", "content": "你好，请介绍一下自己"}],
    "max_tokens": 128
  }'
```

### 预期结果

* 服务在 8080 端口监听，`/v1/chat/completions` 返回正常 JSON。
* 响应包含 `choices[0].message.content`，首 token 延迟（TTFT）在几百毫秒到 1 秒之间。
* 启动日志中 KV cache 计算值不为 0。

### 思考题

1. 如果启动时 OOM，应该先调整 `--gpu-memory-utilization` 还是 `--max-model-len`？两个参数分别影响哪部分显存？
2. `--max-num-seqs` 达到上限后，新请求会怎样？

***

## 实验 3：观察显存与 KV cache，改参数看变化

### 目标

通过调整 `--gpu-memory-utilization` 和 `--max-model-len`，观察启动日志与运行时显存占用的变化，建立显存估算直觉。

### 环境

实验 2 已启动的 vLLM 服务。

### 步骤

1. 基线记录：

```bash theme={null}
# 在宿主机另开一个终端
nvidia-smi
# 记录 vLLM 进程的 GPU Memory-Usage
```

2. 改小 `--gpu-memory-utilization`：

```bash theme={null}
# 先停止旧服务
pkill -f "vllm serve"

# 重新启动，utilization 从 0.90 降到 0.70
vllm serve Qwen/Qwen2.5-7B-Instruct \
  --host 0.0.0.0 --port 8080 \
  --gpu-memory-utilization 0.70 \
  --max-model-len 8192
```

对比启动日志中 `GPU KV cache size` 的变化。记录 nvidia-smi 中 Memory-Usage 的差值。

3. 改小 `--max-model-len`：

```bash theme={null}
pkill -f "vllm serve"

vllm serve Qwen/Qwen2.5-7B-Instruct \
  --host 0.0.0.0 --port 8080 \
  --gpu-memory-utilization 0.90 \
  --max-model-len 4096
```

再次记录 KV cache 与显存占用。

4. 手动估算验证：

对 Qwen2.5-7B-Instruct，fp16/BF16 的 KV cache 每 token 占用约为：

```text theme={null}
2 (K + V) * num_layers * num_kv_heads * head_dim * sizeof(dtype)
= 2 * 28 * 4 * 128 * 2 字节 ≈ 57,344 字节/token
```

若 `--max-model-len=8192`，按单条请求最大长度算，理论峰值 KV = 8192 \* 57344 ≈ 448 MiB。实际 vLLM 按块分配，且需为并发请求预留更多空间，启动日志会给出实际可用的 KV cache tokens 数。

### 预期结果

* `--gpu-memory-utilization` 降低时，KV cache tokens 数减少，但权重显存不变。
* `--max-model-len` 降低时，vLLM 内部可能分配更少的 GPU 块用于 KV cache。
* nvidia-smi 显存占用与日志数值基本对齐。

### 思考题

1. 若把 `--gpu-memory-utilization` 调到 1.0，服务启动后立刻被另一个进程申请显存，会发生什么？
2. 为什么 `--max-model-len` 降到 4096 后，`GPU KV cache size` 可能没有减半？

***

## 实验 4：压测并画出并发-吞吐-延迟曲线

### 目标

用 vLLM 自带 benchmark 工具或自定义 client 测量不同并发下的 throughput 与 p99 TTFT，产出一张可复现的性能曲线。

### 环境

实验 2 的 vLLM 服务，另需一台 client 机或本机多进程发送请求。

### 步骤

1. 使用 vLLM bench serve（需安装 bench 依赖）：

```bash theme={null}
pip install vllm[bench]
```

2. 运行在线 serving benchmark：

```bash theme={null}
vllm bench serve \
  --model Qwen/Qwen2.5-7B-Instruct \
  --host localhost \
  --port 8080 \
  --random-input-len 512 \
  --random-output-len 128 \
  --num-prompts 100
```

3. 固定 input/output 长度，改变并发数（num-prompts 和时间窗口），分别记录：

| 并发数 | throughput (tok/s) | p99 TTFT (s) | p99 TPOT (s) |
| - | - | - | - |
| 1 | | | |
| 4 | | | |
| 8 | | | |
| 16 | | | |
| 32 | | | |

4. 画出并发数-吞吐曲线和并发数-p99 TTFT 曲线。可以用 Python matplotlib 或 Excel 完成。

若要更灵活地控制并发，也可以写 Python 脚本用 `asyncio` + `aiohttp` 发送请求，代码框架如下：

```python theme={null}
import asyncio, aiohttp, time, json

async def send(session, url, payload):
    t0 = time.time()
    async with session.post(url, json=payload) as resp:
        await resp.text()
    return time.time() - t0

async def main(concurrency, num_prompts):
    url = "http://localhost:8080/v1/chat/completions"
    payload = {
        "model": "Qwen/Qwen2.5-7B-Instruct",
        "messages": [{"role": "user", "content": "请写一段关于人工智能的短文"}],
        "max_tokens": 128
    }
    async with aiohttp.ClientSession() as session:
        tasks = [send(session, url, payload) for _ in range(num_prompts)]
        # 用 Semaphore 控制并发
        sem = asyncio.Semaphore(concurrency)
        ...

asyncio.run(main(8, 100))
```

### 预期结果

* 低并发时吞吐随并发线性增长，TTFT 增长缓慢。
* 中高并发时吞吐趋向饱和，TTFT 因排队和 batching 显著上升。
* 存在一个饱和点，超过后增加并发不会提高总吞吐，只会恶化延迟。

### 思考题

1. 为什么并发超过一定值后，总吞吐不再上升？瓶颈在计算还是显存带宽？
2. 如果观察到 p99 TPOT 飙升但 GPU util 不高，可能是什么参数限制？

***

## 实验 5：在 K8s 上装 GPU Operator，部署推理 Deployment

### 目标

在 K8s 集群上部署 NVIDIA GPU Operator，使节点正确报告 `nvidia.com/gpu` 资源，然后部署一个带 GPU 请求的 vLLM Deployment。

### 环境

至少一个 GPU 节点的 K8s 集群，Helm 3，kubectl。无 GPU 时可改用 kind + Mokka 做纯调度演练。

### 步骤

1. 安装 GPU Operator（以 chart v26.7.2 为例）：

```bash theme={null}
helm repo add nvidia https://helm.ngc.nvidia.com/nvidia
helm repo update

helm install gpu-operator nvidia/gpu-operator \
  --namespace gpu-operator \
  --create-namespace \
  --version v26.7.2 \
  --set driver.enabled=true \
  --set toolkit.enabled=true \
  --set dcgmExporter.enabled=true
```

若节点已有预装驱动，设置 `driver.enabled=false`。

2. 验证 pod 状态：

```bash theme={null}
kubectl get pods -n gpu-operator
# 预期：nvidia-device-plugin、nvidia-dcgm-exporter、gpu-feature-discovery 等为 Running
```

3. 验证节点资源：

```bash theme={null}
kubectl get nodes -o custom-columns=\
NAME:.metadata.name,GPUS:.status.allocatable.nvidia\.com/gpu
```

4. 部署 vLLM Deployment：

```yaml theme={null}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: vllm-qwen
spec:
  replicas: 1
  selector:
    matchLabels:
      app: vllm-qwen
  template:
    metadata:
      labels:
        app: vllm-qwen
    spec:
      containers:
      - name: vllm
        image: vllm/vllm-openai:latest
        args:
          - "--model"
          - "Qwen/Qwen2.5-7B-Instruct"
          - "--gpu-memory-utilization"
          - "0.90"
          - "--max-model-len"
          - "8192"
        resources:
          limits:
            nvidia.com/gpu: "1"
        ports:
        - containerPort: 8000
```

```bash theme={null}
kubectl apply -f vllm-deployment.yaml
kubectl wait --for=condition=ready pod -l app=vllm-qwen --timeout=300s
```

5. 暴露 Service 并测试：

```bash theme={null}
kubectl expose deployment vllm-qwen --port=8000 --target-port=8000 --type=ClusterIP
kubectl port-forward svc/vllm-qwen 8080:8000 &
curl http://localhost:8080/v1/models
```

### 预期结果

* GPU Operator 所有组件 Running。
* 节点 `nvidia.com/gpu` allocatable 与实际物理卡数量一致。
* vLLM pod 能调度到 GPU 节点，/v1/models 返回模型列表。

### 思考题

1. 如果 device-plugin pod Running 但节点没有 `nvidia.com/gpu`，应该按什么顺序排查？
2. GPU Operator 的 driver DaemonSet 和 CUDA validator 分别验证什么？

***

## 实验 6：接入 dcgm-exporter 与 vLLM metrics，配 Grafana 和告警

### 目标

让 Prometheus 抓取 GPU 节点指标和 vLLM 推理指标，在 Grafana 画出看板，并配置关键告警规则。

### 环境

实验 5 的 K8s 集群，已部署 GPU Operator（含 dcgm-exporter）。另需 kube-prometheus-stack 或已有 Prometheus。

### 步骤

1. 部署 kube-prometheus-stack：

```bash theme={null}
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

helm install kube-prometheus-stack prometheus-community/kube-prometheus-stack \
  --namespace monitoring --create-namespace
```

2. 确认 dcgm-exporter 已被 ServiceMonitor 选中（GPU Operator 自带 dcgm-exporter ServiceMonitor，需标签匹配）：

```bash theme={null}
kubectl get servicemonitor -n gpu-operator
```

3. 为 vLLM 添加 ServiceMonitor：

```yaml theme={null}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: vllm-metrics
  namespace: monitoring
spec:
  selector:
    matchLabels:
      app: vllm-qwen
  endpoints:
  - port: "8000"
    path: /metrics
    interval: 15s
```

4. 在 Grafana 导入以下关键 PromQL：

| 面板 | PromQL |
| - | - |
| GPU 利用率 | `DCGM_FI_DEV_GPU_UTIL` |
| GPU 显存使用 | `DCGM_FI_DEV_FB_USED / 1024` |
| XID 错误 | `DCGM_FI_DEV_XID_ERRORS` |
| vLLM 运行中请求数 | `vllm:num_requests_running` |
| vLLM 等待中请求数 | `vllm:num_requests_waiting` |
| vLLM KV cache 使用率 | `vllm:gpu_cache_usage_perc`（或新版 `vllm:kv_cache_usage_perc`） |
| vLLM TTFT p99 | `histogram_quantile(0.99, sum(rate(vllm:time_to_first_token_seconds_bucket[1m])) by (le))` |

vLLM 的指标名在不同版本间可能有变化，以所部署版本的 /metrics 端点实际输出为准。

5. 配置 PrometheusRule 告警：

```yaml theme={null}
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: inference-alerts
  namespace: monitoring
spec:
  groups:
  - name: gpu
    rules:
    - alert: GPUXIDError
      expr: DCGM_FI_DEV_XID_ERRORS > 0
      for: 0m
      labels:
        severity: critical
      annotations:
        summary: "GPU XID error detected"
    - alert: GPUHighTemperature
      expr: DCGM_FI_DEV_GPU_TEMP > 85
      for: 2m
      labels:
        severity: warning
      annotations:
        summary: "GPU temperature {{ $value }} C"
  - name: vllm
    rules:
    - alert: VLLMQueueHigh
      expr: vllm:num_requests_waiting > 20
      for: 1m
      labels:
        severity: warning
      annotations:
        summary: "vLLM queue depth high"
    - alert: VLLMKVCacheHigh
      expr: vllm:gpu_cache_usage_perc > 0.95
      for: 2m
      labels:
        severity: warning
      annotations:
        summary: "vLLM KV cache near full"
```

### 预期结果

* Prometheus Target 页面中 dcgm-exporter 和 vLLM 均为 UP。
* Grafana 能看到 GPU 利用率、显存、vLLM 队列深度等时序曲线。
* 手动触发告警条件（如造队列）后，Alertmanager 收到告警。

### 思考题

1. 为什么 `DCGM_FI_DEV_GPU_UTIL` 高不代表推理吞吐高？
2. vLLM 的 `vllm:num_requests_waiting` 与 `vllm:gpu_cache_usage_perc` 哪个更适合作扩容信号？

***

## 实验 7：KEDA 按排队数自动扩缩

### 目标

为 vLLM Deployment 配置 KEDA ScaledObject，按 Prometheus 中 `vllm:num_requests_waiting` 自动扩缩容。

### 环境

实验 5-6 的 K8s 集群，已部署 Prometheus。GPU 节点需足够承载最大副本数。

### 步骤

1. 安装 KEDA：

```bash theme={null}
helm repo add kedacore https://kedacore.github.io/charts
helm repo update

helm install keda kedacore/keda --namespace keda --create-namespace
```

2. 编写 ScaledObject：

```yaml theme={null}
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: vllm-qwen-keda
  namespace: default
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: vllm-qwen
  minReplicaCount: 1
  maxReplicaCount: 4
  pollingInterval: 15
  cooldownPeriod: 300
  triggers:
    - type: prometheus
      metricType: AverageValue
      metadata:
        serverAddress: http://kube-prometheus-stack-prometheus.monitoring.svc:9090
        query: sum(vllm:num_requests_waiting) or vector(0)
        threshold: "25"
        activationThreshold: "1"
```

3. 应用并验证：

```bash theme={null}
kubectl apply -f scaledobject.yaml
kubectl get scaledobject
kubectl get hpa
```

4. 压测触发扩容：

用实验 4 的脚本并发发送大量请求，观察副本数上升：

```bash theme={null}
kubectl get pods -l app=vllm-qwen -w
```

停止压测后等待 cooldownPeriod（300 秒），观察副本数下降。

### 预期结果

* 队列为 0 时保持 minReplicaCount。
* 队列超过 threshold \* current\_replicas 时触发扩容。
* 停止负载后，冷却期结束后缩容到 minReplicaCount。

### 思考题

1. cooldownPeriod 设太短会导致什么问题？为什么 GPU 推理要设得比 Web 服务更长？
2. 如果每个副本需要 1 张 GPU，maxReplicaCount 4 意味着需要 4 张 GPU 节点。如果集群只有 3 张可用 GPU，KEDA 会怎样表现？

***

## 实验 8：time-slicing 或 MIG 共享 GPU

### 目标

配置 GPU time-slicing 或 MIG，使一张物理 GPU 能被多个 Pod 共享。

### 环境

支持 MIG 的 GPU（A100、H100）或任意 NVIDIA GPU（time-slicing）。K8s + GPU Operator 已部署。

### 方案 A：Time-Slicing

1. 创建 ConfigMap：

```yaml theme={null}
apiVersion: v1
kind: ConfigMap
metadata:
  name: time-slicing-config
  namespace: gpu-operator
data:
  any: |-
    version: v1
    sharing:
      timeSlicing:
        renameByDefault: false
        failRequestsGreaterThanOne: false
        resources:
          - name: nvidia.com/gpu
            replicas: 4
```

2. 修改 ClusterPolicy 引用该 ConfigMap，然后重启 device plugin：

```bash theme={null}
kubectl rollout restart -n gpu-operator daemonset/nvidia-device-plugin-daemonset
```

3. 验证节点资源变为 4 倍：

```bash theme={null}
kubectl get node <gpu-node> -o jsonpath='{.status.allocatable.nvidia\.com/gpu}'
# 预期：若原有 1 张 GPU，现在显示 4
```

4. 部署两个各请求 1 GPU 的 Pod，观察它们共享同一张卡：

```yaml theme={null}
# pod-a.yaml 与 pod-b.yaml，各设置 limits.nvidia.com/gpu: "1"
kubectl apply -f pod-a.yaml -f pod-b.yaml
```

注意：time-slicing 不提供显存隔离，任一 Pod 都可能 OOM 整张卡。

### 方案 B：MIG（仅 Ampere+）

1. GPU Operator 安装时设置 mig.strategy：

```bash theme={null}
helm install gpu-operator nvidia/gpu-operator \
  --set mig.strategy=single
```

2. 对节点打标签启用 MIG profile：

```bash theme={null}
kubectl label node <gpu-node> nvidia.com/mig.config=all-1g.10gb --overwrite
```

3. 等待 MIG Manager 配置完成，验证节点资源：

```bash theme={null}
kubectl get node <gpu-node> -o jsonpath='{.status.allocatable.nvidia\.com/gpu}'
# single 策略下每个 MIG 实例作为 nvidia.com/gpu 暴露
```

### 预期结果

* time-slicing：节点 GPU 资源数 = 物理卡数 \* replicas。
* MIG：节点 GPU 资源数 = 物理卡数 \* MIG 实例数，各实例显存互相隔离。

### 思考题

1. time-slicing 和 MIG 在故障隔离上有什么区别？生产上什么场景适合 time-slicing？
2. MIG 的 single 策略与 mixed 策略分别适用于什么场景？

***

## 实验 9：多卡 TP 部署与 nccl-tests

### 目标

在 2 卡或 8 卡机上启动 tensor-parallel 推理，并用 nccl-tests 验证卡间带宽正常。

### 环境

2 卡及以上节点，NVLink 或 PCIe 互联。

### 步骤

1. 多卡 TP 启动 vLLM：

```bash theme={null}
vllm serve Qwen/Qwen2.5-7B-Instruct \
  --tensor-parallel-size 2 \
  --host 0.0.0.0 --port 8080
```

观察日志中 `tensor_parallel_size=2` 的 NCCL 初始化信息。若 NCCL 报错，检查 `NCCL_DEBUG=INFO` 输出。

2. 编译并运行 nccl-tests：

```bash theme={null}
git clone https://github.com/NVIDIA/nccl-tests.git
cd nccl-tests
make MPI=1 MPI_HOME=/usr/lib/x86_64-linux-gnu/openmpi CUDA_HOME=/usr/local/cuda NCCL_HOME=/usr
```

单节点 2 卡测试：

```bash theme={null}
./build/all_reduce_perf -b 8 -e 512M -f 2 -g 2
```

关注 `busbw` 列。NVLink 互联下，2 卡 all-reduce 的大消息 busbw 应接近理论上限的一半以上。PCIe 互联会显著降低。

### 预期结果

* vLLM TP=2 能正常服务请求，两个 GPU 都有显存占用。
* nccl-tests 无 wrong 报错，大消息 busbw 在合理范围内。

### 思考题

1. TP=2 时，若其中一张卡的 NVLink 链路故障，vLLM 会报什么错误？怎么快速定位？
2. 为什么单节点内 TP 的延迟通常低于 PP（pipeline parallelism）？

***

## 实验 10：故障演练（kill 进程、模拟 OOM、占满显存、删掉模型文件）

### 目标

按 SOP 处置常见故障，验证监控与告警链路。

### 环境

实验 5-6 的完整 K8s + vLLM + 监控环境。

### 步骤

| 故障类型 | 注入方法 | 预期现象 | 处置动作 |
| - | - | - | - |
| kill vLLM 进程 | `kubectl exec <pod> -- pkill -9 python` | Pod 重启，请求失败 | 检查 restart count，确认启动日志无异常 |
| 模拟显存 OOM | 启动另一进程申请大量显存 | vLLM 报 CUDA OOM，请求中断 | 清理异常进程，检查 `--gpu-memory-utilization` 是否过高，考虑隔离 |
| 占满显存不释放 | 在 Pod 内运行 `torch.ones` 大 tensor 不释放 | nvidia-smi 显存满，vLLM 新请求排队或失败 | `kubectl delete pod` 强制重建 |
| 删掉模型文件 | `kubectl exec <pod> -- rm -rf /root/.cache/huggingface/` | 下次启动时重新下载，启动时间变长 | 检查模型存储是否应使用 PVC / OSS 缓存，避免重复下载 |
| XID 错误 | 硬件层面难以直接模拟，可用 Mokka 注入 | DCGM 指标 `DCGM_FI_DEV_XID_ERRORS > 0`，告警触发 | 按厂商手册排查：查 `nvidia-smi -q` 错误码，必要时迁移 Pod 并标记节点 |

额外一步：验证 Prometheus 告警接收。

1. 临时把告警阈值调低，触发展开：

```bash theme={null}
kubectl edit prometheusrule inference-alerts
# 把 VLLMQueueHigh 的 expr 从 > 20 改为 > 1
```

2. 发送几条请求制造队列。
3. 检查 Alertmanager 是否收到告警（若为静默模式，先看 Prometheus Alerts 页面）。
4. 恢复阈值。

### 预期结果

* 每种故障的处置时间控制在手册规定的 SLO 内。
* 告警链路端到端通：故障注入到 Alertmanager 收到通知。
* kill 进程和删文件后，Pod 或模型能自动恢复或有明确人工介入步骤。

### 思考题

1. 如果 kill vLLM 进程后 Pod 没有自动重启，应该优先排查什么？
2. 显存 OOM 发生后，为什么有时候 `nvidia-smi` 显示显存仍被占用？
3. 删掉模型文件后 vLLM 启动失败，如何设计存储策略避免生产上出现同类事故？

***

## 自测

1. 在单卡上启动 vLLM，用 `--max-model-len 4096` 与 `8192` 各启动一次，记录启动日志中的 `GPU KV cache size`，比较差异并解释原因。
2. 用 `vllm bench serve` 测量 Qwen2.5-7B 在本地的吞吐与延迟基线，记录表格。
3. 在 kind 集群上安装 GPU Operator（或 Mokka fake GPU），写一个 Deployment YAML，使 Pod 请求 `nvidia.com/gpu: 1` 并成功调度。
4. 写一条 PromQL，查询过去 5 分钟内 vLLM P95 TTFT，并解释 bucket 聚合的原由。
5. 配置一个 KEDA ScaledObject，使 vLLM 在队列深度超过 10 时扩容到最多 3 个副本。
6. 用 nccl-tests 的 `all_reduce_perf` 测试本机 2 卡带宽，记录 busbw，并与 NVLink 理论带宽比较。
7. 模拟一次显存 OOM，按 SOP 清理并恢复服务，记录从故障注入到恢复的时间。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.