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

# 可观测性与告警

> 覆盖 GPU 硬件、K8s 调度、推理引擎、网关与业务五层监控体系，含 DCGM 与 vLLM 核心指标、PromQL 查询、PrometheusRule 告警及链路追踪实践。

LLM 推理服务的可观测性不能仅靠几组 Pod CPU / 内存曲线撑场面。生产上，故障可能发生在 PCIe 链路、驱动 ECC 处理、KV cache 耗尽、preemption 反复发生、请求排队、网关超时，或模型输出质量漂移等任意一层。没分层盯好，查到半夜也定不了界。

这一页教你搭一套覆盖硬件层、节点层、K8s 层、引擎层、网关层和业务层的监控体系。内容包括 dcgm-exporter 部署与关键指标解读、vLLM 核心 Prometheus 指标、可直接用的 PromQL、PrometheusRule 告警规则、Grafana 看板布局建议、日志规范，以及链路追踪接入。

***

## 监控分层架构

我们把监控对象分为五层，每一层出问题都会以不同形式体现在延迟、吞吐、GPU util 或报错信息上。日常值班时，先看哪层在报警，再决定往下钻哪一层。

| 层次 | 典型监控对象 | 关键采集方式 |
| - | - | - |
| 硬件 / 节点 | GPU 温度、功耗、Xid、PCIe 错误、ECC 错误 | DCGM Exporter、node-exporter |
| K8s 调度与容器 | Pod 状态、容器重启、资源申请 / 实际使用、scheduler event | kube-state-metrics、cadvisor |
| 推理引擎 | TTFT、TPOT、KV cache 使用率、preemption、排队数 | vLLM `/metrics`、SGLang `/metrics` |
| 网关 / 代理 | 请求成功率、QPS、P99 延迟、路由错误、限流触发 | ingress / gateway exporter、 envoy / nginx metrics |
| 业务与体验 | 首 token 时间、流式卡顿率、输出长度分布、用户报错率 | 网关或调用方埋点、tracing span |

以下各节按这个顺序展开。实际搭建时，前四层建议全部对接 Prometheus，业务层视情况用 tracing + 自定义事件日志。

***

## 硬件与节点层：DCGM Exporter

NVIDIA DCGM (Data Center GPU Manager) 提供硬件级指标采集，DCGM Exporter 以 DaemonSet 形式跑在每个 GPU 节点，对外暴露 Prometheus 格式的 `/metrics`。它比读 `nvidia-smi` 更稳定，也不需要让业务容器带 NVIDIA 工具。

### 部署方式

生产上推荐用 Helm 部署，并显式启用 MIG 支持或全 GPU 采集，视集群场景而定。

```yaml theme={null}
# dcgm-exporter-values.yaml（摘选）
image:
  repository: nvcr.io/nvidia/k8s/dcgm-exporter
  tag: "4.9.0"

# 采集频率，默认 30s；对 PROF 类指标可保持 30s
config:
  version: 2
  metrics:
    - name: default
      file: /etc/dcgm-exporter/chart/metrics/default-counters.csv
      every: 30s
  sources:
    dcgm:
      watch:
        max_keep_age: 10m

# 监听端口，ServiceMonitor 要一致
service:
  port: 9400
```

Helm 安装命令：

```bash theme={null}
helm repo add dcgm-exporter https://nvidia.github.io/dcgm-exporter
helm repo update
helm install dcgm-exporter dcgm-exporter/dcgm-exporter \
  -n monitoring \
  -f dcgm-exporter-values.yaml
```

装完后确认指标：

```bash theme={null}
# 在节点上
kubectl port-forward -n monitoring svc/dcgm-exporter 9400:9400
curl -s localhost:9400/metrics | grep DCGM_FI_DEV_GPU_UTIL
```

### 核心指标与含义

以下指标在生产环境建议全部采集。

| 指标名 | 类型 | 说明 |
| - | - | - |
| `DCGM_FI_DEV_GPU_UTIL` | gauge | GPU 计算利用率 (百分比)。注意该指标有误导性：它只反映时间与空间维度上多少 warp 在跑，并不能直接说明吞吐是否健康。 |
| `DCGM_FI_DEV_FB_USED` | gauge | 帧缓冲已用显存 (MiB) |
| `DCGM_FI_DEV_FB_FREE` | gauge | 帧缓冲剩余显存 (MiB) |
| `DCGM_FI_DEV_GPU_TEMP` | gauge | GPU 核心温度 (°C) |
| `DCGM_FI_DEV_MEMORY_TEMP` | gauge | 显存温度 (°C) |
| `DCGM_FI_DEV_POWER_USAGE` | gauge | 当前功耗 (W) |
| `DCGM_FI_DEV_TOTAL_ENERGY_CONSUMPTION` | counter | 累计能耗 (mJ) |
| `DCGM_FI_DEV_XID_ERRORS` | gauge | 最新 Xid 错误码 (0 表示无) |
| `DCGM_FI_DEV_ECC_SBE_VOL_TOTAL` | counter | volatile single-bit ECC 错误计数 |
| `DCGM_FI_DEV_ECC_DBE_VOL_TOTAL` | counter | volatile double-bit ECC 错误计数 |
| `DCGM_FI_DEV_ROW_REMAP_UNCORRECTABLE_TOTAL` | counter | 不可纠正行重映射次数 |
| `DCGM_FI_DEV_ROW_REMAP_CORRECTABLE_TOTAL` | counter | 可纠正行重映射次数 |
| `DCGM_FI_DEV_ROW_REMAP_FAILED` | gauge | 行重映射是否失败 (1 为失败) |

PROF 类指标需要在 dcgm-exporter 中启用 profiling 采集，且部分指标需要 root 或 `SYS_ADMIN` capability：

| 指标名 | 类型 | 说明 |
| - | - | - |
| `DCGM_FI_PROF_SM_ACTIVE` | gauge | SM 实际活跃周期比例 |
| `DCGM_FI_PROF_PIPE_TENSOR_ACTIVE` | gauge | Tensor Core 活跃周期比例 |
| `DCGM_FI_PROF_GR_ENGINE_ACTIVE` | gauge | Graphics Engine 活跃比例 |
| `DCGM_FI_PROF_DRAM_ACTIVE` | gauge | DRAM 活跃比例 (memory bandwidth 利用率近似) |

### GPU util 的误导性

`DCGM_FI_DEV_GPU_UTIL` 是很多人的第一直观指标，但推理场景下参考价值有限。举个例子：一批长 prompt 正在 prefill，GPU 很忙，GPU util 能到 90% 以上；但 decode 阶段如果一个 batch 里只有短序列在生成，GPU util 可能掉到 30% 以下，但模型其实还在健康工作，只是 memory-bound 或等待下一次调度而已。

更准确的看法是把 `DCGM_FI_PROF_SM_ACTIVE` 和 `DCGM_FI_PROF_PIPE_TENSOR_ACTIVE` 放在一起看：如果 SM active 很高但 Tensor active 很低，说明算子在用通用 ALU 而非 Tensor Core，通常是 kernel 实现或量化格式的问题；如果两者都低但延迟很高，说明瓶颈在显存带宽或 PCIe，而不是算力。

另一个常见场景：vLLM KV cache 打满，preemption 反复发生，用户体感延迟飙升，但 `DCGM_FI_DEV_GPU_UTIL` 还在 60% 左右波动。只看这个指标会误判为负载不高，实际引擎已经在崩溃边缘。所以引擎层指标必须一起看。

***

## K8s 层：Pod、容器与资源

除了 node-exporter 和 kube-state-metrics，LLM 推理集群最该关注的 K8s 指标包括但不限于：

```promql theme={null}
# Pod 重启次数（排除正常滚动更新）
increase(kube_pod_container_status_restarts_total{namespace="llm-inference"}[1h])

# GPU Pod 处于 Pending 的数量
count(kube_pod_status_phase{phase="Pending", namespace="llm-inference"})

# 容器实际内存使用与 limit 占比
container_memory_working_set_bytes{container!="POD", namespace="llm-inference"}
/
kube_pod_container_resource_limits{resource="memory", namespace="llm-inference"}

# 节点 GPU 已分配 / 可分配
kube_node_status_allocatable{resource="nvidia.com/gpu"}
```

如果你用 Volcano、Kueue 或自己的 gang scheduler，还要把 queue 等待时间、pod group pending 数量等暴露在 Prometheus 里，或者用 scheduler 自己的 metrics endpoint。

***

## 引擎层：vLLM 核心指标

vLLM (以 v1 引擎为例) 在默认启动的 OpenAI-compatible server 上暴露 `/metrics`。

> [!WARNING]
>
> vLLM 指标名随版本变化。v0 与 v1 引擎的指标前缀和具体名称有差异，旧版使用 `gpu_cache_usage_perc`，新版使用 `kv_cache_usage_perc`；`time_per_output_token_seconds` 在 v1 中变为 `request_time_per_output_token_seconds`。生产部署前务必 `curl /metrics` 确认实际名称，并以所用版本的 `--help` 为准。

### 服务级指标 (Gauge / Counter)

| 指标名 | 类型 | 说明 |
| - | - | - |
| `vllm:num_requests_running` | gauge | 当前正在 RUNNING 状态的请求数 |
| `vllm:num_requests_waiting` | gauge | 正在等调度的请求数 |
| `vllm:kv_cache_usage_perc` | gauge | KV cache 块使用率，0\~1 |
| `vllm:num_preemptions_total` | counter | 累计 preemption 次数 |
| `vllm:prompt_tokens_total` | counter | 累计输入 token 数 |
| `vllm:generation_tokens_total` | counter | 累计生成 token 数 |
| `vllm:prefix_cache_hits` | counter | prefix cache 命中次数 |
| `vllm:prefix_cache_queries` | counter | prefix cache 查询次数 |

### 请求级指标 (Histogram)

| 指标名 | 说明 |
| - | - |
| `vllm:time_to_first_token_seconds` | 从请求到达至首 token 生成的时间 (TTFT) |
| `vllm:inter_token_latency_seconds` | 连续流式输出之间的间隔 |
| `vllm:request_time_per_output_token_seconds` | 单请求平均每个输出 token 耗时 (TPOT) |
| `vllm:e2e_request_latency_seconds` | 端到端请求延迟 |
| `vllm:request_queue_time_seconds` | 请求在队列中等待的时间 |
| `vllm:request_prefill_time_seconds` | prefill 阶段耗时 |
| `vllm:request_decode_time_seconds` | decode 阶段耗时 |
| `vllm:request_prompt_tokens` | 输入长度分布 |
| `vllm:request_generation_tokens` | 生成长度分布 |

### 关键概念

* **TTFT (Time to First Token)**：用户发出请求到看到第一个流式输出的时间。影响“秒回”体验。队列等待和长 prefill 都会拉高 TTFT。
* **TPOT / ITL**：TPOT 是单请求 `(e2e - TTFT) / (output_tokens - 1)` 的平均值；ITL 是每个流式事件间隔。ITL 反映用户体感卡顿。
* **preemption**：KV cache 不够时，vLLM 会把部分 RUNNING 请求踢出并重新计算。频繁 preemption 是延迟抖动和吞吐坍塌的直接信号。
* **KV cache 使用率**：接近 1.0 时，新请求容易触发 preemption 或被拒绝。

***

## 网关层

网关指标取决于你用的具体实现。如果用的是 Envoy / Istio / Nginx Ingress，常用指标有：

```promql theme={null}
# 请求成功率
sum(rate(envoy_cluster_upstream_rq_2xx{cluster_name="vllm_backend"}[5m]))
/
sum(rate(envoy_cluster_upstream_rq_total{cluster_name="vllm_backend"}[5m]))

# P99 网关侧延迟
histogram_quantile(0.99,
  sum(rate(envoy_cluster_upstream_rq_time_bucket{cluster_name="vllm_backend"}[5m])) by (le)
)

# 活跃连接数
envoy_cluster_upstream_cx_active{cluster_name="vllm_backend"}
```

网关侧和引擎侧的延迟差值，能帮你判断瓶颈是在网关、网络，还是引擎内部（排队或 prefill 慢）。

***

## PromQL 查询参考

以下查询可直接用于 Grafana panel 或告警规则。示例按 vLLM v1 指标名编写，若你的版本不同请替换。

### TTFT P95

```promql theme={null}
histogram_quantile(
  0.95,
  sum by (le, model_name) (
    rate(vllm:time_to_first_token_seconds_bucket[5m])
  )
)
```

### 吞吐 tokens/s

```promql theme={null}
# 输入吞吐
sum by (model_name) (rate(vllm:prompt_tokens_total[5m]))

# 输出吞吐
sum by (model_name) (rate(vllm:generation_tokens_total[5m]))

# 总吞吐（输入 + 输出）
sum by (model_name) (
  rate(vllm:prompt_tokens_total[5m])
  + rate(vllm:generation_tokens_total[5m])
)
```

### 排队请求数

```promql theme={null}
avg by (pod) (vllm:num_requests_waiting)
```

### 每卡显存使用 (MiB)

```promql theme={null}
DCGM_FI_DEV_FB_USED{job="dcgm-exporter"}
```

### KV cache 使用率

```promql theme={null}
avg by (pod) (vllm:kv_cache_usage_perc)
```

### preemption 速率

```promql theme={null}
sum by (model_name) (rate(vllm:num_preemptions_total[5m]))
```

***

## PrometheusRule 告警规则

以下 YAML 提供一组可直接用的告警规则。请根据实际集群的 namespace、模型名和延迟基线调整阈值。告警按 `severity` 分 critical 和 warning 两级。

```yaml theme={null}
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: llm-inference-alerts
  namespace: monitoring
spec:
  groups:
    - name: gpu-hardware
      rules:
        - alert: GPUXidError
          expr: DCGM_FI_DEV_XID_ERRORS != 0
          for: 0m
          labels:
            severity: critical
          annotations:
            summary: "GPU Xid error detected"
            description: "GPU {{ $labels.gpu }} on node {{ $labels.instance }} reported Xid {{ $value }}. Check dmesg immediately."

        - alert: GPUFallenOffBus
          expr: DCGM_FI_DEV_XID_ERRORS == 79
          for: 0m
          labels:
            severity: critical
          annotations:
            summary: "GPU fallen off the bus"
            description: "Node {{ $labels.instance }} GPU {{ $labels.gpu }} shows Xid 79. Node may need reboot."

        - alert: GPUTemperatureHigh
          expr: DCGM_FI_DEV_GPU_TEMP > 85
          for: 5m
          labels:
            severity: warning
          annotations:
            summary: "GPU temperature high"
            description: "GPU {{ $labels.gpu }} temp {{ $value }}C exceeds 85C for 5m."

        - alert: GPUTemperatureCritical
          expr: DCGM_FI_DEV_GPU_TEMP > 92
          for: 0m
          labels:
            severity: critical
          annotations:
            summary: "GPU temperature critical"
            description: "GPU {{ $labels.gpu }} temp {{ $value }}C exceeds 92C. Risk of thermal throttle or shutdown."

        - alert: GPUHighPowerUsage
          expr: DCGM_FI_DEV_POWER_USAGE > 350
          for: 10m
          labels:
            severity: warning
          annotations:
            summary: "GPU sustained high power"
            description: "GPU {{ $labels.gpu }} power {{ $value }}W sustained > 350W."

        - alert: ECCDoubleBitError
          expr: increase(DCGM_FI_DEV_ECC_DBE_VOL_TOTAL[1h]) > 0
          for: 0m
          labels:
            severity: critical
          annotations:
            summary: "GPU double-bit ECC error"
            description: "GPU {{ $labels.gpu }} detected DBE. Inspect row remapping and consider reset."

    - name: engine-health
      rules:
        - alert: LLMQueueBacklog
          expr: avg by (pod) (vllm:num_requests_waiting) > 10
          for: 2m
          labels:
            severity: warning
          annotations:
            summary: "LLM request queue building"
            description: "Pod {{ $labels.pod }} has {{ $value }} waiting requests for 2m. Check capacity or scale out."

        - alert: LLMKVCacheFull
          expr: avg by (pod) (vllm:kv_cache_usage_perc) > 0.95
          for: 2m
          labels:
            severity: critical
          annotations:
            summary: "KV cache near full"
            description: "Pod {{ $labels.pod }} KV cache {{ $value | humanizePercentage }}. Preemption or OOM likely."

        - alert: LLMTTFTHigh
          expr: histogram_quantile(0.95, sum by (le, model_name) (rate(vllm:time_to_first_token_seconds_bucket[5m]))) > 5
          for: 3m
          labels:
            severity: warning
          annotations:
            summary: "TTFT P95 high"
            description: "Model {{ $labels.model_name }} TTFT P95 {{ $value }}s > 5s."

        - alert: LLMPreemptionSpike
          expr: sum by (model_name) (rate(vllm:num_preemptions_total[5m])) > 0.5
          for: 2m
          labels:
            severity: warning
          annotations:
            summary: "Preemption rate elevated"
            description: "Model {{ $labels.model_name }} preemptions {{ $value }}/s. KV cache pressure or max-num-seqs too high."

        - alert: LLMPodFrequentRestart
          expr: increase(kube_pod_container_status_restarts_total{namespace="llm-inference"}[1h]) > 3
          for: 0m
          labels:
            severity: critical
          annotations:
            summary: "LLM Pod frequent restart"
            description: "Pod {{ $labels.pod }} restarted {{ $value }} times in 1h. Check exit reason and OOM."
```

> [!NOTE]
>
> 阈值不是绝对标准。如果你的模型 prefill 本来就很重（例如 128k context），TTFT 的 P95 基线可能是 8 秒；小模型在 1 秒内都算正常。请按历史基线设置，并使用 Grafana 的“历史同期对比”而不是固定数字。

***

## ServiceMonitor / PodMonitor 示例

以下示例让 Prometheus Operator 自动 scrape vLLM 的 `/metrics` 与 dcgm-exporter。

### vLLM ServiceMonitor

```yaml theme={null}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: vllm-metrics
  namespace: monitoring
spec:
  namespaceSelector:
    matchNames:
      - llm-inference
  selector:
    matchLabels:
      app: vllm-server
  endpoints:
    - port: http
      path: /metrics
      interval: 15s
      scrapeTimeout: 10s
```

### DCGM Exporter PodMonitor

```yaml theme={null}
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: dcgm-exporter-metrics
  namespace: monitoring
spec:
  namespaceSelector:
    matchNames:
      - monitoring
  selector:
    matchLabels:
      app: dcgm-exporter
  podMetricsEndpoints:
    - port: metrics
      path: /metrics
      interval: 30s
      scrapeTimeout: 15s
```

***

## Grafana 看板布局建议

我们把看板按“从上到下，从全局到细节”的顺序排成几个区，值班时一眼扫过去就知道哪里亮红灯。

### Row 1：全局健康

* 在线 Pod 数（按模型、版本分组）
* 请求成功率（网关统计的 2xx / total）
* QPS / RPM（按模型）
* 当前在线用户数 / 并发请求数

### Row 2：延迟与体验

* TTFT P50 / P95 / P99（按模型）
* ITL / TPOT P50 / P95
* E2E 延迟 P95
* 网关延迟 vs 引擎延迟差值

### Row 3：引擎资源与健康

* `num_requests_running` + `num_requests_waiting` 堆叠图
* `kv_cache_usage_perc` 时序
* preemption rate（`/s`）
* prefix cache hit rate

### Row 4：硬件层

* `DCGM_FI_DEV_GPU_UTIL` 与 `DCGM_FI_PROF_SM_ACTIVE`
* `DCGM_FI_PROF_PIPE_TENSOR_ACTIVE`
* `DCGM_FI_DEV_FB_USED` / `FB_FREE`（每卡）
* `DCGM_FI_DEV_GPU_TEMP` 与 `DCGM_FI_DEV_POWER_USAGE`
* `DCGM_FI_DEV_XID_ERRORS` 文本面板（非零时高亮）

### Row 5：K8s 与调度

* Pod 重启次数（近 1h）
* Pending Pod 数
* 节点 GPU 已分配 / 可分配
* Volcano / Kueue queue 深度（如有）

***

## 日志

### 结构化日志

vLLM 默认输出文本日志。建议在生产环境启用结构化日志，统一用 JSON 格式，方便日志平台解析。vLLM 可以通过日志处理器配置 JSON 输出，也可以在外部用 fluent-bit / vector 做格式转换。

最小日志字段建议包含：

| 字段 | 说明 |
| - | - |
| `ts` | 时间戳 (RFC3339) |
| `level` | INFO / WARNING / ERROR |
| `msg` | 日志内容 |
| `pod` | Pod 名 |
| `node` | 节点名 |
| `request_id` | 请求 ID（如有） |
| `model` | 模型名 |

### 请求日志采样

全量记录每个请求的输入输出会带来存储压力，也可能泄露敏感 prompt。生产上建议：

* 对延迟异常（TTFT > threshold 或总延迟 > threshold）的请求全量记录。
* 正常请求按 1% 或 0.1% 采样。
* 请求日志中不要记录完整 prompt 和生成内容，除非有合规审批和脱敏机制。可以记录 token 长度、模型名、延迟、finish reason，以及脱敏后的用户 ID。

### 不要记录完整 prompt 的合规考虑

prompt 中可能包含用户隐私、商业机密或被监管的数据。即使内部平台，也应遵循最小必要原则：

* 日志只保留 token 数量和哈希后的 prompt fingerprint，用于 cache 命中率分析。
* 如需保留原始 prompt，写入独立审计存储，设置短期 TTL 和严格 RBAC。
* 定期扫描日志索引，确认没有原始文本泄露到通用日志系统。

***

## 链路追踪：OpenTelemetry

vLLM 从较新版本开始内置 OpenTelemetry 支持，可以导出 trace 到 OTLP Collector。链路追踪在以下场景特别有价值：

* 跨多个推理实例的请求路由诊断
* 区分网关排队、引擎排队、prefill、decode 各阶段耗时
* 追踪 bad case：某次请求为什么 TTFT 高达 30 秒，是在哪个 span 卡住的

### 开启方式

vLLM 启动时传入 `--otlp-traces-endpoint`：

```bash theme={null}
export OTEL_SERVICE_NAME="vllm-serve-7b"
export OTEL_EXPORTER_OTLP_TRACES_INSECURE=true
vllm serve meta-llama/Llama-2-7b-chat-hf \
  --otlp-traces-endpoint="http://otel-collector.monitoring.svc.cluster.local:4317"
```

在 K8s Deployment 中，可以把这些环境变量写在容器 spec 里，并通过 OTel Collector sidecar 或独立 DaemonSet 收集后转给 Jaeger / Tempo / 云厂商 APM。

### 关键 span 与属性

vLLM trace 中常见 span：

| Span 名 | 说明 |
| - | - |
| `vllm_request` | 单次推理请求总 span |
| `prefill` | prefill 阶段 |
| `decode` | decode 阶段 |
| `scheduling` | 调度与等待阶段 |

常用属性（attributes）：

* `gen_ai.request.model`：模型名
* `gen_ai.usage.prompt_tokens`：输入 token 数
* `gen_ai.usage.completion_tokens`：输出 token 数
* `gen_ai.latency.time_to_first_token`：TTFT
* `gen_ai.latency.time_in_queue`：队列等待时间

如果你在网关或调用方也接入了 OTel，并透传了 `traceparent` header，就可以把整个链路串起来，看到从用户请求进入网关、排队、路由、引擎处理、到流式响应的完整 timeline。

***

## 自测

1. 你在 Grafana 看到 `DCGM_FI_DEV_GPU_UTIL` 持续 90%，但 `vllm:time_to_first_token_seconds` P95 从 1s 涨到了 8s。接下来你会先看哪个指标来确认根因？
2. 写出一条 PromQL，查询过去 5 分钟内模型 `qwen-72b` 的 TTFT P99。
3. 如果 `vllm:kv_cache_usage_perc` 达到 0.98 且 `vllm:num_preemptions_total` 每分钟增加 10 次，列出至少两项可以立刻尝试的缓解措施。
4. 为什么 PROF 类 DCGM 指标（如 `DCGM_FI_PROF_SM_ACTIVE`）需要额外开启 profiling？简述采集时的权限要求。
5. 在 K8s 中配置一个 PodMonitor，让 Prometheus 自动 scrape dcgm-exporter 的指标。
6. 设计一条告警规则：当某个 vLLM Pod 的排队请求数连续 3 分钟超过 20 时触发 warning。


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