采样参数#

本文档描述了 SGLang Runtime 的采样参数。它是 Runtime 的低级端点。

如果您需要一个可以自动处理聊天模板的高级端点,请考虑使用OpenAI 兼容 API

/generate 端点#

/generate 端点接受以下 JSON 格式的参数。详细用法请参阅原生 API 文档

参数

类型/默认值

描述

text

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

输入提示。可以是单个提示或一批提示。

input_ids

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

text 的替代方案。将输入指定为 token ID 而不是文本。

sampling_params

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

下方各节描述的采样参数。

return_logprob

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

是否返回 token 的对数概率。

logprob_start_len

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

如果返回对数概率,指定在提示中的起始位置。默认为“-1”,仅返回输出 token 的对数概率。

top_logprobs_num

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

如果返回对数概率,指定在每个位置返回前 N 个对数概率的数量。

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 处理器。用法请参见下方。

return_hidden_states

bool = False

是否返回模型的 hidden states。请注意,每次更改此设置时,CUDA 图都将重新捕获,这可能会导致性能下降。更多信息请参阅示例

采样参数#

核心参数#

参数

类型/默认值

描述

max_new_tokens

int = 128

最大输出长度,以 token 为单位。

stop

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

一个或多个停止词。如果采样到其中一个词,生成将停止。

stop_token_ids

Optional[List[int]] = None

以 token ID 的形式提供停止词。如果采样到其中一个 token ID,生成将停止。

temperature

float = 1.0

采样下一个 token 时的温度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 * highest_token_probability 的 token 中采样。

惩罚项#

参数

类型/默认值

描述

frequency_penalty

float = 0.0

根据 token 在目前生成中的频率对其进行惩罚。必须在 -22 之间,负数鼓励重复 token,正数鼓励采样新 token。惩罚的程度随 token 的每次出现而线性增长。

presence_penalty

float = 0.0

如果 token 已在当前生成中出现,则对其进行惩罚。必须在 -22 之间,负数鼓励重复 token,正数鼓励采样新 token。如果 token 出现过,惩罚的程度是恒定的。

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。

其他选项#

参数

类型/默认值

描述

n

int = 1

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

spaces_between_special_tokens

bool = True

在 detokenization(反标记化)过程中是否在特殊 token 之间添加空格。

no_stop_trim

bool = False

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

continue_final_message

bool = False

启用时,将移除最终的助手消息,并将其内容用作预填充,以便模型继续该消息而不是开始新的回合。示例请参阅openai_chat_with_response_prefill.py

ignore_eos

bool = False

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

skip_special_tokens

bool = True

在解码过程中移除特殊 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(
    "http://localhost: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(
    "http://localhost: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/test/lang/example_image.png?raw=true

发送请求

import requests

response = requests.post(
    "http://localhost: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 schema、正则表达式或 EBNF 来约束模型的输出。模型输出将保证遵循给定的约束。每次请求只能指定一个约束参数(json_schemaregexebnf)。

SGLang 支持两种语法后端

  • Outlines(默认):支持 JSON schema 和正则表达式约束。

  • XGrammar:支持 JSON schema、正则表达式和 EBNF 约束。

使用 --grammar-backend xgrammar 标志初始化 XGrammar 后端

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: outlines)
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(
    "http://localhost: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(
    "http://localhost: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(
    "http://localhost: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

定义一个自定义 Logit 处理器,使其始终采样特定的 token id。

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(
    "http://localhost: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())