采样参数#

本档介绍了 SGLang Runtime 的采样参数。它是运行时的底层接口。如果您需要一个能自动处理对话模板的高层接口,请考虑使用 OpenAI 兼容 API

/generate 接口#

/generate 接口接收 JSON 格式的以下参数。详细用法请参阅 原生 API 文档。该对象定义在 io_struct.py::GenerateReqInput 中。您也可以阅读源代码以了解更多参数和文档。

参数

类型/默认值

描述

text

Optional[Union[List[str], str]] = None

输入提示词(prompt)。可以是单个提示词或提示词列表。

input_ids

Optional[Union[List[List[int]], List[int]]] = None

文本的 token ID;用户可以指定 text 或 input_ids 其中之一。

input_embeds

Optional[Union[List[List[List[float]]], List[List[float]]]] = None

input_ids 的嵌入向量(embeddings);用户可以指定 text、input_ids 或 input_embeds 其中之一。

image_data

Optional[Union[List[List[ImageDataItem]], List[ImageDataItem], ImageDataItem]] = None

图像输入。支持三种格式:(1) 原始图像:PIL Image、文件路径、URL 或 base64 字符串;(2) 处理器输出:带有 format: "processor_output" 的字典,包含 HuggingFace 处理器输出;(3) 预计算嵌入:带有 format: "precomputed_embedding"feature 的字典,包含预先计算的视觉嵌入。可以是单张图像、图像列表或图像列表的列表。详情请见“多模态输入格式”。

audio_data

Optional[Union[List[AudioDataItem], AudioDataItem]] = None

音频输入。可以是文件名、URL 或 base64 编码字符串。

sampling_params

Optional[Union[List[Dict], Dict]] = None

下文各节中描述的采样参数。

rid

Optional[Union[List[str], str]] = None

请求 ID。

return_logprob

Optional[Union[List[bool], bool]] = None

是否返回 token 的对数概率(log probabilities)。

logprob_start_len

Optional[Union[List[int], int]] = None

如果 return_logprob 为真,则为提示词中开始返回 logprobs 的位置。默认值为“-1”,表示仅返回输出 token 的 logprobs。

top_logprobs_num

Optional[Union[List[int], int]] = None

如果 return_logprob 为真,则为每个位置返回的最大 logprobs 数量。

token_ids_logprob

Optional[Union[List[List[int]], List[int]]] = None

如果 return_logprob 为真,则为需要返回 logprob 的特定 token ID。

return_text_in_logprobs

bool = False

是否在返回的 logprobs 中对 token 进行文本反词元化(detokenize)。

stream

bool = False

是否流式输出。

lora_path

Optional[Union[List[Optional[str]], Optional[str]]] = None

LoRA 的路径。

custom_logit_processor

Optional[Union[List[Optional[str]], str]] = None

用于高级采样控制的自定义 logit 处理器。必须是使用 to_str() 方法序列化的 CustomLogitProcessor 实例。用法见下文。

return_hidden_states

Union[List[bool], bool] = False

是否返回隐藏状态(hidden states)。

采样参数#

该对象定义在 sampling_params.py::SamplingParams 中。您也可以阅读源代码以了解更多参数和文档。

关于默认值的说明#

默认情况下,SGLang 会从模型的 generation_config.json 中初始化若干采样参数(当服务器使用 --sampling-defaults model 启动时,这是默认行为)。若要改用 SGLang/OpenAI 的固定默认值,请使用 --sampling-defaults openai 启动服务器。您始终可以通过 sampling_params 在每个请求中覆盖任何参数。

# Use model-provided defaults from generation_config.json (default behavior)
python -m sglang.launch_server --model-path <MODEL> --sampling-defaults model

# Use SGLang/OpenAI constant defaults instead
python -m sglang.launch_server --model-path <MODEL> --sampling-defaults openai

核心参数#

参数

类型/默认值

描述

max_new_tokens

int = 128

以 token 为单位测量的最大输出长度。

stop

Optional[Union[str, List[str]]] = None

一个或多个 停止词(stop words)。如果采样到这些词之一,生成将停止。

stop_token_ids

Optional[List[int]] = None

以 token ID 形式提供的停止词。如果采样到这些 token ID 之一,生成将停止。

stop_regex

Optional[Union[str, List[str]]] = None

当匹配此列表中的任何正则表达式模式时停止生成。

temperature

float (模型默认值; 备选值 1.0)

采样下一个 token 时的 温度(Temperature)temperature = 0 对应于贪婪采样,较高的温度会导致更多样性的输出。

top_p

float (模型默认值; 备选值 1.0)

Top-p 从累计概率超过 top_p 的最小排序集合中选择 token。当 top_p = 1 时,这等同于对所有 token 进行不受限采样。

top_k

int (模型默认值; 备选值 -1)

Top-k 从概率最高的 k 个 token 中随机选择。

min_p

float (模型默认值; 备选值 0.0)

Min-p 从概率大于 min_p * 最高token概率 的 token 中进行采样。

惩罚因子#

参数

类型/默认值

描述

frequency_penalty

float = 0.0

根据 token 在迄今为止生成内容中出现的频率进行惩罚。必须在 -22 之间,其中负数鼓励 token 重复,正数鼓励采样新 token。惩罚的缩放随 token 的每次出现呈线性增长。

presence_penalty

float = 0.0

如果 token 出现在迄今为止的生成内容中,则对其进行惩罚。必须在 -22 之间,其中负数鼓励 token 重复,正数鼓励采样新 token。只要 token 出现过,惩罚的缩放就是恒定的。

repetition_penalty

float = 1.0

对先前生成 token 的 logit 进行缩放,以抑制(值 > 1)或鼓励(值 < 1)重复。有效范围为 [0, 2]1.0 保持概率不变。

min_new_tokens

int = 0

强制模型至少生成 min_new_tokens 个 token,直到采样到停止词或 EOS token。请注意,如果分布高度偏向这些 token,这可能会导致非预期行为。

受限解码#

关于以下参数,请参考我们专门的 受限解码 指南。

参数

类型/默认值

描述

json_schema

Optional[str] = None

结构化输出的 JSON 模式(schema)。

regex

Optional[str] = None

结构化输出的正则表达式。

ebnf

Optional[str] = None

结构化输出的 EBNF 范式。

structural_tag

Optional[str] = None

结构化输出的结构化标签。

其他选项#

参数

类型/默认值

描述

n

int = 1

指定每个请求生成的输出序列数量。(不鼓励在一个请求中生成多个输出 (n > 1);多次重复相同的提示词可提供更好的控制和效率。)

ignore_eos

bool = False

采样到 EOS token 时不停止生成。

skip_special_tokens

bool = True

在解码过程中移除特殊 token。

spaces_between_special_tokens

bool = True

在反词元化过程中是否在特殊 token 之间添加空格。

no_stop_trim

bool = False

不要从生成的文本中修剪掉停止词或 EOS token。

custom_params

Optional[List[Optional[Dict[str, Any]]]] = None

在使用 CustomLogitProcessor 时使用。用法见下文。

示例#

普通#

启动服务器

python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3-8B-Instruct --port 30000

发送请求

import requests

response = requests.post(
    "https://:30000/generate",
    json={
        "text": "The capital of France is",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 32,
        },
    },
)
print(response.json())

详细示例请见 发送请求

流式传输#

发送请求并流式输出

import requests, json

response = requests.post(
    "https://:30000/generate",
    json={
        "text": "The capital of France is",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 32,
        },
        "stream": True,
    },
    stream=True,
)

prev = 0
for chunk in response.iter_lines(decode_unicode=False):
    chunk = chunk.decode("utf-8")
    if chunk and chunk.startswith("data:"):
        if chunk == "data: [DONE]":
            break
        data = json.loads(chunk[5:].strip("\n"))
        output = data["text"].strip()
        print(output[prev:], end="", flush=True)
        prev = len(output)
print("")

详细示例请见 openai 兼容 api

多模态#

启动服务器

python3 -m sglang.launch_server --model-path lmms-lab/llava-onevision-qwen2-7b-ov

下载图像

curl -o example_image.png -L https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true

发送请求

import requests

response = requests.post(
    "https://:30000/generate",
    json={
        "text": "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n"
                "<|im_start|>user\n<image>\nDescribe this image in a very short sentence.<|im_end|>\n"
                "<|im_start|>assistant\n",
        "image_data": "example_image.png",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 32,
        },
    },
)
print(response.json())

image_data 可以是文件名、URL 或 base64 编码字符串。另请参阅 python/sglang/srt/utils.py:load_image

流式传输的支持方式与 上述 类似。

详细示例请见 OpenAI API Vision

结构化输出 (JSON, Regex, EBNF)#

您可以指定 JSON 模式、正则表达式或 EBNF 来限制模型输出。模型输出将保证遵循给定的限制。一个请求只能指定一个限制参数(json_schemaregexebnf)。

SGLang 支持两种语法后端

  • XGrammar (默认):支持 JSON 模式、正则表达式和 EBNF 限制。

  • Outlines:支持 JSON 模式和正则表达式限制。

如果您想改为初始化 Outlines 后端,可以使用 --grammar-backend outlines 标志

python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \
--port 30000 --host 0.0.0.0 --grammar-backend [xgrammar|outlines] # xgrammar or outlines (default: xgrammar)
import json
import requests

json_schema = json.dumps({
    "type": "object",
    "properties": {
        "name": {"type": "string", "pattern": "^[\\w]+$"},
        "population": {"type": "integer"},
    },
    "required": ["name", "population"],
})

# JSON (works with both Outlines and XGrammar)
response = requests.post(
    "https://:30000/generate",
    json={
        "text": "Here is the information of the capital of France in the JSON format.\n",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 64,
            "json_schema": json_schema,
        },
    },
)
print(response.json())

# Regular expression (Outlines backend only)
response = requests.post(
    "https://:30000/generate",
    json={
        "text": "Paris is the capital of",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 64,
            "regex": "(France|England)",
        },
    },
)
print(response.json())

# EBNF (XGrammar backend only)
response = requests.post(
    "https://:30000/generate",
    json={
        "text": "Write a greeting.",
        "sampling_params": {
            "temperature": 0,
            "max_new_tokens": 64,
            "ebnf": 'root ::= "Hello" | "Hi" | "Hey"',
        },
    },
)
print(response.json())

详细示例请见 结构化输出

自定义 Logit 处理器#

启动服务器时开启 --enable-custom-logit-processor 标志。

python -m sglang.launch_server \
  --model-path meta-llama/Meta-Llama-3-8B-Instruct \
  --port 30000 \
  --enable-custom-logit-processor

定义一个始终采样特定 token id 的自定义 logit 处理器。

from sglang.srt.sampling.custom_logit_processor import CustomLogitProcessor

class DeterministicLogitProcessor(CustomLogitProcessor):
    """A dummy logit processor that changes the logits to always
    sample the given token id.
    """

    def __call__(self, logits, custom_param_list):
        # Check that the number of logits matches the number of custom parameters
        assert logits.shape[0] == len(custom_param_list)
        key = "token_id"

        for i, param_dict in enumerate(custom_param_list):
            # Mask all other tokens
            logits[i, :] = -float("inf")
            # Assign highest probability to the specified token
            logits[i, param_dict[key]] = 0.0
        return logits

发送请求

import requests

response = requests.post(
    "https://:30000/generate",
    json={
        "text": "The capital of France is",
        "custom_logit_processor": DeterministicLogitProcessor().to_str(),
        "sampling_params": {
            "temperature": 0.0,
            "max_new_tokens": 32,
            "custom_params": {"token_id": 5},
        },
    },
)
print(response.json())

发送 OpenAI 聊天补全请求

import openai
from sglang.utils import print_highlight

client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None")

response = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "user", "content": "List 3 countries and their capitals."},
    ],
    temperature=0.0,
    max_tokens=32,
    extra_body={
        "custom_logit_processor": DeterministicLogitProcessor().to_str(),
        "custom_params": {"token_id": 5},
    },
)

print_highlight(f"Response: {response}")