采样参数#
本文档描述了 SGLang Runtime 的采样参数。它是 Runtime 的低级端点。
如果您需要一个可以自动处理聊天模板的高级端点,请考虑使用OpenAI 兼容 API。
/generate
端点#
/generate
端点接受以下 JSON 格式的参数。详细用法请参阅原生 API 文档。
参数 |
类型/默认值 |
描述 |
---|---|---|
text |
|
输入提示。可以是单个提示或一批提示。 |
input_ids |
|
|
sampling_params |
|
下方各节描述的采样参数。 |
return_logprob |
|
是否返回 token 的对数概率。 |
logprob_start_len |
|
如果返回对数概率,指定在提示中的起始位置。默认为“-1”,仅返回输出 token 的对数概率。 |
top_logprobs_num |
|
如果返回对数概率,指定在每个位置返回前 N 个对数概率的数量。 |
stream |
|
是否以流式方式输出。 |
lora_path |
|
LoRA 权重的路径。 |
custom_logit_processor |
|
用于高级采样控制的自定义 logit 处理器。用法请参见下方。 |
return_hidden_states |
|
是否返回模型的 hidden states。请注意,每次更改此设置时,CUDA 图都将重新捕获,这可能会导致性能下降。更多信息请参阅示例。 |
采样参数#
核心参数#
参数 |
类型/默认值 |
描述 |
---|---|---|
max_new_tokens |
|
最大输出长度,以 token 为单位。 |
stop |
|
一个或多个停止词。如果采样到其中一个词,生成将停止。 |
stop_token_ids |
|
以 token ID 的形式提供停止词。如果采样到其中一个 token ID,生成将停止。 |
temperature |
|
采样下一个 token 时的温度。 |
top_p |
|
Top-p 从累积概率超过 |
top_k |
|
Top-k 随机选择概率最高的 |
min_p |
|
Min-p 从概率大于 |
惩罚项#
参数 |
类型/默认值 |
描述 |
---|---|---|
frequency_penalty |
|
根据 token 在目前生成中的频率对其进行惩罚。必须在 |
presence_penalty |
|
如果 token 已在当前生成中出现,则对其进行惩罚。必须在 |
min_new_tokens |
|
强制模型至少生成 |
约束解码#
以下参数请参考我们关于约束解码的专门指南。
参数 |
类型/默认值 |
描述 |
---|---|---|
json_schema |
|
用于结构化输出的 JSON Schema。 |
regex |
|
用于结构化输出的正则表达式。 |
ebnf |
|
用于结构化输出的 EBNF。 |
其他选项#
参数 |
类型/默认值 |
描述 |
---|---|---|
n |
|
指定每次请求生成的输出序列数量。(不建议在一次请求中生成多个输出 (n > 1);重复相同的提示多次可以更好地控制和提高效率。) |
spaces_between_special_tokens |
|
在 detokenization(反标记化)过程中是否在特殊 token 之间添加空格。 |
no_stop_trim |
|
不要从生成的文本中裁剪停止词或 EOS token。 |
continue_final_message |
|
启用时,将移除最终的助手消息,并将其内容用作预填充,以便模型继续该消息而不是开始新的回合。示例请参阅openai_chat_with_response_prefill.py。 |
ignore_eos |
|
采样到 EOS token 时不要停止生成。 |
skip_special_tokens |
|
在解码过程中移除特殊 token。 |
custom_params |
|
在使用 |
示例#
普通#
启动服务器
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_schema
、regex
或 ebnf
)。
SGLang 支持两种语法后端
Outlines(默认):支持 JSON schema 和正则表达式约束。
XGrammar:支持 JSON schema、正则表达式和 EBNF 约束。
XGrammar 当前使用 GGML BNF 格式。
使用 --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())