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

# SGLang 部署与运维

> SGLang 的 RadixAttention、调度器特点、启动参数、多机部署和与 vLLM 的运维差异。

SGLang 是由 LMSYS 团队推出的 LLM 推理引擎，核心设计是 RadixAttention，旨在通过结构化的 KV cache 复用和低延迟调度提升交互式推理的效率。这个页面会讲清楚它的架构特点、启动方式、关键参数含义，以及和 vLLM 在生产环境里的差异。

## RadixAttention 与调度器特点

RadixAttention 是 SGLang 最具辨识度的特性。它把 KV cache 组织成一棵 radix tree（基数树），每个 tree node 对应一段 token 序列的 KV cache block。当新的 prompt 进来时，SGLang 会在 radix tree 里做最长前缀匹配，直接把匹配的 KV cache blocks 挂到当前请求后面，不需要重新计算 prefix。

这和 vLLM 的 prefix caching 类似，但实现方式不同：

| 特性 | vLLM Prefix Caching | SGLang RadixAttention |
| - | - | - |
| 复用粒度 | block-level（固定 block\_size） | token-level 前缀匹配 |
| 淘汰策略 | LRU | 基于引用计数 + LRU |
| 树结构 | 无，纯 hash 表 | radix tree |
| 典型收益 | system prompt 复用 | 多轮对话、多分支生成、结构化输出 |

SGLang 的 scheduler 设计偏向低延迟。它支持：

* **连续 batching**：和 vLLM 一样的动态 batching，running queue 里的请求不会阻塞新请求的 prefill。
* **跳批（jump batching）**：如果当前 running batch 里所有请求都完成了 decode，但还有新的 prefill 请求在等待，scheduler 会立即切换到 prefill，减少 GPU 空转。
* **结构生成缓存**：配合 SGLang 的 Structured Generation（如 JSON schema 约束），radix tree 会把 constraint 的中间状态也缓存下来。

运维时要注意，RadixAttention 的 radix tree 是内存数据结构，树太深或节点太多时会增加 CPU 开销。长上下文 + 高并发场景下，如果 CPU 占用飙高，可以考虑调小相关缓存阈值（以所用版本为准）。

## 安装与启动

SGLang 支持 pip 安装和 Docker 两种形式。生产上推荐 Docker，镜像 tag 要锁定版本。

```bash theme={null}
pip install sglang[all]==0.2.15
```

注意版本差异：SGLang 迭代很快，0.2.x 和 0.3.x 之间的启动参数和内部实现有较大变化。以下参数以 0.2.x 系列为准，升级前务必阅读 release note 并用 `--help` 确认。

### 单卡启动

```bash theme={null}
python -m sglang.launch_server \
  --model-path /models/Qwen2.5-7B-Instruct \
  --tp 1 \
  --mem-fraction-static 0.85 \
  --context-length 8192 \
  --max-running-requests 256
```

### 单机多卡 TP=8

```bash theme={null}
python -m sglang.launch_server \
  --model-path /models/Qwen2.5-72B-Instruct \
  --tp 8 \
  --mem-fraction-static 0.92 \
  --context-length 32768 \
  --max-running-requests 128 \
  --chunked-prefill-size 4096
```

### Docker 启动

```bash theme={null}
docker run --gpus all \
  -p 30000:30000 \
  -v /mnt/model:/model \
  --shm-size 16g \
  lmsysorg/sglang:latest \
  python -m sglang.launch_server \
  --model-path /model/Qwen2.5-72B-Instruct \
  --tp 8 \
  --mem-fraction-static 0.92
```

SGLang 默认监听 30000 端口，和 vLLM 的 8000 不同。部署多实例时要注意端口冲突。

## 关键参数逐个讲

### `--model-path`

本地模型目录或 Hugging Face model id。SGLang 会自动识别模型结构，但自定义架构仍需 `--trust-remote-code`。

### `--tp`

Tensor parallel size。和 vLLM 的 `--tensor-parallel-size` 等价。TP 必须是 2 的幂。SGLang 的 TP 目前主要支持 NCCL backend，多机场景下需要配合 `--nnodes` 使用。

### `--dp`

Data parallel size。SGLang 支持 data parallelism，即同一模型在多个 replica 上运行，由前端 router 分发请求。DP 和 TP 可以组合：TP=8、DP=2 意味着 2 个 replica，每个 replica 占 8 张卡，共 16 张卡。

开启 DP 时需要同时加 `--enable-dp-attention`，让 attention 算子走 DP 路径。不加这个参数 DP 不会生效。

### `--mem-fraction-static`

和 vLLM 的 `--gpu-memory-utilization` 等价，默认值通常是 0.9。含义是：权重加载后，剩余显存中多少比例分配给 KV cache。

### `--context-length`

最大上下文长度。必须小于等于模型 config 里的 `max_position_embeddings`。SGLang 会根据这个值和可用显存计算 KV cache blocks 数，如果不够会报错。解决思路和 vLLM 一样：降 context-length、调 mem-fraction-static、加卡。

### `--max-running-requests`

同时运行的最大请求数。SGLang 里这个值比 vLLM 更严格：如果 running 达到上限，新请求会直接拒绝（HTTP 429），而不是排队等待。生产上要根据压测结果设定这个值，避免雪崩。

### `--chunked-prefill-size`

Prefill 阶段的 chunk 大小，默认通常是 4096 或 8192。和 vLLM 的 `--enable-chunked-prefill` 类似，把一个长 prefill 拆成多个 chunk，让 decode 不被阻塞。值越大，单个 chunk 的 prefill 效率越高，但 decode 被阻塞的时间也越长。

### `--enable-dp-attention`

Data parallelism 下的 attention 优化开关。开启后，SGLang 会把相同 prompt 的 attention 计算合并，减少重复计算。仅在 `--dp > 1` 时有效。

### `--enable-metrics`

开启 Prometheus metrics，默认监听在 `http://localhost:30000/metrics`。如果不加这个参数，metrics 端口不会暴露。关键指标包括：

| 指标名 | 含义 |
| - | - |
| `sglang:num_requests_running` | 当前 running 请求数 |
| `sglang:num_requests_waiting` | 等待队列长度 |
| `sglang:time_to_first_token_seconds` | TTFT |
| `sglang:time_per_output_token_seconds` | TPOT |
| `sglang:prompt_cache_hit_rate` | RadixAttention 的 prefix cache 命中率 |

Prompt cache hit rate 是 SGLang 独有的指标。如果对话服务的 system prompt 很长，这个值应该保持在 0.8 以上。

### 其他版本差异参数

SGLang 版本之间参数变化较快。0.3.x 引入了新的启动器（`sglang.launch_server` 内部重构），部分参数名可能变化。以所用版本的 `--help` 输出为准。升级时建议做以下检查：

1. 在 staging 环境跑一遍 `--help`，diff 两个版本的参数列表。
2. 跑基准测试，对比旧版本和新版本的 TTFT/TPOT/throughput。
3. 检查 metrics 输出是否变化，Grafana dashboard 是否需要更新 PromQL。

## 多机部署思路（以 DeepSeek MoE 为例）

DeepSeek V2/V3 这类 MoE 模型参数量极大（236B 到 671B），单机 8 卡 A100 根本放不下，必须多机部署。SGLang 的多机启动和 vLLM + Ray 不同，它使用 PyTorch Distributed 直接建通信组。

### 启动命令

在两台各 8 卡 A100 的节点上分别执行：

```bash theme={null}
# Node 0（IP: 10.0.0.1，8 张卡）
python -m sglang.launch_server \
  --model-path /models/DeepSeek-V3 \
  --tp 16 \
  --nnodes 2 \
  --node-rank 0 \
  --dist-init-addr 10.0.0.1:29500 \
  --mem-fraction-static 0.85 \
  --context-length 16384 \
  --max-running-requests 64

# Node 1（IP: 10.0.0.2，8 张卡）
python -m sglang.launch_server \
  --model-path /models/DeepSeek-V3 \
  --tp 16 \
  --nnodes 2 \
  --node-rank 1 \
  --dist-init-addr 10.0.0.1:29500 \
  --mem-fraction-static 0.85 \
  --context-length 16384 \
  --max-running-requests 64
```

关键参数：

* `--nnodes`：总节点数。
* `--node-rank`：当前节点编号，从 0 开始。
* `--dist-init-addr`： rendezvous 地址，格式是 `ip:port`，必须是 node 0 的 IP 和一个空闲端口。
* `--tp`：总 tensor parallel size，等于 `nnodes * 单节点 GPU 数`。这里两台各 8 卡，TP=16。

MoE 模型的 expert 路由层会产生额外的 all-to-all 通信，机间带宽成为瓶颈。建议：

1. 机间用 200 Gbps RDMA（RoCE v2 或 InfiniBand）。
2. 如果带宽不足，考虑用 DeepSeek 官方推荐的多专家路由优化（如 ep\_size 调整），但这属于模型层优化，需要和模型团队配合。
3. 监控机间网络带宽利用率：`ibstat` 或 `nvidia-smi topo -m`。

## 与 vLLM 的运维差异

| 维度 | vLLM | SGLang |
| - | - | - |
| 默认端口 | 8000 | 30000 |
| 协议 | OpenAI 兼容 | OpenAI 兼容 + SGLang 结构化 API |
| Prefix cache | block-level hash | RadixAttention token-level |
| Metrics 路径 | /metrics | /metrics（需 `--enable-metrics`） |
| DP 支持 | 需外部网关 | 内置 `--dp` + `--enable-dp-attention` |
| 多机方式 | Ray cluster | PyTorch DDP + `--dist-init-addr` |
| 启动参数风格 | `--tensor-parallel-size` | `--tp` |

生产上的实际差异：

1. **日志格式不同**。SGLang 的日志没有 vLLM 那么详细，尤其是 NCCL 相关的 debug 信息较少。遇到通信问题时，可能需要手动加 `NCCL_DEBUG=INFO` 环境变量。
2. **请求拒绝策略**。SGLang 的 `--max-running-requests` 是硬限制，超了直接 429；vLLM 会排队。前端网关需要针对 429 做退避重试。
3. **端口管理**。SGLang 默认 30000，如果公司网络策略对高位端口有限制，启动时加 `--port 8080` 改到低端口。
4. **模型支持**。SGLang 对 DeepSeek 系列支持走在了前面，如果是 DeepSeek MoE 上线，优先考虑 SGLang。

## 常见问题

### 启动时报 `CUDA error: out of memory`

1. 检查 `--mem-fraction-static`，降到 0.85 或 0.8。
2. MoE 模型注意 expert 数量：DeepSeek V3 有 256 个 expert，每个 token 激活 8 个，显存占用和 dense 模型不一样。估算显存时不要按参数量直接除，要参考模型文档给的激活参数。
3. TP 数是否和 GPU 数匹配。TP=16 时必须能看到 16 张卡，否则会报错。

### Metrics 不返回数据

确认启动时加了 `--enable-metrics`。如果没加，访问 `/metrics` 会返回 404。

### `dist-init-addr` 连接超时

多机部署时，node 1 连不上 node 0，检查：

1. `dist-init-addr` 里的 IP 必须是 node 0 的可访问 IP，不能是 127.0.0.1。
2. 防火墙是否放行了 29500 端口。
3. 两台机器的 NCCL 网络路径是否通：`nccl-tests` 跑一遍 all-reduce。

### DP 模式下负载不均

`--dp 2` 时，SGLang 内置的 router 是简单的轮询。如果两个 replica 的负载差异很大（比如一个卡在长请求），需要在前端加更智能的负载均衡策略（如 least-connections）。

## 自测

1. SGLang 的 RadixAttention 和 vLLM 的 prefix caching 在实现上有什么不同？在生产上哪个更适合多轮对话场景？
2. 在两台 8 卡节点上部署 DeepSeek-V3，写出完整的启动命令，并说明每个参数的作用。
3. 用 `curl` 访问 SGLang 的 `/metrics`，确认 `--enable-metrics` 开启前后返回结果的差异。
4. 对比 SGLang 和 vLLM 在请求超限时的行为差异，并写出前端网关应该如何处理。
5. 在 MoE 模型部署中，为什么 TP=16 时不能简单地按 dense 模型的公式估算单卡显存？


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