离线引擎 API#

SGLang 提供一个直接推理引擎,无需 HTTP 服务器,特别适用于不需要额外 HTTP 服务器会带来不必要复杂性或开销的使用场景。以下是两种通用用例:

  • 离线批量推理

  • 在引擎之上构建自定义服务器

本文档重点介绍离线批量推理,展示四种不同的推理模式:

  • 非流式同步生成

  • 流式同步生成

  • 非流式异步生成

  • 流式异步生成

此外,您可以轻松在 SGLang 离线引擎之上构建自定义服务器。详细示例可参考 custom_server

Nest Asyncio#

请注意,如果您想在 ipython 或其他嵌套循环代码中使用 离线引擎,需要添加以下代码:

import nest_asyncio

nest_asyncio.apply()

高级用法#

该引擎支持 vlm 推理 以及 提取隐藏状态

更多用例请参考 示例

离线批量推理#

SGLang 离线引擎支持高效的批量推理调度。

[ ]:
# 启动离线引擎
import asyncio

import sglang as sgl
import sglang.test.doc_patch
from sglang.utils import async_stream_and_merge, stream_and_merge

llm = sgl.Engine(model_path="qwen/qwen2.5-0.5b-instruct")

非流式同步生成#

[ ]:
prompts = [
    "你好,我的名字是",
    "美国总统是",
    "法国的首都是",
    "AI的未来是",
]

sampling_params = {"temperature": 0.8, "top_p": 0.95}

outputs = llm.generate(prompts, sampling_params)
for prompt, output in zip(prompts, outputs):
    print("===============================")
    print(f"提示: {prompt}\n生成文本: {output['text']}")

流式同步生成#

[ ]:
prompts = [
    "为一个虚构角色写一个简短中性的自我介绍。你好,我的名字是",
    "提供一个关于法国首都城市的简洁事实陈述。法国的首都是",
    "解释人工智能的未来可能趋势。AI的未来是",
]

sampling_params = {
    "temperature": 0.2,
    "top_p": 0.9,
}

print("\n=== 测试带重叠移除的同步流式生成 ===\n")

for prompt in prompts:
    print(f"提示: {prompt}")
    merged_output = stream_and_merge(llm, prompt, sampling_params)
    print("生成文本:", merged_output)
    print()

非流式异步生成#

[ ]:
prompts = [
    "为一个虚构角色写一个简短中性的自我介绍。你好,我的名字是",
    "提供一个关于法国首都城市的简洁事实陈述。法国的首都是",
    "解释人工智能的未来可能趋势。AI的未来是",
]

sampling_params = {"temperature": 0.8, "top_p": 0.95}

print("\n=== 测试异步批量生成 ===")


async def main():
    outputs = await llm.async_generate(prompts, sampling_params)

    for prompt, output in zip(prompts, outputs):
        print(f"\n提示: {prompt}")
        print(f"生成文本: {output['text']}")


asyncio.run(main())

流式异步生成#

[ ]:
prompts = [
    "为一个虚构角色写一个简短中性的自我介绍。你好,我的名字是",
    "提供一个关于法国首都城市的简洁事实陈述。法国的首都是",
    "解释人工智能的未来可能趋势。AI的未来是",
]

sampling_params = {"temperature": 0.8, "top_p": 0.95}

print("\n=== 测试异步流式生成(无重复) ===")


async def main():
    for prompt in prompts:
        print(f"\n提示: {prompt}")
        print("生成文本: ", end="", flush=True)

        # 用我们自定义的重叠感知版本替换对 async_generate 的直接调用
        async for cleaned_chunk in async_stream_and_merge(llm, prompt, sampling_params):
            print(cleaned_chunk, end="", flush=True)

        print()  # 每个提示后换行


asyncio.run(main())
[ ]:
llm.shutdown()