SGLang Frontend Language#

SGLang frontend language can be used to define simple and easy prompts in a convenient, structured way.

Launch A Server#

Launch the server in your terminal and wait for it to initialize.

[1]:
import requests
import os

from sglang import assistant_begin, assistant_end
from sglang import assistant, function, gen, system, user
from sglang import image
from sglang import RuntimeEndpoint, set_default_backend
from sglang.srt.utils import load_image
from sglang.test.test_utils import is_in_ci
from sglang.utils import print_highlight, terminate_process, wait_for_server

if is_in_ci():
    from patch import launch_server_cmd
else:
    from sglang.utils import launch_server_cmd


server_process, port = launch_server_cmd(
    "python -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --host 0.0.0.0"
)

wait_for_server(f"http://localhost:{port}")
print(f"Server started on http://localhost:{port}")
[2025-03-16 09:52:03] server_args=ServerArgs(model_path='Qwen/Qwen2.5-7B-Instruct', tokenizer_path='Qwen/Qwen2.5-7B-Instruct', tokenizer_mode='auto', skip_tokenizer_init=False, load_format='auto', trust_remote_code=False, dtype='auto', kv_cache_dtype='auto', quantization=None, quantization_param_path=None, context_length=None, device='cuda', served_model_name='Qwen/Qwen2.5-7B-Instruct', chat_template=None, is_embedding=False, revision=None, host='0.0.0.0', port=33933, mem_fraction_static=0.88, max_running_requests=200, max_total_tokens=20480, chunked_prefill_size=8192, max_prefill_tokens=16384, schedule_policy='fcfs', schedule_conservativeness=1.0, cpu_offload_gb=0, page_size=1, tp_size=1, stream_interval=1, stream_output=False, random_seed=885926326, constrained_json_whitespace_pattern=None, watchdog_timeout=300, dist_timeout=None, download_dir=None, base_gpu_id=0, gpu_id_step=1, log_level='info', log_level_http=None, log_requests=False, log_requests_level=0, show_time_cost=False, enable_metrics=False, decode_log_interval=40, api_key=None, file_storage_path='sglang_storage', enable_cache_report=False, reasoning_parser=None, dp_size=1, load_balance_method='round_robin', ep_size=1, dist_init_addr=None, nnodes=1, node_rank=0, json_model_override_args='{}', lora_paths=None, max_loras_per_batch=8, lora_backend='triton', attention_backend='flashinfer', sampling_backend='flashinfer', grammar_backend='outlines', speculative_algorithm=None, speculative_draft_model_path=None, speculative_num_steps=5, speculative_eagle_topk=4, speculative_num_draft_tokens=8, speculative_accept_threshold_single=1.0, speculative_accept_threshold_acc=1.0, speculative_token_map=None, enable_double_sparsity=False, ds_channel_config_path=None, ds_heavy_channel_num=32, ds_heavy_token_num=256, ds_heavy_channel_type='qk', ds_sparse_decode_threshold=4096, disable_radix_cache=False, disable_cuda_graph=True, disable_cuda_graph_padding=False, enable_nccl_nvls=False, disable_outlines_disk_cache=False, disable_custom_all_reduce=False, disable_mla=False, disable_overlap_schedule=False, enable_mixed_chunk=False, enable_dp_attention=False, enable_ep_moe=False, enable_torch_compile=False, torch_compile_max_bs=32, cuda_graph_max_bs=160, cuda_graph_bs=None, torchao_config='', enable_nan_detection=False, enable_p2p_check=False, triton_attention_reduce_in_fp32=False, triton_attention_num_kv_splits=8, num_continuous_decode_steps=1, delete_ckpt_after_loading=False, enable_memory_saver=False, allow_auto_truncate=False, enable_custom_logit_processor=False, tool_call_parser=None, enable_hierarchical_cache=False, enable_flashinfer_mla=False, flashinfer_mla_disable_ragged=False, warmups=None, debug_tensor_dump_output_folder=None, debug_tensor_dump_input_file=None, debug_tensor_dump_inject=False)
[2025-03-16 09:52:24 TP0] Init torch distributed begin.
[2025-03-16 09:52:24 TP0] Init torch distributed ends. mem usage=0.00 GB
[2025-03-16 09:52:24 TP0] Load weight begin. avail mem=59.83 GB
[2025-03-16 09:52:24 TP0] The following error message 'operation scheduled before its operands' can be ignored.
[2025-03-16 09:52:25 TP0] Using model weights format ['*.safetensors']
Loading safetensors checkpoint shards:   0% Completed | 0/4 [00:00<?, ?it/s]
Loading safetensors checkpoint shards:  25% Completed | 1/4 [00:00<00:02,  1.27it/s]
Loading safetensors checkpoint shards:  50% Completed | 2/4 [00:01<00:01,  1.29it/s]
Loading safetensors checkpoint shards:  75% Completed | 3/4 [00:02<00:00,  1.27it/s]
Loading safetensors checkpoint shards: 100% Completed | 4/4 [00:03<00:00,  1.26it/s]
Loading safetensors checkpoint shards: 100% Completed | 4/4 [00:03<00:00,  1.26it/s]

[2025-03-16 09:52:28 TP0] Load weight end. type=Qwen2ForCausalLM, dtype=torch.bfloat16, avail mem=30.50 GB, mem usage=29.33 GB.
[2025-03-16 09:52:28 TP0] KV Cache is allocated. #tokens: 20480, K size: 0.55 GB, V size: 0.55 GB
[2025-03-16 09:52:28 TP0] Memory pool end. avail mem=29.20 GB
[2025-03-16 09:52:29 TP0] max_total_num_tokens=20480, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=200, context_len=32768
[2025-03-16 09:52:29] INFO:     Started server process [190849]
[2025-03-16 09:52:29] INFO:     Waiting for application startup.
[2025-03-16 09:52:29] INFO:     Application startup complete.
[2025-03-16 09:52:29] INFO:     Uvicorn running on http://0.0.0.0:33933 (Press CTRL+C to quit)
[2025-03-16 09:52:30] INFO:     127.0.0.1:50702 - "GET /v1/models HTTP/1.1" 200 OK
[2025-03-16 09:52:30] INFO:     127.0.0.1:50706 - "GET /get_model_info HTTP/1.1" 200 OK
[2025-03-16 09:52:30 TP0] Prefill batch. #new-seq: 1, #new-token: 6, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:33] INFO:     127.0.0.1:50718 - "POST /generate HTTP/1.1" 200 OK
[2025-03-16 09:52:33] The server is fired up and ready to roll!


NOTE: Typically, the server runs in a separate terminal.
In this notebook, we run the server and notebook code together, so their outputs are combined.
To improve clarity, the server logs are displayed in the original black color, while the notebook outputs are highlighted in blue.
We are running those notebooks in a CI parallel environment, so the throughput is not representative of the actual performance.
Server started on http://localhost:33933

Set the default backend. Note: Besides the local server, you may use also OpenAI or other API endpoints.

[2]:
set_default_backend(RuntimeEndpoint(f"http://localhost:{port}"))
[2025-03-16 09:52:35] INFO:     127.0.0.1:44462 - "GET /get_model_info HTTP/1.1" 200 OK

Basic Usage#

The most simple way of using SGLang frontend language is a simple question answer dialog between a user and an assistant.

[3]:
@function
def basic_qa(s, question):
    s += system(f"You are a helpful assistant than can answer questions.")
    s += user(question)
    s += assistant(gen("answer", max_tokens=512))
[4]:
state = basic_qa("List 3 countries and their capitals.")
print_highlight(state["answer"])
[2025-03-16 09:52:35 TP0] Prefill batch. #new-seq: 1, #new-token: 31, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:35 TP0] Decode batch. #running-req: 1, #token: 64, token usage: 0.00, gen throughput (token/s): 5.96, #queue-req: 0,
[2025-03-16 09:52:35] INFO:     127.0.0.1:44464 - "POST /generate HTTP/1.1" 200 OK
Sure! Here are three countries and their capitals:

1. **France** - Paris
2. **Japan** - Tokyo
3. **Australia** - Canberra

Multi-turn Dialog#

SGLang frontend language can also be used to define multi-turn dialogs.

[5]:
@function
def multi_turn_qa(s):
    s += system(f"You are a helpful assistant than can answer questions.")
    s += user("Please give me a list of 3 countries and their capitals.")
    s += assistant(gen("first_answer", max_tokens=512))
    s += user("Please give me another list of 3 countries and their capitals.")
    s += assistant(gen("second_answer", max_tokens=512))
    return s


state = multi_turn_qa()
print_highlight(state["first_answer"])
print_highlight(state["second_answer"])
[2025-03-16 09:52:35 TP0] Prefill batch. #new-seq: 1, #new-token: 18, #cached-token: 18, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:36] INFO:     127.0.0.1:44474 - "POST /generate HTTP/1.1" 200 OK
Certainly! Here are three countries along with their respective capitals:

1. **France** - Paris
2. **Italy** - Rome
3. **Japan** - Tokyo
[2025-03-16 09:52:36 TP0] Prefill batch. #new-seq: 1, #new-token: 23, #cached-token: 71, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:36 TP0] Decode batch. #running-req: 1, #token: 97, token usage: 0.00, gen throughput (token/s): 57.11, #queue-req: 0,
[2025-03-16 09:52:37] INFO:     127.0.0.1:44480 - "POST /generate HTTP/1.1" 200 OK
Of course! Here’s another list of three countries and their capitals:

1. **India** - New Delhi
2. **Germany** - Berlin
3. **Canada** - Ottawa

Control flow#

You may use any Python code within the function to define more complex control flows.

[6]:
@function
def tool_use(s, question):
    s += assistant(
        "To answer this question: "
        + question
        + ". I need to use a "
        + gen("tool", choices=["calculator", "search engine"])
        + ". "
    )

    if s["tool"] == "calculator":
        s += assistant("The math expression is: " + gen("expression"))
    elif s["tool"] == "search engine":
        s += assistant("The key word to search is: " + gen("word"))


state = tool_use("What is 2 * 2?")
print_highlight(state["tool"])
print_highlight(state["expression"])
[2025-03-16 09:52:37 TP0] Prefill batch. #new-seq: 1, #new-token: 25, #cached-token: 8, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:37] INFO:     127.0.0.1:44484 - "POST /generate HTTP/1.1" 200 OK
[2025-03-16 09:52:37 TP0] Prefill batch. #new-seq: 2, #new-token: 5, #cached-token: 62, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:37] INFO:     127.0.0.1:44492 - "POST /generate HTTP/1.1" 200 OK
calculator
[2025-03-16 09:52:37 TP0] Prefill batch. #new-seq: 1, #new-token: 13, #cached-token: 33, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:37 TP0] Decode batch. #running-req: 1, #token: 48, token usage: 0.00, gen throughput (token/s): 46.65, #queue-req: 0,
[2025-03-16 09:52:38 TP0] Decode batch. #running-req: 1, #token: 88, token usage: 0.00, gen throughput (token/s): 59.70, #queue-req: 0,
[2025-03-16 09:52:38] INFO:     127.0.0.1:44500 - "POST /generate HTTP/1.1" 200 OK
2 * 2.

Let's calculate it:
\[ 2 * 2 = 4 \]

So, the answer is 4. You didn't really need a calculator for this as it's a simple multiplication, but if you prefer to use one, you can certainly do that for such straightforward calculations.

Parallelism#

Use fork to launch parallel prompts. Because sgl.gen is non-blocking, the for loop below issues two generation calls in parallel.

[7]:
@function
def tip_suggestion(s):
    s += assistant(
        "Here are two tips for staying healthy: "
        "1. Balanced Diet. 2. Regular Exercise.\n\n"
    )

    forks = s.fork(2)
    for i, f in enumerate(forks):
        f += assistant(
            f"Now, expand tip {i+1} into a paragraph:\n"
            + gen("detailed_tip", max_tokens=256, stop="\n\n")
        )

    s += assistant("Tip 1:" + forks[0]["detailed_tip"] + "\n")
    s += assistant("Tip 2:" + forks[1]["detailed_tip"] + "\n")
    s += assistant(
        "To summarize the above two tips, I can say:\n" + gen("summary", max_tokens=512)
    )


state = tip_suggestion()
print_highlight(state["summary"])
[2025-03-16 09:52:38 TP0] Prefill batch. #new-seq: 1, #new-token: 35, #cached-token: 14, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:38 TP0] Prefill batch. #new-seq: 1, #new-token: 35, #cached-token: 14, token usage: 0.00, #running-req: 1, #queue-req: 0,
[2025-03-16 09:52:38 TP0] Decode batch. #running-req: 2, #token: 88, token usage: 0.00, gen throughput (token/s): 77.34, #queue-req: 0,
[2025-03-16 09:52:39 TP0] Decode batch. #running-req: 2, #token: 168, token usage: 0.01, gen throughput (token/s): 122.19, #queue-req: 0,
[2025-03-16 09:52:40 TP0] Decode batch. #running-req: 2, #token: 248, token usage: 0.01, gen throughput (token/s): 122.21, #queue-req: 0,
[2025-03-16 09:52:40 TP0] Decode batch. #running-req: 2, #token: 328, token usage: 0.02, gen throughput (token/s): 125.10, #queue-req: 0,
[2025-03-16 09:52:41] INFO:     127.0.0.1:44524 - "POST /generate HTTP/1.1" 200 OK
[2025-03-16 09:52:41 TP0] Decode batch. #running-req: 1, #token: 226, token usage: 0.01, gen throughput (token/s): 86.91, #queue-req: 0,
[2025-03-16 09:52:41] INFO:     127.0.0.1:44516 - "POST /generate HTTP/1.1" 200 OK
[2025-03-16 09:52:41 TP0] Prefill batch. #new-seq: 1, #new-token: 380, #cached-token: 39, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:42 TP0] Decode batch. #running-req: 1, #token: 436, token usage: 0.02, gen throughput (token/s): 57.34, #queue-req: 0,
[2025-03-16 09:52:42 TP0] Decode batch. #running-req: 1, #token: 476, token usage: 0.02, gen throughput (token/s): 60.73, #queue-req: 0,
[2025-03-16 09:52:43 TP0] Decode batch. #running-req: 1, #token: 516, token usage: 0.03, gen throughput (token/s): 64.00, #queue-req: 0,
[2025-03-16 09:52:44 TP0] Decode batch. #running-req: 1, #token: 556, token usage: 0.03, gen throughput (token/s): 64.06, #queue-req: 0,
[2025-03-16 09:52:44 TP0] Decode batch. #running-req: 1, #token: 596, token usage: 0.03, gen throughput (token/s): 63.85, #queue-req: 0,
[2025-03-16 09:52:45 TP0] Decode batch. #running-req: 1, #token: 636, token usage: 0.03, gen throughput (token/s): 62.61, #queue-req: 0,
[2025-03-16 09:52:46 TP0] Decode batch. #running-req: 1, #token: 676, token usage: 0.03, gen throughput (token/s): 59.28, #queue-req: 0,
[2025-03-16 09:52:46 TP0] Decode batch. #running-req: 1, #token: 716, token usage: 0.03, gen throughput (token/s): 61.51, #queue-req: 0,
[2025-03-16 09:52:47] INFO:     127.0.0.1:57034 - "POST /generate HTTP/1.1" 200 OK
1. **Balanced Diet:** Eating a balanced diet is crucial for maintaining overall health and well-being. It involves consuming a variety of foods in the correct proportions to meet your nutritional needs. A balanced diet should include:

- Carbohydrates, such as fruits, vegetables, and whole grains, which are your body's main energy source.
- Proteins from sources like lean meats, fish, dairy, and legumes, which are essential for cellular repair and growth.
- Healthy fats, from foods like avocados, nuts, and olive oil, which provide the body with energy and support brain health.
- Vitamins and minerals, which can be found in a variety of foods such as vegetables, fruits, and seeds, which are necessary for bodily functions and preventing deficiencies.
- Staying hydrated by drinking enough water.

2. **Regular Exercise:** Engaging in regular exercise helps maintain a healthy weight, strengthens your muscles and bones, and can help prevent chronic diseases such as heart disease, diabetes, and some forms of cancer. It also boosts your mood, reduces stress, and improves your overall mental health. Examples of aerobic activities include jogging, swimming, and cycling, while strength training exercises include activities like weightlifting or bodyweight exercises. Aim for at least:

- 150 minutes of moderate aerobic activity per week.
- Or 75 minutes of vigorous aerobic activity per week.
- Or a combination of both.
- Including strength training exercises at least two days a week.

By following these two tips, you can significantly enhance your physical and mental health, leading to a more vibrant and active lifestyle.

Constrained Decoding#

Use regex to specify a regular expression as a decoding constraint. This is only supported for local models.

[8]:
@function
def regular_expression_gen(s):
    s += user("What is the IP address of the Google DNS servers?")
    s += assistant(
        gen(
            "answer",
            temperature=0,
            regex=r"((25[0-5]|2[0-4]\d|[01]?\d\d?).){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)",
        )
    )


state = regular_expression_gen()
print_highlight(state["answer"])
[2025-03-16 09:52:47 TP0] Prefill batch. #new-seq: 1, #new-token: 18, #cached-token: 12, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:48 TP0] Decode batch. #running-req: 1, #token: 33, token usage: 0.00, gen throughput (token/s): 26.51, #queue-req: 0,
[2025-03-16 09:52:48] INFO:     127.0.0.1:57044 - "POST /generate HTTP/1.1" 200 OK
208.67.222.222

Use regex to define a JSON decoding schema.

[9]:
character_regex = (
    r"""\{\n"""
    + r"""    "name": "[\w\d\s]{1,16}",\n"""
    + r"""    "house": "(Gryffindor|Slytherin|Ravenclaw|Hufflepuff)",\n"""
    + r"""    "blood status": "(Pure-blood|Half-blood|Muggle-born)",\n"""
    + r"""    "occupation": "(student|teacher|auror|ministry of magic|death eater|order of the phoenix)",\n"""
    + r"""    "wand": \{\n"""
    + r"""        "wood": "[\w\d\s]{1,16}",\n"""
    + r"""        "core": "[\w\d\s]{1,16}",\n"""
    + r"""        "length": [0-9]{1,2}\.[0-9]{0,2}\n"""
    + r"""    \},\n"""
    + r"""    "alive": "(Alive|Deceased)",\n"""
    + r"""    "patronus": "[\w\d\s]{1,16}",\n"""
    + r"""    "bogart": "[\w\d\s]{1,16}"\n"""
    + r"""\}"""
)


@function
def character_gen(s, name):
    s += user(
        f"{name} is a character in Harry Potter. Please fill in the following information about this character."
    )
    s += assistant(gen("json_output", max_tokens=256, regex=character_regex))


state = character_gen("Harry Potter")
print_highlight(state["json_output"])
[2025-03-16 09:52:49 TP0] Prefill batch. #new-seq: 1, #new-token: 24, #cached-token: 14, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:49 TP0] Decode batch. #running-req: 1, #token: 66, token usage: 0.00, gen throughput (token/s): 35.22, #queue-req: 0,
[2025-03-16 09:52:49 TP0] Decode batch. #running-req: 1, #token: 106, token usage: 0.01, gen throughput (token/s): 99.41, #queue-req: 0,
[2025-03-16 09:52:50 TP0] Decode batch. #running-req: 1, #token: 146, token usage: 0.01, gen throughput (token/s): 96.04, #queue-req: 0,
[2025-03-16 09:52:50] INFO:     127.0.0.1:57054 - "POST /generate HTTP/1.1" 200 OK
{
"name": "Harry Potter",
"house": "Gryffindor",
"blood status": "Half-blood",
"occupation": "student",
"wand": {
"wood": "Holly",
"core": "Phoenix Feather",
"length": 11.0
},
"alive": "Alive",
"patronus": "Stag",
"bogart": "Quiditch_referee"
}

Batching#

Use run_batch to run a batch of prompts.

[10]:
@function
def text_qa(s, question):
    s += user(question)
    s += assistant(gen("answer", stop="\n"))


states = text_qa.run_batch(
    [
        {"question": "What is the capital of the United Kingdom?"},
        {"question": "What is the capital of France?"},
        {"question": "What is the capital of Japan?"},
    ],
    progress_bar=True,
)

for i, state in enumerate(states):
    print_highlight(f"Answer {i+1}: {states[i]['answer']}")
[2025-03-16 09:52:50 TP0] Prefill batch. #new-seq: 1, #new-token: 1, #cached-token: 13, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:50] INFO:     127.0.0.1:57056 - "POST /generate HTTP/1.1" 200 OK
  0%|          | 0/3 [00:00<?, ?it/s]
[2025-03-16 09:52:50 TP0] Prefill batch. #new-seq: 1, #new-token: 9, #cached-token: 17, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:50 TP0] Prefill batch. #new-seq: 2, #new-token: 20, #cached-token: 34, token usage: 0.00, #running-req: 1, #queue-req: 0,
100%|██████████| 3/3 [00:00<00:00, 22.30it/s]
[2025-03-16 09:52:50] INFO:     127.0.0.1:57058 - "POST /generate HTTP/1.1" 200 OK
[2025-03-16 09:52:50] INFO:     127.0.0.1:57074 - "POST /generate HTTP/1.1" 200 OK
[2025-03-16 09:52:50] INFO:     127.0.0.1:57090 - "POST /generate HTTP/1.1" 200 OK

Answer 1: The capital of the United Kingdom is London.
Answer 2: The capital of France is Paris.
Answer 3: The capital of Japan is Tokyo.

Streaming#

Use stream to stream the output to the user.

[11]:
@function
def text_qa(s, question):
    s += user(question)
    s += assistant(gen("answer", stop="\n"))


state = text_qa.run(
    question="What is the capital of France?", temperature=0.1, stream=True
)

for out in state.text_iter():
    print(out, end="", flush=True)
<|im_start|>system
You are a helpful assistant.<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant
[2025-03-16 09:52:50] INFO:     127.0.0.1:57100 - "POST /generate HTTP/1.1" 200 OK
[2025-03-16 09:52:50 TP0] Prefill batch. #new-seq: 1, #new-token: 1, #cached-token: 25, token usage: 0.00, #running-req: 0, #queue-req: 0,
The capital of France is Paris.<|im_end|>

Complex Prompts#

You may use {system|user|assistant}_{begin|end} to define complex prompts.

[12]:
@function
def chat_example(s):
    s += system("You are a helpful assistant.")
    # Same as: s += s.system("You are a helpful assistant.")

    with s.user():
        s += "Question: What is the capital of France?"

    s += assistant_begin()
    s += "Answer: " + gen("answer", max_tokens=100, stop="\n")
    s += assistant_end()


state = chat_example()
print_highlight(state["answer"])
[2025-03-16 09:52:50 TP0] Prefill batch. #new-seq: 1, #new-token: 17, #cached-token: 14, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:52:50] INFO:     127.0.0.1:57110 - "POST /generate HTTP/1.1" 200 OK
The capital of France is Paris.
[13]:
terminate_process(server_process)

Multi-modal Generation#

You may use SGLang frontend language to define multi-modal prompts. See here for supported models.

[14]:
server_process, port = launch_server_cmd(
    "python -m sglang.launch_server --model-path Qwen/Qwen2.5-VL-7B-Instruct --host 0.0.0.0"
)

wait_for_server(f"http://localhost:{port}")
print(f"Server started on http://localhost:{port}")
[2025-03-16 09:53:09] server_args=ServerArgs(model_path='Qwen/Qwen2.5-VL-7B-Instruct', tokenizer_path='Qwen/Qwen2.5-VL-7B-Instruct', tokenizer_mode='auto', skip_tokenizer_init=False, load_format='auto', trust_remote_code=False, dtype='auto', kv_cache_dtype='auto', quantization=None, quantization_param_path=None, context_length=None, device='cuda', served_model_name='Qwen/Qwen2.5-VL-7B-Instruct', chat_template=None, is_embedding=False, revision=None, host='0.0.0.0', port=37650, mem_fraction_static=0.88, max_running_requests=200, max_total_tokens=20480, chunked_prefill_size=8192, max_prefill_tokens=16384, schedule_policy='fcfs', schedule_conservativeness=1.0, cpu_offload_gb=0, page_size=1, tp_size=1, stream_interval=1, stream_output=False, random_seed=527852539, constrained_json_whitespace_pattern=None, watchdog_timeout=300, dist_timeout=None, download_dir=None, base_gpu_id=0, gpu_id_step=1, log_level='info', log_level_http=None, log_requests=False, log_requests_level=0, show_time_cost=False, enable_metrics=False, decode_log_interval=40, api_key=None, file_storage_path='sglang_storage', enable_cache_report=False, reasoning_parser=None, dp_size=1, load_balance_method='round_robin', ep_size=1, dist_init_addr=None, nnodes=1, node_rank=0, json_model_override_args='{}', lora_paths=None, max_loras_per_batch=8, lora_backend='triton', attention_backend='flashinfer', sampling_backend='flashinfer', grammar_backend='outlines', speculative_algorithm=None, speculative_draft_model_path=None, speculative_num_steps=5, speculative_eagle_topk=4, speculative_num_draft_tokens=8, speculative_accept_threshold_single=1.0, speculative_accept_threshold_acc=1.0, speculative_token_map=None, enable_double_sparsity=False, ds_channel_config_path=None, ds_heavy_channel_num=32, ds_heavy_token_num=256, ds_heavy_channel_type='qk', ds_sparse_decode_threshold=4096, disable_radix_cache=False, disable_cuda_graph=True, disable_cuda_graph_padding=False, enable_nccl_nvls=False, disable_outlines_disk_cache=False, disable_custom_all_reduce=False, disable_mla=False, disable_overlap_schedule=False, enable_mixed_chunk=False, enable_dp_attention=False, enable_ep_moe=False, enable_torch_compile=False, torch_compile_max_bs=32, cuda_graph_max_bs=160, cuda_graph_bs=None, torchao_config='', enable_nan_detection=False, enable_p2p_check=False, triton_attention_reduce_in_fp32=False, triton_attention_num_kv_splits=8, num_continuous_decode_steps=1, delete_ckpt_after_loading=False, enable_memory_saver=False, allow_auto_truncate=False, enable_custom_logit_processor=False, tool_call_parser=None, enable_hierarchical_cache=False, enable_flashinfer_mla=False, flashinfer_mla_disable_ragged=False, warmups=None, debug_tensor_dump_output_folder=None, debug_tensor_dump_input_file=None, debug_tensor_dump_inject=False)
Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.48, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.
Using a slow image processor as `use_fast` is unset and a slow processor was saved with this model. `use_fast=True` will be the default behavior in v4.48, even if the model was saved with a slow processor. This will result in minor differences in outputs. You'll still be able to use a slow processor with `use_fast=False`.
[2025-03-16 09:53:32 TP0] Overlap scheduler is disabled for multimodal models.
[2025-03-16 09:53:32 TP0] Automatically reduce --mem-fraction-static to 0.836 because this is a multimodal model.
[2025-03-16 09:53:32 TP0] Init torch distributed begin.
[2025-03-16 09:53:32 TP0] Init torch distributed ends. mem usage=0.00 GB
[2025-03-16 09:53:32 TP0] Load weight begin. avail mem=78.81 GB
[2025-03-16 09:53:33 TP0] The following error message 'operation scheduled before its operands' can be ignored.
[2025-03-16 09:53:33 TP0] Using model weights format ['*.safetensors']
Loading safetensors checkpoint shards:   0% Completed | 0/5 [00:00<?, ?it/s]
Loading safetensors checkpoint shards:  20% Completed | 1/5 [00:00<00:03,  1.06it/s]
Loading safetensors checkpoint shards:  40% Completed | 2/5 [00:01<00:02,  1.10it/s]
Loading safetensors checkpoint shards:  60% Completed | 3/5 [00:02<00:01,  1.57it/s]
Loading safetensors checkpoint shards:  80% Completed | 4/5 [00:02<00:00,  1.49it/s]
Loading safetensors checkpoint shards: 100% Completed | 5/5 [00:03<00:00,  1.37it/s]
Loading safetensors checkpoint shards: 100% Completed | 5/5 [00:03<00:00,  1.35it/s]

[2025-03-16 09:53:37 TP0] Load weight end. type=Qwen2_5_VLForConditionalGeneration, dtype=torch.bfloat16, avail mem=63.02 GB, mem usage=15.79 GB.
[2025-03-16 09:53:37 TP0] KV Cache is allocated. #tokens: 20480, K size: 0.55 GB, V size: 0.55 GB
[2025-03-16 09:53:37 TP0] Memory pool end. avail mem=61.65 GB
[2025-03-16 09:53:39 TP0] max_total_num_tokens=20480, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=200, context_len=128000
[2025-03-16 09:53:39] INFO:     Started server process [194167]
[2025-03-16 09:53:39] INFO:     Waiting for application startup.
[2025-03-16 09:53:39] INFO:     Application startup complete.
[2025-03-16 09:53:39] INFO:     Uvicorn running on http://0.0.0.0:37650 (Press CTRL+C to quit)
[2025-03-16 09:53:39] INFO:     127.0.0.1:60062 - "GET /v1/models HTTP/1.1" 200 OK
[2025-03-16 09:53:40] INFO:     127.0.0.1:60078 - "GET /get_model_info HTTP/1.1" 200 OK
[2025-03-16 09:53:40 TP0] Prefill batch. #new-seq: 1, #new-token: 6, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:53:44] INFO:     127.0.0.1:60084 - "POST /generate HTTP/1.1" 200 OK
[2025-03-16 09:53:44] The server is fired up and ready to roll!


NOTE: Typically, the server runs in a separate terminal.
In this notebook, we run the server and notebook code together, so their outputs are combined.
To improve clarity, the server logs are displayed in the original black color, while the notebook outputs are highlighted in blue.
We are running those notebooks in a CI parallel environment, so the throughput is not representative of the actual performance.
Server started on http://localhost:37650
[15]:
set_default_backend(RuntimeEndpoint(f"http://localhost:{port}"))
[2025-03-16 09:53:44] INFO:     127.0.0.1:52044 - "GET /get_model_info HTTP/1.1" 200 OK

Ask a question about an image.

[16]:
@function
def image_qa(s, image_file, question):
    s += user(image(image_file) + question)
    s += assistant(gen("answer", max_tokens=256))


image_url = "https://github.com/sgl-project/sglang/blob/main/test/lang/example_image.png?raw=true"
image_bytes, _ = load_image(image_url)
state = image_qa(image_bytes, "What is in the image?")
print_highlight(state["answer"])
[2025-03-16 09:53:56 TP0] Prefill batch. #new-seq: 1, #new-token: 307, #cached-token: 0, token usage: 0.00, #running-req: 0, #queue-req: 0,
[2025-03-16 09:54:01 TP0] Decode batch. #running-req: 1, #token: 340, token usage: 0.02, gen throughput (token/s): 1.85, #queue-req: 0,
[2025-03-16 09:54:01] INFO:     127.0.0.1:52048 - "POST /generate HTTP/1.1" 200 OK
The image shows a man balancing on one leg, with parts of Continuing Education (CE) flyers being trampled or lying beneath increasingly higher stacks erected on crutches hovering in anticipation—at the back bumper.
[17]:
terminate_process(server_process)
[2025-03-16 09:54:01] Child process unexpectedly failed with an exit code 9. pid=194803
[2025-03-16 09:54:01] Child process unexpectedly failed with an exit code 9. pid=194734