# PaddleOCR-VL Source: https://docs.sglang.io/cookbook/autoregressive/Baidu/PaddleOCR-VL Deploy PaddleOCR-VL 1.6 / 1.5 / 0.9B with SGLang — Baidu's 0.9B NaViT + ERNIE-4.5 document-parsing VLM for OCR, tables, formulas and charts in 109 languages, on a single H100, H200 or B200. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick a release and your hardware to generate the launch command. The model is 0.9B and single-GPU, so there is one serving recipe per platform; the axis that actually moves cost is **Page Resolution**, which caps how many image tokens one page is worth. ## Playground Use the Playground to layer tensor parallelism on top of the selected deployment cell. At this size TP is a latency knob, not a capacity one — the weights fit on one GPU. ## 1. Model Introduction **PaddleOCR-VL** is Baidu's compact document-parsing vision-language model: a NaViT-style dynamic-resolution SigLIP vision encoder feeding an **ERNIE-4.5-0.3B** language backbone, 0.9B parameters in total, released under **Apache 2.0**. It recognizes text, tables, formulas, charts and seals across **109 languages**, and is small enough that a single GPU serves it comfortably. SGLang serves **this model**, which is the recognition stage of PaddleOCR's document-parsing pipeline — not the pipeline itself. Layout and region detection, cropping, reading order and the assembly of markdown or JSON stay in PaddleOCR, which calls a model endpoint once per region. That split is why the model is prompt-conditioned rather than instruction-following: the caller decides whether a crop is a table, a formula or a chart (§3.1), and SGLang is the backend that answers. All three releases share an identical `config.json` (same `PaddleOCRVLForConditionalGeneration` architecture, same tower and backbone dimensions), so one SGLang recipe serves every variant and only the model path changes.
Variant Total params Use
**[PaddleOCR-VL-1.6](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6)** 0.9B Latest. Best tables, Chinese characters and seals; drop-in for 1.5.
**[PaddleOCR-VL-1.5](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.5)** 0.9B Previous generation; pin it if you have calibrated against its output.
**[PaddleOCR-VL](https://huggingface.co/PaddlePaddle/PaddleOCR-VL)** 0.9B The original 0.9B release.
**Recommended generation:** greedy decoding (`temperature=0`) with a per-page `max_tokens` budget — the model card uses 512 for a single region and the reference server allows more for a full page. These are informational; do not hardcode them in library code. **Resources:** [Hugging Face](https://huggingface.co/PaddlePaddle/PaddleOCR-VL-1.6) · [PaddleOCR on GitHub](https://github.com/PaddlePaddle/PaddleOCR) ## 2. Configuration Tips * **Page resolution is the main cost knob.** The vision tower and the prefill both scale with the patch count of a page. `max_pixels` is expressed in 28x28 units (patch size 14 with a 2x2 merge), so `max_pixels / 784` is the image-token budget per page. The checkpoint's own default is 1280 tokens; the **Page Resolution** selector in the Deploy panel emits the corresponding `--mm-process-config` value. Lower it for clean born-digital PDFs, raise it for dense scans and small print. * **Prompt selects the task.** PaddleOCR-VL is prompt-conditioned rather than instruction-following — use the exact task strings in §3.1. A free-form question will not behave like a chat model. * **Leave `--trust-remote-code` off.** The checkpoints ship their own `configuration_paddleocr_vl.py` / `processing_paddleocr_vl.py`, but `transformers` 5.12 supports `paddleocr_vl` natively — and the bundled remote image processor is the slower of the two implementations (measured 87.4 ms vs 39.1 ms per 1080p page). Passing the flag pins SGLang to the remote copy. Serving without it produced byte-identical OCR output on every page we checked and about 5% more requests per second at 32-way concurrency. * **Preprocessing is parallelized for you.** A full-resolution page costs tens of milliseconds of CPU to resize, normalize and patchify, which caps throughput long before the GPU saturates, so this model runs the image processor across several workers by default. `--mm-processor-worker-num` overrides the count; raising it past the default did not help in our measurements. * **Keep the radix cache on for repeated pages.** Unlike whole-document batch OCR over unique scans, a workload that re-asks about the same page (different task prompts on one image) reuses the image prefix. Add `--disable-radix-cache` only if every request carries a different page. * **The saturated-throughput flags earn their place.** A page is \~2700 tokens, so the default 8192-token prefill budget packs only three of them into a forward. Raising it to 16384 and letting decode ride along in the same batch (`--enable-mixed-chunk`, `--num-continuous-decode-steps 2`) measured +11% requests per second at 32-way concurrency and cut queued TTFT by 23%, with single-stream latency unchanged. Measured on an H200; on a smaller card lower `--chunked-prefill-size` until it fits. * **Prefill CUDA graph is on for this model.** SGLang normally switches the breakable prefill graph off for every multimodal architecture; PaddleOCR-VL is allowlisted back in, which is worth 16.1 ms → 11.5 ms of single-stream TTFT on text-only prompts. Image-carrying batches are rejected at graph replay and run eager, so this helps mixed and text traffic, not pure page parsing. No flag needed. * **Tensor parallelism is optional.** The weights are under 2 GB in BF16; TP>1 only shortens the vision-encoder and prefill critical path, at the cost of a collective per layer. Measure before adopting it. * **Context length.** The backbone advertises 131072 positions, but a parsed page rarely needs more than a few thousand tokens. The recipe pins `--context-length 16384` so the KV pool stays small and concurrency stays high; raise it only if you batch many pages into one request. ### Measured on one H200 One 1080p page (\~2700 image tokens) in, 128 tokens out, prefix cache disabled, median TTFT:
Configuration TTFT, 1 stream req/s at 32 concurrent
With `--trust-remote-code` (remote image processor) 219 ms 10.9
Recipe above (native image processor) **114 ms** **11.3**
Throughput at saturation is bound by the vision tower, which runs full attention over every patch of the page — so the **Page Resolution** selector is the lever that moves it, not tensor parallelism. ## 3. Advanced Usage ### 3.1 Task prompts PaddleOCR-VL exposes its capabilities through a small set of fixed prompts. Send the prompt as the text part and the page as the image part of the same user turn.
Prompt Task
`OCR:` Plain text recognition.
`Table Recognition:` Table structure and cell contents.
`Formula Recognition:` Mathematical expressions.
`Chart Recognition:` Chart contents.
`Spotting:` Text with locations. Benefits from the high-detail resolution setting.
`Seal Recognition:` Seals and stamps (1.6).
Structured tasks answer in the model's own markup, not HTML: `Table Recognition:` returns OTSL-style cell tokens (`` per cell, `` per row), so a caller that wants HTML or markdown converts them itself. > **Table Recognition Output** > > ```text Output theme={null} > MethodsRPFFPSSegLink [26]70.086.077.08.9PixelLink [4]73.283.077.8-TextSnake [18]73.983.278.31.1 > ... (one per cell, one per row, to the end of the table) > ``` > **OCR Request (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="PaddlePaddle/PaddleOCR-VL-1.6", > messages=[ > { > "role": "user", > "content": [ > {"type": "text", "text": "OCR:"}, > { > "type": "image_url", > "image_url": { > "url": "https://raw.githubusercontent.com/PaddlePaddle/PaddleOCR/release/2.9/doc/imgs_en/img_12.jpg" > }, > }, > ], > } > ], > max_tokens=2048, > ) > > print(response.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > ACKNOWLEDGEMENTS > We would like to thank all the designers and contributors who have been involved in the > production of this book; their contributions have been indispensable to its creation. We would > also like to express our gratitude to all the producers for their invaluable opinions and > assistance throughout this project. And to the many others whose names are not credited but > have made specific input in this book, we thank you for your continuous support. > ``` ### 3.2 Parsing a multi-page document The model parses one page per request. Render each page to an image, then fan the pages out concurrently — SGLang batches the vision encoders of in-flight requests into a single forward, so concurrency is what keeps the GPU busy on a model this small. > **Concurrent Page Parsing (Python)** > > ```python Example theme={null} > import base64 > from concurrent.futures import ThreadPoolExecutor > > import pymupdf > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > > def render(page, dpi=200): > pixmap = page.get_pixmap(dpi=dpi) > return base64.b64encode(pixmap.tobytes("png")).decode("ascii") > > > def parse(page_png_b64): > response = client.chat.completions.create( > model="PaddlePaddle/PaddleOCR-VL-1.6", > messages=[ > { > "role": "user", > "content": [ > {"type": "text", "text": "OCR:"}, > { > "type": "image_url", > "image_url": { > "url": f"data:image/png;base64,{page_png_b64}" > }, > }, > ], > } > ], > max_tokens=2048, > ) > return response.choices[0].message.content > > > document = pymupdf.open("your_document.pdf") > pages = [render(page) for page in document] > > with ThreadPoolExecutor(max_workers=16) as pool: > for index, text in enumerate(pool.map(parse, pages)): > print(f"--- page {index + 1} ---") > print(text) > ``` > **Example Output** > > ```text Output theme={null} > --- page 1 --- > (a) Total-Text > (b) Total-Text > (c) CTW1500 > (d) CTW1500 > > Figure 8. Visual experimental results. The blue contours are boundary proposals, and the > green contours are final detection boundaries. > Table 6. Experimental results on CTW-1500. > Methods > Ext > R > P > F > FPS > TextSnake [18] > Syn > 85.3 > 67.9 > 75.6 > - > ... (page continues) > --- page 2 --- > ... (one block per page, in page order) > ``` # Unlimited-OCR Source: https://docs.sglang.io/cookbook/autoregressive/Baidu/Unlimited-OCR Deploy Baidu Unlimited-OCR with SGLang for long document OCR using prefill-aware sliding-window attention. ## Deployment > **Install SGLang** > > Unlimited-OCR support is in [SGLang PR #29186](https://github.com/sgl-project/sglang/pull/29186). Until that PR is included in a tagged SGLang release, install from a build that contains the PR. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install -U uv > uv venv --python 3.12 && source .venv/bin/activate > > git clone https://github.com/sgl-project/sglang.git > cd sglang > git fetch origin pull/29186/head && git checkout FETCH_HEAD > uv pip install --prerelease=allow -e python > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your hardware to generate the launch command. The recipe uses FlashAttention-3 with `--page-size 1`, which is required by the current prefill-aware sliding-window attention path. It also disables radix cache by default, which is the better fit for batch OCR workloads where each request usually contains a different image. ## Playground Use the Playground to adjust tensor parallelism on top of the selected deployment cell. ## 1. Model Introduction [Unlimited-OCR](https://huggingface.co/baidu/Unlimited-OCR) is Baidu's multimodal OCR model for document parsing. It uses a sliding-window language backbone, but SGLang serves it with a prefill-aware sliding-window path so image and prompt tokens remain visible during long decode. The SGLang integration loads the standalone Unlimited-OCR architecture with SAM and CLIP vision encoders plus a DeepSeek-style language backbone. It supports OpenAI-compatible image requests and model-specific image processing options through `images_config`. **Resources:** [Hugging Face](https://huggingface.co/baidu/Unlimited-OCR) · [SGLang PR #29186](https://github.com/sgl-project/sglang/pull/29186) ## 2. Configuration Tips * **Attention backend**: use `--attention-backend fa3 --page-size 1`. The prefill-aware SWA page table is built with token-level locations, so page size 1 is required. * **Radix cache**: keep `--disable-radix-cache` for batch OCR over different documents. If your workload repeatedly asks about the same image and prompt, remove this flag to allow prefix reuse through `PureSWARadixCache`. * **Long OCR generations**: keep the default prefill-aware SWA path enabled. It retains prompt and image KV while still applying a sliding window to generated text. * **Custom logit processor**: keep `--enable-custom-logit-processor` in the launch command. * **Image modes**: pass `images_config.image_mode` per request. Supported modes are `tiny`, `small`, `base`, `large`, and `gundam`. Multiple images are supported only for `tiny`, `small`, and `base`. * **Default image mode**: when `images_config.image_mode` is omitted, SGLang uses `gundam`. ## 3. Advanced Usage ### 3.1 OCR request > **OCR Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="baidu/Unlimited-OCR", > messages=[ > { > "role": "user", > "content": [ > {"type": "text", "text": "document parsing."}, > { > "type": "image_url", > "image_url": { > "url": "https://example.com/your_document.png" > }, > }, > ], > } > ], > max_tokens=2048, > temperature=0, > extra_body={"images_config": {"image_mode": "gundam"}}, > ) > > print(response.choices[0].message.content) > ``` ### 3.2 Choosing an image mode Use lower modes to reduce prefill cost for simple images, and use `gundam` for high-detail document parsing.
Mode Use Multiple images
`tiny` Lowest prefill cost. Yes
`small` Lightweight OCR requests. Yes
`base` Balanced quality and cost. Yes
`large` Higher resolution single-image OCR. No
`gundam` Default high-detail document parsing mode. No
# Clef Source: https://docs.sglang.io/cookbook/autoregressive/Cloudflare/clef Deploy Cloudflare's Clef 27B and Clef Flash 9B decision models with SGLang. Select either variant for BF16 text and image decisions on one NVIDIA B200, B300, or H200. ## Deployment > **Install SGLang** > > Clef support merged after v0.5.21 in [#42721](https://github.com/sgl-project/sglang/pull/42721). Use the pinned nightly wheel or Docker image below. See the [installation guide](/docs/get-started/install) for other methods. > > **Python (pip / uv)** > > This command selects the wheel from [nightly build 37ae292e6f](https://github.com/sgl-project/sglang/actions/runs/37897861964), which includes Clef support. It targets Python 3.10 on Linux x86\_64 with glibc 2.39 or newer. > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv venv --python 3.10 > source .venv/bin/activate > uv pip install --prerelease=allow --index-strategy unsafe-best-match --extra-index-url https://docs.sglang.ai/whl/cu130/ "sglang==0.5.22.dev20261009+g37ae292e6f" > ``` > > Run the command from the wizard’s Python tab in this environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-clef > ``` > > The [Clef image build](https://github.com/sgl-project/sglang/actions/runs/37893990016) produces this image from the #42721 merge commit. Run the command from the wizard’s Docker tab. Both checkpoints are public; no Hugging Face token is required. Choose your GPU, then Clef or Clef Flash. The wizard updates the model in the launch command and sample request. Both models run on one GPU in BF16 with TP=1 using the default settings; the commands need only the model path, host, and port. ## 1. Model introduction Cloudflare post-trained Clef from Qwen3.8-27B and Clef Flash from Qwen3.5-9B, then released both under the Apache-2.0 license. Each model keeps its backbone and vision encoder and adds a joint schema head. The head reads the backbone’s final hidden states, routes state evidence to each option, and lets questions attend to one another. It returns one logit per allowed option in a single prefill, with no text generation.
Variant Checkpoint Backbone
Clef (27B) [Cloudflare/clef](https://huggingface.co/Cloudflare/clef) Qwen3.8-27B
Clef Flash (9B) [Cloudflare/clef-flash](https://huggingface.co/Cloudflare/clef-flash) Qwen3.5-9B
Pass a text string, JSON object, or JSON array as the state, with optional images. `/v1/systemone` returns one answer per question: a `choice` over allowed options, a `noul` probability of true, or a `score` over ordered levels. ## 2. Configuration tips * **Route.** Send requests to `/v1/systemone`, or set your System One client’s base URL to the server. This includes TypeSafe SDK clients. See the [API reference](/docs/supported-models/decision_models#system-one-compatible-api) for request and response fields. Clef refuses `/v1/decisions`, chat, and generation requests. * **One GPU, one prefill per request.** Keep TP=1 and PP=1. All questions share one prompt, so the model reads the state once. SGLang detects `joint_head_config.json`, loads `joint_head.safetensors`, and enables embedding mode. It disables radix caching, chunked prefill, and CUDA graphs. No reasoning parser, tool-call parser, or chat-template override is needed. * **Answers.** `probabilities` are the softmax of the head’s logits for each question. `confidence` uses the System One adapter formulas. It can differ from the checkpoint’s reference `systemone()`, which reports the top option’s probability as confidence. Answers omit `x_label_mass` because the head scores only the allowed options. * **Long states.** Prompts, including images, are capped at 16,384 tokens, the reference `encode_record` function’s default `max_length`. The effective limit can be lower, depending on the server context, KV token pool, and `--max-prefill-tokens`. The server truncates the state to leave room for the questions and images. If those do not fit even without the state, it rejects the request. * **Images.** Send each image in `images` as a data URL, such as `data:image/jpeg;base64,...`, or an HTTP(S) URL. Keep the data-URL prefix for JPEGs: bare base64 starts with `/`, which the loader treats as a file path, causing the request to fail. Images precede the state. ## 3. Advanced usage ### 3.1 Text decisions Set `MODEL` to the checkpoint you selected in the wizard. The request works with either variant. > **Text decision example (Python)** > > ```python Example theme={null} > import requests > > MODEL = "Cloudflare/clef-flash" # Or "Cloudflare/clef". > > response = requests.post( > "http://localhost:30000/v1/systemone", > json={ > "model": MODEL, > "state": "My Stripe integration keeps failing. I am losing sales. Please help ASAP.", > "questions": { > "routing": { > "type": "choice", > "instructions": "Which team should handle this request?", > "criteria": { > "billing": "Charges and refunds", > "technical_support": "Integration errors", > "sales": "Questions about buying a product", > }, > }, > "urgency": {"type": "noul", "instructions": "Does this message express urgency?"}, > "frustration": { > "type": "score", > "instructions": "How frustrated is the customer?", > "criteria": ["Calm", "Frustrated but civil", "Very angry"], > }, > }, > }, > timeout=60, > ) > response.raise_for_status() > answers = response.json()["answers"] > print("Routing:", answers["routing"]["choice"]) > print("Urgency:", answers["urgency"]["noul"]) > print("Frustration:", answers["frustration"]["score"]) > print("Usage:", response.json()["usage"]) > ``` > **Example output** > > Captured with Clef Flash on one H200. Probabilities can vary with the model variant, hardware, and numerical backend. > > ```text Output theme={null} > Routing: technical_support > Urgency: 0.9492946352021694 > Frustration: 1.7297646970642042 > Usage: {'input_tokens': 334, 'output_tokens': 0} > ``` ## 4. GSM8K accuracy [Decision Index 0.2.1](https://github.com/apolinario/decision-index/blob/9eb2dbe2a358004c8782c66e40a83ac07b953fec/docs/suite.md) evaluates all 1,319 GSM8K test problems with both four-choice and ten-choice questions, for 2,638 requests per configuration. The table reports accuracy across both formats through `/v1/systemone`. | Model | [Reported](https://huggingface.co/Cloudflare/clef#results) | H200 | B200 | B300 | | - | -: | -: | -: | -: | | Clef | 80.8% | 80.71% | 80.59% | 80.59% | | Clef Flash | 67.3% | 67.32% | 67.36% | 67.36% | All runs use BF16 and TP=1 on one GPU. # Ornith-1.0 Source: https://docs.sglang.io/cookbook/autoregressive/DeepReinforce/Ornith-1.0 Deploy DeepReinforce Ornith-1.0 with SGLang - a self-improving agentic-coding model family with 397B, 35B, and 9B checkpoints plus FP8 and GGUF variants. ## Deployment > **Install SGLang** > > Ornith-1.0 model cards recommend SGLang `>=0.5.9`. The Deploy panel below emits the base serve command; the reasoning and tool-call parsers from the model-card quickstarts (`--reasoning-parser qwen3` for `...` traces, `--tool-call-parser qwen3_coder` for Qwen-style XML tool calls) are added on top via the [Playground](#playground). > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow "sglang>=0.5.9" > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > For how to launch the image, see [Install -> Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick an Ornith checkpoint to generate the launch command. The non-FP8 397B recipe requires an H200 single node in this matrix. The 397B-FP8 recipe is available on H100 and H200 with TP=8; H100 also supports the 35B and 9B checkpoints. The 35B recipes use tensor parallelism 2 in this matrix. The 9B checkpoint is dense and serves on a single GPU by default; the command panel makes that default explicit with `--tp 1`. ## Playground The Playground layers SGLang features on top of whichever cell the Deploy panel is showing — only your overrides change, and any change flips the badge to **Not Verified** until the new configuration is run end-to-end. For Ornith-1.0 the knobs are the reasoning and tool-call parsers: * **Reasoning Parser** appends `--reasoning-parser qwen3`. Ornith emits `...` traces; with this on, SGLang surfaces them as `message.reasoning_content` instead of leaving the tags inline in `content`. * **Tool Call Parser** appends `--tool-call-parser qwen3_coder`, so Qwen-style XML tool calls are returned as OpenAI-compatible `tool_calls`. ## 1. Model Introduction [Ornith-1.0](https://huggingface.co/collections/deepreinforce-ai/ornith-10) is DeepReinforce's self-improving open-source model family for agentic coding. The model cards describe the family as post-trained on top of Gemma 4 and Qwen 3.5, and the collection currently includes 397B, 35B, and 9B repos plus FP8 and GGUF variants. The model cards report results on Terminal-Bench 2.1, SWE-Bench, NL2Repo, ClawEval, and SWE Atlas benchmarks. **Key Features:** * **Agentic coding specialization**: the model cards describe Ornith-1.0 as specialized for agentic coding and report coding-agent benchmark results. * **Self-improving training**: the model cards state that Ornith-1.0 uses reinforcement learning to optimize both solution rollouts and the scaffold that drives those rollouts. * **Reasoning model behavior**: assistant responses begin with a `...` reasoning block before the final answer; enable the `--reasoning-parser qwen3` toggle in the [Playground](#playground) to split it into `reasoning_content`. * **Tool calling**: emits Qwen-style XML tool calls; enable the `--tool-call-parser qwen3_coder` toggle in the [Playground](#playground). * **Long context**: model-card recipes use `--context-length 262144`. * **MIT license**: the Hugging Face repos are released under MIT. **Available Models:**
Model Format Deploy Panel Notes
[deepreinforce-ai/Ornith-1.0-397B](https://huggingface.co/deepreinforce-ai/Ornith-1.0-397B) BF16 H200 only Flagship 397B MoE checkpoint; model-card baseline uses TP=8 on an H200 single node.
[deepreinforce-ai/Ornith-1.0-397B-FP8](https://huggingface.co/deepreinforce-ai/Ornith-1.0-397B-FP8) FP8 H100 / H200 FP8 repo in the collection; the deploy command uses this repo id with TP=8.
[deepreinforce-ai/Ornith-1.0-35B](https://huggingface.co/deepreinforce-ai/Ornith-1.0-35B) BF16 H100 / H200 35B MoE checkpoint; the deploy command uses TP=2.
[deepreinforce-ai/Ornith-1.0-35B-FP8](https://huggingface.co/deepreinforce-ai/Ornith-1.0-35B-FP8) FP8 H100 / H200 FP8 repo in the collection; the deploy command uses this repo id with TP=2.
[deepreinforce-ai/Ornith-1.0-9B](https://huggingface.co/deepreinforce-ai/Ornith-1.0-9B) BF16 H100 / H200 Dense 9B checkpoint; the model card describes it as designed for efficient single-GPU deployment.
[deepreinforce-ai/Ornith-1.0-35B-GGUF](https://huggingface.co/deepreinforce-ai/Ornith-1.0-35B-GGUF) GGUF No Listed for completeness; GGUF targets llama.cpp-style local inference, not the SGLang server recipe here.
[deepreinforce-ai/Ornith-1.0-9B-GGUF](https://huggingface.co/deepreinforce-ai/Ornith-1.0-9B-GGUF) GGUF No Listed for completeness; the model card shows llama.cpp and Ollama examples for the GGUF build.
**License:** [MIT](https://huggingface.co/deepreinforce-ai/Ornith-1.0-397B/blob/main/LICENSE) **Resources:** [Hugging Face collection](https://huggingface.co/collections/deepreinforce-ai/ornith-10) · [Ornith blog](https://deep-reinforce.com/ornith_1_0.html) ## 2. Configuration Tips * **Reasoning parser**: Ornith responses include `...`. Enable the `--reasoning-parser qwen3` toggle in the [Playground](#playground) so OpenAI-compatible responses expose the reasoning trace as `message.reasoning_content`. * **Tool-call parser**: enable the `--tool-call-parser qwen3_coder` toggle in the [Playground](#playground) so `` blocks are returned as OpenAI-compatible tool calls. * **Context length**: the model-card SGLang recipes use `--context-length 262144`. Lower it if you need more memory headroom. * **Tensor parallelism**: the 397B model-card recipes use `--tp 8`; in this single-node matrix, non-FP8 397B is H200-only, while 397B-FP8 is available on both H100 and H200. The 35B deploy commands use `--tp 2`. The 9B model-card recipe is single-GPU by default; the command panel makes that explicit with `--tp 1`. Adjust TP to match your node and memory budget. * **Sampling**: model cards recommend `temperature=0.6`, `top_p=0.95`, and `top_k=20` for normal use. Their reported benchmark setup may use different task-specific sampling parameters. * **Benchmarks**: benchmark numbers in the model cards are reported by DeepReinforce. They are useful for context, but the command panel leaves recipes unverified until exact runs are signed off. ## 3. Usage Examples ### 3.1 Basic Chat Completion `message.reasoning_content` is only populated when the server was launched with the `--reasoning-parser qwen3` toggle (see the [Playground](#playground)); otherwise the `...` trace stays inline in `message.content`. > **Python client** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="Ornith-1.0-9B", > messages=[ > {"role": "user", "content": "Write a compact Python function is_prime(n)."} > ], > temperature=0.6, > top_p=0.95, > max_tokens=1024, > extra_body={"top_k": 20}, > ) > > message = response.choices[0].message > print("=============== Reasoning ===============") > print(message.reasoning_content) > print("=============== Answer ==================") > print(message.content) > ``` ### 3.2 Tool Calling Enable the `--tool-call-parser qwen3_coder` toggle in the [Playground](#playground) and launch with the resulting command. Then use the standard OpenAI-compatible `tools` field: > **Tool-call request** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [{ > "type": "function", > "function": { > "name": "run_tests", > "description": "Run the project's test suite.", > "parameters": { > "type": "object", > "properties": { > "target": {"type": "string", "description": "Test target or command"} > }, > "required": ["target"], > }, > }, > }] > > response = client.chat.completions.create( > model="Ornith-1.0-9B", > messages=[{"role": "user", "content": "Run the unit tests for the parser module."}], > tools=tools, > tool_choice="auto", > temperature=0.6, > top_p=0.95, > max_tokens=2048, > ) > > print(response.choices[0].message.tool_calls) > ``` # Ornith-1.5 Source: https://docs.sglang.io/cookbook/autoregressive/DeepReinforce/Ornith-1.5 Deploy Ornith-1.5 with SGLang on NVIDIA H100 and H200 GPUs, with recipes for 9B, 35B-A3B, 122B, and 397B models, FP8, reasoning, and tool calling. ## Deployment These recipes target a single Linux node with NVIDIA CUDA GPUs. The Ornith-1.5 model cards recommend SGLang `>=0.5.9`. Both parsers are included in every launch command: `qwen3` separates reasoning from the answer, and `qwen3_coder` parses tool calls. > **Install SGLang** > > **Python** > > ```bash Command theme={null} > pip install --upgrade "sglang>=0.5.9" > ``` > > Run the Python command from the deployment panel in this environment. See the [installation guide](/docs/get-started/install) for platform-specific requirements. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > Select Docker in the deployment panel to generate the container command. Choose your hardware, model size, and checkpoint format. The 9B recipe uses one GPU, 35B-A3B uses two, and 122B and 397B use eight. BF16 397B requires H200 in this matrix; its FP8 checkpoint is also available on H100. Select **BF16** for a BF16 checkpoint or **FP8** for an FP8 checkpoint. All commands use Hugging Face repository IDs and default to port **30000**. ## 1. Model introduction Ornith-1.5 is an agentic model family published by [Ornith AI](https://huggingface.co/ornith-ai). The 9B, 35B-A3B, 122B, and 397B checkpoints use Qwen3.5 architectures. The family extends Ornith-1.0's self-improvement loop by jointly optimizing task generation, scaffold construction, and solution rollouts through reinforcement learning. The model cards describe applications in coding, reasoning, and tool-using agents. The recipes expose an OpenAI-compatible API with separate reasoning output, parsed tool calls, and a 262,144-token context window. The table lists the checkpoints covered by this recipe.
Checkpoint Format Recipe
[Ornith-1.5-9B](https://huggingface.co/ornith-ai/Ornith-1.5-9B) BF16 Dense; 1× H100 or H200
[Ornith-1.5-35B-A3B](https://huggingface.co/ornith-ai/Ornith-1.5-35B-A3B) BF16 MoE, \~3B active; 2× H100 or H200
[Ornith-1.5-35B-A3B-FP8](https://huggingface.co/ornith-ai/Ornith-1.5-35B-A3B-FP8) FP8 2× H100 or H200
[Ornith-1.5-122B](https://huggingface.co/ornith-ai/Ornith-1.5-122B) BF16 MoE, 256 experts with 8 routed per token; 8× H100 or H200
[Ornith-1.5-397B](https://huggingface.co/ornith-ai/Ornith-1.5-397B) BF16 MoE; 8× H200
[Ornith-1.5-397B-FP8](https://huggingface.co/ornith-ai/Ornith-1.5-397B-FP8) FP8 8× H100 or H200
The official [9B](https://huggingface.co/ornith-ai/Ornith-1.5-9B), [35B-A3B](https://huggingface.co/ornith-ai/Ornith-1.5-35B-A3B), [122B](https://huggingface.co/ornith-ai/Ornith-1.5-122B), and [397B](https://huggingface.co/ornith-ai/Ornith-1.5-397B) model cards declare the MIT license. **Resources:** [Ornith-1.5 model repositories](https://huggingface.co/ornith-ai/models?search=Ornith-1.5) · [Ornith-1.5 blog](https://ornith.ai/ornith_1_5.html) ## 2. Configuration tips * **Model IDs:** use the `ornith-ai` namespace. The 35B repository includes the `-A3B` suffix. FP8 selections use the actual `-FP8` repository rather than the BF16 repository shown in their model-card quickstarts. * **Context and memory:** every recipe uses `--context-length 262144`. The 9B, 35B-A3B, and 397B recipes use `--mem-fraction-static 0.85`; the 122B recipe uses `0.80`. Lower the context length if you need more memory headroom. * **Reasoning:** `--reasoning-parser qwen3` exposes reasoning as `message.reasoning_content`, with the answer in `message.content`. * **Tool calling:** `--tool-call-parser qwen3_coder` exposes parsed calls in `message.tool_calls`. Your application executes the requested function and submits its result in a follow-up tool message. * **Sampling:** 35B-A3B and 397B recommend `temperature=0.6`, `top_p=0.95`, and `top_k=20`. For 9B and 122B, the model cards recommend `temperature=1.0` and `presence_penalty=1.5` for general tasks, or `temperature=0.6` and `presence_penalty=0.0` for precise coding; both use `top_p=0.95`, `top_k=20`, `min_p=0.0`, and `repetition_penalty=1.0`. These settings are distinct from benchmark-specific settings. The Python examples below use the precise-coding sampling settings. ## 3. Usage examples These requests use the precise-coding sampling settings shared by 9B and 122B. Set `model` to the deployment panel's `--served-model-name`, such as `Ornith-1.5-9B` or `Ornith-1.5-122B`. The examples use the default port; match the client port if you change the launch port. > **Chat completion with reasoning (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > response = client.chat.completions.create( > model="Ornith-1.5-9B", > messages=[{"role": "user", "content": "Write a compact Python is_prime function."}], > temperature=0.6, > top_p=0.95, > presence_penalty=0.0, > max_tokens=1024, > extra_body={"top_k": 20, "min_p": 0.0, "repetition_penalty": 1.0}, > ) > message = response.choices[0].message > print("Reasoning:", getattr(message, "reasoning_content", None)) > print("Answer:", message.content) > ``` > **Tool-call request (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > response = client.chat.completions.create( > model="Ornith-1.5-9B", > messages=[{"role": "user", "content": "Run the parser module's unit tests."}], > tools=[{ > "type": "function", > "function": { > "name": "run_tests", > "description": "Run the project's test suite.", > "parameters": { > "type": "object", > "properties": {"target": {"type": "string"}}, > "required": ["target"], > }, > }, > }], > tool_choice="auto", > temperature=0.6, > top_p=0.95, > presence_penalty=0.0, > max_tokens=2048, > extra_body={"top_k": 20, "min_p": 0.0, "repetition_penalty": 1.0}, > ) > message = response.choices[0].message > print("Reasoning:", getattr(message, "reasoning_content", None)) > print("Tool calls:", message.tool_calls) > ``` ### Agent integration Configure your agent or coding CLI to use the same OpenAI-compatible endpoint: * **API base URL:** `http://localhost:30000/v1`. * **API key:** `EMPTY` for a local server without API-key authentication. * **Model:** the selected checkpoint's `--served-model-name`, such as `Ornith-1.5-122B`. Use the served model name rather than the Hugging Face repository ID when the two differ. Keep both parsers enabled so the agent receives separate reasoning and structured tool calls. Your agent executes tools and returns their results to the server in subsequent messages. # DeepSeek-Math-V2 Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-Math-V2 ## 1. Model Introduction [DeepSeek-Math-V2](https://huggingface.co/deepseek-ai/DeepSeek-Math-V2) is DeepSeek's advanced mathematical reasoning model with strong theorem-proving capabilities. The model demonstrates exceptional performance on mathematical competitions, achieving gold-level scores on IMO 2025 and CMO 2024, and a near-perfect 118/120 on Putnam 2024 with scaled test-time compute. **Key Features:** * **Strong Theorem-Proving**: Gold-level performance on IMO 2025 and CMO 2024 * **Self-Verifiable Reasoning**: Implements self-verifiable mathematical reasoning for improved accuracy * **Competition-Level Math**: Near-perfect score (118/120) on Putnam 2024 * **Large MoE Model**: \~671B total parameters, requires high-memory GPUs (B200 183GB or B300 275GB) **Available Models:** * **BF16 (Full Weights)**: [deepseek-ai/DeepSeek-Math-V2](https://huggingface.co/deepseek-ai/DeepSeek-Math-V2) - Full precision weights **License:** To use DeepSeek-Math-V2, you must agree to DeepSeek's Community License. See [LICENSE](https://huggingface.co/deepseek-ai/DeepSeek-Math-V2/blob/main/LICENSE) for details. ## 2. SGLang Installation Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, and deployment strategy. Run this Command:

> [!WARNING]
>
> DeepSeek-Math-V2 is built on DeepSeek-V3.2 and uses DSA sparse attention. All recipes here run the DSA indexer top-k on the default `--dsa-topk-backend sgl-kernel`. Other top-k backend choices have not been fully validated on this model.

### 3.2 Configuration Tips

**Hardware Requirements:**

* **B200 (183GB)**: BF16 tp=8
* **B300 (275GB)**: BF16 tp=8

**DP Attention:**

* Enable DP attention for high-throughput scenarios
* The `--attn-dp-size` value commonly matches the `--tp` value
* Trade-off: Higher throughput at the cost of slightly increased latency

## 4. Model Invocation

### 4.1 Deployment Command

Deploy the model using the command generated above. Example for B200:

```shell Command theme={null}
sglang serve --model-path deepseek-ai/DeepSeek-Math-V2 \
  --tp 8 \
  --ep 8 \
  --reasoning-parser deepseek-r1 \
  --host 0.0.0.0 \
  --port 30000
```

### 4.2 Mathematical Reasoning

DeepSeek-Math-V2 excels at mathematical problem-solving with step-by-step reasoning.

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Mathematical reasoning problem
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-Math-V2",
    messages=[
        {"role": "user", "content": "Prove that for any positive integer n, the sum 1 + 2 + 3 + ... + n = n(n+1)/2"}
    ],
    max_tokens=4096,
    stream=True
)

# Process the stream
thinking_started = False
has_thinking = False
has_answer = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
We need to prove that for any positive integer n, the sum 1 + 2 + 3 + ... + n = n(n+1)/2.

This is a classic formula for the sum of the first n natural numbers. We can prove by induction.

Base case: n=1, LHS = 1, RHS = 1*(1+1)/2 = 1*2/2 = 1. Holds.

Inductive step: Assume true for n = k, i.e., 1 + 2 + ... + k = k(k+1)/2. Then for n = k+1, sum = 1 + 2 + ... + k + (k+1) = [k(k+1)/2] + (k+1) = (k(k+1) + 2(k+1))/2 = (k+1)(k+2)/2 = (k+1
)((k+1)+1)/2. So holds for k+1. By induction, holds for all positive integers n.

...
=============== Content =================
We can prove the well-known formula for the sum of the first \(n\) positive integers in several ways. Two of the most elementary are presented below.

---

### 1. Proof by mathematical induction

**Base case (\(n=1\))**:
\[
1 = \frac{1\cdot(1+1)}{2}= \frac{1\cdot2}{2}=1,
\]
so the formula holds for \(n=1\).

**Inductive hypothesis:**
Assume that for some positive integer \(k\) the formula is true, i.e.
\[
1+2+\dots+k = \frac{k(k+1)}{2}.
\]

**Inductive step (\(k \to k+1\))**:
Consider the sum up to \(k+1\):
\[
\begin{aligned}
1+2+\dots+k+(k+1) &= \bigl(1+2+\dots+k\bigr) + (k+1) \\[4pt]
&= \frac{k(k+1)}{2} + (k+1) \qquad\text{(by the induction hypothesis)}\\[4pt]
&= (k+1)\left(\frac{k}{2}+1\right)\\[4pt]
&= (k+1)\frac{k+2}{2}\\[4pt]
&= \frac{(k+1)(k+2)}{2}\\[4pt]
&= \frac{(k+1)\bigl((k+1)+1\bigr)}{2}.
\end{aligned}
\]
Thus the formula also holds for \(n=k+1\).

By the principle of mathematical induction,
\[
1+2+3+\dots+n = \frac{n(n+1)}{2}
\]
for every positive integer \(n\).

---

### 2. Proof by pairing (Gauss’s trick)

Let
\[
S = 1 + 2 + 3 + \dots + n.
\]

Write the same sum in reverse order:
\[
S = n + (n-1) + (n-2) + \dots + 1.
\]

Add the two equalities term‑by‑term:
\[
\begin{aligned}
2S &= (1+n) + \bigl(2+(n-1)\bigr) + \bigl(3+(n-2)\bigr) + \dots + (n+1)\\
    &= \underbrace{(n+1)+(n+1)+\dots+(n+1)}_{n\ \text{times}}\\
    &= n\,(n+1).
\end{aligned}
\]

Therefore
\[
S = \frac{n(n+1)}{2}.
\]

Both proofs are rigorous and show that the formula holds for all positive integers \(n\).
```

### 4.3 Competition-Level Problems

**Example: IMO-style Problem:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# IMO-style problem
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-Math-V2",
    messages=[
        {"role": "user", "content": "Let a, b, c be positive real numbers such that abc = 1. Prove that (a-1+1/b)(b-1+1/c)(c-1+1/a) <= 1."}
    ],
    max_tokens=8192,
    stream=True
)

# Process the stream
thinking_started = False
has_thinking = False
has_answer = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        if delta.content:
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
We need to prove that for positive real numbers a,b,c with abc = 1, we have:

\[
(a - 1 + \frac{1}{b})(b - 1 + \frac{1}{c})(c - 1 + \frac{1}{a}) \le 1.
\]

We can rewrite the expressions: Since abc=1, we have 1/b = ac, 1/c = ab, 1/a = bc. Wait careful: abc=1 => 1/b = ac? Actually 1/b = ac? Let's check: abc=1 => ac = 1/b? Multiply both sides by something: abc=1 => (ac) b = 1 => ac = 1/b. Yes, because (ac) * b = 1 => ac = 1/b. Similarly, ab = 1/c, bc = 1/a. So we can rewrite:

...
=============== Content =================

We are given positive real numbers \(a,b,c\) with \(abc=1\). We must prove

\[
\Bigl(a-1+\frac1b\Bigr)\Bigl(b-1+\frac1c\Bigr)\Bigl(c-1+\frac1a\Bigr)\le 1 .
\]

---

### 1.  A convenient substitution

Because \(abc=1\), we can write

\[
a=\frac{x}{y},\qquad b=\frac{y}{z},\qquad c=\frac{z}{x}
\]

with positive numbers \(x,y,z\).
(For instance, take \(x=1,\;y=\frac1a,\;z=\frac1{ab}\); then indeed \(a=\frac{x}{y},\;b=\frac{y}{z}\) and, using \(abc=1\), we obtain \(c=\frac{z}{x}=\frac1{ab}=c\).)

---

### 2.  Rewriting the factors

\[
\begin{aligned}
a-1+\frac1b &=\frac{x}{y}-1+\frac{z}{y}= \frac{x+z-y}{y},\\[2mm]
b-1+\frac1c &=\frac{y}{z}-1+\frac{x}{z}= \frac{x+y-z}{z},\\[2mm]
c-1+\frac1a &=\frac{z}{x}-1+\frac{y}{x}= \frac{y+z-x}{x}.
\end{aligned}
\]

Hence the product becomes

\[
P=\Bigl(a-1+\frac1b\Bigr)\Bigl(b-1+\frac1c\Bigr)\Bigl(c-1+\frac1a\Bigr)
   =\frac{(x+z-y)(x+y-z)(y+z-x)}{xyz}.
\]

---

### 3.  Reducing to a known inequality

We have to show \(P\le1\), i.e.

\[
(x+z-y)(x+y-z)(y+z-x)\le xyz .
\tag{1}
\]

Set

\[
p=x+y+z,\qquad q=xy+yz+zx,\qquad r=xyz .
\]

Notice that

\[
x+z-y=p-2y,\quad x+y-z=p-2z,\quad y+z-x=p-2x .
\]

Therefore

\[
\begin{aligned}
(x+z-y)(x+y-z)(y+z-x)
&=(p-2x)(p-2y)(p-2z)\\
&=p^{3}-2p^{2}(x+y+z)+4p(xy+yz+zx)-8xyz\\
&=-p^{3}+4pq-8r .
\end{aligned}
\]

Inequality (1) is thus equivalent to

\[
-p^{3}+4pq-8r\le r\quad\Longleftrightarrow\quad 4pq-p^{3}\le 9r .
\tag{2}
\]

---

### 4.  Applying Schur’s inequality

Schur’s inequality of third degree states that for any non‑negative \(x,y,z\)

\[
p^{3}+9r\ge 4pq .
\]

Rearranged, this is exactly \(4pq-p^{3}\le 9r\), which is (2).
Since our \(x,y,z\) are positive, Schur’s inequality applies and (2) holds.

Consequently (1) is true, and we obtain \(P\le1\).

---

### 5.  Equality case

Equality in Schur’s inequality for positive numbers occurs only when \(x=y=z\).
Then \(a=b=c=1\), and indeed the product equals \(1\).

---

Thus for all positive \(a,b,c\) with \(abc=1\),

\[
\Bigl(a-1+\frac1b\Bigr)\Bigl(b-1+\frac1c\Bigr)\Bigl(c-1+\frac1a\Bigr)\le 1 .
\]

∎
```

## 5. Benchmark

### 5.1 Accuracy Benchmark

#### 5.1.1 GSM8K Benchmark

**Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Test Results:**

```text Output theme={null}
Accuracy: 0.975
Invalid: 0.000
Latency: 34.358 s
Output throughput: 540.162 token/s
```

### 5.2 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8x, 183GB each)
* Model: DeepSeek-Math-V2
* Tensor Parallelism: 8
* SGLang Version: 0.5.8

#### 5.2.1 Latency Benchmark

**Benchmark Command:**

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model deepseek-ai/DeepSeek-Math-V2 \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

**Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  53.34
Total input tokens:                      1972
Total input text tokens:                 1972
Total generated tokens:                  2784
Total generated tokens (retokenized):    2778
Request throughput (req/s):              0.19
Input token throughput (tok/s):          36.97
Output token throughput (tok/s):         52.19
Peak output token throughput (tok/s):    56.00
Peak concurrent requests:                3
Total token throughput (tok/s):          89.16
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5330.72
Median E2E Latency (ms):                 5879.28
P90 E2E Latency (ms):                    8320.33
P99 E2E Latency (ms):                    9921.29
---------------Time to First Token----------------
Mean TTFT (ms):                          183.38
Median TTFT (ms):                        177.92
P99 TTFT (ms):                           217.64
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          17.96
Median TPOT (ms):                        18.39
P99 TPOT (ms):                           19.03
---------------Inter-Token Latency----------------
Mean ITL (ms):                           18.57
Median ITL (ms):                         18.63
P95 ITL (ms):                            19.26
P99 ITL (ms):                            19.48
Max ITL (ms):                            24.93
==================================================
```

#### 5.2.2 Throughput Benchmark

**Benchmark Command:**

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model deepseek-ai/DeepSeek-Math-V2 \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

**Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  217.36
Total input tokens:                      301701
Total input text tokens:                 301701
Total generated tokens:                  188375
Total generated tokens (retokenized):    187456
Request throughput (req/s):              4.60
Input token throughput (tok/s):          1388.05
Output token throughput (tok/s):         866.67
Peak output token throughput (tok/s):    2589.00
Peak concurrent requests:                109
Total token throughput (tok/s):          2254.72
Concurrency:                             89.81
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   19521.73
Median E2E Latency (ms):                 12076.76
P90 E2E Latency (ms):                    47248.87
P99 E2E Latency (ms):                    86862.79
---------------Time to First Token----------------
Mean TTFT (ms):                          790.40
Median TTFT (ms):                        456.81
P99 TTFT (ms):                           4223.33
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          106.52
Median TPOT (ms):                        107.24
P99 TPOT (ms):                           238.33
---------------Inter-Token Latency----------------
Mean ITL (ms):                           100.29
Median ITL (ms):                         38.34
P95 ITL (ms):                            237.00
P99 ITL (ms):                            347.49
Max ITL (ms):                            3642.56
==================================================
```


# DeepSeek-OCR
Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-OCR



## 1. Model Introduction

[DeepSeek-OCR](https://github.com/deepseek-ai/DeepSeek-OCR) is DeepSeek's advanced OCR (Optical Character Recognition) model designed for high-accuracy text extraction from images. The model is optimized for various document processing and image-to-text conversion tasks.

**Key Features:**

* **Advanced OCR**: High-accuracy text recognition from images and documents
* **Multi-Modality**: Supports various image formats and document types

**Available Models:**

* **Base Model**: [deepseek-ai/DeepSeek-OCR](https://huggingface.co/deepseek-ai/DeepSeek-OCR) - Recommended for OCR tasks

**License:**
To use DeepSeek-OCR, you must agree to DeepSeek's Community License. See [LICENSE](https://huggingface.co/deepseek-ai/DeepSeek-OCR/blob/main/LICENSE) for details.

For more details, please refer to the [official DeepSeek-OCR repository](https://github.com/deepseek-ai/DeepSeek-OCR).

## 2. SGLang Installation

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, and deployment strategy.

Run this Command:


## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 OCR-Specific Prompts

DeepSeek-OCR accepts recommended prompts from the model card:

```text theme={null}

<|grounding|>Convert the document to markdown.
```

```text theme={null}

Free OCR.
```

**OpenAI-compatible image request example:**

```python Example theme={null}
import requests

url = "http://localhost:30000/v1/chat/completions"

data = {
    "model": "deepseek-ai/DeepSeek-OCR",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "\n<|grounding|>Convert the document to markdown."
                },
                {
                    "type": "image_url",
                    "image_url": {"url": "https://example.com/your_image.jpg"}
                },
            ],
        }
    ],
    "max_tokens": 512,
}

response = requests.post(url, json=data)
print(response.text)
```

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: AMD MI300X GPU (1x)
* Model: DeepSeek-OCR
* Tensor Parallelism: 1
* sglang version: 0.5.7

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios. To simulate real-world usage patterns, we configure each request with 1024 input tokens and 1024 output tokens, representing typical medium-length conversations with detailed responses.

#### 5.1.1 Latency-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path deepseek-ai/DeepSeek-OCR \
  --tp 1 \
  --dtype float16 \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 8000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 8000 \
  --model deepseek-ai/DeepSeek-OCR \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  4.45
Total input tokens:                      1972
Total input text tokens:                 1972
Total input vision tokens:               0
Total generated tokens:                  2784
Total generated tokens (retokenized):    2770
Request throughput (req/s):              2.25
Input token throughput (tok/s):          442.89
Output token throughput (tok/s):         625.26
Peak output token throughput (tok/s):    635.00
Peak concurrent requests:                4
Total token throughput (tok/s):          1068.16
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   443.32
Median E2E Latency (ms):                 493.29
---------------Time to First Token----------------
Mean TTFT (ms):                          21.59
Median TTFT (ms):                        20.89
P99 TTFT (ms):                           24.81
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          1.47
Median TPOT (ms):                        1.52
P99 TPOT (ms):                           1.53
---------------Inter-Token Latency----------------
Mean ITL (ms):                           1.52
Median ITL (ms):                         1.51
P95 ITL (ms):                            1.76
P99 ITL (ms):                            1.93
Max ITL (ms):                            8.28
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path deepseek-ai/DeepSeek-OCR \
  --tp 1 \
  --ep 1 \
  --dtype float16 \
  --host 0.0.0.0 \
  --port 8000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 8000 \
  --model deepseek-ai/DeepSeek-OCR \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  16.24
Total input tokens:                      301698
Total input text tokens:                 301698
Total input vision tokens:               0
Total generated tokens:                  188375
Total generated tokens (retokenized):    186927
Request throughput (req/s):              61.59
Input token throughput (tok/s):          18582.90
Output token throughput (tok/s):         11602.84
Peak output token throughput (tok/s):    15479.00
Peak concurrent requests:                179
Total token throughput (tok/s):          30185.75
Concurrency:                             85.53
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   1388.60
Median E2E Latency (ms):                 901.43
---------------Time to First Token----------------
Mean TTFT (ms):                          73.36
Median TTFT (ms):                        50.21
P99 TTFT (ms):                           349.53
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          7.42
Median TPOT (ms):                        7.31
P99 TPOT (ms):                           27.99
---------------Inter-Token Latency----------------
Mean ITL (ms):                           7.04
Median ITL (ms):                         4.62
P95 ITL (ms):                            21.11
P99 ITL (ms):                            36.92
Max ITL (ms):                            172.15
==================================================
```


# DeepSeek-OCR-2
Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-OCR-2



## 1. Model Introduction

[DeepSeek-OCR-2](https://github.com/deepseek-ai/DeepSeek-OCR-2) is DeepSeek's next-generation OCR (Optical Character Recognition) model, building on DeepSeek-OCR with improved accuracy and broader document understanding capabilities. The model is optimized for high-accuracy text extraction from images across a wide variety of document types and formats.

**Key Features:**

* **Semantic-Aware Visual Encoding (DeepEncoder V2)**: DeepSeek-OCR-2 introduces DeepEncoder V2, which models document reading order in a more human-like, semantic-driven manner rather than relying on fixed raster scanning. This significantly improves logical reading flow in complex layouts (e.g., multi-column documents).
* **Stronger Layout and Structural Understanding**: DeepSeek-OCR-2 demonstrates improved performance on structured documents such as tables, forms, and dense multi-column pages. It reduces reading-order errors and improves overall document parsing robustness compared to the original version.
* **Improved Accuracy While Maintaining Token Efficiency**: The original DeepSeek-OCR emphasized aggressive visual token compression. OCR-2 maintains high token efficiency while delivering higher benchmark performance, particularly on document-level understanding tasks.
* **Better Generalization Across Complex Document Tasks**: DeepSeek-OCR-2 performs more consistently across multilingual documents, structured data extraction, and visually complex content, making it more suitable for real-world document intelligence scenarios beyond plain text OCR.

**Available Models:**

* **Base Model**: [deepseek-ai/DeepSeek-OCR-2](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2) - Recommended for OCR tasks

**License:**
To use DeepSeek-OCR-2, you must agree to DeepSeek's Community License. See [LICENSE](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2/blob/main/LICENSE.txt) for details.

For more details, please refer to the [official DeepSeek-OCR-2 repository](https://github.com/deepseek-ai/DeepSeek-OCR-2).

## 2. SGLang Installation

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

The DeepSeek-OCR-2 series offers models in various sizes and architectures, optimized for different hardware platforms including NVIDIA GPUs, AMD GPUs, Intel Arc Pro B-Series GPUs(codename: BMG (Battlemage)), and Intel Xeon CPUs. The recommended launch configurations vary by hardware and model size.

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, and deployment strategy. SGLang supports serving DeepSeek-OCR-2 on NVIDIA H200 and B200, AMD MI300X, MI355X, and MI325X GPUs, and Intel Arc Pro B-Series GPUs, as well as Intel Xeon CPUs.

Run this Command:


**Note**: DeepSeek-OCR-2 has \~3B parameters and easily fits on a single modern GPU. For low-latency serving, no model parallelism is needed. For high-throughput requirements, consider using data parallelism with the SGLang Model Gateway — see [DP, DPA and SGLang DP Router](../../../docs/advanced_features/sgl_model_gateway) for more details.

### 3.2 Configuration Tips

* **Single GPU Deployment:** DeepSeek-OCR-2 (\~3B parameters) fits on a single modern GPU — no tensor parallelism required for low-latency serving.
* **High Throughput:** For high-throughput scenarios, use data parallelism with the SGLang Model Gateway. See [DP, DPA and SGLang DP Router](../../../docs/advanced_features/sgl_model_gateway).
* **NCCL timeout:** If model loading is slow, increase `--dist-timeout 3600`.
* **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for NUMA binding settings.

## 4. Model Invocation

### 4.1 Basic Usage

**OpenAI-compatible request example**

```python Example theme={null}
import requests

url = "http://localhost:30000/v1/chat/completions"

data = {
    "model": "deepseek-ai/DeepSeek-OCR-2",
    "messages": [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "\n<|grounding|>Convert the document to markdown."},
                {"type": "image_url", "image_url": {"url": "https://example.com/your_image.jpg"}},
            ],
        }
    ],
    "max_tokens": 512,
}

response = requests.post(url, json=data)
print(response.text)
```

**Reference**

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Recommended Prompts

The following prompts are recommended by the [official model card](https://huggingface.co/deepseek-ai/DeepSeek-OCR-2#main-prompts).

**Structured document conversion** — extracts text while preserving layout:

```text Example theme={null}

<|grounding|>Convert the document to markdown.
```

**Free-form OCR** — extracts without layouts:

```text Example theme={null}

Free OCR.
```

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA H200 GPU (1x)
* Model: DeepSeek-OCR-2
* Tensor Parallelism: 1
* sglang version: 0.0.0.dev1+g93fca0bbc

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios. To simulate real-world usage patterns, we configure each request with 1024 input tokens and 1024 output tokens, representing typical medium-length conversations with detailed responses. For more details on how to perform evaluation, see [Evaluating New Models with SGLang](../../../docs/developer_guide/evaluating_new_models).

#### 5.1.1 Latency-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
sglang serve \
  --model-path deepseek-ai/DeepSeek-OCR-2 \
  --enable-multimodal \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 0.0.0.0 \
  --port 30000 \
  --model deepseek-ai/DeepSeek-OCR-2 \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  3.54
Total input tokens:                      1972
Total input text tokens:                 1972
Total generated tokens:                  2784
Total generated tokens (retokenized):    2710
Request throughput (req/s):              2.83
Input token throughput (tok/s):          557.53
Output token throughput (tok/s):         787.10
Peak output token throughput (tok/s):    818.00
Peak concurrent requests:                5
Total token throughput (tok/s):          1344.63
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   352.69
Median E2E Latency (ms):                 392.34
P90 E2E Latency (ms):                    540.64
P99 E2E Latency (ms):                    639.01
---------------Time to First Token----------------
Mean TTFT (ms):                          18.08
Median TTFT (ms):                        16.57
P99 TTFT (ms):                           25.67
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          1.18
Median TPOT (ms):                        1.21
P99 TPOT (ms):                           1.22
---------------Inter-Token Latency----------------
Mean ITL (ms):                           1.21
Median ITL (ms):                         1.21
P95 ITL (ms):                            1.28
P99 ITL (ms):                            1.44
Max ITL (ms):                            4.32
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
sglang serve \
  --model-path deepseek-ai/DeepSeek-OCR-2 \
  --enable-multimodal \
  --tp 1 \
  --ep 1 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 0.0.0.0 \
  --port 30000 \
  --model deepseek-ai/DeepSeek-OCR-2 \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  14.79
Total input tokens:                      301698
Total input text tokens:                 301698
Total generated tokens:                  188375
Total generated tokens (retokenized):    185236
Request throughput (req/s):              67.63
Input token throughput (tok/s):          20402.54
Output token throughput (tok/s):         12738.99
Peak output token throughput (tok/s):    17508.00
Peak concurrent requests:                187
Total token throughput (tok/s):          33141.53
Concurrency:                             86.87
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   1284.50
Median E2E Latency (ms):                 866.07
P90 E2E Latency (ms):                    3027.32
P99 E2E Latency (ms):                    5490.63
---------------Time to First Token----------------
Mean TTFT (ms):                          86.08
Median TTFT (ms):                        50.09
P99 TTFT (ms):                           613.92
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          7.79
Median TPOT (ms):                        6.54
P99 TPOT (ms):                           50.10
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.42
Median ITL (ms):                         4.64
P95 ITL (ms):                            23.65
P99 ITL (ms):                            39.62
Max ITL (ms):                            452.65
==================================================
```


# DeepSeek-R1
Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-R1



## 1. Model Introduction

[DeepSeek-R1](https://github.com/deepseek-ai/DeepSeek-R1) is DeepSeek's advanced reasoning model that combines powerful language understanding with step-by-step reasoning capabilities. The model is available in multiple quantization formats optimized for different hardware platforms.

**Key Features:**

* **Advanced Reasoning**: Built-in reasoning capabilities for complex problem-solving
* **Multiple Quantizations**: FP8 and FP4 variants for different performance/memory trade-offs
* **Hardware Optimization**: Specifically tuned for NVIDIA B200 (Blackwell) and H200 (Hopper) GPUs, AMD MI300X, MI325X and MI355X GPUs, as well as Intel Xeon CPUs
* **High Performance**: Optimized for both throughput and latency scenarios

**Available Models:**

* **FP8 (8-bit quantized)**: [deepseek-ai/DeepSeek-R1-0528](https://huggingface.co/deepseek-ai/DeepSeek-R1-0528) - Recommended for H200 and MI300X
* **FP4 (4-bit quantized)**: [nvidia/DeepSeek-R1-0528-FP4-v2](https://huggingface.co/nvidia/DeepSeek-R1-0528-FP4-v2) - Recommended for B200 and MI355X
* **BF16 (upcast from FP8)**: [unsloth/DeepSeek-R1-0528-BF16](https://huggingface.co/unsloth/DeepSeek-R1-0528-BF16)
* **INT8 (channel-wise)**: [meituan/DeepSeek-R1-Channel-INT8](https://huggingface.co/meituan/DeepSeek-R1-Channel-INT8)
* **W4A8**: [novita/Deepseek-R1-0528-W4AFP8](https://huggingface.co/novita/Deepseek-R1-0528-W4AFP8)
* **AWQ (4-bit)**: [QuixiAI/DeepSeek-R1-0528-AWQ](https://huggingface.co/QuixiAI/DeepSeek-R1-0528-AWQ)
* **MXFP4**: [amd/DeepSeek-R1-MXFP4](https://huggingface.co/amd/DeepSeek-R1-MXFP4)

**License:**
To use DeepSeek-R1, you must agree to DeepSeek's Community License. See [LICENSE](https://huggingface.co/deepseek-ai/DeepSeek-R1-0528/blob/main/LICENSE) for details.

For more details, please refer to the [official DeepSeek-R1 repository](https://github.com/deepseek-ai/DeepSeek-R1).

## 2. SGLang Installation

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate a basic deployment command for your hardware platform, quantization method, and deployment strategy.

Run this Command:


### 3.2 Optimal Configurations

Pareto-optimal configurations for B200, H200, MI300X, MI325X, and MI355X hardware.

Run this Command:


### 3.3 Configuration Tips

DeepSeek-R1 shares the same MoE architecture as DeepSeek-V3, so the same hardware and optimization recommendations apply.

**Recommended GPU configurations by weight type:**

Weight Type Supported Hardware
**FP8** (recommended) 8× H200, 8× B200, 8× MI300X, 2×8× H100/H800/H20
**BF16** (upcast from FP8) 2×8× H200, 2×8× MI300X, 4×8× H100/H800, 4×8× A100/A800
**INT8** 16× A100/A800, 32× L40S, Xeon 6980P CPU, 4× Ascend A3 Series
**W4A8 / AWQ / MXFP4 / NVFP4** 8× H20/H100, 4× H200; 8× H100/A100; 8/4× MI355X/MI350X; 8/4× B200
> The official DeepSeek-R1 checkpoint is already in FP8 format — do **not** add `--quantization fp8` when serving it. **DeepGEMM precompilation (NVIDIA Hopper / Blackwell):** Precompile GEMM kernels to avoid JIT overhead (\~10 min): ```bash theme={null} python3 -m sglang.compile_deep_gemm --model deepseek-ai/DeepSeek-R1 --tp 8 --trust-remote-code ``` **Data Parallelism Attention (`--attn-dp-size`):** Recommended for high-throughput scenarios. Use `--tp 8 --attn-dp-size 8` on a single 8-GPU node. **NCCL timeout:** If model loading is slow, increase: `--dist-timeout 3600`. **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings. ## 4. Model Invocation ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) ### 4.2 Advanced Usage #### 4.2.1 Reasoning Parser DeepSeek-R1 supports advanced reasoning capabilities with built-in thinking process. Enable the reasoning parser during deployment to separate the thinking and content sections: ```shell Command theme={null} python -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-R1-0528 \ --reasoning-parser deepseek-r1 \ --tp 8 ``` **Streaming with Thinking Process:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Enable streaming to see the thinking process in real-time response = client.chat.completions.create( model="deepseek-ai/DeepSeek-R1-0528", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], temperature=0.7, max_tokens=2048, stream=True ) # Process the stream has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: # Close thinking section and add content header if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= To solve this problem, I need to calculate 15% of 240. Step 1: Convert 15% to decimal: 15% = 0.15 Step 2: Multiply 240 by 0.15 Step 3: 240 × 0.15 = 36 =============== Content ================= The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36. ``` **Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions. #### 4.2.2 Tool Calling DeepSeek-R1 supports tool calling capabilities. Enable the tool call parser: ```shell Command theme={null} python -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-R1-0528 \ --reasoning-parser deepseek-r1 \ --tool-call-parser deepseekv3 \ --chat-template examples/chat_template/tool_chat_template_deepseekr1.jinja \ --tp 8 ``` **Python Example (with Thinking Process):** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Make request with streaming to see thinking process response = client.chat.completions.create( model="deepseek-ai/DeepSeek-R1-0528", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, temperature=0.7, stream=True ) # Process streaming response thinking_started = False has_thinking = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print tool calls if hasattr(delta, 'tool_calls') and delta.tool_calls: # Close thinking section if needed if has_thinking and thinking_started: print("\n=============== Content =================", flush=True) thinking_started = False for tool_call in delta.tool_calls: if tool_call.function: print(f"🔧 Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") # Print content if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information. I should call the function with location="Beijing". =============== Content ================= 🔧 Tool Call: get_weather Arguments: 🔧 Tool Call: None Arguments: {"location": "Beijing"} ``` **Note:** * The reasoning parser shows how the model decides to use a tool * Tool calls are clearly marked with the function name and arguments * You can then execute the function and send the result back to continue the conversation **Handling Tool Call Results:** ```python Example theme={null} # After getting the tool call, execute the function def get_weather(location, unit="celsius"): # Your actual weather API call here return f"The weather in {location} is 22°{unit[0].upper()} and sunny." # Send tool result back to the model messages = [ {"role": "user", "content": "What's the weather in Beijing?"}, { "role": "assistant", "content": None, "tool_calls": [{ "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": '{"location": "Beijing", "unit": "celsius"}' } }] }, { "role": "tool", "tool_call_id": "call_123", "content": get_weather("Beijing", "celsius") } ] final_response = client.chat.completions.create( model="deepseek-ai/DeepSeek-R1-0528", messages=messages, temperature=0.7 ) print(final_response.choices[0].message.content) # Output: "The weather in Beijing is currently 22°C and sunny." ``` #### 4.2.3 Multi-Token Prediction (EAGLE Speculative Decoding) DeepSeek-R1 supports EAGLE-based Multi-Token Prediction (MTP), the same mechanism as DeepSeek-V3. Refer to [DeepSeek-V3 §4.2.3](/cookbook/autoregressive/DeepSeek/DeepSeek-V3#4-2-3-multi-token-prediction-eagle-speculative-decoding) for the complete launch command, flag reference, tuning guidance (`--speculative-num-steps`, `--speculative-eagle-topk`, `--max-running-requests`), and `bench_speculative.py` link. R1's speed benchmark commands that include `--speculative-*` flags use this mechanism. #### 4.2.4 Thinking Budget Limit the model's thinking token budget using `CustomLogitProcessor`. Launch with `--enable-custom-logit-processor`: ```shell Command theme={null} python3 -m sglang.launch_server \ --model deepseek-ai/DeepSeek-R1 \ --tp 8 \ --port 30000 \ --reasoning-parser deepseek-r1 \ --enable-custom-logit-processor ``` ```python Example theme={null} import openai from sglang.srt.sampling.custom_logit_processor import DeepSeekR1ThinkingBudgetLogitProcessor client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="*") response = client.chat.completions.create( model="deepseek-ai/DeepSeek-R1", messages=[{"role": "user", "content": "Is Paris the Capital of France?"}], max_tokens=1024, extra_body={ "custom_logit_processor": DeepSeekR1ThinkingBudgetLogitProcessor().to_str(), "custom_params": {"thinking_budget": 512}, }, ) print(response) ``` ## 5. Benchmark This section uses **industry-standard configurations** for comparable benchmark results. ### 5.1 Speed Benchmark **Test Environment:** * Hardware: B200 GPU (8x) * Model: DeepSeek-R1-0528 * Tensor Parallelism: 8 * SGLang Version: 0.5.6.post1 **Benchmark Methodology:** We use industry-standard benchmark configurations to ensure results are comparable across frameworks and hardware platforms. #### 5.1.1 Standard Test Scenarios Three core scenarios reflect real-world usage patterns:
Scenario Input Length Output Length Use Case
**Chat** 1K 1K Most common conversational AI workload
**Reasoning** 1K 8K Long-form generation, complex reasoning tasks
**Summarization** 8K 1K Document summarization, RAG retrieval
#### 5.1.2 Concurrency Levels Test each scenario at different concurrency levels to capture the throughput vs. latency trade-off: * **Low Concurrency**: `--max-concurrency 1` (Latency-optimized) * **Medium Concurrency**: `--max-concurrency 16` (Balanced) * **High Concurrency**: `--max-concurrency 100` (Throughput-optimized) #### 5.1.3 Number of Prompts For each concurrency level, configure `num_prompts` to simulate realistic user loads: * **Quick Test**: `num_prompts = concurrency × 1` (minimal test) * **Recommended**: `num_prompts = concurrency × 5` (standard benchmark) * **Stable Measurements**: `num_prompts = concurrency × 10` (production-grade) *** #### 5.1.4 Benchmark Commands **Scenario 1: Chat (1K/1K) - Most Important** * **Model Deployment** ```bash Command theme={null} python -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-R1-0528 \ --tp 8 ``` * Low Concurrency (Latency-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 40.00 Total input tokens: 6101 Total input text tokens: 6101 Total input vision tokens: 0 Total generated tokens: 4210 Total generated tokens (retokenized): 4205 Request throughput (req/s): 0.25 Input token throughput (tok/s): 152.52 Output token throughput (tok/s): 105.24 Peak output token throughput (tok/s): 110.00 Peak concurrent requests: 2 Total token throughput (tok/s): 257.76 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 3998.40 Median E2E Latency (ms): 3207.53 ---------------Time to First Token---------------- Mean TTFT (ms): 153.00 Median TTFT (ms): 140.76 P99 TTFT (ms): 214.66 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 9.16 Median TPOT (ms): 9.15 P99 TPOT (ms): 9.21 ---------------Inter-Token Latency---------------- Mean ITL (ms): 9.16 Median ITL (ms): 9.15 P95 ITL (ms): 9.47 P99 ITL (ms): 9.63 Max ITL (ms): 15.45 ================================================== ``` * Medium Concurrency (Balanced) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 51.21 Total input tokens: 39668 Total input text tokens: 39668 Total input vision tokens: 0 Total generated tokens: 40725 Total generated tokens (retokenized): 40458 Request throughput (req/s): 1.56 Input token throughput (tok/s): 774.66 Output token throughput (tok/s): 795.30 Peak output token throughput (tok/s): 1088.00 Peak concurrent requests: 21 Total token throughput (tok/s): 1569.96 Concurrency: 13.93 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 8918.33 Median E2E Latency (ms): 9466.16 ---------------Time to First Token---------------- Mean TTFT (ms): 273.51 Median TTFT (ms): 131.71 P99 TTFT (ms): 839.57 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 17.56 Median TPOT (ms): 17.46 P99 TPOT (ms): 28.68 ---------------Inter-Token Latency---------------- Mean ITL (ms): 17.02 Median ITL (ms): 14.70 P95 ITL (ms): 16.41 P99 ITL (ms): 112.38 Max ITL (ms): 461.90 ================================================== ``` * High Concurrency (Throughput-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 110.46 Total input tokens: 249831 Total input text tokens: 249831 Total input vision tokens: 0 Total generated tokens: 252162 Total generated tokens (retokenized): 251441 Request throughput (req/s): 4.53 Input token throughput (tok/s): 2261.80 Output token throughput (tok/s): 2282.90 Peak output token throughput (tok/s): 3900.00 Peak concurrent requests: 109 Total token throughput (tok/s): 4544.71 Concurrency: 92.26 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 20380.71 Median E2E Latency (ms): 19391.65 ---------------Time to First Token---------------- Mean TTFT (ms): 563.14 Median TTFT (ms): 147.62 P99 TTFT (ms): 2632.11 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 40.11 Median TPOT (ms): 41.98 P99 TPOT (ms): 50.10 ---------------Inter-Token Latency---------------- Mean ITL (ms): 39.37 Median ITL (ms): 26.36 P95 ITL (ms): 98.16 P99 ITL (ms): 150.08 Max ITL (ms): 2052.85 ================================================== ``` **Scenario 2: Reasoning (1K/8K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 411.34 Total input tokens: 6101 Total input text tokens: 6101 Total input vision tokens: 0 Total generated tokens: 44452 Total generated tokens (retokenized): 44390 Request throughput (req/s): 0.02 Input token throughput (tok/s): 14.83 Output token throughput (tok/s): 108.07 Peak output token throughput (tok/s): 110.00 Peak concurrent requests: 2 Total token throughput (tok/s): 122.90 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 41132.04 Median E2E Latency (ms): 44288.71 ---------------Time to First Token---------------- Mean TTFT (ms): 125.76 Median TTFT (ms): 126.19 P99 TTFT (ms): 137.69 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 9.21 Median TPOT (ms): 9.20 P99 TPOT (ms): 9.27 ---------------Inter-Token Latency---------------- Mean ITL (ms): 9.23 Median ITL (ms): 9.22 P95 ITL (ms): 9.64 P99 ITL (ms): 9.86 Max ITL (ms): 15.18 ================================================== ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 348.93 Total input tokens: 39668 Total input text tokens: 39668 Total input vision tokens: 0 Total generated tokens: 318226 Total generated tokens (retokenized): 317630 Request throughput (req/s): 0.23 Input token throughput (tok/s): 113.69 Output token throughput (tok/s): 912.02 Peak output token throughput (tok/s): 1088.00 Peak concurrent requests: 19 Total token throughput (tok/s): 1025.70 Concurrency: 14.07 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 61360.70 Median E2E Latency (ms): 62071.20 ---------------Time to First Token---------------- Mean TTFT (ms): 176.02 Median TTFT (ms): 153.75 P99 TTFT (ms): 268.44 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 15.42 Median TPOT (ms): 15.59 P99 TPOT (ms): 16.07 ---------------Inter-Token Latency---------------- Mean ITL (ms): 15.39 Median ITL (ms): 15.17 P95 ITL (ms): 16.62 P99 ITL (ms): 18.13 Max ITL (ms): 226.59 ================================================== ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 589.31 Total input tokens: 158939 Total input text tokens: 158939 Total input vision tokens: 0 Total generated tokens: 1300705 Total generated tokens (retokenized): 1297658 Request throughput (req/s): 0.54 Input token throughput (tok/s): 269.70 Output token throughput (tok/s): 2207.16 Peak output token throughput (tok/s): 2944.00 Peak concurrent requests: 68 Total token throughput (tok/s): 2476.86 Concurrency: 57.03 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 105032.36 Median E2E Latency (ms): 108229.09 ---------------Time to First Token---------------- Mean TTFT (ms): 223.91 Median TTFT (ms): 158.15 P99 TTFT (ms): 474.86 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 25.94 Median TPOT (ms): 26.72 P99 TPOT (ms): 27.99 ---------------Inter-Token Latency---------------- Mean ITL (ms): 25.79 Median ITL (ms): 25.37 P95 ITL (ms): 26.70 P99 ITL (ms): 105.49 Max ITL (ms): 237.91 ================================================== ``` **Scenario 3: Summarization (8K/1K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 40.65 Total input tokens: 41941 Total input text tokens: 41941 Total input vision tokens: 0 Total generated tokens: 4210 Total generated tokens (retokenized): 4195 Request throughput (req/s): 0.25 Input token throughput (tok/s): 1031.65 Output token throughput (tok/s): 103.56 Peak output token throughput (tok/s): 110.00 Peak concurrent requests: 2 Total token throughput (tok/s): 1135.20 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 4063.62 Median E2E Latency (ms): 3296.13 ---------------Time to First Token---------------- Mean TTFT (ms): 165.91 Median TTFT (ms): 154.96 P99 TTFT (ms): 240.92 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 9.26 Median TPOT (ms): 9.27 P99 TPOT (ms): 9.42 ---------------Inter-Token Latency---------------- Mean ITL (ms): 9.28 Median ITL (ms): 9.28 P95 ITL (ms): 9.66 P99 ITL (ms): 9.83 Max ITL (ms): 14.06 ================================================== ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 56.71 Total input tokens: 300020 Total input text tokens: 300020 Total input vision tokens: 0 Total generated tokens: 41589 Total generated tokens (retokenized): 41490 Request throughput (req/s): 1.41 Input token throughput (tok/s): 5290.75 Output token throughput (tok/s): 733.41 Peak output token throughput (tok/s): 1024.00 Peak concurrent requests: 20 Total token throughput (tok/s): 6024.16 Concurrency: 14.25 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 10098.99 Median E2E Latency (ms): 10623.46 ---------------Time to First Token---------------- Mean TTFT (ms): 486.80 Median TTFT (ms): 189.59 P99 TTFT (ms): 2138.73 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 19.06 Median TPOT (ms): 19.23 P99 TPOT (ms): 30.69 ---------------Inter-Token Latency---------------- Mean ITL (ms): 18.53 Median ITL (ms): 15.63 P95 ITL (ms): 16.64 P99 ITL (ms): 109.71 Max ITL (ms): 1471.36 ================================================== ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-R1-0528 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 115.55 Total input tokens: 1273893 Total input text tokens: 1273893 Total input vision tokens: 0 Total generated tokens: 169680 Total generated tokens (retokenized): 169275 Request throughput (req/s): 2.77 Input token throughput (tok/s): 11024.93 Output token throughput (tok/s): 1468.50 Peak output token throughput (tok/s): 2254.00 Peak concurrent requests: 70 Total token throughput (tok/s): 12493.43 Concurrency: 59.45 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 21465.98 Median E2E Latency (ms): 20686.26 ---------------Time to First Token---------------- Mean TTFT (ms): 913.93 Median TTFT (ms): 224.92 P99 TTFT (ms): 6257.83 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 39.93 Median TPOT (ms): 40.99 P99 TPOT (ms): 60.91 ---------------Inter-Token Latency---------------- Mean ITL (ms): 38.83 Median ITL (ms): 26.29 P95 ITL (ms): 113.81 P99 ITL (ms): 176.94 Max ITL (ms): 5521.53 ================================================== ``` #### 5.1.5 Understanding the Results **Key Metrics:** * **Request Throughput (req/s)**: Number of requests processed per second * **Output Token Throughput (tok/s)**: Total tokens generated per second * **Mean TTFT (ms)**: Time to First Token - measures responsiveness * **Mean TPOT (ms)**: Time Per Output Token - measures generation speed * **Mean ITL (ms)**: Inter-Token Latency - measures streaming consistency **Why These Configurations Matter:** * **1K/1K (Chat)**: Represents the most common conversational AI workload. This is the highest priority scenario for most deployments. * **1K/8K (Reasoning)**: Tests long-form generation capabilities crucial for complex reasoning, code generation, and detailed explanations. * **8K/1K (Summarization)**: Evaluates performance with large context inputs, essential for RAG systems, document Q\&A, and summarization tasks. * **Variable Concurrency**: Captures the Pareto frontier - the optimal trade-off between throughput and latency at different load levels. Low concurrency shows best-case latency, high concurrency shows maximum throughput. **Interpreting Results:** * Compare your results against baseline numbers for your hardware * Higher throughput at same latency = better performance * Lower TTFT = more responsive user experience * Lower TPOT = faster generation speed ### 5.2 Accuracy Benchmark Document model accuracy on standard benchmarks: #### 5.2.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 1319 \ --num-threads 1316 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. **Test Results:** ```text Output theme={null} Accuracy: 0.959 Invalid: 0.000 Latency: 29.185 s Output throughput: 4854.672 token/s ``` # DeepSeek-V3 Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-V3 ## 1. Model Introduction [DeepSeek V3](https://huggingface.co/deepseek-ai/DeepSeek-V3) is a large-scale Mixture-of-Experts (MoE) language model developed by DeepSeek, designed to deliver strong general-purpose reasoning, coding, and tool-augmented capabilities with high training and inference efficiency. As the latest generation in the DeepSeek model family, DeepSeek V3 introduces systematic architectural and training innovations that significantly improve performance across reasoning, mathematics, coding, and long-context understanding, while maintaining a competitive compute cost. Key highlights include: * **Efficient MoE architecture**: DeepSeek V3 adopts a fine-grained Mixture-of-Experts design with a large number of experts and sparse activation, enabling high model capacity while keeping inference and training costs manageable. * **Advanced reasoning and coding**: The model demonstrates strong performance on mathematical reasoning, logical inference, and real-world coding benchmarks, benefiting from improved data curation and training strategies. * **Long-context capability**: DeepSeek V3 supports extended context lengths, allowing it to handle long documents, complex multi-step reasoning, and agent-style workflows more effectively. * **Tool use and function calling**: The model is trained to support structured outputs and tool invocation, enabling seamless integration with external tools and agent frameworks during inference. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and thinking capabilities. Run this Command:

### 3.2 Configuration Tips

**Recommended GPU configurations by weight type:**

Weight Type Supported Hardware
**FP8** (recommended) 8× H200, 8× B200, 8× MI300X, 2×8× H100/H800/H20
**BF16** (upcast from FP8) 2×8× H200, 2×8× MI300X, 4×8× H100/H800, 4×8× A100/A800
**INT8** 16× A100/A800, 32× L40S, Xeon 6980P CPU, 4× Ascend A3 Series
**W4A8 / AWQ / MXFP4 / NVFP4** 8× H20/H100, 4× H200; 8× H100/A100; 8/4× MI355X/MI350X; 8/4× B200
> The official DeepSeek-V3 checkpoint is already in FP8 format — do **not** add `--quantization fp8` when serving it. **DeepGEMM precompilation (NVIDIA Hopper / Blackwell):** Precompile GEMM kernels before the first server run to avoid JIT overhead (\~10 min): ```bash theme={null} python3 -m sglang.compile_deep_gemm --model deepseek-ai/DeepSeek-V3 --tp 8 --trust-remote-code ``` DeepGEMM is enabled by default on Hopper/Blackwell and can be disabled with `SGLANG_ENABLE_JIT_DEEPGEMM=0`. **Data Parallelism Attention (`--attn-dp-size`):** Recommended for high-throughput scenarios with large batch sizes. Reduces KV-cache duplication across TP ranks. Use `--tp 8 --attn-dp-size 8` on a single 8-GPU node. Not recommended for low-latency, small-batch workloads. **NCCL timeout:** If model loading is slow and you hit an NCCL timeout, increase it: `--dist-timeout 3600`. **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings. ## 4. Model Invocation ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [Basic API Usage](../../../docs/get-started/quickstart) ### 4.2 Advanced Usage #### 4.2.1 Reasoning Parser DeepSeek-V3 supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections: ```shell Command theme={null} python -m sglang.launch_server \ --model deepseek-ai/DeepSeek-V3 \ --reasoning-parser deepseek-v3 \ --tp 8 ``` **Streaming with Thinking Process:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Enable streaming to see the thinking process in real-time response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V3", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], temperature=0.7, max_tokens=2048, extra_body = {"chat_template_kwargs": {"thinking": True}}, stream=True ) # Process the stream has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: # Close thinking section and add content header if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= To determine 15% of a number, follow these steps: **Step 1: Understand the Problem** You need to find 15% of a given number. Let's assume the number is 240 for this example. **Step 2: Convert the Percentage to a Decimal** To work with percentages in calculations, convert the percentage to its decimal form. To do this, divide the percentage by 100. \[ 15\% = \frac{15}{100} = 0.15 \] **Step 3: Multiply the Decimal by the Number** Now, multiply the decimal form of the percentage by the number you want to find the percentage of. \[ 0.15 \times 240 \] **Step 4: Perform the Multiplication** Calculate the product: \[ 0.15 \times 240 = 36 \] **Step 5: Conclusion** Therefore, 15% of 240 is: \boxed{36} The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36. ``` **Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions. #### 4.2.2 Tool Calling DeepSeek-V3 supports tool calling capabilities. Enable the tool call parser: **Deployment Command:** ```shell Command theme={null} python -m sglang.launch_server \ --model deepseek-ai/DeepSeek-V3 \ --tool-call-parser deepseekv3 \ --reasoning-parser deepseek-v3 \ --chat-template ./examples/chat_template/tool_chat_template_deepseekv3.jinja \ --tp 8 \ --host 0.0.0.0 \ --port 30000 ``` **Quick Test (curl):** ```shell Command theme={null} curl "http://127.0.0.1:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ -d '{ "temperature": 0, "max_tokens": 100, "model": "deepseek-ai/DeepSeek-V3", "tools": [{"type": "function", "function": {"name": "query_weather", "description": "Get weather of a city", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}], "messages": [{"role": "user", "content": "How'\''s the weather in Beijing today?"}] }' ``` > [!NOTE] > > Use a low `temperature` (e.g. `0`) for more consistent tool call results. The `--chat-template` flag above provides an improved unified prompt for tool use. **Python Example (with Thinking Process):** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Make request with streaming to see thinking process response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V3", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, extra_body = {"chat_template_kwargs": {"thinking": True}}, temperature=0.7, stream=True ) # Process streaming response thinking_started = False has_thinking = False tool_calls_accumulator = {} for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Accumulate tool calls if hasattr(delta, 'tool_calls') and delta.tool_calls: # Close thinking section if needed if has_thinking and thinking_started: print("\n=============== Content =================\n", flush=True) thinking_started = False for tool_call in delta.tool_calls: index = tool_call.index if index not in tool_calls_accumulator: tool_calls_accumulator[index] = { 'name': None, 'arguments': '' } if tool_call.function: if tool_call.function.name: tool_calls_accumulator[index]['name'] = tool_call.function.name if tool_call.function.arguments: tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments # Print content if delta.content: print(delta.content, end="", flush=True) # Print accumulated tool calls for index, tool_call in sorted(tool_calls_accumulator.items()): print(f"🔧 Tool Call: {tool_call['name']}") print(f" Arguments: {tool_call['arguments']}") print() ``` **Output Example:** ```text Output theme={null} 🔧 Tool Call: get_weather Arguments: {"location": "Beijing", "unit": "celsius"} ``` **Note:** * The reasoning parser shows how the model decides to use a tool * Tool calls are clearly marked with the function name and arguments * You can then execute the function and send the result back to continue the conversation **Handling Tool Call Results:** Please attach the code blocks below to the previous Python script. ```python Example theme={null} # After getting the tool call, execute the function def get_weather(location, unit="celsius"): # Your actual weather API call here return f"The weather in {location} is 22°{unit[0].upper()} and sunny." # Send tool result back to the model messages = [ {"role": "user", "content": "What's the weather in Beijing?"}, { "role": "assistant", "content": None, "tool_calls": [{ "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": '{"location": "Beijing", "unit": "celsius"}' } }] }, { "role": "tool", "tool_call_id": "call_123", "content": get_weather("Beijing", "celsius") } ] final_response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V3", messages=messages, temperature=0.7 ) print(final_response.choices[0].message.content) # Output: "The weather in Beijing is currently 22°C and sunny." ``` #### 4.2.3 Multi-Token Prediction (EAGLE Speculative Decoding) SGLang implements DeepSeek V3 Multi-Token Prediction (MTP) based on [EAGLE speculative decoding](../../../docs/advanced_features/speculative_decoding#eagle-decoding). With this optimization, decoding speed improves by up to **1.8×** at batch size 1 and **1.5×** at batch size 32 on H200 TP8. **Enable with:** ```shell Command theme={null} python3 -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V3-0324 \ --speculative-algorithm EAGLE \ --trust-remote-code \ --tp 8 ``` The default configuration is `--speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. Find the best values for your workload with [bench\_speculative.py](https://github.com/sgl-project/sglang/blob/main/scripts/playground/bench_speculative.py). The minimum viable config is `--speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2`. > [!NOTE] > > For large batch sizes (>48), increase `--max-running-requests` beyond the default of 48 for MTP. Also set `--cuda-graph-bs-decode` to include your target batch sizes (default captured sizes for speculative decoding: 48). > [!TIP] > > The spec-v2 overlap scheduler is enabled by default. It improves performance by overlapping draft and verification stages. Pass `--disable-overlap-schedule` to disable. #### 4.2.4 MLA Optimizations DeepSeek V3 uses [Multi-head Latent Attention (MLA)](https://arxiv.org/pdf/2405.04434), an attention mechanism that improves inference efficiency. SGLang implements several optimizations: * **Weight Absorption:** Reorders matrix multiplications to improve decoding phase efficiency. * **MLA Attention Backends:** FA3, Flashinfer, FlashMLA, TRTLLM MLA (Blackwell), and Triton. FA3 is the default. * **FP8 Quantization:** W8A8 FP8 and KV Cache FP8, with BMM operators for weight-absorbed MLA in FP8. * **CUDA Graph & Torch.compile:** Both MLA and MoE support CUDA Graph and Torch.compile for reduced decoding latency. * **Chunked Prefix Cache:** Increases throughput for long-sequence chunked prefill (FlashAttention3 backend only). Overall, these optimizations achieve up to **7×** output throughput improvement vs. the baseline. **Reference:** See [SGLang v0.3 blog](https://lmsys.org/blog/2024-09-04-sglang-v0-3/#deepseek-multi-head-latent-attention-mla-throughput-optimizations) and [Slides](https://github.com/sgl-project/sgl-learning-materials/blob/main/slides/lmsys_1st_meetup_deepseek_mla.pdf) for details. #### 4.2.5 Multi-Node Deployment For multi-node serving and hardware-specific examples: * [8× H200 / 4–8× B200](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#using-docker-recommended) * [8× MI300X](../../../docs/hardware-platforms/amd_gpu#running-deepseek-v3) * [2×8× H200 with Docker](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-two-h2008-nodes-and-docker) * [4×8× A100](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-four-a1008-nodes) * [8× A100 AWQ](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-8-a100a800-with-awq-quantization) * [16× A100 INT8](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-16-a100a800-with-int8-quantization) * [32× L40S INT8](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-32-l40s-with-int8-quantization) * [Xeon 6980P CPU](../../../docs/hardware-platforms/cpu_server#example-running-deepseek-v3-1-terminus) * [4× Ascend A3 Series (int8)](../../../docs/hardware-platforms/ascend-npus/model-deployment/tutorials/deepseek_r1#multi-node-pd-disaggregation-deployment) **Blog references for large-scale deployment:** * [Deploying DeepSeek on GB200 NVL72 with PD and Large Scale EP](https://lmsys.org/blog/2025-06-16-gb200-part-1/) ([Part I](https://lmsys.org/blog/2025-06-16-gb200-part-1/), [Part II](https://lmsys.org/blog/2025-09-25-gb200-part-2/)) * [PD Disaggregation and Large-Scale Expert Parallelism on 96× H100](https://lmsys.org/blog/2025-05-05-large-scale-ep/) * [Best Practices for Serving DeepSeek-R1 on H20](https://lmsys.org/blog/2025-09-26-sglang-ant-group/) ## 5. Benchmark ### 5.1 Speed Benchmark **Test Environment:** * Hardware: AMD MI300X GPU (8x) * Model: DeepSeek-V3 * Tensor Parallelism: 8 * sglang version: 0.5.7 We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios. To simulate real-world usage patterns, we configure each request with 1024 input tokens and 1024 output tokens, representing typical medium-length conversations with detailed responses. #### 5.1.1 Latency-Sensitive Benchmark * Model Deployment Command: ```shell Command theme={null} python3 -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V3 \ --tp 8 \ --attn-dp-size 8 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --host 0.0.0.0 \ --port 8000 ``` * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --host 127.0.0.1 \ --port 8000 \ --model deepseek-ai/DeepSeek-V3 \ --random-input-len 1024 \ --random-output-len 1024 \ --num-prompts 10 \ --max-concurrency 1 ``` * **Test Results:** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 81.27 Total input tokens: 1972 Total input text tokens: 1972 Total input vision tokens: 0 Total generated tokens: 2784 Total generated tokens (retokenized): 2774 Request throughput (req/s): 0.12 Input token throughput (tok/s): 24.27 Output token throughput (tok/s): 34.26 Peak output token throughput (tok/s): 65.00 Peak concurrent requests: 2 Total token throughput (tok/s): 58.52 Concurrency: 1.00 Accept length: 2.61 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 8123.17 Median E2E Latency (ms): 7982.65 ---------------Time to First Token---------------- Mean TTFT (ms): 1080.76 Median TTFT (ms): 1248.82 P99 TTFT (ms): 1896.37 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 25.04 Median TPOT (ms): 24.76 P99 TPOT (ms): 32.09 ---------------Inter-Token Latency---------------- Mean ITL (ms): 25.41 Median ITL (ms): 20.14 P95 ITL (ms): 60.28 P99 ITL (ms): 60.99 Max ITL (ms): 61.49 ================================================== ``` #### 5.1.2 Throughput-Sensitive Benchmark * Model Deployment Command: ```shell Command theme={null} python3 -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V3 \ --tp 8 \ --ep 8 \ --attn-dp-size 8 \ --host 0.0.0.0 \ --port 8000 ``` * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --host 127.0.0.1 \ --port 8000 \ --model deepseek-ai/DeepSeek-V3 \ --random-input-len 1024 \ --random-output-len 1024 \ --num-prompts 1000 \ --max-concurrency 100 ``` * **Test Results:** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 406.16 Total input tokens: 301701 Total input text tokens: 301701 Total input vision tokens: 0 Total generated tokens: 188375 Total generated tokens (retokenized): 187542 Request throughput (req/s): 2.46 Input token throughput (tok/s): 742.81 Output token throughput (tok/s): 463.80 Peak output token throughput (tok/s): 1299.00 Peak concurrent requests: 109 Total token throughput (tok/s): 1206.61 Concurrency: 87.53 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 35552.98 Median E2E Latency (ms): 21466.07 ---------------Time to First Token---------------- Mean TTFT (ms): 1521.51 Median TTFT (ms): 476.80 P99 TTFT (ms): 8329.50 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 214.73 Median TPOT (ms): 152.00 P99 TPOT (ms): 1155.85 ---------------Inter-Token Latency---------------- Mean ITL (ms): 182.10 Median ITL (ms): 79.18 P95 ITL (ms): 398.60 P99 ITL (ms): 1488.96 Max ITL (ms): 43465.60 ================================================== ``` ### 5.2 Accuracy Benchmark #### 5.2.1 GSM8K Benchmark * **Benchmark Command:** ```shell Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:8000/v1 \ --num-examples 200 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. * **Test Results**: * DeepSeek-V3 ```text Output theme={null} Accuracy: 0.960 Invalid: 0.000 Latency: 32.450 s Output throughput: 614.211 token/s ``` #### 5.2.2 MMLU Benchmark * **Benchmark Command:** ```shell Command theme={null} sgl-eval run mmlu \ --base-url http://127.0.0.1:8000/v1 \ --num-threads 64 --max-tokens 2048 ``` The command evaluates all 57 subjects. Historical results below use the removed 10-subject harness and are not measurements of the sgl-eval command above. * **Test Results**: * DeepSeek-V3 ```text Output theme={null} subject: abstract_algebra, #q:100, acc: 0.800 subject: anatomy, #q:135, acc: 0.874 subject: astronomy, #q:152, acc: 0.928 subject: business_ethics, #q:100, acc: 0.880 subject: clinical_knowledge, #q:265, acc: 0.928 subject: college_biology, #q:144, acc: 0.965 subject: college_chemistry, #q:100, acc: 0.670 subject: college_computer_science, #q:100, acc: 0.840 subject: college_mathematics, #q:100, acc: 0.800 subject: college_medicine, #q:173, acc: 0.861 Total latency: 58.339 Average accuracy: 0.871 ``` # DeepSeek-V3.1 Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-V3_1 ## 1. Model Introduction [DeepSeek V3.1](https://huggingface.co/deepseek-ai/DeepSeek-V3.1) is an advanced Mixture-of-Experts (MoE) large language model developed by DeepSeek, representing a major capability and usability upgrade over DeepSeek V3. As a refined iteration in the DeepSeek V3 family, DeepSeek V3.1 introduces a hybrid reasoning paradigm that supports both fast non-thinking responses and explicit multi-step reasoning, alongside significantly improved tool calling and agentic behavior. The model demonstrates strong performance across reasoning, mathematics, coding, long-context understanding, and real-world agent workflows, benefiting from continued training, alignment optimization, and inference-time refinements. DeepSeek V3.1 is designed to serve as a robust general-purpose foundation model, well suited for conversational AI, structured tool invocation, search-augmented generation, and complex multi-step tasks, while maintaining high efficiency through its sparse MoE architecture. **[DeepSeek-V3.1-Terminus](https://huggingface.co/deepseek-ai/DeepSeek-V3.1-Terminus)** is an experimental version designed for general conversations and long-context processing. It features hybrid thinking capabilities, allowing you to toggle between "Think" mode for deliberate reasoning and "Non-Think" mode for faster responses. Recommended for general conversations, long-context processing, and experimental use cases. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and thinking capabilities. Run this Command:

### 3.2 Configuration Tips

DeepSeek-V3.1 shares the same model architecture as DeepSeek-V3, so the same hardware and optimization recommendations apply.

**Recommended GPU configurations by weight type:**

Weight Type Supported Hardware
**FP8** (recommended) 8× H200, 8× B200, 8× MI300X, 2×8× H100/H800/H20
**BF16** (upcast from FP8) 2×8× H200, 2×8× MI300X, 4×8× H100/H800, 4×8× A100/A800
**INT8** 16× A100/A800, 32× L40S, Xeon 6980P CPU, 4× Ascend A3 Series
**W4A8 / AWQ / MXFP4 / NVFP4** 8× H20/H100, 4× H200; 8× H100/A100; 8/4× MI355X/MI350X; 8/4× B200
> The official DeepSeek-V3.1 checkpoint is already in FP8 format — do **not** add `--quantization fp8` when serving it. **DeepGEMM precompilation (NVIDIA Hopper / Blackwell):** Precompile GEMM kernels before the first server run to avoid JIT overhead (\~10 min): ```bash theme={null} python3 -m sglang.compile_deep_gemm --model deepseek-ai/DeepSeek-V3.1 --tp 8 --trust-remote-code ``` DeepGEMM is enabled by default on Hopper/Blackwell and can be disabled with `SGLANG_ENABLE_JIT_DEEPGEMM=0`. **Data Parallelism Attention (`--attn-dp-size`):** Recommended for high-throughput scenarios with large batch sizes. Reduces KV-cache duplication across TP ranks. Use `--tp 8 --attn-dp-size 8` on a single 8-GPU node. Not recommended for low-latency, small-batch workloads. **NCCL timeout:** If model loading is slow and you hit an NCCL timeout, increase it: `--dist-timeout 3600`. **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings. ## 4. Model Invocation ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [Basic API Usage](../../../docs/get-started/quickstart) ### 4.2 Advanced Usage #### 4.2.1 Reasoning Parser DeepSeek-V3.1 supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections: ```shell Command theme={null} python -m sglang.launch_server \ --model deepseek-ai/DeepSeek-V3.1-Terminus \ --reasoning-parser deepseek-v3 \ --tp 8 \ --host 0.0.0.0 \ --port 8000 ``` **Streaming with Thinking Process:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) # Enable streaming to see the thinking process in real-time response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V3.1-Terminus", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], temperature=0.7, max_tokens=2048, extra_body = {"chat_template_kwargs": {"thinking": True}}, stream=True ) # Process the stream has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: # Close thinking section and add content header if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= First, the problem is asking for 15% of 240. Percent means per hundred, so 15% is the same as 15 out of 100, or 15/100. To find a percentage of a number, I can multiply the number by the percentage expressed as a decimal. So, I need to convert 15% to a decimal. To do that, I divide 15 by 100, which gives me 0.15. Now, I multiply 0.15 by 240. So, the calculation is 0.15 × 240. I can compute this step by step. First, I know that 15% of 100 is 15, but since 240 is larger, I need to adjust. Alternatively, I can think of 10% of 240, which is easy because 10% is just 240 divided by 10, which is 24. Then, 5% is half of 10%, so half of 24 is 12. Therefore, 15% is 10% plus 5%, so 24 plus 12, which equals 36. I should also do the multiplication to confirm. 0.15 × 240. I can break it down: 0.15 × 200 = 30, and 0.15 × 40 = 6, so 30 + 6 = 36. Same answer. So, 15% of 240 is 36. The problem says "step by step," so I should present it clearly. =============== Content ================= To find 15% of 240, follow these steps: 1. Understand that "percent" means "per hundred," so 15% is equivalent to \( \frac{15}{100} \). 2. Convert 15% to a decimal by dividing by 100: \( 15\% = \frac{15}{100} = 0.15 \). 3. Multiply the decimal by 240: \( 0.15 \times 240 \). 4. Perform the multiplication: - \( 0.15 \times 200 = 30 \) - \( 0.15 \times 40 = 6 \) - Add the results: \( 30 + 6 = 36 \). Alternatively, you can find 15% by breaking it into parts: - 10% of 240 is \( \frac{10}{100} \times 240 = 0.10 \times 240 = 24 \). - 5% of 240 is half of 10%, so \( \frac{24}{2} = 12 \). - Add 10% and 5%: \( 24 + 12 = 36 \). Thus, 15% of 240 is 36. ``` **Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions. #### 4.2.2 Tool Calling DeepSeek-V3.1 and DeepSeek-V3.1-Terminus support tool calling capabilities. Enable the tool call parser: **Deployment Command:** ```shell Command theme={null} python -m sglang.launch_server \ --model deepseek-ai/DeepSeek-V3.1-Terminus \ --tool-call-parser deepseekv31 \ --reasoning-parser deepseek-v3 \ --chat-template ./examples/chat_template/tool_chat_template_deepseekv31.jinja \ --tp 8 \ --host 0.0.0.0 \ --port 8000 ``` For DeepSeek-V3.1, use `--tool-call-parser deepseekv31` as well. **Python Example (with Thinking Process):** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Make request with streaming to see thinking process response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V3.1-Terminus", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, extra_body = {"chat_template_kwargs": {"thinking": True}}, temperature=0.7, stream=True ) # Process streaming response thinking_started = False has_thinking = False tool_calls_accumulator = {} for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Accumulate tool calls if hasattr(delta, 'tool_calls') and delta.tool_calls: # Close thinking section if needed if has_thinking and thinking_started: print("\n=============== Content =================\n", flush=True) thinking_started = False for tool_call in delta.tool_calls: index = tool_call.index if index not in tool_calls_accumulator: tool_calls_accumulator[index] = { 'name': None, 'arguments': '' } if tool_call.function: if tool_call.function.name: tool_calls_accumulator[index]['name'] = tool_call.function.name if tool_call.function.arguments: tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments # Print content if delta.content: print(delta.content, end="", flush=True) # Print accumulated tool calls for index, tool_call in sorted(tool_calls_accumulator.items()): print(f"🔧 Tool Call: {tool_call['name']}") print(f" Arguments: {tool_call['arguments']}") print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= Hmm, the user is asking for the weather in Beijing. This is a straightforward request that matches exactly what the weather tool can provide. I need to call the get_weather function with Beijing as the location parameter. The user didn't specify a temperature unit, so I'll default to Celsius since that's commonly used in most parts of the world. The tool call format needs to be precise - just the city name and unit selection. Once I get the weather data back, I'll present it clearly to the user.I'll check the weather in Beijing for you. =============== Content ================= 🔧 Tool Call: get_weather Arguments: {"location": "Beijing", "unit": "celsius"} ``` **Note:** * The reasoning parser shows how the model decides to use a tool * Tool calls are clearly marked with the function name and arguments * You can then execute the function and send the result back to continue the conversation **Handling Tool Call Results:** Please attach the code blocks below to the previous Python script. ```python Example theme={null} # After getting the tool call, execute the function def get_weather(location, unit="celsius"): # Your actual weather API call here return f"The weather in {location} is 22°{unit[0].upper()} and sunny." # Send tool result back to the model messages = [ {"role": "user", "content": "What's the weather in Beijing?"}, { "role": "assistant", "content": None, "tool_calls": [{ "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": '{"location": "Beijing", "unit": "celsius"}' } }] }, { "role": "tool", "tool_call_id": "call_123", "content": get_weather("Beijing", "celsius") } ] final_response = client.chat.completions.create( model="deepseek-ai/DeepSeek-V3.1-Terminus", messages=messages, temperature=0.7 ) print(final_response.choices[0].message.content) # Output: "Currently, it is **22°C and sunny** in Beijing." ``` #### 4.2.3 Multi-Token Prediction (EAGLE Speculative Decoding) DeepSeek-V3.1 shares the same architecture as DeepSeek-V3 and supports the same EAGLE-based MTP speculative decoding path. Refer to [DeepSeek-V3 §4.2.3](/cookbook/autoregressive/DeepSeek/DeepSeek-V3#4-2-3-multi-token-prediction-eagle-speculative-decoding) for the full configuration, tuning guidance, and `bench_speculative.py` reference. The `--speculative-num-steps`, `--speculative-eagle-topk`, and `--max-running-requests` recommendations apply equally to V3.1. ## 5. Benchmark ### 5.1 Speed Benchmark **Test Environment:** * Hardware: AMD MI300X GPU (8x) * Model: DeepSeek-V3.1-Terminus * Tensor Parallelism: 8 * sglang version: 0.5.7 **Benchmark Methodology:** We use industry-standard benchmark configurations to ensure results are comparable across frameworks and hardware platforms. #### 5.1.1 Standard Test Scenarios Three core scenarios reflect real-world usage patterns:
Scenario Input Length Output Length Use Case
**Chat** 1K 1K Most common conversational AI workload
**Reasoning** 1K 8K Long-form generation, complex reasoning tasks
**Summarization** 8K 1K Document summarization, RAG retrieval
#### 5.1.2 Concurrency Levels Test each scenario at different concurrency levels to capture the throughput vs. latency trade-off: * **Low Concurrency**: `--max-concurrency 1` (Latency-optimized) * **Medium Concurrency**: `--max-concurrency 16` (Balanced) * **High Concurrency**: `--max-concurrency 100` (Throughput-optimized) #### 5.1.3 Number of Prompts For each concurrency level, configure `num_prompts` to simulate realistic user loads: * **Quick Test**: `num_prompts = concurrency × 1` (minimal test) * **Recommended**: `num_prompts = concurrency × 5` (standard benchmark) * **Stable Measurements**: `num_prompts = concurrency × 10` (production-grade) *** #### 5.1.4 Benchmark Commands **Scenario 1: Chat (1K/1K) - Most Important** * **Model Deployment** ```bash Command theme={null} python -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V3.1 \ --tp 8 ``` * Low Concurrency (Latency-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 106.24 Total input tokens: 6101 Total input text tokens: 6101 Total input vision tokens: 0 Total generated tokens: 4220 Total generated tokens (retokenized): 4201 Request throughput (req/s): 0.09 Input token throughput (tok/s): 57.43 Output token throughput (tok/s): 39.72 Peak output token throughput (tok/s): 43.00 Peak concurrent requests: 2 Total token throughput (tok/s): 97.15 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 10620.29 Median E2E Latency (ms): 8868.09 ---------------Time to First Token---------------- Mean TTFT (ms): 557.85 Median TTFT (ms): 213.58 P99 TTFT (ms): 1625.28 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 23.84 Median TPOT (ms): 23.90 P99 TPOT (ms): 24.03 ---------------Inter-Token Latency---------------- Mean ITL (ms): 23.90 Median ITL (ms): 23.92 P95 ITL (ms): 24.15 P99 ITL (ms): 24.25 Max ITL (ms): 25.44 ================================================== ``` * Medium Concurrency (Balanced) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 107.71 Total input tokens: 39668 Total input text tokens: 39668 Total input vision tokens: 0 Total generated tokens: 40805 Total generated tokens (retokenized): 40625 Request throughput (req/s): 0.74 Input token throughput (tok/s): 368.28 Output token throughput (tok/s): 378.84 Peak output token throughput (tok/s): 508.00 Peak concurrent requests: 19 Total token throughput (tok/s): 747.12 Concurrency: 13.72 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 18473.65 Median E2E Latency (ms): 19558.42 ---------------Time to First Token---------------- Mean TTFT (ms): 607.91 Median TTFT (ms): 191.32 P99 TTFT (ms): 2135.13 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 35.50 Median TPOT (ms): 35.99 P99 TPOT (ms): 43.62 ---------------Inter-Token Latency---------------- Mean ITL (ms): 35.10 Median ITL (ms): 32.18 P95 ITL (ms): 33.03 P99 ITL (ms): 159.99 Max ITL (ms): 453.99 ================================================== ``` * High Concurrency (Throughput-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 207.65 Total input tokens: 249831 Total input text tokens: 249831 Total input vision tokens: 0 Total generated tokens: 252662 Total generated tokens (retokenized): 251238 Request throughput (req/s): 2.41 Input token throughput (tok/s): 1203.15 Output token throughput (tok/s): 1216.79 Peak output token throughput (tok/s): 2100.00 Peak concurrent requests: 106 Total token throughput (tok/s): 2419.94 Concurrency: 91.02 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 37800.20 Median E2E Latency (ms): 35921.56 ---------------Time to First Token---------------- Mean TTFT (ms): 835.15 Median TTFT (ms): 236.88 P99 TTFT (ms): 2868.52 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 73.33 Median TPOT (ms): 76.35 P99 TPOT (ms): 97.63 ---------------Inter-Token Latency---------------- Mean ITL (ms): 73.30 Median ITL (ms): 50.82 P95 ITL (ms): 180.67 P99 ITL (ms): 186.83 Max ITL (ms): 1661.39 ================================================== ``` **Scenario 2: Reasoning (1K/8K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 1097.29 Total input tokens: 6101 Total input text tokens: 6101 Total input vision tokens: 0 Total generated tokens: 44462 Total generated tokens (retokenized): 44313 Request throughput (req/s): 0.01 Input token throughput (tok/s): 5.56 Output token throughput (tok/s): 40.52 Peak output token throughput (tok/s): 43.00 Peak concurrent requests: 2 Total token throughput (tok/s): 46.08 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 109725.52 Median E2E Latency (ms): 117748.67 ---------------Time to First Token---------------- Mean TTFT (ms): 156.67 Median TTFT (ms): 156.19 P99 TTFT (ms): 159.87 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 24.41 Median TPOT (ms): 24.51 P99 TPOT (ms): 24.96 ---------------Inter-Token Latency---------------- Mean ITL (ms): 24.65 Median ITL (ms): 24.58 P95 ITL (ms): 25.68 P99 ITL (ms): 25.93 Max ITL (ms): 29.80 ================================================== ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 775.02 Total input tokens: 39668 Total input text tokens: 39668 Total input vision tokens: 0 Total generated tokens: 318306 Total generated tokens (retokenized): 317426 Request throughput (req/s): 0.10 Input token throughput (tok/s): 51.18 Output token throughput (tok/s): 410.70 Peak output token throughput (tok/s): 512.00 Peak concurrent requests: 18 Total token throughput (tok/s): 461.89 Concurrency: 13.86 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 134236.65 Median E2E Latency (ms): 135181.28 ---------------Time to First Token---------------- Mean TTFT (ms): 214.35 Median TTFT (ms): 194.12 P99 TTFT (ms): 300.27 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 33.72 Median TPOT (ms): 34.00 P99 TPOT (ms): 34.75 ---------------Inter-Token Latency---------------- Mean ITL (ms): 33.69 Median ITL (ms): 33.71 P95 ITL (ms): 34.50 P99 ITL (ms): 34.92 Max ITL (ms): 164.76 ================================================== ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 1231.97 Total input tokens: 158939 Total input text tokens: 158939 Total input vision tokens: 0 Total generated tokens: 1301025 Total generated tokens (retokenized): 1296845 Request throughput (req/s): 0.26 Input token throughput (tok/s): 129.01 Output token throughput (tok/s): 1056.05 Peak output token throughput (tok/s): 1472.00 Peak concurrent requests: 67 Total token throughput (tok/s): 1185.07 Concurrency: 56.17 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 216256.25 Median E2E Latency (ms): 224192.84 ---------------Time to First Token---------------- Mean TTFT (ms): 317.68 Median TTFT (ms): 235.28 P99 TTFT (ms): 649.39 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 53.30 Median TPOT (ms): 55.10 P99 TPOT (ms): 56.58 ---------------Inter-Token Latency---------------- Mean ITL (ms): 53.13 Median ITL (ms): 52.95 P95 ITL (ms): 56.23 P99 ITL (ms): 181.04 Max ITL (ms): 208.61 ================================================== ``` **Scenario 3: Summarization (8K/1K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 114.47 Total input tokens: 41941 Total input text tokens: 41941 Total input vision tokens: 0 Total generated tokens: 4220 Total generated tokens (retokenized): 4194 Request throughput (req/s): 0.09 Input token throughput (tok/s): 366.39 Output token throughput (tok/s): 36.87 Peak output token throughput (tok/s): 42.00 Peak concurrent requests: 2 Total token throughput (tok/s): 403.26 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 11442.86 Median E2E Latency (ms): 9508.87 ---------------Time to First Token---------------- Mean TTFT (ms): 883.78 Median TTFT (ms): 481.38 P99 TTFT (ms): 2217.45 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 24.93 Median TPOT (ms): 25.05 P99 TPOT (ms): 26.11 ---------------Inter-Token Latency---------------- Mean ITL (ms): 25.08 Median ITL (ms): 25.08 P95 ITL (ms): 26.18 P99 ITL (ms): 26.28 Max ITL (ms): 27.41 ================================================== ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 162.33 Total input tokens: 300020 Total input text tokens: 300020 Total input vision tokens: 0 Total generated tokens: 41669 Total generated tokens (retokenized): 41443 Request throughput (req/s): 0.49 Input token throughput (tok/s): 1848.27 Output token throughput (tok/s): 256.70 Peak output token throughput (tok/s): 467.00 Peak concurrent requests: 19 Total token throughput (tok/s): 2104.97 Concurrency: 14.52 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 29456.89 Median E2E Latency (ms): 27628.16 ---------------Time to First Token---------------- Mean TTFT (ms): 1784.30 Median TTFT (ms): 1347.21 P99 TTFT (ms): 5384.54 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 53.65 Median TPOT (ms): 52.09 P99 TPOT (ms): 74.39 ---------------Inter-Token Latency---------------- Mean ITL (ms): 53.23 Median ITL (ms): 34.52 P95 ITL (ms): 35.81 P99 ITL (ms): 513.25 Max ITL (ms): 2865.73 ================================================== ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model deepseek-ai/DeepSeek-V3.1 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 282.55 Total input tokens: 1273893 Total input text tokens: 1273893 Total input vision tokens: 0 Total generated tokens: 170000 Total generated tokens (retokenized): 169081 Request throughput (req/s): 1.13 Input token throughput (tok/s): 4508.6 Output token throughput (tok/s): 601.67 Peak output token throughput (tok/s): 1216 Peak concurrent requests: 68 Total token throughput (tok/s): 5110.27 Concurrency: 59.81 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 52810.32 Median E2E Latency (ms): 50981.81 ---------------Time to First Token---------------- Mean TTFT (ms): 786.69 Median TTFT (ms): 499.38 P99 TTFT (ms): 2925.98 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 97.93 Median TPOT (ms): 103.45 P99 TPOT (ms): 157.84 ---------------Inter-Token Latency---------------- Mean ITL (ms): 98.11 Median ITL (ms): 55.7 P95 ITL (ms): 240.71 P99 ITL (ms): 1114.36 ================================================== ``` #### 5.1.5 Understanding the Results **Key Metrics:** * **Request Throughput (req/s)**: Number of requests processed per second * **Output Token Throughput (tok/s)**: Total tokens generated per second * **Mean TTFT (ms)**: Time to First Token - measures responsiveness * **Mean TPOT (ms)**: Time Per Output Token - measures generation speed * **Mean ITL (ms)**: Inter-Token Latency - measures streaming consistency **Why These Configurations Matter:** * **1K/1K (Chat)**: Represents the most common conversational AI workload. This is the highest priority scenario for most deployments. * **1K/8K (Reasoning)**: Tests long-form generation capabilities crucial for complex reasoning, code generation, and detailed explanations. * **8K/1K (Summarization)**: Evaluates performance with large context inputs, essential for RAG systems, document Q\&A, and summarization tasks. * **Variable Concurrency**: Captures the Pareto frontier - the optimal trade-off between throughput and latency at different load levels. Low concurrency shows best-case latency, high concurrency shows maximum throughput. **Interpreting Results:** * Compare your results against baseline numbers for your hardware * Higher throughput at same latency = better performance * Lower TTFT = more responsive user experience * Lower TPOT = faster generation speed ### 5.2 Accuracy Benchmark Document model accuracy on standard benchmarks: #### 5.2.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 1319 \ --num-threads 1316 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. **Test Results:** ```text Output theme={null} Accuracy: 0.959 Invalid: 0.000 Latency: 29.185 s Output throughput: 4854.672 token/s ``` # DeepSeek-V3.2 Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-V3_2 ## 1. Model Introduction The DeepSeek-V3.2 series includes three model variants, each optimized for different use cases: **[DeepSeek-V3.2-Exp](https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Exp)** is an upgraded version of DeepSeek-V3.1-Terminus, introducing the DeepSeek Sparse Attention (DSA) mechanism through continued training. DSA is a fine-grained sparse attention mechanism powered by a lightning indexer, enabling DeepSeek-V3.2-Exp to achieve significant efficiency improvements in long-context scenarios. Recommended for general conversations, long-context processing, and efficient inference. **[DeepSeek-V3.2](https://huggingface.co/deepseek-ai/DeepSeek-V3.2)** is the standard version suitable for general tasks and conversational scenarios. For local deployment, we recommend setting the sampling parameters to temperature = 1.0, top\_p = 0.95. Recommended for standard conversations and general tasks. **[DeepSeek-V3.2-Speciale](https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Speciale)** is a special variant designed exclusively for deep reasoning tasks. This model is specifically optimized for scenarios requiring complex logical reasoning and deep thinking. However this model does not support tool calls (see below). For local deployment, we recommend setting the sampling parameters to temperature = 1.0, top\_p = 0.95. Recommended for deep reasoning tasks, complex logical problems, and mathematical reasoning. **[DeepSeek-V3.2-NVFP4](https://huggingface.co/nvidia/DeepSeek-V3.2-NVFP4)** is an NVIDIA-optimized NVFP4-quantized variant of DeepSeek-V3.2 for Blackwell devices. It uses ModelOpt FP4 quantization with a choice of MoE runner backends (`flashinfer_trtllm` (recommended), `flashinfer_cutlass`, or `flashinfer_cutedsl`), enabling efficient deployment with lower tensor parallelism (TP=4). It supports the same features as DeepSeek-V3.2 including tool calling, reasoning, and speculative decoding (MTP). **[DeepSeek-V3.2-MXFP4](https://huggingface.co/amd/DeepSeek-V3.2-mxfp4)** is an OCP-MXFP4 optimized variant for DeepSeek-V3.2 for AMD MI300X/MI355X devices. It uses OCP MXFP4 quantization with a triton mxfp4 backend (the same backend for gptoss-120B), enabling efficient deployment with lower tensor parallelism (TP=8) in a single node. It includes the same features as DeepSeek-V3.2 including tool calling, reasoning, fp8-kv, CP, TP and speculative decoding MTP. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ### 2.1 Docker Images Pre-built Docker images are available for different hardware platforms: ```bash Command theme={null} # NVIDIA H200 / B200 docker pull lmsysorg/sglang:latest # AMD MI350 / MI355X docker pull lmsysorg/sglang:v0.5.8-rocm700-mi35x # AMD MI300X # Note: v0.5.8-rocm700-mi30x does not include PR #17504. # Prefer the newest MI30x ROCm image tag from Docker Hub when available, or build from source. docker pull lmsysorg/sglang:v0.5.8-rocm700-mi30x # Ascend NPU (A2/A3 Series) docker pull lmsysorg/sglang:dsv32-a2 docker pull lmsysorg/sglang:dsv32-a3 ``` ## 3. Model Deployment This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and thinking capabilities. SGLang supports serving DeepSeek V3.2 on NVIDIA H200, B200, and AMD MI300X/MI355X GPUs. Run this Command:

> [!WARNING]
>
> All recipes here run the DSA indexer top-k on the default `--dsa-topk-backend sgl-kernel`. Other top-k backend choices have not been fully validated on DeepSeek-V3.2.

### 3.2 Configuration Tips

* **Short-sequence MHA prefill (adaptive):** For prefill sequences shorter than 2048 tokens (default threshold), the DSA backend automatically switches to standard MHA (using FlashAttention variable-length on SM90, TRT-LLM ragged MHA on SM100). To extend this to longer sequences set env var `SGLANG_DSA_PREFILL_DENSE_ATTN_KV_LEN_THRESHOLD` to a larger value (potential minor accuracy trade-off).
* **DSA prefill/decode attention kernels (`--dsa-prefill-backend`, `--dsa-decode-backend`):** The `dsa` backend is automatically selected for DeepSeek-V3.2. Available kernels: `flashmla_sparse`, `flashmla_sparse_q8` (native FP8 e4m3 sparse prefill — no fp8→bf16 dequantization round-trip; Hopper SM90 + `--kv-cache-dtype fp8_e4m3` only, prefill only), `flashmla_kv`, `flashmla_auto`, `fa3` (Hopper only), `tilelang` (GPU/HPU/NPU), `aiter` (AMD, decode only), `trtllm` (Blackwell only). Defaults: Hopper BF16 KV → `flashmla_sparse` prefill / `fa3` decode; Hopper FP8 KV → `flashmla_kv` both; Blackwell BF16 → `flashmla_sparse` / `trtllm`; Blackwell FP8 → `trtllm` both.
* **Index Cache:** Reuses indexer results across layers for efficiency at negligible accuracy cost. For **GLM-5** specifically, append `--json-model-override-args '{"index_topk_pattern": "FFSFSSSFSSFFFSSSFFFSFSSSSSSFFSFFSFFSSFFFFFFSFFFFFSFFSSSSSSFSFFFSFSSSFSFFSFFSSS"}'` for a better speed/accuracy tradeoff.
* **HiSparse (experimental):** Reduces per-request GPU memory during long-context decode by offloading KV data to CPU pinned memory. Requires PD disaggregation mode (decode instance only). See [HiSparse Guide](../../../docs/advanced_features/hisparse_guide).
* **NVFP4 on Blackwell:** Specify `--quantization modelopt_fp4` and `--moe-runner-backend flashinfer_trtllm` (recommended) / `flashinfer_cutlass` / `flashinfer_cutedsl`. Full example:
  ```bash theme={null}
  python -m sglang.launch_server --model nvidia/DeepSeek-V3.2-NVFP4 --tp 4 \
    --quantization modelopt_fp4 --moe-runner-backend flashinfer_trtllm \
    --tool-call-parser deepseekv32 --reasoning-parser deepseek-v3
  ```
* **NCCL timeout:** Slow model loading → add `--dist-timeout 3600`.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [Basic API Usage](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

DeepSeek-V3.2 supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections:

```shell Command theme={null}
sglang serve \
  --model-path deepseek-ai/DeepSeek-V3.2-Exp \
  --reasoning-parser deepseek-v3 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V3.2-Exp",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    extra_body = {"chat_template_kwargs": {"thinking": True}},
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
To solve this problem, I need to calculate 15% of 240.
Step 1: Convert 15% to decimal: 15% = 0.15
Step 2: Multiply 240 by 0.15
Step 3: 240 × 0.15 = 36
=============== Content =================

The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36.
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.2 Tool Calling

DeepSeek-V3.2 and DeepSeek-V3.2-Exp support tool calling capabilities. But they use different parameters. Enable the tool call parser:

**Note:** DeepSeek-V3.2-Speciale does **NOT** support tool calling. Launch it with reasoning parser only:

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path deepseek-ai/DeepSeek-V3.2-Speciale \
  --trust-remote-code \
  --tp-size 8 --attn-dp-size 8 \
  --reasoning-parser deepseek-v3
```

**Deployment Command:**

For DeepSeek-V3.2-Exp:

```shell Command theme={null}
sglang serve \
  --model-path deepseek-ai/DeepSeek-V3.2-Exp \
  --tool-call-parser deepseekv31 \
  --reasoning-parser deepseek-v3 \
  --chat-template ./examples/chat_template/tool_chat_template_deepseekv32.jinja \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

For DeepSeek-V3.2, use `--tool-call-parser deepseekv32` and remove `--chat-template`.

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V3.2-Exp",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    extra_body = {"chat_template_kwargs": {"thinking": True}},
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information.
I should call the function with location="Beijing".
=============== Content =================

Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V3.2-Exp",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The weather in Beijing is currently 22°C and sunny."
```

#### 4.2.3 Multi-Token Prediction (EAGLE Speculative Decoding)

SGLang implements Multi-Token Prediction (MTP) for DeepSeek V3.2 based on [EAGLE speculative decoding](../../../docs/advanced_features/speculative_decoding#eagle-decoding). This optimization significantly improves decoding speed for small batch sizes.

**With DP Attention:**

```bash Command theme={null}
python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 --attn-dp-size 8 \
  --speculative-algorithm EAGLE \
  --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4
```

**With Pure TP:**

```bash Command theme={null}
python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 \
  --speculative-algorithm EAGLE \
  --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4
```

Find optimal values for your workload with [bench\_speculative.py](https://github.com/sgl-project/sglang/blob/main/scripts/playground/bench_speculative.py). The minimum viable config is `--speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2`.

> [!NOTE]
>
> `--max-running-requests` defaults to 48 for MTP. Increase it for larger batch sizes.

> [!TIP]
>
> The spec-v2 overlap scheduler is enabled by default. Pass `--disable-overlap-schedule` to disable.

#### 4.2.4 PD Disaggregation

Prefill-Decode (PD) disaggregation separates prefill and decode stages onto different instances, improving GPU utilization for mixed workloads.

**Prefill command:**

```bash Command theme={null}
python -m sglang.launch_server \
  --model-path deepseek-ai/DeepSeek-V3.2-Exp \
  --disaggregation-mode prefill \
  --host $LOCAL_IP \
  --port $PORT \
  --tp 8 \
  --attn-dp-size 8 \
  --dist-init-addr ${HOST}:${DIST_PORT} \
  --trust-remote-code \
  --disaggregation-bootstrap-port 8998 \
  --mem-fraction-static 0.9
```

**Decode command:**

```bash Command theme={null}
python -m sglang.launch_server \
  --model-path deepseek-ai/DeepSeek-V3.2-Exp \
  --disaggregation-mode decode \
  --host $LOCAL_IP \
  --port $PORT \
  --tp 8 \
  --attn-dp-size 8 \
  --dist-init-addr ${HOST}:${DIST_PORT} \
  --trust-remote-code \
  --mem-fraction-static 0.9
```

**Router command:**

```bash Command theme={null}
python -m sglang_router.launch_router --pd-disaggregation \
  --prefill $PREFILL_ADDR 8998 \
  --decode $DECODE_ADDR \
  --host 127.0.0.1 \
  --port 30000
```

For production deployments (RBG / LWS-based, DeepEP EP parallelism), see [multi\_node\_deployment docs](../../../docs/references/multi_node_deployment/rbg_pd/deepseekv32_pd).

#### 4.2.5 DSA Long-Sequence Context Parallel and PP/CP

Enable prefill context parallelism (CP) on CUDA with `--enable-prefill-cp --cp-strategy interleave` for long-sequence workloads.

> [!WARNING]
>
> Zigzag prefill CP (`--cp-strategy zigzag`) is temporarily unavailable for DeepSeek V3.2, GLM-5, GLM-5.1, GLM-5.2, and GLM-5.3. Use `interleave` for these models. Attention DP is supported, with `tp_size / attn_dp_size` CP ranks in each DP group. Dense FFNs retain their configured TP width; `--moe-dense-tp-size 1` selects local dense computation.

**Interleave** (`--cp-strategy interleave`): Distributes tokens by `token_idx % cp_size`. It supports fused MoE, FP8 KV cache, and multi-batch prefill.

```bash Command theme={null}
# Interleave — FusedMoE + CP8
python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp \
  --tp 8 --enable-prefill-cp --attn-cp-size 8 \
  --cp-strategy interleave --max-running-requests 32
```

**PP + CP (multi-node):** Combines Pipeline Parallelism and Context Parallelism for cross-node scaling. The production-optimized configurations below have been verified on Hopper:

We suggested `DP2` + `MTP` for local deployment of agentic workflow with DeepSeek V3.2 on Hopper platform:

```shell Command theme={null}
export SGLANG_DEEPEP_LL_COMBINE_SEND_NUM_SMS=32
export SGLANG_SET_CPU_AFFINITY=1

# Test workload ISL/OSL=1k/1k, raw tap : 4948.16 toks/sec, MAX ITL 5970
#   dp 2 : 5019.54  toks/sec, MAX ITL 7233
#   dp 4 : 4942.82  toks/sec, MAX ITL 35654
#   dp 2 + mtp : 6842.51 toks/sec, MAX ITL 3081
sglang_args=$(echo serve \
  --model-path $MAPPED_MODEL_PATH \
  --nccl-init $MASTER_ADDR:$MASTER_PORT --nnodes 2 --node-rank $RANK --tp 16 \
  --attn-dp-size 2 --page-size 64 \
  --trust-remote-code --host "0.0.0.0" --port 30000 \
  --log-requests \
  --context-length 65536 --max-running-requests 128 \
  --speculative-algorithm EAGLE \
  --speculative-num-steps 2 --speculative-eagle-topk 1 --speculative-num-draft-tokens 3 \
  --allow-auto-truncate --enable-metrics \
  --tool-call-parser deepseekv32 --reasoning-parser deepseek-v3 \
  --served-model-name DeepSeek-V3.2-Opt-dp2-mtp
)

sglang_args=($sglang_args)

sglang "${sglang_args[@]}" 2>&1 | tee $LOG_DIR/$RANK.log
```

**CP + PP + EP**

`CP` is currently enabled with `PP=2` on Hopper platform and we can reduce TP=16 to TP=8 from standalone deployment:

```shell Command theme={null}
# verified on Hopper platform
sglang_args=$(echo serve \
  --model-path $MAPPED_MODEL_PATH \
  --nccl-init $MASTER_ADDR:$MASTER_PORT --nnodes 2 --node-rank $RANK --tp 8 --pp-size 2 \
  --moe-a2a-backend deepep --ep-size 16  \
  --page-size 128 \
  --chunked-prefill-size 16384 \
  --attention-backend dsa \
  --dsa-prefill-backend flashmla_sparse \
  --dsa-decode-backend flashmla_sparse \
  --enable-prefill-cp \
  --cp-strategy interleave \
  --cuda-graph-max-bs-decode 128 \
  --max-running-requests 128 \
  --trust-remote-code --host "0.0.0.0" --port 30000 \
  --log-requests \
  --context-length 65536 \
  --allow-auto-truncate --enable-metrics \
  --tool-call-parser deepseekv32 --reasoning-parser deepseek-v3 \
  --served-model-name DeepSeek-V3.2-dsa-pp-cp-ep
)

sglang_args=($sglang_args)

sglang "${sglang_args[@]}" 2>&1 | tee $LOG_DIR/$RANK.log
```

**fp8 KV + CP + PP**

FP8 KV reduces the memory footprint. For DeepSeek V3.2, combine it with interleave CP and PP, without attention DP:

```shell Command theme={null}
# verified in Hopper platform
cp_config=" \
  --enable-prefill-cp \
  --cp-strategy interleave \
"

# see discussion : https://github.com/sgl-project/sglang/pull/12065
sglang_args=$(echo serve \
  --model-path $MAPPED_MODEL_PATH \
  --nccl-init $MASTER_ADDR:$MASTER_PORT --nnodes 2 --node-rank $RANK --tp 8 --pp-size 2 --pp-async-batch-depth 1 \
  --trust-remote-code --host "0.0.0.0" --port 30000 \
  --log-requests \
  --context-length 65536 --max-running-requests 128 \
  $cp_config \
  --kv-cache-dtype fp8_e4m3 \
  --allow-auto-truncate --enable-metrics \
  --tool-call-parser deepseekv32 --reasoning-parser deepseek-v3 \
  --served-model-name DeepSeek-V3.2-Opt-fp8kv-pp2-cp4
)

sglang_args=($sglang_args)

sglang "${sglang_args[@]}" 2>&1 | tee $LOG_DIR/$RANK.log
```

## 5. Benchmark

### 5.1 Speed Benchmark on Blackwell

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8x)
* Model: DeepSeek-V3.2-Exp
* Tensor Parallelism: 8
* sglang version: 0.5.6

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios. To simulate real-world usage patterns, we configure each request with 1024 input tokens and 1024 output tokens, representing typical medium-length conversations with detailed responses.

#### 5.1.1 Latency-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
sglang serve \
  --model-path deepseek-ai/DeepSeek-V3.2-Exp \
  --tp 8 \
  --speculative-algorithm EAGLE \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model deepseek-ai/DeepSeek-V3.2-Exp \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  29.11
Total input tokens:                      1972
Total input text tokens:                 1972
Total input vision tokens:               0
Total generated tokens:                  2784
Total generated tokens (retokenized):    2777
Request throughput (req/s):              0.34
Input token throughput (tok/s):          67.73
Output token throughput (tok/s):         95.62
Peak output token throughput (tok/s):    157.00
Peak concurrent requests:                3
Total token throughput (tok/s):          163.36
Concurrency:                             1.00
Accept length:                           2.46
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2909.74
Median E2E Latency (ms):                 3088.27
P90 E2E Latency (ms):                    4200.62
P99 E2E Latency (ms):                    5588.52
---------------Time to First Token----------------
Mean TTFT (ms):                          317.58
Median TTFT (ms):                        191.31
P99 TTFT (ms):                           740.79
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          9.09
Median TPOT (ms):                        9.25
P99 TPOT (ms):                           11.73
---------------Inter-Token Latency----------------
Mean ITL (ms):                           9.35
Median ITL (ms):                         7.64
P95 ITL (ms):                            22.81
P99 ITL (ms):                            23.33
Max ITL (ms):                            31.45
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
sglang serve \
  --model-path deepseek-ai/DeepSeek-V3.2-Exp \
  --tp 8 \
  --ep 8 \
  --attn-dp-size 8 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model deepseek-ai/DeepSeek-V3.2-Exp \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  219.09
Total input tokens:                      301701
Total input text tokens:                 301701
Total input vision tokens:               0
Total generated tokens:                  188375
Total generated tokens (retokenized):    187443
Request throughput (req/s):              4.56
Input token throughput (tok/s):          1377.06
Output token throughput (tok/s):         859.80
Peak output token throughput (tok/s):    2465.00
Peak concurrent requests:                109
Total token throughput (tok/s):          2236.86
Concurrency:                             88.05
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   19291.23
Median E2E Latency (ms):                 11927.39
---------------Time to First Token----------------
Mean TTFT (ms):                          530.36
Median TTFT (ms):                        444.00
P99 TTFT (ms):                           1504.78
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          106.16
Median TPOT (ms):                        106.69
P99 TPOT (ms):                           221.12
---------------Inter-Token Latency----------------
Mean ITL (ms):                           100.46
Median ITL (ms):                         41.73
P95 ITL (ms):                            225.67
P99 ITL (ms):                            392.37
Max ITL (ms):                            975.03
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* **Test Results**:
  * DeepSeek-V3.2-Exp
    ```
    Accuracy: 0.980
    Invalid: 0.000
    Latency: 19.128 s
    Output throughput: 965.919 token/s
    ```

* **Full GSM8K (1319 questions)** — evaluate the complete test set with sgl-eval:

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 1319 \
  --num-threads 1319
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

* 8-shot:
  ```
  Accuracy: 0.956
  Invalid: 0.000
  Latency: 25.109 s
  Output throughput: 5226.235 token/s
  ```
* 20-shot (long-context; stays close to the 8-shot result):
  ```
  Accuracy: 0.956
  Invalid: 0.000
  Latency: 29.545 s
  Output throughput: 4418.617 token/s
  ```

#### 5.2.2 MMLU Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run mmlu \
  --base-url http://127.0.0.1:30000/v1 \
  --num-threads 64 --max-tokens 2048
```

The command evaluates all 57 subjects. Historical results below use the removed 10-subject harness and are not measurements of the sgl-eval command above.

* **Test Results**:
  * DeepSeek-V3.2-Exp
    ```
    subject: abstract_algebra, #q:100, acc: 0.780
    subject: anatomy, #q:135, acc: 0.874
    subject: astronomy, #q:152, acc: 0.961
    subject: business_ethics, #q:100, acc: 0.860
    subject: clinical_knowledge, #q:265, acc: 0.925
    subject: college_biology, #q:144, acc: 0.972
    subject: college_chemistry, #q:100, acc: 0.660
    subject: college_computer_science, #q:100, acc: 0.880
    subject: college_mathematics, #q:100, acc: 0.840
    subject: college_medicine, #q:173, acc: 0.879
    Total latency: 7.961
    Average accuracy: 0.879
    ```

#### 5.2.3 GPQA-Diamond Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gpqa --base-url http://127.0.0.1:30000/v1 --num-examples 198 --max-tokens 128000 --n-repeats 8 --thinking
```

* **Historical Test Results** (model: `deepseek-ai/DeepSeek-V3.2-Exp`, 8×B200; measured with the earlier `sglang.test.run_eval` GPQA command):
  * Default (`temperature=0`): mean **0.797** over 8 runs — closely matches the official GPQA-Diamond score of **79.9** for DeepSeek-V3.2-Exp reported in its [model card](https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Exp)
  * With `temperature=1.0, top_p=0.95` (as recommended by DeepSeek):

```shell Command theme={null}
sgl-eval run gpqa --base-url http://127.0.0.1:30000/v1 --num-examples 198 --max-tokens 128000 --n-repeats 8 --top-p 0.95 --temperature 1.0 --thinking
```

```
Repeat: 8, mean: 0.840
Scores: ['0.848', '0.808', '0.848', '0.838', '0.879', '0.813', '0.838', '0.848']
```

#### 5.2.4 AIME 2025 Benchmark

Results on AIME 2025 (8×B200), evaluated with [sgl-eval](https://github.com/sgl-project/sgl-eval):

Model pass\@1 avg-of-4 majority\@4 pass\@4
DeepSeek-V3.2-Exp 87.50% ± 1.67% 90.00% 90.00%
DeepSeek-V3.2 92.50% ± 1.67% 94.71% 96.67%
DeepSeek-V3.2-Speciale 95.00% ± 1.92% 95.83% 100.00%
**Reproduction.** Install [sgl-eval](https://github.com/sgl-project/sgl-eval), launch the server with the tool-call and reasoning parsers, then run `sgl-eval run`. The AIME 2025 dataset ships with sgl-eval, and thinking is on by default for it: ```bash Command theme={null} pip install sgl-eval sgl-eval run aime25 \ --base-url http://localhost:30000/v1 \ --model deepseek-ai/DeepSeek-V3.2-Exp \ --n-repeats 4 \ --temperature 1.0 \ --top-p 0.95 \ --max-tokens 64000 # Use --max-tokens 120000 for the DeepSeek-V3.2-Speciale model ``` ### 5.3 Speed Benchmark on Hopper **Test Environment:** * Hardware: NVIDIA H800 GPU (16x) * Model: DeepSeek-V3.2 * Tensor Parallelism: 16 * sglang version: 0.5.9 #### 5.3.1 Latency-Sensitive Benchmark * Model Deployment Command: ```shell Command theme={null} export SGLANG_DEEPEP_LL_COMBINE_SEND_NUM_SMS=32 export SGLANG_SET_CPU_AFFINITY=1 # Test workload ISL/OSL=1k/1k, raw tap : 4948.16 toks/sec, MAX ITL 5970 # dp 2 : 5019.54 toks/sec, MAX ITL 7233 # dp 4 : 4942.82 toks/sec, MAX ITL 35654 # dp 2 + mtp : 6842.51 toks/sec, MAX ITL 3081 sglang_args=$(echo serve \ --model-path $MAPPED_MODEL_PATH \ --nccl-init $MASTER_ADDR:$MASTER_PORT --nnodes 2 --node-rank $RANK --tp 16 \ --attn-dp-size 2 --page-size 64 \ --trust-remote-code --host "0.0.0.0" --port 30000 \ --log-requests \ --context-length 65536 --max-running-requests 128 \ --speculative-algorithm EAGLE \ --speculative-num-steps 2 --speculative-eagle-topk 1 --speculative-num-draft-tokens 3 \ --allow-auto-truncate --enable-metrics \ --tool-call-parser deepseekv32 --reasoning-parser deepseek-v3 \ --served-model-name DeepSeek-V3.2-Opt-dp2-mtp ) sglang_args=($sglang_args) sglang "${sglang_args[@]}" 2>&1 | tee $LOG_DIR/$RANK.log ``` * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --host $MASTER_ADDR \ --port 30000 \ --model deepseek-ai/DeepSeek-V3.2 \ --random-input-len 1024 \ --random-output-len 1024 \ --num-prompts 10 \ --max-concurrency 1 ``` * **Test Results:** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: 64.0 Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 48.96 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 4217 Request throughput (req/s): 0.20 Input token throughput (tok/s): 124.62 Output token throughput (tok/s): 86.20 Peak output token throughput (tok/s): 113.00 Peak concurrent requests: 2 Total token throughput (tok/s): 210.81 Concurrency: 1.00 Accept length: 3.27 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 4893.12 Median E2E Latency (ms): 3742.47 P90 E2E Latency (ms): 8877.37 P99 E2E Latency (ms): 10769.85 ---------------Time to First Token---------------- Mean TTFT (ms): 199.88 Median TTFT (ms): 176.15 P99 TTFT (ms): 272.49 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 10.99 Median TPOT (ms): 10.88 P99 TPOT (ms): 13.93 ---------------Inter-Token Latency---------------- Mean ITL (ms): 11.15 Median ITL (ms): 8.86 P95 ITL (ms): 17.29 P99 ITL (ms): 33.71 Max ITL (ms): 36.84 ================================================== ``` #### 5.3.2 Throughput-Sensitive Benchmark We simply use the same deployment method and vary the throughput by maximizing concurrencies: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --host $MASTER_ADDR \ --port 30000 \ --model deepseek-ai/DeepSeek-V3.2 \ --random-input-len 1024 \ --random-output-len 1024 \ --num-prompts 2048 \ --max-concurrency 1024 # see picture below why we use 1024 for concurrency, hence num prompts 2048 ``` DeepSeek 3.2 can steadily support concurrency up to `1024` and when concurrency is greater than `128`, the TTFT increase sharply: ![DeepSeek V3.2 Concurrency ISL/OSL=1024/128](https://github.com/user-attachments/assets/d5c9c9fb-44f3-4793-a0fd-f8fa954546f5) Performance record: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: 64.0 Max request concurrency: 1024 Successful requests: 2048 Benchmark duration (s): 408.09 Total input tokens: 1048992 Total input text tokens: 1048992 Total generated tokens: 1032734 Total generated tokens (retokenized): 1031817 Request throughput (req/s): 5.02 Input token throughput (tok/s): 2570.50 Output token throughput (tok/s): 2530.66 Peak output token throughput (tok/s): 5092.00 Peak concurrent requests: 1035 Total token throughput (tok/s): 5101.16 Concurrency: 763.41 Accept length: 3.26 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 152117.70 Median E2E Latency (ms): 181704.84 P90 E2E Latency (ms): 215924.77 P99 E2E Latency (ms): 231679.59 ---------------Time to First Token---------------- Mean TTFT (ms): 127729.28 Median TTFT (ms): 170098.94 P99 TTFT (ms): 185705.73 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 49.18 Median TPOT (ms): 48.48 P99 TPOT (ms): 77.24 ---------------Inter-Token Latency---------------- Mean ITL (ms): 48.46 Median ITL (ms): 52.11 P95 ITL (ms): 110.26 P99 ITL (ms): 200.63 Max ITL (ms): 2666.37 ================================================== ``` By adding `--random-range-ratio 1`, we could get even higher statistical numbers: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: 64.0 Max request concurrency: 1024 Successful requests: 2048 Benchmark duration (s): 612.87 Total input tokens: 2097152 Total input text tokens: 2097152 Total generated tokens: 2097152 Total generated tokens (retokenized): 2096201 Request throughput (req/s): 3.34 Input token throughput (tok/s): 3421.84 Output token throughput (tok/s): 3421.84 Peak output token throughput (tok/s): 9077.00 Peak concurrent requests: 1039 Total token throughput (tok/s): 6843.68 Concurrency: 772.66 Accept length: 3.26 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 231222.27 Median E2E Latency (ms): 289846.24 P90 E2E Latency (ms): 314480.41 P99 E2E Latency (ms): 320392.27 ---------------Time to First Token---------------- Mean TTFT (ms): 194081.02 Median TTFT (ms): 252945.22 P99 TTFT (ms): 279637.50 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 36.31 Median TPOT (ms): 36.73 P99 TPOT (ms): 46.33 ---------------Inter-Token Latency---------------- Mean ITL (ms): 36.31 Median ITL (ms): 23.18 P95 ITL (ms): 96.79 P99 ITL (ms): 135.81 Max ITL (ms): 3121.00 ================================================== ``` # DeepSeek-V4 Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-V4 Deploy DeepSeek-V4 with SGLang — verified launch commands, benchmarks, and tuning for Flash Official (0731), Flash, Flash Vision (Exp), Pro, and Pro Official (0813). ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). A minimal example (substitute the inner `sglang serve ...` with whatever the command generator below produces): > > **NVIDIA GPUs** > > A single image — `lmsysorg/sglang:latest` — covers the **datacenter GPUs** in this cookbook (B200 / B300 / GB200 / GB300 / H100 / H200 / RTX PRO 6000). The one exception is **Flash Vision (Exp)**, whose support has not shipped in a release yet: its cells use the preview image `lmsysorg/sglang:dev-dsv4-flash-vision` (the command panel picks it automatically — see the [Flash Vision notes](#vision-note)). **DGX Spark** is the other exception: its three cells (Flash Official FP4, Flash Official NVFP4, Flash Vision FP4) use the DGX Spark–only preview image `lmsysorg/sglang:dev-v4f-2dgx-v2` (the command panel picks it automatically — see the [DGX Spark notes](#spark-note)); do not use that image on any other hardware. > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > > docker run --gpus all \ > --shm-size 32g \ > -p 30000:30000 \ > -v ~/.cache/huggingface:/root/.cache/huggingface \ > --env "HF_TOKEN=" \ > --ipc=host \ > lmsysorg/sglang:latest \ > sglang serve > ``` > > **AMD GPUs (ROCm)** > > AMD uses the daily-updated `lmsysorg/sglang-rocm` images. You can find the latest images on [Docker Hub](https://hub.docker.com/r/lmsysorg/sglang-rocm/tags). We recommend the ROCm 7.2 version. > > For example: > > * **MI355X** → `lmsysorg/sglang-rocm:v0.5.22-rocm720-mi35x-20261016` > * **MI300X** → `lmsysorg/sglang-rocm:v0.5.22-rocm720-mi30x-20261016` > > ```bash Command theme={null} > docker pull lmsysorg/sglang-rocm:v0.5.22-rocm720-{mi35x,mi30x}-20261016 > > docker run \ > --device=/dev/kfd --device=/dev/dri \ > --group-add video \ > --cap-add=SYS_PTRACE --security-opt seccomp=unconfined \ > --shm-size 32g --ipc=host \ > -p 30000:30000 \ > -v ~/.cache/huggingface:/root/.cache/huggingface \ > --env "HF_TOKEN=" \ > lmsysorg/sglang-rocm:v0.5.22-rocm720-{mi35x,mi30x}-20261016 \ > sglang serve > ``` For **MI355X → Pro / Pro Official → FP4 → Multi-Nodes**, the panel generates a **1P1D deployment**: one prefill node and one decode node, each running an independent worker. Select **Router**, **Prefill**, or **Decode** to copy its command. Start the [UMBP tier](#3-8-unified-cache-external-linker-umbp) on the prefill node, then both workers, then the router. Send client requests to the router on port `8000`. The MI355X multi-node strategies **Low-Latency**, **Balanced**, and **High-Throughput** use fixed concurrency presets of **16**, **48**, and **256**, respectively. **Pro** uses EAGLE/MTP; **Pro Official (0813)** uses DSpark. Both enable UMBP on prefill by default. The Playground inherits the selected worker, including its speculative decoder and cache settings. Run these recipes' **Python** commands inside the ROCm image shown in the **Docker** tab, where Aiter is already enabled. Add explicit parser and network-device settings through the Playground's **Parsers** and **PD Disagg → IB Device** controls. Pick your hardware + recipe to generate the launch command. The three serving strategies cover the common operating points: * **Low-Latency** — fastest reply for a single user. Pick for chat. * **Balanced** — good speed with several users at once. Use for typical multi-user serving. * **High-Throughput** — most tokens per second across many users. Best for batch jobs. > [!NOTE] > > The **Flash Vision (Exp)** variant runs on a dedicated preview Docker image, `lmsysorg/sglang:dev-dsv4-flash-vision` — its support ([sgl-project/sglang#37253](https://github.com/sgl-project/sglang/pull/37253)) has not shipped in a release yet. The command panel's Docker mode emits that image automatically for Flash Vision cells; see the [Flash Vision notes](#vision-note). > [!NOTE] > > For a runnable end-to-end example, see the [DeepSeek-V4-Flash demo notebook](https://github.com/sgl-project/sglang/blob/main/docs/demo/deepseek_v4_flash.ipynb). **Panel controls** (top of the command box):
  • **Python / Docker** — bare `sglang serve …` for an existing SGLang env, or a `docker run … sglang serve …` wrap against the per-hardware image from the [Install SGLang](#install) panel above.
  • **⧉ Copy** — copies the current command (with whichever framing is active) to your clipboard.
  • **\$ cURL** — a sample request against `localhost:30000` to confirm the server is up.
  • **⚙ Env** — edits the placeholders (`HOST_IP`, `PORT`, `HF_TOKEN`, `NODE_RANK`, `NODE0_IP`) the command and cURL share. Persists in localStorage across cookbooks.
  • **Verified / Not Verified** badge — green when the `(hw, variant, quant, strategy, nodes)` combo has been run end-to-end on real hardware; yellow when auto-derived from a neighbor and not yet re-checked.
## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. The base is read live from your Deploy selection — only your overrides change. The knobs come in two flavors: * **Built-in SGLang features** — parallelism overrides (TP / CP / DP-Attention — DP-Attention's value is the DP degree, with `off` to disable), MoE backend + EP, reasoning / tool-call parsers, speculative-decoding presets, prefill/decode disaggregation, HiCache tiers, and HiSparse hierarchical sparse attention (decode-role only — the card appears once PD-Disagg mode is set to decode). * **DeepSeek-V4 specific features** — MegaMoE W4A8 / W4A4 fused kernel (Blackwell only; Hopper SM90 uses a separate all-FP8 MegaMoE path — see Configuration Tips below). Lines highlighted **green** are added by your overrides; lines with **red strikethrough** were in the verified base but stripped by an override. When no override differs from the base cell, the playground inherits the base's **Verified** badge; any actual change flips it to **Not Verified** until the new configuration is run end-to-end and submitted back. **Panel controls** reuse **Python / Docker** · **⧉ Copy** · **\$ cURL** · **⚙ Env** from the Deploy panel, plus one extra:
  • **Submit ↗** — opens a pre-filled GitHub issue so you can land your override combo as a new verified cookbook cell. Shown only while the badge says **Not Verified**; click it once you've actually run the command on your hardware and confirmed it works.
## Agentic Long-Context Deployment Agentic workloads, such as coding agents and other multi-turn, tool-using assistants, send long prompts whose prefixes grow and repeat from turn to turn. Serving them well depends on reusing the KV cache across turns, offloading it beyond GPU memory, and keeping each session on the workers that already hold its prefix. This section gives complete launch commands for such deployments, each benchmarked in [SemiAnalysis InferenceX](https://inferencex.semianalysis.com/) and linked to the run that measured it. Pick a hardware platform, checkpoint, deployment shape, concurrency, KV cache offloading mechanism and router to get every process of the deployment as a raw command, one tab per process in launch order. * **Router.** Each configuration was submitted behind one front door: Dynamo (`dynamo.frontend` with `dynamo.sglang` workers) or SGLang (`sglang.launch_server`, behind `sglang_router` when there are several workers or DP-attention ranks). * **KV offload.** Choose among these KV cache offloading mechanisms: none (GPU KV only), HiCache (host DRAM), or a Mooncake store attached through the external linker. The Mooncake option needs an image whose SGLang build includes `--enable-unified-cache-external-linker`. * **Container image.** Run the commands inside the image listed for each configuration. Several are SGLang nightly images, so flag names follow that image. ## 1. Model Introduction **DeepSeek-V4** is the next-generation Mixture-of-Experts model from DeepSeek, released 2026-04-24 under an **MIT License**. The 0731 Flash and 0813 Pro refreshes add checkpoints with a bundled DSpark draft head, and the experimental Flash Vision checkpoint builds image understanding on top of the 0731 Flash base:
Variant Total params Active (MoE) Use
**[DeepSeek-V4-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash)** **284B** 13B single-node serving on B200 / B300 / GB200 / GB300 / H200 (TP=4); RTX PRO 6000 (TP=2); H100 (TP=8)
**[DeepSeek-V4-Flash-0731](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731)** **304** 13B Flash Official (0731), with a bundled DSpark draft head; verified on 8×B200, 4×GB300, and 4×H200
**[DeepSeek-V4-Flash-Vision-Exp](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-Vision-Exp)** **305B** 13B Flash Vision (Exp) — experimental multimodal (image-text-to-text): the 0731 Flash base + vision encoder & aligner; verified on 4×B200 (TP=4), requires the [preview build](#vision-note)
**[DeepSeek-V4-Pro](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro)** **1.6T** 49B high-capacity: B200 / B300 (TP=8) · GB300 (TP=4) · H200 FP4 (TP=8) · GB200 (2-node, TP=8) · H200 FP8 (2-node, TP=16) · H100 (2-node, TP=16)
**[DeepSeek-V4-Pro-0813](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro-0813)** **1.65T** 49B Pro Official (0813), with a bundled DSpark draft head; verified on 4×GB300 (TP=4) · B200 / B300 / H200 FP4 (TP=8) · GB200 (2-node, TP=8) · H100 (2-node, TP=16) · MI355X
The Instruct checkpoints ship as **FP4 MoE experts + FP8 attention / dense** (one mixed-precision checkpoint covers every FP4-capable GPU). Matching `*-Base` repos ship pure FP8 mixed and are for further pre-training only — not for chat or tool calling. **Highlights:** hybrid CSA + HCA attention (\~27% inference FLOPs / \~10% KV cache vs DSv3.2 at 1M context), manifold-constrained hyper-connections (mHC), Muon optimizer, **1M-token context** (32T+ pre-training tokens), three reasoning modes (*Non-think* / *Think High* / *Think Max* — use ≥ 384K context for Think Max), and a dedicated `encoding_dsv4.encode_messages` Python encoder + DSML tool-call grammar. **Recommended generation:** `temperature=1.0`, `top_p=1.0`. **Resources:** HuggingFace · [Flash Official (0731)](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-0731) · [Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash) · [Flash Vision (Exp)](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-Vision-Exp) · [Pro](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro) · [Pro Official (0813)](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro-0813) · ModelScope · [Flash](https://modelscope.cn/models/deepseek-ai/DeepSeek-V4-Flash) · [Pro](https://modelscope.cn/models/deepseek-ai/DeepSeek-V4-Pro). ## 2. Configuration Tips **Concurrency & DeepEP dispatch buffer** Must hold: `max-running-requests × MTP_draft_tokens ≤ SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK`. Violating it blows DeepEP's dispatch buffer at steady-state load (`deep_ep.cpp:1105`). When tuning, move `--cuda-graph-max-bs-decode`, `--max-running-requests`, and the env together. The generator currently picks values on the **conservative** side (mirroring an internal stress-test matrix). They run safely out of the box but likely leave throughput on the table — please tune them up toward your actual workload's peak concurrency and report findings back so the defaults can be revised. **Speculative decoding** The original Flash and Pro recipes use EAGLE. Flash Official (0731) and Pro Official (0813) use the bundled DSpark draft head; see [DSpark](#3-4-dspark-speculative-decoding) for its launch and tuning notes. > [!WARNING] > > Do not use EAGLE on the checkpoints that bundle a DSpark head. On 0813, `--speculative-algorithm EAGLE` starts and serves without any error, but the draft head it binds accepts nothing — every decode batch logs `accept len: 1.00, accept rate: 0.00`, so you pay the draft cost for zero speedup. Output stays correct, which is what makes it easy to miss. Switch to `--speculative-algorithm DSPARK`; the startup log then reports `Draft checkpoint bundles a DSpark head`. For the original Flash and Pro checkpoints: * `low-latency`: steps=3, draft-tokens=4 → largest win at bs=1. * `balanced`: steps=1, draft-tokens=2 → gentler MTP, reduces throughput hit at higher batch. * `high-throughput`: MTP disabled — at saturation the verify step costs more than it saves. * MTP runs on the v2 speculative path. **DGX Spark (2x GB10): Flash Official FP4 / NVFP4, Flash Vision FP4** The **DGX Spark** row has three recipes, all **Balanced · Multi-Nodes**: **Flash Official (0731) · FP4**, **Flash Official (0731) · NVFP4**, and **Flash Vision (Exp) · FP4**. None of these checkpoints fits one 128GB GB10, so every recipe runs TP=2 across two DGX Sparks connected over ConnectX-7 (RoCE). Every other DGX Spark combination is greyed out on purpose. * **Docker image** — all three cells use `lmsysorg/sglang:dev-v4f-2dgx-v2`, a preview build made **only for DGX Spark** (branch `b12x-vision` @ `452239a74f`): it bakes in the SM12x `b12x` MoE (W4A8) and compressed-MLA attention kernels ([#34878](https://github.com/sgl-project/sglang/pull/34878), [#35899](https://github.com/sgl-project/sglang/pull/35899), [#34018](https://github.com/sgl-project/sglang/pull/34018)), the Flash Vision model support ([#37253](https://github.com/sgl-project/sglang/pull/37253)), the b12x image-prefill fix that lets Flash Vision serve images on SM12x, the NVFP4 MTP-layer dispatch fix, and the CuTeDSL and NCCL pins the GB10 pair needs. Do not use it on other hardware, and use the panel's Docker mode — the bare Python command needs the `b12x` kernel package this image ships. * **Run the same command on both Sparks** with `--node-rank 0` / `--node-rank 1` and `--dist-init-addr` pointing at node 0 over the ConnectX-7 link. The `docker run` flags the panel emits (`--network host --ulimit memlock=-1:-1 --cap-add IPC_LOCK --device /dev/infiniband`) are what let NCCL use RDMA; without them NCCL silently falls back to TCP and decode slows by roughly 40%. * **Env knobs** in the cells are part of the recipe: `SGLANG_SM120_FLASHMLA_BACKEND=b12x` selects the b12x attention path, `SGLANG_B12X_MAX_TOKENS` must equal `--chunked-prefill-size`, and `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` avoids unified-memory fragmentation OOMs on GB10. * **NVFP4 (`nvidia/DeepSeek-V4-Flash-0731-NVFP4`)** — only the routed experts are NVFP4; attention, shared experts and the DSpark MTP layer stay in the checkpoint's native formats. On SM12x that means three extra flags: `--moe-runner-backend flashinfer_cutlass` (b12x's MoE is MXFP4-only and trtllm-gen kernels are sm100-only), `--speculative-moe-runner-backend b12x` (the DSpark draft's MTP experts are MXFP4 and run on b12x), and `--disable-shared-experts-fusion` (HashTopK rejects fused shared experts under the cutlass runner). Throughput and DSpark acceptance match the FP4 cell within noise. * **Flash Vision** — images are served natively on the b12x recipe with the same flags as Flash Official (send `image_url` content on `/v1/chat/completions`, see [Vision](#3-5-vision-image-inputs)); text-only requests work unchanged. Expect roughly 15–20% lower text throughput than Flash Official on this checkpoint — its bundled DSpark head accepts fewer drafts (\~3.2 vs \~3.9) — with text accuracy intact. **DeepSeek-V4-Flash-Vision-Exp (Experimental)** [`deepseek-ai/DeepSeek-V4-Flash-Vision-Exp`](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-Vision-Exp) is DeepSeek's first experimental multimodal V4 checkpoint: the 0731 Flash base plus a vision encoder and aligner, served through the same `sglang serve` flow with OpenAI-style `image_url` inputs (see [Vision](#3-5-vision-image-inputs) below). Select the **Flash Vision** variant in the Deploy panel for its recipes. * **Preview build required** — support lands via [sgl-project/sglang#37253](https://github.com/sgl-project/sglang/pull/37253) and has not shipped in a release. Docker mode on the Flash Vision cells already emits the preview image `lmsysorg/sglang:dev-dsv4-flash-vision`; for a Python environment, install SGLang from that PR's branch. The DGX Spark Flash Vision cell is the exception: it uses the DGX Spark image `lmsysorg/sglang:dev-v4f-2dgx-v2` (see the [DGX Spark notes](#spark-note)). * **Verified matrix** — MMMU-Pro via sgl-eval at `temperature 1.0`, `top-p 0.95`, `--reasoning-effort max`. * **Engine auto-configuration** — the engine picks the `flashinfer_mxfp4` MoE runner and auto-disables shared-experts fusion for this checkpoint (its HashTopK routing rejects fused shared experts); don't pass `--enforce-shared-experts-fusion`. * **Chunked prefill & radix cache stay enabled** — the scheduler keeps image spans consistent automatically: chunked-prefill truncation points are span-aligned (an image span always prefills within a single extend, overshooting the chunk budget by at most one span), and a radix-cache prefix match ending deep inside an image span is re-issued from the span start. * **Speculative decoding** — the checkpoint bundles a DSpark head, and the low-latency recipes enable it with `--speculative-algorithm DSPARK` (verified with image batches on B200 via the MMMU-Pro round; the other hardware rows are pending verification). The balanced and high-throughput recipes run target-only: they use DP Attention, which DSpark is incompatible with on current releases. As on the 0731/0813 checkpoints, do not pass the EAGLE flags. **Shared experts fusion (Blackwell, flashinfer\_mxfp4)** On the Blackwell fp4 recipes (`--moe-runner-backend flashinfer_mxfp4`), the shared expert runs as a separate FP8 MLP on an alternate stream by default. Adding: ```bash Command theme={null} --enforce-shared-experts-fusion ``` routes it as one extra MXFP4 expert through the same trtllm-gen MoE kernel, so the whole MoE runs on a single stream (\~4 fewer kernel launches and 2 fewer stream syncs per MoE layer). The shared expert is requantized from FP8 to MXFP4 at load time. Measured on GB200 tp4: gsm8k and AIME25 accuracy on par with the unfused baseline; Mean TTFT -13% to -21% and P99 ITL -15% to -53% at QPS 1-8 with neutral throughput. Only for deployments without expert parallelism (e.g. the single-node low-latency recipes): with `moe_ep_size > 1` the flag is rejected at startup, unless the DeepEP/MegaMOE per-rank shared-slot path is in use. Not applicable to [Flash Vision (Exp)](#vision-note) — the engine auto-disables the fusion on that checkpoint. **Compressed attention state dtype** DeepSeek-V4 uses hybrid compressed attention for long-context efficiency. `SGLANG_DSV4_COMPRESS_STATE_DTYPE` controls the dtype of the C4 / C128 compressed attention state pools. Supported values are `float32` / `fp32` (default: `float32`) and `bfloat16` / `bf16`. For BF16 on the offline compression path: ```bash Command theme={null} SGLANG_DSV4_COMPRESS_STATE_DTYPE=bf16 \ sglang serve \ --model-path deepseek-ai/DeepSeek-V4-Flash \ ``` This BF16 setting applies only to the compressed attention state pools and reduces the GPU memory footprint of each compressed-state slot. It does not change model weight precision or the main KV cache dtype. With automatic pool sizing and no explicit capacity cap, the same memory budget holds more slots, and the startup log shows larger `c4_state` and `c128_state` pool sizes. Keep the default `float32` setting for the most conservative behavior. **EPLB + Waterfill (Experimental)** For recorded/static EPLB reproduction, first record an expert-distribution file by following [Capture expert selection distribution in MoE models](../../../docs/basic_usage/native_api.mdx#capture-expert-selection-distribution-in-moe-models). For reproduction runs, use the generated `expert_distribution_recorder_*.pt` as the initial expert location. **Please checkout to latest main branch for this feature.** For non-PD reproduction, use: ```bash Command theme={null} --moe-a2a-backend deepep \ --deepep-mode auto \ --init-expert-location /path/to/expert_distribution_recorder_*.pt \ --enable-waterfill ``` For PD-Disagg reproduction, use `normal` mode on the prefill server and `low_latency` mode on the decode server. Add the same `--init-expert-location` flag to both commands: ```bash Command theme={null} # prefill --moe-a2a-backend deepep \ --deepep-mode normal \ --init-expert-location /path/to/expert_distribution_recorder_*.pt \ --enable-waterfill # decode --moe-a2a-backend deepep \ --deepep-mode low_latency \ --init-expert-location /path/to/expert_distribution_recorder_*.pt \ --enable-waterfill ``` You can also add `--ep-num-redundant-experts` and `--eplb-algorithm` to customize EPLB placement. Waterfill also supports MegaMOE. Use `--moe-a2a-backend megamoe --enable-waterfill` to keep the MegaMOE backend while applying Waterfill to the fused shared expert slot. **FP4 Indexer (Experimental)** DeepSeek-V4 uses the default indexer path unless `--enable-deepseek-v4-fp4-indexer` is set. Enable this flag to use the experimental FP4 C4 indexer. This path is intended for decode-heavy long-context workloads where reducing indexer cache bandwidth is beneficial. On **NVIDIA (SM100 / SM120)**, pair the flag with DeepGEMM FP4 indexer support and the FlashInfer MXFP4 MoE runner: ```bash Command theme={null} # Please use the latest main branch for this feature. sglang serve \ --model-path deepseek-ai/DeepSeek-V4-Flash \ --tp 4 \ --moe-runner-backend flashinfer_mxfp4 \ --enable-deepseek-v4-fp4-indexer ``` On **AMD MI355X (gfx95)**, the AITER FP4 indexer kernels are available on ROCm. Keep the standard MI355 recipe and add only the indexer flag. Do not need to pass `--moe-runner-backend flashinfer_mxfp4`: ```bash Command theme={null} # Please use the latest ROCm image for this feature. sglang serve \ --model-path deepseek-ai/DeepSeek-V4-Pro \ --tp 8 \ --attention-backend dsv4 \ --enable-deepseek-v4-fp4-indexer \ ``` **NVFP4 Hybrid Checkpoints** The [`nvidia/DeepSeek-V4-Pro-NVFP4`](https://huggingface.co/nvidia/DeepSeek-V4-Pro-NVFP4) and [`nvidia/DeepSeek-V4-Flash-NVFP4`](https://huggingface.co/nvidia/DeepSeek-V4-Flash-NVFP4) checkpoints quantize MoE experts to **NVFP4** while keeping attention and dense layers in **FP8**. The official releases have matching NVFP4 checkpoints at [`nvidia/DeepSeek-V4-Flash-0731-NVFP4`](https://huggingface.co/nvidia/DeepSeek-V4-Flash-0731-NVFP4) and [`nvidia/DeepSeek-V4-Pro-0813-NVFP4`](https://huggingface.co/nvidia/DeepSeek-V4-Pro-0813-NVFP4). All of them require `--moe-runner-backend flashinfer_trtllm_routed` which will be automatically selected if not provided. ```bash Command theme={null} sglang serve \ --model-path nvidia/DeepSeek-V4-Pro-NVFP4 \ --tp 8 ``` or ```bash Command theme={null} sglang serve \ --model-path nvidia/DeepSeek-V4-Flash-NVFP4 \ --tp 8 ``` Requires Blackwell (SM100+). The MTP layer in this checkpoint stays MXFP4-packed and is routed through the `Mxfp4FlashinferTrtllmMoEMethod` path automatically. The official (0731 / 0813) NVFP4 checkpoints preserve the bundled DSpark draft head, so their low-latency recipes use `--speculative-algorithm DSPARK` instead of the EAGLE/MTP shape flags — same as the corresponding original-precision official checkpoints. **Hopper (H100 / H200) note** Two options are available for running DeepSeek-V4 on Hopper: * **Original FP4 checkpoints** — run the MoE experts with W4A16 kernels (Marlin or the FlashInfer SM90 CUTLASS runner) as the command generator picks for Hopper cells. With FlashInfer >= 0.6.18 you can instead select the **W4A8** path — MXFP4 weights with FP8 activations via FlashInfer's Humming kernels — by adding `--flashinfer-mxfp4-moe-precision fp8` to `--moe-runner-backend flashinfer_mxfp4`; the low-latency Hopper cells now generate this form. Both work on H100 and H200; FP4 is the only option for H100 (no FP8 path). It is TP-only; on H200 the Pro variant fits on a single 8-GPU node, while H100 Pro needs 2 nodes (TP=16). * **Converted FP8 checkpoints** (H100 and H200 only) — pre-repackaged FP8 weights at [`sgl-project/DeepSeek-V4-Flash-FP8`](https://huggingface.co/sgl-project/DeepSeek-V4-Flash-FP8) and [`sgl-project/DeepSeek-V4-Pro-FP8`](https://huggingface.co/sgl-project/DeepSeek-V4-Pro-FP8) unlock DP-attention + DeepEP and richer parallelism (e.g. Pro TP=16 across 2 nodes). On these FP8 checkpoints you can additionally enable the all-FP8 **MegaMoE** path on SM90 for higher long-context / large-decode throughput — see the **SM90 (Hopper) FP8 MegaMoE** note in Configuration Tips below. PD-Disagg recipes on H200 may require `docker run --privileged --ulimit memlock=-1` (or `--device /dev/infiniband:/dev/infiniband --cap-add IPC_LOCK`) so mooncake can discover the IB HCAs; without IB exposure mooncake silently falls back to TCP, which can lead to garbled KV transfer on large checkpoints. **RTX PRO 6000 (SM120 / Blackwell Desktop) note** RTX PRO 6000 (96 GB) runs **Flash only** with the FlashInfer MXFP4 MoE runner. V4-Pro doesn't fit on 8× 96 GB; the Deploy panel greys out unsupported recipes. HiCache and MegaMoE are **not** supported on RTX PRO 6000. **AMD (MI300X / MI355X) note** * **Model checkpoints** — for correct accuracy, the FP4 model uses the stock `deepseek-ai/DeepSeek-V4-{Flash,Pro}`, and the FP8 model uses the repackaged `sgl-project/DeepSeek-V4-{Flash,Pro}-FP8`. * **Supported models** — **MI300X** supports DeepSeek-V4-Flash in FP8; **MI355X** supports DeepSeek-V4-Flash / Pro in both FP4 and FP8. All recipes run single-node. * **TP / DP setting (MI355X)** — both TP=4 and TP=8 are supported. At low concurrency we recommend **TP-only**; at high concurrency use **TP + DP** (balanced / high-throughput recipes). The verified MI355X DP recipes additionally set `--attn-dp-size 8 --enable-dp-attention-local-control-broadcast --tokenizer-worker-num 8 --stream-interval 20 --prefill-decode-interval 10`. * **MTP** — speculative decoding on the original Flash / Pro checkpoints, which bundle an MTP head; add `--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. Pro Official (0813) has no MTP head, so these flags do not apply there and the Playground does not offer them. * **DSpark (MI355X Pro Official 0813)** — the 0813 checkpoint bundles the DSpark draft head, and DSpark is the only speculative algorithm it supports. Enable `--speculative-algorithm DSPARK` (low-latency) and see the [MI355X agentic recipe](#3-6-agentic-long-context-with-hicache-dram-offload-mi355x-fp4-dspark) for the long-context path. DSpark also runs under **PD disaggregation** — see the Pro Official pairs in [§3.7](#3-7-pd-disaggregation-on-mi355x-mori-io). * **Kernels** — uses the Unified KV attention and the flydsl MoE. * **FP4 indexer (MI355X)** — FP4 C4 indexer is supported via `--enable-deepseek-v4-fp4-indexer` on top of the standard ROCm recipe. **MoRI EP (AMD expert parallelism)** On AMD, expert parallelism uses the **MoRI** all-to-all backend (`--moe-a2a-backend mori`), not DeepEP. Add the flags below on top of the verified recipe when sharding experts across GPUs; set `--ep-size` to the EP degree (typically the GPU count on one node). Two optional env vars improve MoRI throughput (both off by default): ```bash Command theme={null} export SGLANG_MORI_DISPATCH_DTYPE=mxfp8 export SGLANG_MORI_RECV_BOUND=1 sglang serve \ --model-path {MODEL_PATH} \ --tp 8 --attn-dp-size 8 \ --ep-size 8 --moe-a2a-backend mori --deepep-mode normal \ ``` * **FP4**: enable both env vars. * **FP8**: use `SGLANG_MORI_RECV_BOUND=1` only; omit `SGLANG_MORI_DISPATCH_DTYPE=mxfp8`. **MegaMoE** MegaMoE fuses expert dispatch + GEMM into a single kernel for higher throughput on MoE layers. To enable it, use the **MegaMoE** chip in the Playground below — the playground will swap `--moe-a2a-backend deepep` for `--moe-a2a-backend megamoe` and add the relevant launch settings automatically. Two variants are exposed: * **W4A8** — default MegaMoE kernel (FP4 weights, FP8 activations). * **W4A4** — adds `--enable-w4a4-mxfp4-megamoe` to run the custom W4A4 kernel (FP4 activations). The flag configures the required DeepGEMM settings. Higher throughput with negligible accuracy drop (\~89.5 GPQA on Pro). Notes: * The W4A8 / W4A4 variants above are **Blackwell-only** (B200 / B300 / GB200 / GB300). On **Hopper (SM90, H100 / H200)** use the all-FP8 MegaMoE path described below instead. * MegaMoE is **only wired into the `high-throughput` recipe** on Blackwell (per [sgl-project/sglang#26451](https://github.com/sgl-project/sglang/pull/26451)). The chip is hidden on `low-latency` and `balanced` — switch to `high-throughput` to expose it. * When running MegaMoE, don't set `--moe-runner-backend` manually. * Adjust `SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK` based on your workload and memory usage. Setting higher number of tokens for MegaMoE requires more HBM space (recommended: 8320 for high-throughput). **SM90 (Hopper) FP8 MegaMoE (Experimental)** On SM90 (Hopper, H100 / H200), the all-FP8 MegaMoE path routes MoE through the DeepGEMM `mega_moe` runner for higher long-context / large-decode throughput on the FP8 checkpoints. Unlike the Blackwell W4A8 / W4A4 variants above, experts stay in **FP8** — keep `SGLANG_DSV4_FP4_EXPERTS=0`. It requires a `sgl-deep-gemm` build with SM90 FP8 MegaMoE support. **Please use the latest image for this feature.** Enable the MegaMoE path with `--moe-a2a-backend megamoe` ```bash Command theme={null} SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK=4096 \ SGLANG_DSV4_FP4_EXPERTS=0 \ sglang serve \ --model-path sgl-project/DeepSeek-V4-Flash-FP8 \ --tp 8 \ --moe-a2a-backend megamoe \ --chunked-prefill-size 4096 ``` `SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK` caps the number of tokens the MegaMoE path processes per rank (i.e. per GPU); the MegaMoE path is only used for batches at or below this cap. The right value depends on your parallelism / token-split scheme, and larger values reserve more HBM. **GB300 PD-Disagg cross-pod MNNVL** On some GB300 clusters with cross-pod KV transfer over NVLink, mooncake may fail with `nvlink_transport.cpp:497 Requested address ... not found!`. If this happens, prepend `MC_FORCE_MNNVL=1 NCCL_MNNVL_ENABLE=1 NCCL_CUMEM_ENABLE=1` to both prefill and decode `sglang serve` commands. ## 3. Advanced Usage ### 3.1 Reasoning Enable the `deepseek-v4` reasoning parser (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to separate thinking from the final answer into `reasoning_content` vs `content`. > **Streaming with Thinking Process (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI( > base_url="http://localhost:30000/v1", > api_key="EMPTY" > ) > > response = client.chat.completions.create( > model="deepseek-ai/DeepSeek-V4-Flash", > messages=[ > {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} > ], > max_tokens=2048, > extra_body={"chat_template_kwargs": {"thinking": True}}, > stream=True, > ) > > thinking_started = False > has_thinking = False > has_answer = False > > for chunk in response: > if not chunk.choices: > continue > delta = chunk.choices[0].delta > > if getattr(delta, "reasoning_content", None): > if not thinking_started: > print("=============== Thinking =================", flush=True) > thinking_started = True > has_thinking = True > print(delta.reasoning_content, end="", flush=True) > > if delta.content: > if has_thinking and not has_answer: > print("\n=============== Content =================", flush=True) > has_answer = True > print(delta.content, end="", flush=True) > > print() > ``` > **Example Output** > > ```text Output theme={null} > We are asked: "What is 15% of 240?" This is a simple percentage problem. I need to provide a step-by-step solution. The user wants the solution explained step by step. I'll calculate 15% of 240: 0.15 * 240 = 36. I'll break it down into steps: understand what percent means, convert percentage to decimal or fraction, then multiply. I'll present the answer clearly.To find 15% of 240, follow these steps: > > **Step 1: Understand the meaning of percent** > "Percent" means "per hundred," so 15% means 15 out of every100, or \( \frac{15}{100} \). > > **Step2: Convert the percentage to a decimal or fraction** > \( 15\% = \frac{15}{100} = 0.15 \) > > **Step3: Multiply by the given number** > Multiply the decimal form by 240: > \( 0.15 \times 240 \) > > **Step4: Perform the multiplication** > \( 0.15 \times 240 = 36 \) > > **Answer:** 15% of 240 is **36**. > ``` ### 3.2 Tool Calling Enable the `deepseekv4` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. > **Python Example with Thinking Process** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI( > base_url="http://localhost:30000/v1", > api_key="EMPTY" > ) > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["location"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="deepseek-ai/DeepSeek-V4-Flash", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > extra_body={"chat_template_kwargs": {"thinking": True}}, > stream=True, > ) > > thinking_started = False > has_thinking = False > tool_calls_accumulator = {} > > for chunk in response: > if not chunk.choices: > continue > delta = chunk.choices[0].delta > > if getattr(delta, "reasoning_content", None): > if not thinking_started: > print("=============== Thinking =================", flush=True) > thinking_started = True > has_thinking = True > print(delta.reasoning_content, end="", flush=True) > > if getattr(delta, "tool_calls", None): > if has_thinking and thinking_started: > print("\n=============== Content =================\n", flush=True) > thinking_started = False > for tool_call in delta.tool_calls: > index = tool_call.index > if index not in tool_calls_accumulator: > tool_calls_accumulator[index] = {"name": None, "arguments": ""} > if tool_call.function: > if tool_call.function.name: > tool_calls_accumulator[index]["name"] = tool_call.function.name > if tool_call.function.arguments: > tool_calls_accumulator[index]["arguments"] += tool_call.function.arguments > > if delta.content: > print(delta.content, end="", flush=True) > > for index, tool_call in sorted(tool_calls_accumulator.items()): > print(f"Tool Call: {tool_call['name']}") > print(f" Arguments: {tool_call['arguments']}") > > print() > ``` > **Example Output** > > ```text Output theme={null} > The user wants to know the weather in Beijing. I'll use the get_weather function with Beijing as the location. I don't need to specify a unit, so I'll just use the default. > > <|DSML|tool_calls> > <|DSML|invoke name="get_weather"> > <|DSML|parameter name="location" string="true">Beijing > > > ``` ### 3.3 HiCache (Hierarchical KV Caching) HiCache enables multi-tier KV cache offloading (GPU → CPU → Storage), significantly expanding effective context capacity for long-context and multi-turn scenarios. Combined with UnifiedRadixTree, it provides intelligent prefix caching across all tiers. To enable HiCache, open the **HiCache** card in the [Playground above](#playground) and flip **Enable**: * **L2 (GPU + CPU)** — leave Storage on `auto` (default). Cold KV pages spill to CPU pinned memory only. * **L3 (GPU + CPU + Storage)** — pick a Storage backend (`file` / `mooncake` / `hf3fs` / `nixl`); the Playground emits the canonical `page_first_direct` mem-layout + `direct` IO backend + `wait_complete` prefetch policy, matching the [HiCache best-practices recipe](../../../docs/advanced_features/hicache_best_practices). For AMD devices, * **L2 (GPU + CPU)** — leave Storage on `auto` (default). Cold KV pages spill to CPU pinned memory only. Use `direct` IO backend + `page_first_direct` or `layer-first` mem-layout. * **L3 (GPU + CPU + Storage)** — pick a Storage backend (`file`); the Playground emits the canonical `page_first_direct` mem-layout + `direct` IO backend + `wait_complete` prefetch policy, matching the [HiCache best-practices recipe](../../../docs/advanced_features/hicache_best_practices). The Write policy knob defaults to `write_through` (the upstream default); switch to `write_back` / `write_through_selective` to trade durability for write speed when the storage tier is slow. For more details, see the [HiCache documentation](../../../docs/advanced_features/hicache). For the alternative that skips the host tier entirely, see [§3.8 UMBP](#3-8-unified-cache-external-linker-umbp) — it is a sibling of HiCache, not a storage backend for it, and the two cannot be enabled together. ### 3.4 DSpark (Speculative Decoding) Flash Official (0731) and Pro Official (0813) bundle a DSpark draft head in `deepseek-ai/DeepSeek-V4-Flash-0731` and `deepseek-ai/DeepSeek-V4-Pro-0813`. The target and draft weights therefore come from the same checkpoint: enable DSpark with `--speculative-algorithm DSPARK` and do not set a separate `--speculative-draft-model-path`. The experimental [Flash Vision checkpoint](#vision-note) also bundles a DSpark head, enabled the same way: the Flash Vision low-latency recipes ship with `--speculative-algorithm DSPARK` (verified with image batches on B200 via the MMMU-Pro round; other hardware rows pending). The balanced and high-throughput Flash Vision recipes stay target-only because they run DP Attention. Unlike the EAGLE recipes for the original Flash and Pro checkpoints, this recipe omits `--speculative-num-steps`, `--speculative-eagle-topk`, and `--speculative-num-draft-tokens`. SGLang reads the DSpark shape from the checkpoint. > [!NOTE] > > The Pro Official (0813) low-latency speed numbers in the Deploy panel were measured with `SGLANG_SIMULATE_ACC_LEN=4`, which pins the DSpark accept length at exactly 4.00. The recipe as shipped earns **4.678** on the same engine, so those rows read slightly conservative. The GSM8K figure for that cell is from the shipped command. The verified 4×GB300 FP4 low-latency command is: ```bash Command theme={null} sglang serve \ --trust-remote-code \ --model-path deepseek-ai/DeepSeek-V4-Flash-0731 \ --tp 4 \ --moe-runner-backend flashinfer_mxfp4 \ --speculative-algorithm DSPARK \ --mem-fraction-static 0.90 \ --chunked-prefill-size 4096 \ --swa-full-tokens-ratio 0.1 \ --host 0.0.0.0 \ --port 30000 ``` Keep `--mem-fraction-static 0.90` on this topology to leave enough headroom for the batch-256 verify graph. The first cold start can take 10–15 minutes while FlashInfer autotunes and SGLang captures the draft and verify graphs; later starts reuse the cache. This path is verified end-to-end on 4×GB300 with SGLang v0.5.16. **Tune proposed draft tokens.** `--speculative-dspark-block-size N` asks DSpark to propose `N` tokens per step; the target verifies a window of `N + 1`. If the flag is omitted, SGLang reads the value from the checkpoint. Both the 0731 and 0813 checkpoints resolve to five proposed tokens (the startup log reports `gamma=5, verify_num_draft_tokens=6`), which is the verified default. Use the **DSpark Proposed Draft Tokens** slider in the [Playground](#playground) to sweep one through five. Larger blocks can improve decode latency when acceptance stays high, but they also increase verification work and graph memory. Start from the checkpoint default, then sweep downward under the real prompt-length and concurrency distribution. The gain is usually largest for short interactive traffic and narrows as prefill dominates. Track P50/P99 TTFT and TPOT, total throughput, accepted length, GPU memory, and stop rate rather than choosing from acceptance alone. For every candidate, compare with the same recipe without `--speculative-algorithm DSPARK`. Restart the server between the DSpark and non-speculative legs, keep the request corpus, sampling, concurrency, and warmup identical, and give each `bench_serving` leg its own `--flush-cache`. Leave `--speculative-draft-attention-backend` unset unless a separate profiling run justifies an override. DSpark requires `pp_size == 1`. Selecting a prefill or decode role in the Playground keeps the inherited DSpark flags on both roles; for PD-disaggregated configurations that run DSpark, see the [Agentic Long-Context Deployment](#agentic-long-context-deployment) and the [MI355X Pro Official PD pairs](#3-7-pd-disaggregation-on-mi355x-mori-io). The MI355X Flash Official recipes run target-only, and so do the DP-Attention recipes in the Deploy panel — for DP-Attention configurations that do run DSpark, see the [Agentic Long-Context Deployment](#agentic-long-context-deployment) and the [MI355X agentic recipe](#3-6-agentic-long-context-with-hicache-dram-offload-mi355x-fp4-dspark). If a larger draft block or concurrency causes graph-capture OOM, lower `--mem-fraction-static`, the draft block size, or the configured maximum running requests, then rerun both performance and accuracy gates. ### 3.5 Vision (Image Inputs) The experimental [`DeepSeek-V4-Flash-Vision-Exp`](https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash-Vision-Exp) checkpoint (the **Flash Vision** variant in the Deploy panel — see the [configuration notes](#vision-note)) takes images via the OpenAI-compatible `image_url` content type, as public URLs or base64 `data:` URIs; text and images mix freely in one message. Vision input works with the same server the Deploy panel produces — no extra model-specific flags needed. > **Image Understanding (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="deepseek-ai/DeepSeek-V4-Flash-Vision-Exp", > messages=[{ > "role": "user", > "content": [ > {"type": "image_url", > "image_url": {"url": "https://raw.githubusercontent.com/sgl-project/sglang/main/examples/assets/example_image.png"}}, > {"type": "text", "text": "Describe this image in a few sentences."}, > ], > }], > ) > > message = response.choices[0].message > if getattr(message, "reasoning_content", None): > print("=============== Thinking =================") > print(message.reasoning_content) > print("=============== Content =================") > print(message.content) > ``` > **Example Output** > > ```text Output theme={null} > Pending update... > ``` ### 3.6 Agentic Long-Context with HiCache DRAM Offload (MI355X FP4, DSpark) Three commands follow, one per concurrency range. They share the model, parser, attention and DSpark flags, and differ in parallelism, MoE path and host offload: | | TP8 | TP8 + HiCache | DP8 | DP8 EP8 MegaMoE | | - | - | - | - | - | | Concurrency | 1–16 | 32–48 | 128 | 128–384 | | Parallelism | TP8 | TP8 | TP8+DP8 | TP8+DP8+EP8 | | MoE | replicated | replicated | replicated | MegaMoEv2 | | HiCache | off | on | on | on | | `--mem-fraction-static` | 0.86 | 0.86 | 0.92 | 0.85 | DeepSeek-V4-Pro-0813 bundles the DSpark head, so `--speculative-draft-model-path` is not needed. `--speculative-dspark-block-size 6` is the AL-optimal draft length on the committed golden curve (verify window 7). Keep `SGLANG_DSV4_UNIFIED_KV_FP8=1` on every command. The first three use `--enforce-shared-experts-fusion`; the MegaMoE command uses `--disable-shared-experts-fusion` instead. Four adjustments are not in the commands below. Add them when they apply: * `--cuda-graph-backend-prefill breakable` at concurrency 1–4. * `--enable-prefill-cp --cp-strategy interleave --enable-cp-decode-attn-tp` on the TP-only commands at concurrency 16 and above. Prefill context parallelism splits each prompt across all eight ranks (CP size = TP size). * `SGLANG_DSV4_GROUPED_ASM=1` on the TP-only commands at concurrency 16 and above — the kernel needs at least 16 requests per draft token. * At concurrency 384 on the MegaMoE command: `--prefill-decode-interval 20`, `SGLANG_AMD_FLYDSL_MEGA_MOE_DECODE_MTPR=1024`, and `AITER_MEGA_FIXED_SLOT_MAX_MTPR=2047`. **TP8, concurrency 1–16:** ```bash Command theme={null} SGLANG_OPT_UNIFIED_CACHE_FREE_OUT_OF_WINDOW_SLOTS=1 \ SGLANG_DSV4_UNIFIED_KV_FP8=1 \ SGLANG_HIP_DSV4_C4_INDEXER_ROWGROUP=1 \ SGLANG_USE_ROCM700A=0 \ TORCH_BLAS_PREFER_HIPBLASLT=1 \ SGLANG_HACK_FLASHMLA_BACKEND=unified_kv_triton \ AITER_BF16_FP8_MOE_BOUND=0 \ SGLANG_OPT_USE_AITER_BATCHED_GEMM=1 \ SGLANG_OPT_FP8_WO_A_FUSED_INVROPE=1 \ python3 -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V4-Pro-0813 \ --trust-remote-code \ --tp 8 \ --prefill-decode-interval 20 \ --attention-backend dsv4 \ --enable-deepseek-v4-fp4-indexer \ --page-size 256 \ --swa-full-tokens-ratio 0.1 \ --kv-cache-dtype fp8_e4m3 \ --enforce-shared-experts-fusion \ --mem-fraction-static 0.86 \ --chunked-prefill-size 16384 \ --tool-call-parser deepseekv4 \ --reasoning-parser deepseek-v4 \ --speculative-algorithm DSPARK \ --speculative-dspark-block-size 6 \ --watchdog-timeout 3600 ``` **TP8 + HiCache, concurrency 32–48:** the same command with HiCache DRAM offload added. `--hicache-ratio` is the host/device token ratio; `1.5` is what stays under a \~2.7 TB host DRAM budget at TP8. The same five flags appear in the two DP commands below. ```bash Command theme={null} --enable-hierarchical-cache \ --hicache-ratio 1.5 \ --hicache-write-policy write_through \ --hicache-io-backend direct \ --hicache-mem-layout page_first_direct ``` **DP8 (DP Attention), concurrency 128:** ```bash Command theme={null} SGLANG_OPT_UNIFIED_CACHE_FREE_OUT_OF_WINDOW_SLOTS=1 \ SGLANG_DSV4_UNIFIED_KV_FP8=1 \ SGLANG_HIP_DSV4_C4_INDEXER_ROWGROUP=1 \ SGLANG_USE_ROCM700A=0 \ TORCH_BLAS_PREFER_HIPBLASLT=1 \ SGLANG_HACK_FLASHMLA_BACKEND=unified_kv_triton \ AITER_BF16_FP8_MOE_BOUND=0 \ SGLANG_OPT_USE_AITER_BATCHED_GEMM=1 \ SGLANG_OPT_FP8_WO_A_FUSED_INVROPE=1 \ SGLANG_SHARED_EXPERT_TP1=1 \ SGLANG_DP_SHARED_EXPERT_LOCAL=1 \ SGLANG_DP_USE_GATHERV=1 \ SGLANG_DP_USE_REDUCE_SCATTER=1 \ python3 -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V4-Pro-0813 \ --trust-remote-code \ --tp 8 \ --attn-dp-size 8 \ --enable-dp-lm-head \ --enable-prefill-delayer \ --enable-dp-attention-local-control-broadcast \ --tokenizer-worker-num 8 \ --stream-interval 20 \ --prefill-decode-interval 20 \ --prefill-delayer-token-usage-low-watermark 0.7 \ --load-balance-method total_requests \ --attention-backend dsv4 \ --enable-deepseek-v4-fp4-indexer \ --page-size 256 \ --swa-full-tokens-ratio 0.1 \ --kv-cache-dtype fp8_e4m3 \ --enforce-shared-experts-fusion \ --mem-fraction-static 0.92 \ --chunked-prefill-size 131072 \ --tool-call-parser deepseekv4 \ --reasoning-parser deepseek-v4 \ --speculative-algorithm DSPARK \ --speculative-dspark-block-size 6 \ --enable-hierarchical-cache \ --hicache-ratio 1.5 \ --hicache-write-policy write_through \ --hicache-io-backend direct \ --hicache-mem-layout page_first_direct \ --watchdog-timeout 3600 ``` `--chunked-prefill-size` is a global budget divided by `--attn-dp-size`, so 131072 keeps 16384 tokens per rank. `--enable-dp-lm-head` is required for DSpark under DP attention. Front the DP ranks with `sglang_router --policy cache_aware`, so a multi-turn session lands on the rank already holding its prefix; above concurrency 160 add `--balance-abs-threshold 32`. Both apply to the MegaMoE command below as well. **DP8 EP8 MegaMoE, concurrency 128–384:** ```bash Command theme={null} SGLANG_OPT_UNIFIED_CACHE_FREE_OUT_OF_WINDOW_SLOTS=1 \ SGLANG_DSV4_UNIFIED_KV_FP8=1 \ SGLANG_HIP_DSV4_C4_INDEXER_ROWGROUP=1 \ SGLANG_USE_ROCM700A=0 \ TORCH_BLAS_PREFER_HIPBLASLT=1 \ SGLANG_HACK_FLASHMLA_BACKEND=unified_kv_triton \ AITER_BF16_FP8_MOE_BOUND=0 \ SGLANG_OPT_USE_AITER_BATCHED_GEMM=1 \ SGLANG_OPT_FP8_WO_A_FUSED_INVROPE=1 \ SGLANG_AMD_USE_FLYDSL_MEGA_MOE=1 \ SGLANG_AMD_FLYDSL_MEGA_MOE_MTPR=16384 \ SGLANG_AMD_FLYDSL_MEGA_MOE_DECODE_MTPR=512 \ AITER_MEGA_FIXED_SLOT_MAX_MTPR=1023 \ SGLANG_AMD_FLYDSL_MEGA_QUANT=a8w4 \ MORI_SHMEM_HEAP_SIZE=17179869184 \ SGLANG_AITER_MEGA_RANK_SYNC=1 \ SGLANG_AITER_MEGA_EPLB_PREFILL_ONLY=1 \ SGLANG_AITER_MEGA_EPLB_FUSED_MAP_RECORD=1 \ SGLANG_EPLB_P2P_BATCH_CHUNK_SIZE=7 \ SGLANG_DP_USE_REDUCE_SCATTER=0 \ GPU_MAX_HW_QUEUES=5 \ python3 -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V4-Pro-0813 \ --trust-remote-code \ --tp 8 \ --attn-dp-size 8 \ --ep 8 \ --enable-dp-lm-head \ --enable-prefill-delayer \ --enable-dp-attention-local-control-broadcast \ --tokenizer-worker-num 8 \ --stream-interval 20 \ --prefill-decode-interval 40 \ --prefill-delayer-token-usage-low-watermark 0.7 \ --load-balance-method total_requests \ --attention-backend dsv4 \ --enable-deepseek-v4-fp4-indexer \ --page-size 256 \ --swa-full-tokens-ratio 0.1 \ --kv-cache-dtype fp8_e4m3 \ --moe-a2a-backend megamoe \ --moe-dense-tp-size 1 \ --disable-shared-experts-fusion \ --enable-eplb \ --eplb-rebalance-num-iterations 200 \ --expert-distribution-recorder-mode stat \ --mem-fraction-static 0.85 \ --chunked-prefill-size 131072 \ --tool-call-parser deepseekv4 \ --reasoning-parser deepseek-v4 \ --speculative-algorithm DSPARK \ --speculative-dspark-block-size 6 \ --enable-hierarchical-cache \ --hicache-ratio 1.5 \ --hicache-write-policy write_through \ --hicache-io-backend direct \ --hicache-mem-layout page_first_direct \ --watchdog-timeout 3600 ``` This command adds expert parallelism on top of the DP8 one. [§3.7](#3-7-pd-disaggregation-on-mi355x-mori-io) explains `SGLANG_AMD_USE_FLYDSL_MEGA_MOE`, `SGLANG_AMD_FLYDSL_MEGA_MOE_MTPR` and the MORI symmetric heap; the heap is 16 GiB here rather than 8 GiB because `--mem-fraction-static 0.85` leaves more GPU memory free. `SGLANG_DP_USE_REDUCE_SCATTER=0` turns off the reduce-scatter path that MegaMoE's all-to-all replaces. The three `SGLANG_AITER_MEGA_*` variables and `--enable-eplb` enable expert-load balancing, recorded during prefill only. `SGLANG_EPLB_P2P_BATCH_CHUNK_SIZE=7` keeps each RCCL P2P group under 31 ops during EPLB rebalance. ### 3.7 PD Disaggregation on MI355X (MORI-IO) The prefill and decode roles can use any transport the **PD Disagg** card in the [Playground above](#playground) offers. On MI300X / MI355X that is **MORI-IO**, **Mooncake** and **NiXL**, and all three stay selectable. This section covers MORI-IO only, because it is the transport every AMD recipe in this cookbook was measured with. It is also what the card selects by default on those two platforms, and it is the one transport that is ROCm-only, so the card hides it on the CUDA platforms. The MI355X multi-node recipes start with **IB Device → Auto**. Select the `rdma0-7 (all NICs)` option in the Playground to add the explicit NIC list. ROCm nodes enumerate their NICs as `rdmaN`, so the card hides the ConnectX `mlx5_*` names on AMD platforms. On CUDA platforms it hides the `rdmaN` list instead. Both roles need the RDMA NICs passed into the container, so the **Docker** output adds the fabric flags below on top of the usual ROCm device access from the [Install panel](#install). `/dev/infiniband` covers `rdma_cm` and the per-NIC `uverbs0`…`uverbs7` nodes, and the memlock/`IPC_LOCK` pair is what lets MORI-IO pin the buffers it registers with the NICs: ```bash Command theme={null} docker run \ --device=/dev/kfd --device=/dev/dri --device /dev/infiniband \ --group-add video --cap-add IPC_LOCK \ --cap-add=SYS_PTRACE --security-opt seccomp=unconfined \ --ulimit memlock=-1 --ulimit stack=67108864 \ --ulimit nofile=1048576:1048576 \ --network host --ipc=host --shm-size 32g \ -v ~/.cache/huggingface:/root/.cache/huggingface \ lmsysorg/sglang-rocm:v0.5.22-rocm720-mi35x-20261019 \ python3 -m sglang.launch_server ``` Use this image for the **MI355X Pro / Pro Official FP4 multi-node** workers and router, including the additional concurrency points below. The Deployment and Playground Docker outputs select it for all three PD roles. It supports the documented `SGLANG_DSV4_DENSE_MXSCALE` and `SGLANG_ROUTER_P2C_LOAD_METRIC` settings. `--network host` replaces the single-node `-p` mapping because the two roles run on different hosts. For the **MI355X Pro / Pro Official FP4** presets, **High-Throughput** sets `MORI_IO_QP_MAX_SEND_WR=32767` and `MORI_IO_QP_MAX_CQE=32768` on both MORI roles. Low-Latency and Balanced use the transport's default queue sizes. The send-queue backoff timeout uses MORI's default of 5 seconds. #### Role-based configuration Select **MI355X → Pro Official → FP4 → Multi-Nodes**, then a strategy and role. Replace the host and model-path placeholders with your deployment's values. The Pro Official commands use the kernel and routing settings described below. | Strategy | Concurrency | Prefill → Decode | `--max-running-requests` | DSpark block size | | - | - | - | - | - | | Low-Latency | 16 | TP4 → TP8 | 32 | 6 | | Balanced | 48 | TP4 → TP8 | 96 | 3 | | High-Throughput | 256 | TP8+DP8+EP8 → TP8+DP8 | 512 | 3 | These are two separate workers: neither receives `--nnodes 2` or a cross-node TP rendezvous address. Prefill listens on `30000`, decode on `30100`, and the router on `8000`. Other hardware's Multi-Nodes recipes can still represent a model sharded across nodes. `--cuda-graph-bs-decode` covers 1 to `--max-running-requests / attn_dp_size`: the full value on the TP-only rows and an eighth on the DP8 rows. Each strategy sets both workers' admission limit and decode's graph sizes together. The TP-only points use `--mem-fraction-static 0.86` and SWA ratio `0.1`; the DP8 points use `0.92` and `0.15`. All prefill roles enable [UMBP](#3-8-unified-cache-external-linker-umbp), `--optimistic-prefill-attempts 2`, and cache reporting. Decode does not use an offload tier. The high-throughput prefill worker uses Aiter MegaMoEv2 with EP8; decode keeps TP MoE. All Pro Official PD workers enable `SGLANG_DSV4_UNIFIED_KV_FP8=1`. Low-Latency and Balanced also set `SGLANG_DSV4_DENSE_MXSCALE=1` on both roles; High-Throughput sets mxscale on decode only. The decode dispatch budget is `64 × (DSpark block size + 1)`: `MORI_MAX_DISPATCH_TOKENS_DECODE=448` at concurrency 16 and `256` at concurrency 48 or 256. The commands below show concurrency 256. Select **Pro** to use the original checkpoint's **EAGLE/MTP 3-1-4** head with the same topology and admission limits. Its commands contain no DSpark parameters. In the Playground, **Off (greedy)** removes speculative decoding. Enabling **HiCache** automatically turns off **Unified Cache External Linker** and removes UMBP's socket configuration and optimistic prefill. Enabling the linker turns HiCache off. > [!NOTE] > > Selecting a TP-only role forces **DP-Attention** off and greys the control. `--max-running-requests` is server-wide and floor-divided by `attn_dp_size`, so turning DP on would cut the per-rank batch below the captured `--cuda-graph-bs-decode` values without changing either flag in the command. > [!WARNING] > > **Speculative decoding changes how you size `--max-running-requests`.** For the strategy presets above, a target concurrency of N uses `N*2` on **both** roles; at N the served batch stays below the concurrency you are aiming for. This holds for DSpark and EAGLE/MTP alike. The table above follows it: 32 serves a concurrency of 16, 96 serves 48, and 512 serves the high-throughput concurrency of 256. The Pro Official c1 override below is an exception: retain 8 request slots on each role even though client concurrency is 1. > > The decode role's `--cuda-graph-bs-decode` then has to cover `N*2 / attn_dp_size`, the per-rank batch. The strategy presets apply both rules: decode graphs cover 1–32, 1–96, and 1–64, respectively. Two things then differ between the two roles regardless of strategy: * **CUDA graphs.** Prefill runs `--disable-cuda-graph`, because the FP4 indexer's prefill path is not captured. Decode captures `--cuda-graph-bs-decode`. * **Speculative decoding** is the same on both. Keep `--speculative-dspark-block-size` equal on the two roles. The original Flash and Pro checkpoints have no DSpark head and use their MTP head instead: `--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. **MoE parallelism differs too, on the high-throughput pair.** Each role uses what suits its batch size. Prefill runs **EP8**, with the experts split across the 8 ranks: it processes a 65536-token chunk, so the split pays for the all-to-all it costs. Decode runs **TP8**, with the experts replicated on every rank, because a few tokens per request per step would not pay for it. The two commands below are that pair at concurrency 256, on one prefill node and one decode node. Run each on its own host, then front them with the router. **Prefill, EP8:** ```bash Command theme={null} GPU_MAX_HW_QUEUES=5 \ SGLANG_AMD_USE_FLYDSL_MEGA_MOE=1 \ SGLANG_AMD_FLYDSL_MEGA_QUANT=a8w4 \ MORI_SHMEM_HEAP_SIZE=8G \ SGLANG_DSV4_UNIFIED_KV_FP8=1 \ SGLANG_DP_USE_REDUCE_SCATTER=0 \ UMBP_STANDALONE_ADDRESS=unix:///tmp/umbp/standalone.grpc.sock \ python3 -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V4-Pro-0813 \ --trust-remote-code \ --host 0.0.0.0 --port 6100 \ --disaggregation-mode prefill \ --disaggregation-bootstrap-port 7200 \ --disaggregation-transfer-backend mori \ --disaggregation-ib-device rdma3,rdma0,rdma2,rdma1,rdma7,rdma4,rdma6,rdma5 \ --tp-size 8 --dp-size 8 --ep-size 8 \ --enable-dp-attention \ --enable-dp-attention-local-control-broadcast \ --enable-dp-lm-head \ --moe-a2a-backend megamoe \ --moe-dense-tp-size 1 \ --enforce-shared-experts-fusion \ --attention-backend dsv4 \ --enable-deepseek-v4-fp4-indexer \ --kv-cache-dtype fp8_e4m3 \ --page-size 256 \ --swa-full-tokens-ratio 0.15 \ --mem-fraction-static 0.92 \ --chunked-prefill-size 65536 \ --max-running-requests 512 \ --context-length 1048576 \ --disable-cuda-graph \ --speculative-algorithm DSPARK \ --speculative-dspark-block-size 3 \ --speculative-num-steps 1 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --enable-unified-cache-external-linker \ --unified-cache-external-linker-backend mori \ --optimistic-prefill-attempts 2 \ --enable-cache-report \ --load-balance-method round_robin \ --tokenizer-worker-num 8 \ --stream-interval 20 \ --tool-call-parser deepseekv4 \ --reasoning-parser deepseek-v4 \ --enable-metrics \ --watchdog-timeout 3600 ``` **Decode, TP8:** ```bash Command theme={null} GPU_MAX_HW_QUEUES=5 \ SGLANG_DSV4_UNIFIED_KV_FP8=1 \ SGLANG_DSV4_DENSE_MXSCALE=1 \ SGLANG_SHARED_EXPERT_TP1=1 \ SGLANG_DP_SHARED_EXPERT_LOCAL=1 \ SGLANG_DP_USE_GATHERV=1 \ MORI_MAX_DISPATCH_TOKENS_DECODE=256 \ python3 -m sglang.launch_server \ --model-path deepseek-ai/DeepSeek-V4-Pro-0813 \ --trust-remote-code \ --host 0.0.0.0 --port 6100 \ --disaggregation-mode decode \ --disaggregation-transfer-backend mori \ --disaggregation-ib-device rdma3,rdma0,rdma2,rdma1,rdma7,rdma4,rdma6,rdma5 \ --tp-size 8 --dp-size 8 \ --enable-dp-attention \ --enable-dp-attention-local-control-broadcast \ --enable-dp-lm-head \ --enforce-shared-experts-fusion \ --attention-backend dsv4 \ --enable-deepseek-v4-fp4-indexer \ --kv-cache-dtype fp8_e4m3 \ --page-size 256 \ --swa-full-tokens-ratio 0.15 \ --mem-fraction-static 0.92 \ --max-running-requests 512 \ --cuda-graph-bs-decode 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 \ --context-length 1048576 \ --speculative-algorithm DSPARK \ --speculative-dspark-block-size 3 \ --speculative-num-steps 1 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --load-balance-method round_robin \ --tokenizer-worker-num 8 \ --stream-interval 20 \ --tool-call-parser deepseekv4 \ --reasoning-parser deepseek-v4 \ --enable-metrics \ --watchdog-timeout 3600 ``` Decode sets neither `--ep-size` nor `--moe-a2a-backend`. `--moe-a2a-backend` names the dispatch path for expert parallelism, so at `ep_size` 1 there is nothing for it to name, and the MoE runs replicated across TP. The shared-expert, `SGLANG_DP_USE_GATHERV`, and `SGLANG_DP_USE_REDUCE_SCATTER` settings control the `all_gatherv` / `reduce_scatterv` path. Shared-expert locality and gatherv default to off; reduce-scatter defaults to on for ROCm. The commands only set the values that differ from those defaults. That is what decode's TP MoE uses and what prefill's all-to-all replaces, so leaving them on under EP8 would run both over the same tokens. The rest of the difference is the prefill-only set already described above: `--chunked-prefill-size`, `--disable-cuda-graph`, and the linker flags with `--optimistic-prefill-attempts` / `--enable-cache-report`. Decode replaces the first two with `--cuda-graph-bs-decode`. On the prefill env: * `SGLANG_AMD_USE_FLYDSL_MEGA_MOE=1` is required. `--moe-a2a-backend megamoe` alone runs the DeepGEMM MegaMoE path, which has no ROCm kernel. Do not set this variable on decode: the scheduler reads it too, so it also changes how decode schedules batches. * `SGLANG_AMD_FLYDSL_MEGA_MOE_MTPR` must be at least `--chunked-prefill-size / attn_dp_size`, here 65536 / 8. Below that SGLang reports no error and runs fused MoE for the extra tokens. 8192 is the default, so the command omits this variable. Set it explicitly if you increase the per-rank chunk size. * `MORI_SHMEM_HEAP_SIZE` sizes the MORI symmetric heap, where MegaMoEv2 allocates its dispatch and combine buffers. It needs about 0.51 GiB per 1024 tokens of MTPR — about 4.2 GiB at 8192 — and the 4 GiB default fails during CUDA graph capture. SGLang allocates the whole heap at the first MegaMoE forward pass, after the KV cache pool, so it consumes the GPU memory `--mem-fraction-static` left free whether MegaMoE fills it or not. 8 GiB fits next to `0.92`; [§3.6](#3-6-agentic-long-context-with-hicache-dram-offload-mi355x-fp4-dspark) runs at `0.85` and can afford more. > [!NOTE] > > These recipes leave `MORI_SHMEM_MODE` unset and use MORI's default `STATIC_HEAP`. The pinned Aiter MegaMoEV2 implementation allocates its buffers through `mori_shmem_create_tensor()` / `shmem_malloc()` after SGLang initializes MORI shmem. This requires the symmetric heap; the separate MORI CCO allocator is not used by this implementation. If your launch script exports `MORI_SHMEM_MODE=ISOLATION`, unset it before launching MegaMoE: its peer-pointer lookup requires the heap mapping. Keep `MORI_SHMEM_HEAP_SIZE=8G` for the prefill recipe above. **Both roles set `SGLANG_DSV4_UNIFIED_KV_FP8=1` at every Pro Official PD concurrency**, which splits the unified KV cache pool into an FP8 nope pool and a BF16 rope pool. It requires the `unified_kv_triton` kernels, which the base cell already selects through `SGLANG_HACK_FLASHMLA_BACKEND`. The value must match on both roles — the PD handshake compares KV cache layouts and fails if they differ. The DSpark draft worker stays BF16 either way. #### Router configuration Run the two roles on separate nodes with the same transport and IB device, then front them with the router the card prints. On MI355X it is cache-aware: `--policy consistent_hashing` keeps a conversation on the prefill worker that already holds its prefix, and `--balance-abs-threshold 2` / `--balance-rel-threshold 1.1` stop that affinity from starving the peer. The TP-only presets keep `--decode-policy round_robin`. Pro Official's DP-attention presets (concurrency 192–512, including the High-Throughput preset at 256) instead use: ```bash Router settings theme={null} SGLANG_ROUTER_P2C_LOAD_METRIC=least_requests \ python3 -m sglang_router.launch_router \ --pd-disaggregation \ --prefill http://:30000 \ --decode http://:30100 \ --host 0.0.0.0 --port 8000 \ --policy consistent_hashing --dp-aware \ --decode-policy power_of_two \ --worker-startup-check-interval 1 \ --cache-threshold 0.3 \ --balance-abs-threshold 2 --balance-rel-threshold 1.1 \ --disable-circuit-breaker --health-failure-threshold 100 \ --health-check-timeout-secs 600 --health-check-interval-secs 30 ``` Power-of-two compares in-flight request counts across decode DP ranks. The one-second load polling interval replaces the 30-second default. Check for `Power-of-two load metric: LeastRequests` in the router startup log. The multi-node router presets retain the default request timeout. The standalone high-throughput Playground preset uses `--request-timeout-secs 14400`. At high concurrency the prefill role queues many requests. When the default 1800 s passes the router aborts the request, and an abort that lands while MORI is writing KV cache over RDMA leaves the transfer neither finished nor failed: that prefill worker can no longer send KV cache to decode, and you have to restart it. > [!WARNING] > > `--request-timeout-secs` is the timeout of the HTTP request from the router to the worker, not a limit on queue time. At 14400 the router also waits four hours before giving up on a worker that has stopped responding. That is acceptable where prefill queues are long, which is why the lower-concurrency recipes keep the default. Lower it again if you lower the concurrency. #### Additional Pro Official concurrency points The panel keeps its c16 / c48 / c256 strategy presets. Apply the following overrides to the **Multi-Nodes** commands to reproduce the optimized recipe's endpoints. Here `cN` means a target concurrency of N. **c1 (replaces c4):** start from Low-Latency. Keep prefill TP4, set decode to `--tp 4`, and set `--max-running-requests 8` on both roles. Replace decode's graph list with `--cuda-graph-bs-decode 1 2 3 4 5 6 7 8`. Keep DSpark block size 6 (7 draft tokens), `MORI_MAX_DISPATCH_TOKENS_DECODE=448`, and both kernel switches on both roles. The source also sets `SGLANG_MLA_HCA_KV_SPLITS=8` on both roles; the FP8 KV path does not read this setting. Keep these 8 server slots and graph sizes when benchmarking with client concurrency 1; do not reduce them to 2 using the strategy presets' `N*2` rule. **c32:** start from Low-Latency, keep TP4 → TP8 and block size 6, set both admission limits to 64, and capture decode graph sizes 1–64. Both roles use FP8 KV and mxscale, as at c16 and c48. **c192 / c384 / c512:** start from High-Throughput. Keep TP8+DP8+EP8 prefill → TP8+DP8 decode, DSpark block size 3 (4 draft tokens), and decode dispatch budget 256. Set both admission limits to 384 / 768 / 1024 and capture decode graph sizes 1–48 / 1–96 / 1–128, respectively. Keep FP8 KV on both roles, mxscale on decode only, and the power-of-two router settings above. At c384 and c512, add `--request-timeout-secs 14400` to the router. **c512 prefill EPLB:** additionally set these environment variables on the prefill worker: ```bash Prefill environment theme={null} export SGLANG_AITER_MEGA_RANK_SYNC=1 export SGLANG_AITER_MEGA_EPLB_PREFILL_ONLY=1 export SGLANG_AITER_MEGA_EPLB_FUSED_MAP_RECORD=1 ``` Append these flags to its launch command: ```text Prefill flags theme={null} --enable-eplb --eplb-rebalance-num-iterations 200 --expert-distribution-recorder-mode stat ``` Keep shared-expert fusion enabled. Rank synchronization lets idle DP ranks participate in MegaMoE dispatch; the prefill-only mode records load and advances rebalancing on synchronized extend passes. Do not set `--expert-balancedness-report-mode` with this mode: it can deadlock prefill on the first request. Decode uses TP MoE and receives none of these EPLB settings. EPLB is specific to c512; the c256 panel preset leaves it disabled. ### 3.8 Unified Cache External Linker (UMBP) The **unified cache external linker** is the second way to move KV cache off the GPU. The linker is the SGLang feature, and you enable it with `--enable-unified-cache-external-linker`. UMBP is one store the linker can use; you select it with `--unified-cache-external-linker-backend mori`. The Playground card uses the feature name, not the store name. The linker is an **alternative to [HiCache](#3-3-hicache-hierarchical-kv-caching), not a tier inside it**. HiCache is a hierarchy — GPU, then pinned host memory, then optionally a storage backend. The linker connects the unified radix tree directly to the external store, with no host cache tier in between, so pages load and offload against that store. SGLang rejects the two together, so enabling the **Unified Cache External Linker** card in the [Playground above](#playground) strips the whole HiCache flag family from the command: ```bash Command theme={null} --enable-unified-cache-external-linker \ --unified-cache-external-linker-backend mori ``` For **MI355X Pro / Pro Official FP4**, the Playground keeps the two Enable controls mutually exclusive: turning either on automatically turns the other off. You can also leave both off. The **Backend** knob picks the linker backend. `mori` is the UMBP pool; `mooncake` drives the same direct-linker path against a Mooncake store instead. **The linker does not need PD disaggregation.** It works in aggregated serving as well, with the **PD Disagg** card set to Off. The §3.7 pairs use it on their prefill role because that is where the KV is produced, but that is a property of those recipes, not a requirement of the linker. Turn the card on next to any command whose selection satisfies the condition below. **DP Attention is not required.** The linker runs under pure TP as well, and the Pro Official low-latency and balanced prefill roles in [§3.7](#3-7-pd-disaggregation-on-mi355x-mori-io) are exactly that shape. DP Attention does change how much the tier holds, so it is worth understanding before you size one. The linker keys its objects by rank, and MLA KV is replicated across TP. Under pure TP, a TP8 worker therefore opens eight separate keyspaces, and all eight hold copies of the same tokens: the tier stores an eighth of the distinct tokens that its byte budget suggests. At TP4 it stores a quarter. DP Attention collapses the keys onto one shared keyspace, so the whole budget counts. Size the pool for the copies you will actually get, and do not read the byte budget as a distinct-token figure. Every MI355X Pro / Pro Official multi-node prefill role uses a **standalone** UMBP tier: a separate `umbp_standalone_server` process on the prefill node owns the DRAM pool, and the prefill server attaches to it over a Unix socket. Start the tier server first; the 1500 GB DRAM budget below is what the verified runs used: ```bash Command theme={null} mkdir -p /tmp/umbp UMBP_DRAM_CAPACITY=1500000000000 \ UMBP_DRAM_USE_HUGEPAGES=1 \ UMBP_SSD_ENABLED=0 \ MORI_UMBP_LOG_LEVEL=info \ /umbp_standalone_server unix:///tmp/umbp/standalone.grpc.sock ``` Reserve enough hugepages for the 1.5 TB tier on a host with at least 3 TB DRAM, leaving memory for model loading and the worker. Wait for `host memory registered for GPU access` before starting prefill. For the pinned ROCm image, the tier binary is `/sgl-workspace/mori/python/mori/umbp_standalone_server`; include `/sgl-workspace/mori/python/mori` in `LD_LIBRARY_PATH`. If the tier also runs in Docker, pass the ROCm and RDMA devices and hugepage access through to that container and mount `-v /tmp/umbp:/tmp/umbp` in **both** containers. The generated Prefill Docker command already includes that socket-directory mount. The standalone server defaults to `unix:///run/umbp/standalone/node0.grpc.sock` when neither an address argument nor `UMBP_STANDALONE_ADDRESS` is supplied (`UMBP_NODE_ID` replaces `node0` when set). SGLang's client has no default standalone address: set `UMBP_STANDALONE_ADDRESS` to enable this mode. These commands use an explicit socket under `/tmp/umbp` so the server and worker share the same path. UMBP defaults to a 4 GiB DRAM capacity, hugepages disabled, and a 30-second startup wait. This recipe uses 1.5 TB with hugepages enabled and keeps the default startup wait. It also sets `UMBP_SSD_ENABLED=0` to disable the SSD tier (whose config default is enabled), and `MORI_UMBP_LOG_LEVEL=info` to expose the readiness log (the default log level is error). Then launch the prefill role with the socket in its environment. The Deployment panel and Playground include this address and use the default 30-second startup wait. ```bash Command theme={null} UMBP_STANDALONE_ADDRESS=unix:///tmp/umbp/standalone.grpc.sock \ sglang serve ... ``` Two further limits are worth knowing before you size a run. The pool is a per-node process, so a worker that spans nodes would shard its keyspace by node. And under PD disaggregation the §3.7 pairs run the linker on the prefill role only, so the decode worker offloads nothing; in aggregated serving the single worker offloads its own KV. # DeepSeek-V4.1 Source: https://docs.sglang.io/cookbook/autoregressive/DeepSeek/DeepSeek-V4_1 Deploy DeepSeek-V4.1 Flash with SGLang — launch recipes, feature compatibility, and tuning notes for GB300, H200, B200, B300 and MI355X. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > DeepSeek-V4.1 Flash support has **not shipped in an SGLang release yet**, so a stock `pip install sglang` cannot serve it. Use the preview Docker image below. > > **Docker** > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). > > **NVIDIA GPUs** — every NVIDIA cell on this page uses the preview build `lmsysorg/sglang:dev-dsv41` (H200 / B200 / B300 / GB300); the command panel picks it automatically. > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-dsv41 > > docker run --gpus all \ > --shm-size 32g \ > -p 30000:30000 \ > -v ~/.cache/huggingface:/root/.cache/huggingface \ > --env "HF_TOKEN=" \ > --ipc=host \ > lmsysorg/sglang:dev-dsv41 \ > sglang serve > ``` > > **AMD GPUs (ROCm)** — AMD uses the daily-updated `lmsysorg/sglang-rocm` images. You can find the latest images on [Docker Hub](https://hub.docker.com/r/lmsysorg/sglang-rocm/tags). We recommend the ROCm 10 version. > > ```bash Command theme={null} > docker pull lmsysorg/sglang-rocm:v0.5.22-rocm10-mi35x-20261021 > > docker run \ > --device=/dev/kfd --device=/dev/dri \ > --group-add video \ > --cap-add=SYS_PTRACE --security-opt seccomp=unconfined \ > --shm-size 32g --ipc=host \ > -p 30000:30000 \ > -v ~/.cache/huggingface:/root/.cache/huggingface \ > --env "HF_TOKEN=" \ > lmsysorg/sglang-rocm:v0.5.22-rocm10-mi35x-20261021 \ > sglang serve > ``` Pick your hardware + recipe to generate the launch command: * **Low-Latency** — fastest reply for a single user. Pick for chat. * **High-Throughput** — most tokens per second across many users. Best for batch jobs. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## Agentic Long-Context Deployment Agentic workloads, such as coding agents and other multi-turn, tool-using assistants, send long prompts whose prefixes grow and repeat from turn to turn. Serving them well depends on reusing the KV cache across turns, offloading it beyond GPU memory, and keeping each session on the workers that already hold its prefix. This section gives complete launch commands for such deployments, each benchmarked in [SemiAnalysis InferenceX](https://inferencex.semianalysis.com/) and linked to the run that measured it. Pick a hardware platform, checkpoint, deployment shape, concurrency, KV cache offloading mechanism and router to get every process of the deployment as a raw command, one tab per process in launch order. * **Router.** Each configuration was submitted behind one front door: Dynamo (`dynamo.frontend` with `dynamo.sglang` workers) or SGLang (`sglang.launch_server`, behind `sglang_router` when there are several workers or DP-attention ranks). * **KV offload.** Choose among these KV cache offloading mechanisms: none (GPU KV only), HiCache (host DRAM), or a Mooncake store attached through the external linker. The Mooncake option needs an image whose SGLang build includes `--enable-unified-cache-external-linker`. * **Container image.** Run the commands inside the image listed for each configuration. Several are SGLang nightly images, so flag names follow that image. ## 1. Model Introduction **DeepSeek-V4.1 Flash** is a sparse-attention Mixture-of-Experts model (`model_type: deepseek_v4.1`) served through SGLang's `dsv4` backend: 40 decoder layers, 384 routed experts at top-6 plus one shared expert, fp8 dense weights at a 32-wide `ue8m0` block scale with fp4 routed experts. It also carries **DSpark**, its own three-stage speculative draft, which the Low-Latency recipe turns on. **Architecture.** Every layer keeps one 512-wide KV latent per position and uses it as both key and value for all 64 query heads, with no separate value projection. Each layer reads two stores that behave oppositely: **compressed latents**, produced only at source layers and shared forward, collapsing 2 positions into 1 in layers 2–19 and 1-to-1 from layer 20 on; and a **128-position sliding window**, recomputed per layer from that layer's own activations, so it can never be shared but also never grows with context. Consumers address a source's cache by plain `loc // ratio` arithmetic with no mapping table, so compressed state lives and dies with the full prefix for free. The residual stream is four parallel copies mixed by a per-token doubly stochastic matrix; each sublayer's mixing coefficients are consumed by the *next* sublayer, which lets that projection overlap the main GEMMs. **Sparse retrieval.** KV source layers and index source layers are different lists — four of the former, eight of the latter. The four extra index layers produce no keys at all; they re-score layer 20's keys with their own query, so retrieval decisions are made twice as often as keys are stored. Each retrieving layer picks a top-512 candidate set. **Engram.** An additive n-gram hash memory at two layers. Token ids are normalized *before* hashing, so `" The"`, `"the"` and `"THE"` cannot fork into separate rows. Its two fp8 tables are the largest single block of weight in the checkpoint, and by default they load row-sharded across the TP group, which costs an all-reduce per engram layer. `SGLANG_ENABLE_DSV41_ENGRAM_HOST_TABLE=1` (**opt-in**) moves them to host memory instead: the freed HBM goes to the KV pool and output is bitwise unchanged — at the cost of host RAM, a longer load, and needing huge-page backing to keep the gather cheap. `SGLANG_DSV41_ENGRAM_HOST_TABLE_LAYOUT` trades the two all-reduces for page size: `shared` (the default) maps a single copy all ranks read and needs no reduce; `per_rank` splits that same table into one shard per rank and keeps the reduce, but is the only one the kernel reliably backs with 2 MiB pages. **SWA bounded replay.** Decoder SWA bounded replay runs the early layers over the whole extend and the late layers over only each request’s last 128 tokens, sharing late-layer KV from source layer 20. It defaults on for supported CUDA/HIP configurations without context parallelism, including both PD roles on CUDA. Encoder SWA replay can be combined with decoder replay, subject to encoder-specific validation. Eager and breakable prefill are supported; full prefill graphs keep it disabled. With DP attention, automatic enablement requires attention TP 1 and the `none` or `megamoe` MoE backend on CUDA, or `none` on HIP. Use `--enable-decoder-swa-bounded-replay` to explicitly enable replay, subject to compatibility validation. Bounded replay is not numerically equivalent to full prefill. A request for prompt logprobs or for every hidden state runs its whole prompt through the late layers with full sliding windows; other requests, including their output-token logprobs, use the bounded computation. Use `--no-enable-decoder-swa-bounded-replay` to retain full prefill, for example for RL rollouts whose logprobs must match the trainer. **Kernels.** At decode token counts these kernels are launch-bound rather than bandwidth-bound, so the work is fusion and overlap: the compressor projection, ratio-2 pooling, RoPE with fp4 quantization and indexer packing, paged fp4 indexer scoring with top-k resolved straight to cache addresses, and the mHC statistics and Sinkhorn — with compression, indexing and mHC overlapped against attention and FFN on dedicated streams. All of it is selected automatically; the environment switches it once sat behind were removed, so there is nothing to turn on. One caveat outranks the fusions: **output is not bitwise stable across batch composition today** — two default kernels are shape-guarded to a single token — and `--enable-deterministic-inference` is refused on this backend. **Recommended generation:** reasoning evaluations were run at `temperature=1.0`, `top_p=0.95` with reasoning effort `max` (informational — do not hardcode these in application code). **Resources:** [HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash). ## 2. Configuration Tips ### Do not override the backends `--attention-backend`, `--moe-runner-backend` and `--fp8-gemm-backend` are selected automatically from the model, hardware, forward mode and shape. On GB300 they resolve to `dsv4` / `flashinfer_mxfp4` / `flashinfer_cutedsl`. Confirm them in the startup log rather than passing them. On gfx950 the MI355X recipes pin `--fp8-gemm-backend aiter` and leave the other two to resolve. Overriding them is the most common cause of a disappointing measurement: it leaves the 32-wide ue8m0 blocks on the Triton `_w8a8_block_fp8_matmul` fallback, which dominates the decode step and costs most of the model's bs=1 throughput. If your decode rate looks like a small fraction of what you expected, check the resolved backends first. ## 3. Advanced Usage ### 3.1 Reasoning Enable the reasoning parser — `--reasoning-parser auto` resolves to `deepseek-v41` (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to separate thinking from the final answer. The parser puts the thinking block in `reasoning_content` and the answer in `content`; without it both arrive concatenated in `content`. The parser can only split a thinking block the model actually produced, and **thinking is off by default** (`SGLANG_DEFAULT_THINKING=false`). Sending `reasoning_effort` turns it on: any value other than `none` also switches `chat_template_kwargs.thinking` on for you. A request that carries neither comes back with an empty `reasoning_content` however the parser is configured. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="deepseek-ai/DeepSeek-V4.1-Flash", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > reasoning_effort="high", > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` On the request, `reasoning_effort` accepts the tiers `low` (50), `high` (75), `xhigh` (75), and `max` (100), or a float in `[0.0, 0.99]` that maps onto the model's 1–100 budget. An integer budget is reachable only through `chat_template_kwargs.reasoning_effort`, and that route does not switch thinking on by itself — pair it with `chat_template_kwargs.thinking`. `none` turns thinking off. The remaining OpenAI tiers, which have no V4.1 counterpart (`minimal`, `medium`), log a warning and fall back to the server-side default rather than erroring; that default is `high` (75), and `SGLANG_DSV41_REASONING_EFFORT` overrides it. ### 3.2 Tool Calling Enable the tool-call parser — `--tool-call-parser auto` resolves to `deepseekv41` (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. DeepSeek-V4.1 uses spaced DSML tool tags, which the stock DeepSeek-V4 detector does not parse — the `deepseekv41` detector is required. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather in a city", > "parameters": { > "type": "object", > "properties": {"location": {"type": "string"}}, > "required": ["location"], > }, > }, > }] > > resp = client.chat.completions.create( > model="deepseek-ai/DeepSeek-V4.1-Flash", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > reasoning_effort="high", > ) > choice = resp.choices[0] > print("finish_reason:", choice.finish_reason) > print("tool_calls:", choice.message.tool_calls) > print("reasoning:", getattr(choice.message, "reasoning_content", None)) > ``` A successful call returns `finish_reason: "tool_calls"` with a single `get_weather` entry whose arguments carry the requested location. If you see the raw DSML markup in `content` instead, the parser flag is missing. ### 3.3 Speculative Decoding (DSpark) DSpark is DeepSeek-V4.1 Flash's own bundled draft — there is no EAGLE or MTP path for this model, and no `--speculative-num-steps` knob (the draft-token count is resolved from the checkpoint). Turn it on with `--speculative-algorithm DSPARK --speculative-dspark-block-size 5`, which is what the Low-Latency cells do. What to expect: * A DSpark step costs meaningfully more than a plain decode step, so the win at bs=1 is roughly the accept length divided by that fixed step cost. It is a real speed-up on interactive workloads, but not proportional to the number of draft tokens. * Acceptance is strongly workload-dependent — highest on maths and code, lower on open-ended chat, lower still on agentic traces. Size your expectations from the workload you actually run, and measure it rather than assuming. * The step cost does not move with accept length or with the draft block size, so tuning `--speculative-dspark-block-size` will not buy throughput. This is also why the High-Throughput recipe turns speculation off: at large batch the fixed step cost stops paying for itself. ### 3.4 PD Disaggregation Prefill/decode disaggregation is validated token-identical against a single server across 32 greedy prompts, with GSM8K matching through the router. Use the **PD Disaggregation** card in the Playground to generate the prefill role, the decode role and the router command. Both roles run MegaAttention (`--dsv4-attn-backend flashmla_mega`) by default on SM100/SM103, as a single server does. Prefill and decode must store KV in the same layout, so they must agree on `--dsv4-attn-backend` and `SGLANG_DSV4_KV_LAYOUT`; a decode server paired with a prefill whose layout differs fails its first request with a `KV layout mismatch` error. A decode on a GPU other than SM100/SM103 therefore needs `--dsv4-attn-backend flashmla` on the prefill too. One deployment note: Mooncake needs the RDMA fabric visible inside the container, so launch with `--device /dev/infiniband:/dev/infiniband --cap-add IPC_LOCK --ulimit memlock=-1`. Without it Mooncake selects its NVLink transport, which only serves buffers from its own allocator and fails with `Requested address ... not found`. If you hit that, force TCP with `MOONCAKE_PROTOCOL=tcp` and `MC_FORCE_TCP=1` — the Playground's Mooncake option sets both. PD runs with DSpark: on a DSpark recipe both Playground roles keep the speculative flags, and the prefill and decode servers must both pass them. The server accepts this with Mooncake or NIXL transfer, static verification (`SGLANG_RAGGED_VERIFY_MODE`, `static` by default), and no context parallelism on decode (CP=1, DCP=1); it rejects any other combination at startup. ### 3.5 HiCache (Hierarchical KV Caching) HiCache extends RadixAttention with a hierarchy of KV cache tiers, significantly expanding effective context capacity for long-context and multi-turn scenarios. To enable HiCache, open the **HiCache** card in the [Playground above](#playground) and flip **Enable**: the Playground emits `--enable-hierarchical-cache` on top of the recipe's flags, and cold KV pages spill to CPU pinned memory (L2, GPU + CPU) instead of being dropped from the GPU pool. The host pool is sized by ratio (`--hicache-ratio 2`), not by a fixed `--hicache-size`. The Write policy knob controls the GPU → CPU write and defaults to `write_through` (the upstream default): every page is mirrored to the CPU tier as it is written. `write_through_selective` backs up only hot data and `write_back` defers the copy to eviction, trading cache freshness for host-side I/O. The card is not offered on MI355X: hierarchical cache has not been validated on ROCm for this model yet. Only the L2 tier is exposed here. For the storage (L3) tier and the canonical flag set, see the [HiCache best-practices recipe](../../../docs/advanced_features/hicache_best_practices) and the [HiCache documentation](../../../docs/advanced_features/hicache). ### 3.6 Agentic Long-Context on MI355X (FP4, DSpark) Agentic replay is a different workload: long-context prompts, multi-turn sessions that reuse their own prefix across turns, and subagent branches that fan out within one session. Concurrency below counts live sessions, not requests. Every command keeps the engram tables on the host, and none adds a HiCache tier. The sessions fit the device pool. TP2 covers concurrency 1 to 32 and TP4 covers 1 to 16; at 32 and 64 the same two GPUs also run DP attention with TP MoE. **TP2 or TP4, concurrency 1–16:** * TP2 raises `--mem-fraction-static` at concurrency 16; TP4 stops at 16 and holds 0.70, with a quarter of the checkpoint per rank leaving room to spare. * A longer `--prefill-decode-interval` runs more decode rounds between prefill batches, trading TTFT for P90 inter-token latency. * Up to concurrency 8 it pairs with `--schedule-policy lpm`, which admits the requests with the longest cached prefix first. * These points set `--enable-amd-monokernel`. Do not set `SGLANG_HIP_DSV41_INDEX_K_PAGE8`: the monokernel refuses that layout. The braced values in the command follow concurrency: | Concurrency | 1 | 2 | 4 | 8 | 16 | 32 | | - | - | - | - | - | - | - | | `--max-running-requests` | 2 | 4 | 8 | 16 | 32 | 64 | | `--swa-prefix-tails` | 128 | 128 | 256 | 512 | 1024 | 2048 | | `--prefill-decode-interval` | 192 | 192 | 192 | 192 | 96 | 32 | | `--schedule-policy` | lpm | lpm | lpm | lpm | fcfs | fcfs | | `--mem-fraction-static`, TP2 | 0.70 | 0.70 | 0.70 | 0.70 | 0.80 | 0.80 | | `--mem-fraction-static`, TP4 | 0.70 | 0.70 | 0.70 | 0.70 | 0.70 | — | ```bash Command theme={null} SGLANG_DEFAULT_THINKING=1 \ SGLANG_DSV41_REASONING_EFFORT=high \ SGLANG_ENABLE_DSV41_ENGRAM_HOST_TABLE=1 \ SGLANG_DSV41_ENGRAM_HOST_TABLE_LAYOUT=per_rank \ SGLANG_USE_AITER=1 \ SGLANG_USE_ROCM700A=0 \ TORCH_BLAS_PREFER_HIPBLASLT=1 \ TRITON_HIP_USE_ASYNC_COPY=0 \ ROCM_QUICK_REDUCE_QUANTIZATION=INT8 \ SGLANG_OPT_HIP_OPUS_SPARSE_PREFILL=true \ SGLANG_OPT_HIP_FLYDSL_MXFP8=1 \ SGLANG_HIP_FP4_INDEXER_ROWGROUP=1 \ HSA_NO_SCRATCH_RECLAIM=0 \ GPU_MAX_HW_QUEUES=2 \ sglang serve \ --model-path deepseek-ai/DeepSeek-V4.1-Flash \ --trust-remote-code \ --tp {2 or 4} \ --ep-size 1 \ --speculative-algorithm DSPARK \ --speculative-dspark-block-size 5 \ --enable-amd-monokernel \ --enforce-shared-experts-fusion \ --fp8-gemm-backend aiter \ --enable-decoder-swa-bounded-replay \ --cuda-graph-backend-prefill disabled \ --mem-fraction-static {mem-fraction-static} \ --chunked-prefill-size 16384 \ --prefill-decode-interval {prefill-decode-interval} \ --schedule-policy {schedule-policy} \ --swa-prefix-tails {swa-prefix-tails} \ --max-running-requests {max-running-requests} \ --cuda-graph-max-bs-decode 64 \ --reasoning-parser auto \ --tool-call-parser auto \ --watchdog-timeout 3600 ``` **TP2, concurrency 32:** the command above with the concurrency-32 column, without `--enable-amd-monokernel`, and with `SGLANG_HIP_DSV41_INDEX_K_PAGE8=1`. **DP2, concurrency 32–64:** two DP attention ranks, one per GPU, with the MoE still tensor parallel across both. The braced values follow concurrency: | Concurrency | 32 | 64 | | - | - | - | | `--mem-fraction-static` | 0.80 | 0.85 | | `--prefill-decode-interval` | 32 | 16 | | `--swa-prefix-tails` | 2048 | 4096 | ```bash Command theme={null} SGLANG_DEFAULT_THINKING=1 \ SGLANG_DSV41_REASONING_EFFORT=high \ SGLANG_ENABLE_DSV41_ENGRAM_HOST_TABLE=1 \ SGLANG_DSV41_ENGRAM_HOST_TABLE_LAYOUT=per_rank \ SGLANG_USE_AITER=1 \ SGLANG_USE_ROCM700A=0 \ TORCH_BLAS_PREFER_HIPBLASLT=1 \ TRITON_HIP_USE_ASYNC_COPY=0 \ ROCM_QUICK_REDUCE_QUANTIZATION=INT8 \ SGLANG_OPT_HIP_OPUS_SPARSE_PREFILL=true \ SGLANG_OPT_HIP_FLYDSL_MXFP8=1 \ SGLANG_HIP_FP4_INDEXER_ROWGROUP=1 \ SGLANG_HIP_DSV41_INDEX_K_PAGE8=1 \ HSA_NO_SCRATCH_RECLAIM=0 \ GPU_MAX_HW_QUEUES=5 \ SGLANG_SHARED_EXPERT_TP1=1 \ SGLANG_DP_USE_GATHERV=1 \ SGLANG_DP_USE_REDUCE_SCATTER=1 \ SGLANG_AITER_CAPTURE_COPY_IN=1 \ sglang serve \ --model-path deepseek-ai/DeepSeek-V4.1-Flash \ --trust-remote-code \ --tp 2 \ --attn-dp-size 2 \ --ep-size 1 \ --enable-dp-lm-head \ --enable-prefill-delayer \ --enable-dp-attention-local-control-broadcast \ --tokenizer-worker-num 2 \ --prefill-delayer-token-usage-low-watermark 0.7 \ --load-balance-method total_requests \ --speculative-algorithm DSPARK \ --speculative-dspark-block-size 5 \ --enforce-shared-experts-fusion \ --fp8-gemm-backend aiter \ --enable-decoder-swa-bounded-replay \ --cuda-graph-backend-prefill disabled \ --mem-fraction-static {mem-fraction-static} \ --chunked-prefill-size 32768 \ --prefill-decode-interval {prefill-decode-interval} \ --swa-prefix-tails {swa-prefix-tails} \ --max-running-requests 64 \ --cuda-graph-max-bs-decode 64 \ --reasoning-parser auto \ --tool-call-parser auto \ --watchdog-timeout 3600 ``` Front the server with `sglang_router --policy cache_aware --dp-aware`, so a multi-turn session lands on the DP rank already holding its prefix. # Ernie4.5 Source: https://docs.sglang.io/cookbook/autoregressive/Ernie/Ernie4.5 ## 1. Model Introduction The **ERNIE-4.5** series is a family of large language models developed by Baidu. ERNIE (Enhanced Representation through Knowledge Integration) 4.5 represents an advanced version of the ERNIE series, optimized for general-purpose tasks and conversational scenarios. ERNIE-4.5 delivers advanced features as below: * **Heterogeneous Modality Structure**: MoE architecture that supports parameter sharing across modalities while allowing dedicated parameters for each individual modality, enhancing multimodal understanding without compromising, and even improving, performance on text-related tasks. * **Vision Encoder**: Dedicated adaptive-resolution ViT with 2D RoPE and image packing; for video, adaptive frame sampling and timestamp rendering, supporting both shared and modality-specific visual processing. * **Adapter**: Shared modality-bridging module with spatial and temporal compression to align vision to text embedding space, enabling cross-modal understanding without compromising text representations. * **Multimodal Position Embedding**: Unified 3D RoPE (temporal, height, width) for vision and 1D RoPE for text in a single embedding space, supporting parameter sharing while encoding modality-specific positions. * **Hardware Optimization**: Specifically tuned for AMD MI300X, MI325X, MI355X GPUs and Intel Xeon CPUs. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and thinking capabilities. Run this Command:

## 4. API Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

The following example demonstrates deployment using ERNIE-4.5-21B-A3B-PT.

```shell Command theme={null}
python -m sglang.launch_server \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --tp 1
```

**Basic Python Client Example:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="baidu/ERNIE-4.5-21B-A3B-PT",
    messages=[
        {"role": "user", "content": "What is artificial intelligence?"}
    ],
    temperature=1.0,
    top_p=0.95,
    max_tokens=1024
)

print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
**Artificial Intelligence (AI)** is the simulation of human intelligence processes by machines, particularly computer systems. These processes include **learning** (acquiring information and rules for using the information), **reasoning** (using rules to reach approximate or definite conclusions), and **self-correction**. AI encompasses a wide range of techniques, algorithms, and methodologies designed to enable machines to perform tasks that typically require human intelligence.

### Key Characteristics of AI:
...

### In Summary:
AI represents a transformative force with the potential to revolutionize industries and enhance human capabilities. However, its development requires careful consideration of ethical, legal, and social implications to ensure that it benefits society as a whole. As AI continues to evolve, ongoing dialogue among stakeholders will be crucial to balancing innovation with responsibility.
```

**Streaming Example:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="baidu/ERNIE-4.5-21B-A3B-PT",
    messages=[
        {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    temperature=1.0,
    top_p=0.95,
    max_tokens=2048,
    stream=True
)

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta
        if delta.content:
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
Sure! Here’s a simple explanation of quantum computing:

### **Quantum Computing: Making Computers Super Fast (But Weird) Using Quantum Rules**

1. **Classic vs. Quantum Computers**
   - **Normal computers** use **bits** (0s and 1s) to store and process information.
   - **Quantum computers** use **qubits** (short for quantum bits). Unlike bits, qubits can be **0, 1, or both at the same time** (this is called **superposition**).

2. **Superposition: The Magic Behind Speed**
   - A single qubit can represent **0 and 1 simultaneously**, like a coin spinning in the air.
   - Many qubits working together (in something called **quantum parallelism**) can **check multiple possibilities at once**, making quantum computers much faster for certain problems.

3. **Entanglement: Making Qubits Link**
   - When qubits are **entangled**, their states are linked—changing one instantly affects the other, no matter how far apart they are (this is called **spooky action at a distance** by Einstein).
   - Entanglement allows quantum computers to process information in **very efficient ways**.

4. **What Quantum Computers Are Good At**
   - **Cracking encryption** (like RSA).
   - **Factoring large numbers** (used in encryption and cryptography).
   - **Searching unsorted databases** (way faster than classical computers).
   - **Simulating quantum systems** (like molecules for drug discovery).
   - **Optimizing problems** (like logistics or finance).

5. **Challenges & Current State**
   - Qubits are **fragile** and easily disturbed (called **decoherence**).
   - Engineers are working to keep qubits stable long enough to do useful calculations.
   - Today’s quantum computers are **small and experimental**, but the goal is to build powerful ones that outperform classical supercomputers.

### **Final Thought**
Quantum computing isn’t just a faster calculator—it’s a **new way of thinking about problems** using the weird laws of physics. While still new, it has the potential to revolutionize fields like medicine, AI, and cybersecurity.

Would you like an example of how a quantum computer might solve a problem? 😊
```

## 5. Benchmark

This section uses **industry-standard configurations** for comparable benchmark results.

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: AMD MI300X GPU (1x)
* Model: ERNIE-4.5-21B-A3B-PT
* Tensor Parallelism: 1
* SGLang Version: 0.5.7

**Benchmark Methodology:**

We use industry-standard benchmark configurations to ensure results are comparable across frameworks and hardware platforms.

#### 5.1.1 Standard Scenario Benchmark

* Model Deployment Command:

```bash Command theme={null}
python -m sglang.launch_server \
  --model-path baidu/ERNIE-4.5-21B-A3B-PT \
  --tp 1
```

##### 5.1.1.1 Low Concurrency (Latency-Optimized)

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  58.72
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4219
Request throughput (req/s):              0.17
Input token throughput (tok/s):          103.90
Output token throughput (tok/s):         71.87
Peak output token throughput (tok/s):    245.00
Peak concurrent requests:                2
Total token throughput (tok/s):          175.77
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5869.86
Median E2E Latency (ms):                 1870.80
---------------Time to First Token----------------
Mean TTFT (ms):                          4152.58
Median TTFT (ms):                        36.81
P99 TTFT (ms):                           37498.23
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          4.07
Median TPOT (ms):                        4.09
P99 TPOT (ms):                           4.09
---------------Inter-Token Latency----------------
Mean ITL (ms):                           4.08
Median ITL (ms):                         4.08
P95 ITL (ms):                            4.14
P99 ITL (ms):                            4.20
Max ITL (ms):                            4.67
==================================================
```

##### 5.1.1.2 Medium Concurrency (Balanced)

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  34.30
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    40773
Request throughput (req/s):              2.33
Input token throughput (tok/s):          1156.62
Output token throughput (tok/s):         1189.77
Peak output token throughput (tok/s):    1392.00
Peak concurrent requests:                21
Total token throughput (tok/s):          2346.39
Concurrency:                             14.14
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   6060.62
Median E2E Latency (ms):                 6496.70
---------------Time to First Token----------------
Mean TTFT (ms):                          78.90
Median TTFT (ms):                        45.90
P99 TTFT (ms):                           234.33
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          11.99
Median TPOT (ms):                        12.16
P99 TPOT (ms):                           14.81
---------------Inter-Token Latency----------------
Mean ITL (ms):                           11.75
Median ITL (ms):                         11.48
P95 ITL (ms):                            12.24
P99 ITL (ms):                            34.85
Max ITL (ms):                            105.01
==================================================
```

##### 5.1.1.3 High Concurrency (Throughput-Optimized)

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  66.63
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    252449
Request throughput (req/s):              7.50
Input token throughput (tok/s):          3749.79
Output token throughput (tok/s):         3792.28
Peak output token throughput (tok/s):    4902.00
Peak concurrent requests:                113
Total token throughput (tok/s):          7542.06
Concurrency:                             90.33
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   12036.90
Median E2E Latency (ms):                 11782.16
---------------Time to First Token----------------
Mean TTFT (ms):                          104.86
Median TTFT (ms):                        84.62
P99 TTFT (ms):                           297.85
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          23.89
Median TPOT (ms):                        24.62
P99 TPOT (ms):                           26.91
---------------Inter-Token Latency----------------
Mean ITL (ms):                           23.66
Median ITL (ms):                         20.48
P95 ITL (ms):                            45.57
P99 ITL (ms):                            54.31
Max ITL (ms):                            185.12
==================================================
```

#### 5.1.2 Reasoning Scenario Benchmark

##### 5.1.2.1 Low Concurrency

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  185.11
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  44462
Total generated tokens (retokenized):    44423
Request throughput (req/s):              0.05
Input token throughput (tok/s):          32.96
Output token throughput (tok/s):         240.19
Peak output token throughput (tok/s):    245.00
Peak concurrent requests:                2
Total token throughput (tok/s):          273.15
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   18508.84
Median E2E Latency (ms):                 19866.81
---------------Time to First Token----------------
Mean TTFT (ms):                          32.59
Median TTFT (ms):                        32.14
P99 TTFT (ms):                           38.58
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          4.13
Median TPOT (ms):                        4.13
P99 TPOT (ms):                           4.20
---------------Inter-Token Latency----------------
Mean ITL (ms):                           4.16
Median ITL (ms):                         4.12
P95 ITL (ms):                            4.31
P99 ITL (ms):                            4.36
Max ITL (ms):                            7.28
==================================================
```

##### 5.1.2.2 Medium Concurrency

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  263.48
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  318306
Total generated tokens (retokenized):    317984
Request throughput (req/s):              0.30
Input token throughput (tok/s):          150.55
Output token throughput (tok/s):         1208.09
Peak output token throughput (tok/s):    1408.00
Peak concurrent requests:                19
Total token throughput (tok/s):          1358.64
Concurrency:                             14.35
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   47249.55
Median E2E Latency (ms):                 47828.67
---------------Time to First Token----------------
Mean TTFT (ms):                          62.77
Median TTFT (ms):                        57.10
P99 TTFT (ms):                           93.70
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          11.92
Median TPOT (ms):                        12.09
P99 TPOT (ms):                           12.50
---------------Inter-Token Latency----------------
Mean ITL (ms):                           11.86
Median ITL (ms):                         12.04
P95 ITL (ms):                            12.68
P99 ITL (ms):                            13.61
Max ITL (ms):                            39.94
==================================================
```

##### 5.1.2.3 High Concurrency

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 320 \
  --max-concurrency 64 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  428.30
Total input tokens:                      158939
Total input text tokens:                 158939
Total input vision tokens:               0
Total generated tokens:                  1301025
Total generated tokens (retokenized):    1299877
Request throughput (req/s):              0.75
Input token throughput (tok/s):          371.09
Output token throughput (tok/s):         3037.63
Peak output token throughput (tok/s):    3880.00
Peak concurrent requests:                69
Total token throughput (tok/s):          3408.73
Concurrency:                             57.08
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   76392.58
Median E2E Latency (ms):                 79698.73
---------------Time to First Token----------------
Mean TTFT (ms):                          92.79
Median TTFT (ms):                        78.71
P99 TTFT (ms):                           168.89
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          18.81
Median TPOT (ms):                        19.15
P99 TPOT (ms):                           19.81
---------------Inter-Token Latency----------------
Mean ITL (ms):                           18.77
Median ITL (ms):                         18.77
P95 ITL (ms):                            19.86
P99 ITL (ms):                            42.08
Max ITL (ms):                            74.36
==================================================
```

#### 5.1.3 Summarization Scenario Benchmark

##### 5.1.3.1 Low Concurrency

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  18.59
Total input tokens:                      41941
Total input text tokens:                 41941
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4216
Request throughput (req/s):              0.54
Input token throughput (tok/s):          2256.43
Output token throughput (tok/s):         227.04
Peak output token throughput (tok/s):    245.00
Peak concurrent requests:                2
Total token throughput (tok/s):          2483.46
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   1856.72
Median E2E Latency (ms):                 1513.87
---------------Time to First Token----------------
Mean TTFT (ms):                          86.66
Median TTFT (ms):                        72.30
P99 TTFT (ms):                           167.13
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          4.19
Median TPOT (ms):                        4.22
P99 TPOT (ms):                           4.30
---------------Inter-Token Latency----------------
Mean ITL (ms):                           4.20
Median ITL (ms):                         4.23
P95 ITL (ms):                            4.34
P99 ITL (ms):                            4.42
Max ITL (ms):                            5.68
==================================================
```

##### 5.1.3.2 Medium Concurrency

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  40.25
Total input tokens:                      300020
Total input text tokens:                 300020
Total input vision tokens:               0
Total generated tokens:                  41669
Total generated tokens (retokenized):    41646
Request throughput (req/s):              1.99
Input token throughput (tok/s):          7454.72
Output token throughput (tok/s):         1035.37
Peak output token throughput (tok/s):    1310.00
Peak concurrent requests:                20
Total token throughput (tok/s):          8490.09
Concurrency:                             14.37
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   7229.56
Median E2E Latency (ms):                 7578.95
---------------Time to First Token----------------
Mean TTFT (ms):                          137.38
Median TTFT (ms):                        122.59
P99 TTFT (ms):                           485.34
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          14.04
Median TPOT (ms):                        14.24
P99 TPOT (ms):                           20.77
---------------Inter-Token Latency----------------
Mean ITL (ms):                           13.64
Median ITL (ms):                         12.36
P95 ITL (ms):                            14.72
P99 ITL (ms):                            57.39
Max ITL (ms):                            411.31
==================================================
```

##### 5.1.3.3 High Concurrency

* Benchmark Command:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model baidu/ERNIE-4.5-21B-A3B-PT \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 320 \
  --max-concurrency 64 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  78.33
Total input tokens:                      1273893
Total input text tokens:                 1273893
Total input vision tokens:               0
Total generated tokens:                  170000
Total generated tokens (retokenized):    169888
Request throughput (req/s):              4.09
Input token throughput (tok/s):          16262.33
Output token throughput (tok/s):         2170.20
Peak output token throughput (tok/s):    3005.00
Peak concurrent requests:                73
Total token throughput (tok/s):          18432.53
Concurrency:                             58.79
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   14392.52
Median E2E Latency (ms):                 14460.70
---------------Time to First Token----------------
Mean TTFT (ms):                          184.82
Median TTFT (ms):                        155.24
P99 TTFT (ms):                           379.82
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          26.97
Median TPOT (ms):                        28.31
P99 TPOT (ms):                           33.61
---------------Inter-Token Latency----------------
Mean ITL (ms):                           26.79
Median ITL (ms):                         20.55
P95 ITL (ms):                            47.55
P99 ITL (ms):                            145.64
Max ITL (ms):                            287.62
==================================================
```

### 5.2 Accuracy Benchmark

Document model accuracy on standard benchmarks:

#### 5.2.1 GSM8K Benchmark

* Benchmark Command:

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 1319 \
  --num-threads 1316
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

* Test Results:
  * ERNIE-4.5-21B-A3B-PT
  ```
  Accuracy: 0.865
  Invalid: 0.000
  Latency: 21.669 s
  Output throughput: 10359.790 token/s
  ```


# Ernie4.5-VL
Source: https://docs.sglang.io/cookbook/autoregressive/Ernie/Ernie4.5-VL



## 📝 Community Contribution Welcome

This guide is currently under development. We welcome community contributions!

If you have experience deploying **Ernie4.5-VL** with SGLang, please help us complete this documentation.

## 🚀 How to Contribute

```shell Command theme={null}
git clone https://github.com/YOUR_USERNAME/sglang-cookbook.git
cd sglang-cookbook
git checkout -b add-ernie4-5-vl-guide
# Edit this file and submit a PR
```

## 📚 Reference

* [GLM-4.6V](../GLM/GLM-4.6V)

***

**Let's build this together!** 🌟


# Chroma-1.0
Source: https://docs.sglang.io/cookbook/autoregressive/FlashLabs/Chroma1.0



## 1. Model Introduction

[Chroma-1.0](https://github.com/FlashLabs-AI-Corp/FlashLabs-Chroma) is an open-source end-to-end speech conversation model developed by FlashLabs, focusing on the following core capabilities:

* **Real-time Speech Generation**: Supports low-latency speech synthesis, suitable for real-time conversational scenarios.
* **Customized Voice Cloning**: Capable of cloning and replicating specific speaker voice characteristics.
* **End-to-End Architecture**: Provides a complete processing workflow from speech to speech.
* **Speech Reasoning**: Equipped with reasoning capabilities to understand and process speech content.

## 2. Architecture Overview

**Chroma-1.0** utilizes a hybrid serving architecture rather than a direct SGLang deployment. This design choice is driven by:

1. **Complex Model Architecture**: The end-to-end speech processing pipeline involves specialized components that go beyond standard text generation loops.
2. **KV Cache & State Management**: The model requires custom handling of KV caches that differs from standard implementations.
3. **Batching Limitations**: The current implementation supports a batch size of 1, meaning SGLang's advanced continuous batching capabilities are not yet fully applicable.

Therefore, you will start the **FlashLabs Server**, which manages the overall workflow and selectively leverages SGLang for specific inference components where supported.

* **Outer Layer**: FlashLabs Server (Handles Audio I/O, State, and Model Logic)
* **Inner Engine**: SGLang Instance (Utilized for specific acceleration where applicable)

## 3. Installation & Setup

We recommend following these steps to set up the environment and prepare the model.

### Step 1: Get the Docker Image

Pull the official pre-built image from Docker Hub to ensure all dependencies are correctly configured.

```bash Command theme={null}
docker pull flashlabs/chroma:latest
```

### Step 2: Download Model Weights

Download the **Chroma-4B** weights from Hugging Face. You can choose one of the following methods:

**Method 1: Using Python (Recommended)**

```bash Command theme={null}
huggingface-cli download FlashLabs/Chroma-4B --local-dir Chroma-4B
```

**Method 2: Using Git Clone**

Make sure you have Git LFS installed before cloning.

```bash Command theme={null}
# Install Git LFS first
git lfs install

# Clone the repository
git clone https://huggingface.co/FlashLabs/Chroma-4B Chroma-4B
```

### Step 3: Download Chroma Codes (SGLang version)

```bash Command theme={null}
git clone https://github.com/FlashLabs-AI-Corp/Chroma-SGLang.git

cd Chroma-SGLang
```

### Step 4: Run the Server

```bash Command theme={null}
docker run -d \
  --gpus all \
  -p 8000:8000 \
  -w /app/Chroma-SGLang \
  -v "your_Chroma-SGLang_path":/app/Chroma-SGLang \
  -v "your_chroma_path":/model \
  -e CHROMA_MODEL_PATH=/model \
  -e DP_SIZE="1" \
  flashlabs/chroma:latest \
  /opt/conda/bin/python -m uvicorn api_server:app \
  --host 0.0.0.0 \
  --port 8000 \
  --workers 1
```

or run simply the following one line command

```bash Command theme={null}
docker-compose up -d
```

## 5. Client Usage Example

Once the server is running, you can interact with it using HTTP requests.

### Python Client

```python Example theme={null}
import requests
import base64

url = "http://localhost:8000/v1/chat/completions"
headers = {"Content-Type": "application/json"}

payload = {
    "model": "chroma",
    "messages": [
        {
            "role": "system",
            "content": "You are Chroma, a voice agent developed by FlashLabs."
        },
        {
            "role": "user",
            "content": [
                {"type": "audio", "audio": "assets/question_audio.wav"}
            ]
        }
    ],
    "max_tokens": 1000,
    "return_audio": True
}

response = requests.post(url, json=payload, headers=headers)
result = response.json()

if result.get("audio"):
    audio_data = base64.b64decode(result["audio"])
    with open("output.wav", "wb") as f:
        f.write(audio_data)
    print("Audio saved to output.wav")
```

### OpenAI SDK Compatible Example

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="dummy",
    base_url="http://localhost:8000/v1"
)

response = client.chat.completions.create(
    model="chroma",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {
            "role": "user",
            "content": [
                {"type": "audio", "audio": "assets/question_audio.wav"}
            ]
        }
    ],
    extra_body={
        "prompt_text": "I have not... I'm so exhausted, I haven't slept in a very long time. It could be because... Well, I used our... Uh, I'm, I just use... This is what I use every day. I use our cleanser every day, I use serum in the morning and then the moistu- daily moisturizer. That's what I use every morning.",
        "prompt_audio": "assets/ref_audio.wav",
        "return_audio": True
    }
)

print(response)
```

### CLI (cURL)

```bash Command theme={null}
curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "chroma",
    "messages": [
      {
        "role": "system",
        "content": "You are Chroma, a voice agent developed by FlashLabs."
      },
      {
        "role": "user",
        "content": [
          {
            "type": "audio",
            "audio": "assets/question_audio.wav"
          }
        ]
      }
    ],
    "max_tokens": 1000,
    "return_audio": true
  }' | jq -r '.audio' | base64 -d > output.wav
```


# GLM-4.5
Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-4.5



## 1. Model Introduction

[GLM-4.5](https://huggingface.co/zai-org/GLM-4.5) is a powerful language model developed by Zhipu AI, featuring advanced capabilities in reasoning, function calling, and multi-modal understanding.

**Key Features:**

* **Advanced Reasoning**: Built-in reasoning capabilities for complex problem-solving
* **Multiple Quantizations**: BF16 and FP8 variants for different performance/memory trade-offs
* **Hardware Optimization**: Specifically tuned for AMD MI300X/MI325X/MI355X GPUs
* **High Performance**: Optimized for both throughput and latency scenarios

**Available Models:**

* **BF16 (Full precision)**: [zai-org/GLM-4.5](https://huggingface.co/zai-org/GLM-4.5) - Recommended for MI300X/MI325X/MI355X
* **FP8 (8-bit quantized)**: [zai-org/GLM-4.5-FP8](https://huggingface.co/zai-org/GLM-4.5-FP8) - Recommended for MI300X/MI325X/MI355X

**License:**

Please refer to the [official GLM-4.5 model card](https://huggingface.co/zai-org/GLM-4.5) for license details.

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, deployment strategy, and thinking capabilities.

Run this Command:


### 3.2 Configuration Tips

* **EAGLE Speculative Decoding:** Supported for GLM-4.5/4.6. Add `--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. The spec-v2 overlap scheduler is enabled by default; pass `--disable-overlap-schedule` to disable.
* **Thinking Budget:** Use `--enable-custom-logit-processor` flag and pass `Glm4MoeThinkingBudgetLogitProcessor` in requests to cap the model's thinking token count (see section 4.2.3).

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

GLM-4.5 supports Thinking mode by default. Enable the reasoning parser during deployment to separate the thinking and the content sections:

```shell Command theme={null}
python -m sglang.launch_server \
  --model zai-org/GLM-4.5 \
  --reasoning-parser glm45 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="zai-org/GLM-4.5",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
To solve this problem, I need to calculate 15% of 240.
Step 1: Convert 15% to decimal: 15% = 0.15
Step 2: Multiply 240 by 0.15
Step 3: 240 × 0.15 = 36
=============== Content =================

The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36.
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.2 Tool Calling

> [!NOTE]
>
> **Parser names by model:** GLM-4.5 and GLM-4.6 use `--tool-call-parser glm45`. GLM-4.7 and GLM-4.7-Flash use `--tool-call-parser glm47`. All GLM models use `--reasoning-parser glm45` regardless of generation.

GLM-4.5 supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model zai-org/GLM-4.5 \
  --reasoning-parser glm45 \
  --tool-call-parser glm45 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="zai-org/GLM-4.5",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                if tool_call.function:
                    print(f"Tool Call: {tool_call.function.name}")
                    print(f"   Arguments: {tool_call.function.arguments}")

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information.
I should call the function with location="Beijing".
=============== Content =================

Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

#### 4.2.3 Thinking Budget

Limit the number of thinking tokens using `CustomLogitProcessor`. Launch with `--enable-custom-logit-processor`:

```python Example theme={null}
import openai
from sglang.srt.sampling.custom_logit_processor import Glm4MoeThinkingBudgetLogitProcessor

client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="*")
response = client.chat.completions.create(
    model="zai-org/GLM-4.5",
    messages=[{"role": "user", "content": "Is Paris the Capital of France?"}],
    max_tokens=1024,
    extra_body={
        "custom_logit_processor": Glm4MoeThinkingBudgetLogitProcessor().to_str(),
        "custom_params": {"thinking_budget": 512},
    },
)
print(response)
```

## 5. Benchmark

This section uses **industry-standard configurations** for comparable benchmark results.

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: AMD MI300X (8x), AMD MI325X (8x), AMD MI355X (8x)
* Model: GLM-4.5
* Tensor Parallelism: 8
* SGLang Version: 0.5.6.post1

**Benchmark Methodology:**

We use industry-standard benchmark configurations to ensure results are comparable across frameworks and hardware platforms.

#### 5.1.1 Standard Test Scenarios

Three core scenarios reflect real-world usage patterns:

Scenario Input Length Output Length Use Case
**Chat** 1K 1K Most common conversational AI workload
**Reasoning** 1K 8K Long-form generation, complex reasoning tasks
**Summarization** 8K 1K Document summarization, RAG retrieval
#### 5.1.2 Concurrency Levels Test each scenario at three concurrency levels to capture the throughput vs. latency tradeoff (Pareto frontier): * **Low Concurrency**: `--max-concurrency 1` (Latency-optimized) * **Medium Concurrency**: `--max-concurrency 16` (Balanced) * **High Concurrency**: `--max-concurrency 100` (Throughput-optimized) #### 5.1.3 Number of Prompts For each concurrency level, configure `num_prompts` to simulate realistic user loads: * **Quick Test**: `num_prompts = concurrency × 1` (minimal test) * **Recommended**: `num_prompts = concurrency × 5` (standard benchmark) * **Stable Measurements**: `num_prompts = concurrency × 10` (production-grade) *** #### 5.1.4 Benchmark Commands **Scenario 1: Chat (1K/1K) - Most Important** * **Model Deployment** ```bash Command theme={null} python -m sglang.launch_server \ --model zai-org/GLM-4.5 \ --tp 8 ``` * Low Concurrency (Latency-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * Medium Concurrency (Balanced) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` * High Concurrency (Throughput-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` **Scenario 2: Reasoning (1K/8K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` **Scenario 3: Summarization (8K/1K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.5 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` #### 5.1.5 Understanding the Results **Key Metrics:** * **Request Throughput (req/s)**: Number of requests processed per second * **Output Token Throughput (tok/s)**: Total tokens generated per second * **Mean TTFT (ms)**: Time to First Token - measures responsiveness * **Mean TPOT (ms)**: Time Per Output Token - measures generation speed * **Mean ITL (ms)**: Inter-Token Latency - measures streaming consistency **Why These Configurations Matter:** * **1K/1K (Chat)**: Represents the most common conversational AI workload. This is the highest priority scenario for most deployments. * **1K/8K (Reasoning)**: Tests long-form generation capabilities crucial for complex reasoning, code generation, and detailed explanations. * **8K/1K (Summarization)**: Evaluates performance with large context inputs, essential for RAG systems, document Q\&A, and summarization tasks. * **Variable Concurrency**: Captures the Pareto frontier - the optimal tradeoff between throughput and latency at different load levels. Low concurrency shows best-case latency, high concurrency shows maximum throughput. **Interpreting Results:** * Compare your results against baseline numbers for your hardware * Higher throughput at same latency = better performance * Lower TTFT = more responsive user experience * Lower TPOT = faster generation speed ### 5.2 Accuracy Benchmark Document model accuracy on standard benchmarks: #### 5.2.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. # GLM-4.5V Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-4.5V ## 1. Model Introduction [GLM-4.5V](https://huggingface.co/zai-org/GLM-4.5V) is a state-of-the-art multimodal vision-language model from ZhipuAI, built on the next-generation flagship text foundation model GLM-4.5-Air (106B parameters, 12B active). It achieves SOTA performance among models of the same scale across 42 public vision-language benchmarks. Through efficient hybrid training, GLM-4.5V focuses on real-world usability and enables full-spectrum vision reasoning across diverse visual content types. **Hardware Support:** NVIDIA B200/H100/H200, AMD MI300X/MI325X/MI355X GLM-4.5V introduces several key features: * **Image Reasoning & Grounding** Scene understanding, complex multi-image analysis, and spatial recognition with precise visual element localization. Supports bounding box predictions with normalized coordinates (0-1000) for accurate object detection. * **Video Understanding** Long video segmentation and event recognition, supporting comprehensive temporal analysis across extended video sequences. * **GUI Agent Tasks** Screen reading, icon recognition, and desktop operation assistance for agent-based applications. Enables natural interaction with graphical user interfaces. * **Complex Chart & Long Document Parsing** Research report analysis and information extraction from documents with text, charts, tables, and figures. Processes up to 64K tokens of multimodal context. * **Thinking Mode Switch** Allows users to balance between quick responses and deep reasoning. Users can enable/disable Chain-of-Thought reasoning based on task requirements for improved accuracy and interpretability. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration The GLM-4.5V offers models in various sizes and architectures, optimized for different hardware platforms. The recommended launch configurations vary by hardware and model size. **Interactive Command Generator**: Use the interactive configuration generator below to customize your deployment settings. Select your hardware platform, model size, quantization method, and other options to generate the appropriate launch command. Run this Command:

### 3.2 Configuration Tips

* **TTFT Optimization** : Set `SGLANG_USE_CUDA_IPC_TRANSPORT=1` to use CUDA IPC for transferring multimodal features, which significantly improves TTFT. This consumes additional memory and may require adjusting `--mem-fraction-static` and/or `--max-running-requests`. (additional memory is proportional to image size \* number of images in current running requests.)
* **TP=8 Configuration**: When using Tensor Parallelism (TP) of 8, the vision attention's 12 heads cannot be evenly divided. You can resolve this by adding `--mm-enable-dp-encoder`.
* **Fast Model Loading**: For large models (like the 106B version), you can speed up model loading by using `--model-loader-extra-config='{"enable_multithread_load": "true","num_threads": 64}'`.
* **Hardware Notes:**
  * **H100 (FP8):** Use the FP8 checkpoint for best memory efficiency.
  * **A100 / H100 (BF16):** Use standard multimodal parameters to manage throughput and GPU memory usage.
  * **H200 / B200:** Runs out of the box, supporting full context length plus concurrent image + video processing.
* **Additional Multimodal Parameters:**
  * `--mm-attention-backend fa3`: Specify multimodal attention backend (Flash Attention 3).
  * `--mm-feature-transport=cuda_ipc`: Use CUDA IPC shared memory for multimodal data transport to avoid D2H memory copies and significantly improve E2E latency.

**Example with full multimodal optimizations:**

```bash Command theme={null}
SGLANG_USE_CUDA_IPC_TRANSPORT=1 \
SGLANG_VLM_CACHE_SIZE_MB=0 \
python -m sglang.launch_server \
  --model-path zai-org/GLM-4.5V \
  --host 0.0.0.0 \
  --port 30000 \
  --trust-remote-code \
  --tp-size 8 \
  --enable-cache-report \
  --log-level info \
  --max-running-requests 64 \
  --mem-fraction-static 0.65 \
  --chunked-prefill-size 8192 \
  --attention-backend fa3 \
  --mm-attention-backend fa3 \
  --mm-enable-dp-encoder \
  --enable-metrics
```

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Multi-Modal Inputs

GLM-4.5V supports both image and video inputs. Here's a basic example with image input:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                }
            },
            {
                "type": "text",
                "text": "Describe this image in detail."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="zai-org/GLM-4.5V",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example Output:**

```text Output theme={null}
Response costs: 3.37s
Generated text: Auntie Anne's

CINNAMON SUGAR
1 x 17,000                    17,000

SUB TOTAL                    17,000

GRAND TOTAL                  17,000

CASH IDR                     20,000

CHANGE DUE                  3,000
```

**Multi-Image Input Example:**

GLM-4.5V can process multiple images in a single request for comparison or analysis:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://www.civitatis.com/f/china/hong-kong/guia/taxi.jpg"
                }
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://cdn.cheapoguides.com/wp-content/uploads/sites/7/2025/05/GettyImages-509614603-1280x600.jpg"
                }
            },
            {
                "type": "text",
                "text": "Compare these two images and describe the differences in 100 words or less. Focus on the key visual elements, colors, textures, and any notable contrasts between the two scenes. Be specific about what you see in each image."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="zai-org/GLM-4.5V",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example Output:**

```text Output theme={null}
Response costs: 3.86s
Generated text: The first image shows a close - up of a few red taxis on a street with storefronts in the background. The taxis are in a line, and the scene has an urban, busy feel with visible shop displays. The second image is an aerial view of a large taxi parking area with numerous red and green taxis, some with hoods open. The scene is more open, with a parking lot layout, and includes elements like a bridge and grassy areas. Key differences: number of taxis (few vs many), perspective (close - up vs aerial), color variety (mostly red vs red and green), and setting (street with shops vs parking lot).
```

**Video Input Example:**

GLM-4.5V supports video understanding by processing video URLs:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "video_url",
                "video_url": {
                    "url": "https://videos.pexels.com/video-files/4114797/4114797-uhd_3840_2160_25fps.mp4"
                }
            },
            {
                "type": "text",
                "text": "Describe what happens in this video."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="zai-org/GLM-4.5V",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Note:**

* For video processing, ensure you have sufficient context length configured (up to 64K tokens)
* Video processing may require more memory; adjust `--mem-fraction-static` accordingly
* You can also provide local file paths using `file://` protocol

**Example Output:**

```text Output theme={null}
Response costs: 3.89s
Generated text: A person wearing blue gloves is using a microscope. They are adjusting the focus knob with one hand while holding a pipette with the other, suggesting they are preparing or examining a sample on the slide beneath the objective lens. The microscope's 40x objective lens is positioned over the slide, indicating a high-magnification observation. The person carefully manipulates the slide and the microscope controls, likely to achieve a clear view of the specimen.
```

#### 4.2.2 Thinking Mode

GLM-4.5V supports thinking mode for enhanced reasoning. Enable thinking mode during deployment:

```shell Command theme={null}
python -m sglang.launch_server \
  --model-path zai-org/GLM-4.5V \
  --reasoning-parser glm45 \
  --tp 4 \
  --host 0.0.0.0 \
  --port 30000
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="zai-org/GLM-4.5V",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

**Disable Thinking Mode:**

To disable thinking mode for a specific request:

```python Example theme={null}
response = client.chat.completions.create(
    model="zai-org/GLM-4.5V",
    messages=[{"role": "user", "content": "What is the capital of France?"}],
    extra_body={"chat_template_kwargs": {"enable_thinking": False}}
)
```

#### 4.2.3 Tool Calling

GLM-4.5V supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model-path zai-org/GLM-4.5V \
  --reasoning-parser glm45 \
  --tool-call-parser glm45 \
  --tp 4 \
  --host 0.0.0.0 \
  --port 30000
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="zai-org/GLM-4.5V",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"🔧 Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information.
I should call the function with location="Beijing".
=============== Content =================

🔧 Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="zai-org/GLM-4.5V",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The weather in Beijing is currently 22°C and sunny."
```

#### 4.2.4 Thinking Budget

Beyond enabling/disabling the full reasoning mode (section 4.2.2), you can cap the number of thinking tokens using `CustomLogitProcessor`. Launch with `--enable-custom-logit-processor` and pass `Glm4MoeThinkingBudgetLogitProcessor` in the request:

```python Example theme={null}
import openai
from sglang.srt.sampling.custom_logit_processor import Glm4MoeThinkingBudgetLogitProcessor

client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="*")
response = client.chat.completions.create(
    model="zai-org/GLM-4.5V",
    messages=[{"role": "user", "content": "Describe this image briefly."}],
    max_tokens=1024,
    extra_body={
        "custom_logit_processor": Glm4MoeThinkingBudgetLogitProcessor().to_str(),
        "custom_params": {"thinking_budget": 512},
    },
)
print(response)
```

## 5. Benchmark

### 5.1 Accuracy Benchmark

Document model accuracy on standard benchmarks:

#### 5.1.1 MMMU Benchmark

* Benchmark Command

```bash Command theme={null}
python3 benchmark/mmmu/bench_sglang.py --response-answer-regex "<\|begin_of_box\|>(.*)<\|end_of_box\|>" --port 30000 --concurrency 64
```

* Test Result

```text Output theme={null}
Benchmark time: 616.6163094160147
answers saved to: ./answer_sglang.json
Evaluating...
answers saved to: ./answer_sglang.json
{'Accounting': {'acc': 0.867, 'num': 30},
 'Agriculture': {'acc': 0.567, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.667, 'num': 30},
 'Art': {'acc': 0.667, 'num': 30},
 'Art_Theory': {'acc': 0.9, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.8, 'num': 30},
 'Biology': {'acc': 0.6, 'num': 30},
 'Chemistry': {'acc': 0.533, 'num': 30},
 'Clinical_Medicine': {'acc': 0.667, 'num': 30},
 'Computer_Science': {'acc': 0.8, 'num': 30},
 'Design': {'acc': 0.867, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.667, 'num': 30},
 'Economics': {'acc': 0.833, 'num': 30},
 'Electronics': {'acc': 0.433, 'num': 30},
 'Energy_and_Power': {'acc': 0.733, 'num': 30},
 'Finance': {'acc': 0.767, 'num': 30},
 'Geography': {'acc': 0.667, 'num': 30},
 'History': {'acc': 0.8, 'num': 30},
 'Literature': {'acc': 0.9, 'num': 30},
 'Manage': {'acc': 0.733, 'num': 30},
 'Marketing': {'acc': 0.9, 'num': 30},
 'Materials': {'acc': 0.567, 'num': 30},
 'Math': {'acc': 0.8, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.767, 'num': 30},
 'Music': {'acc': 0.3, 'num': 30},
 'Overall': {'acc': 0.732, 'num': 900},
 'Overall-Art and Design': {'acc': 0.683, 'num': 120},
 'Overall-Business': {'acc': 0.82, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.787, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.783, 'num': 120},
 'Overall-Science': {'acc': 0.707, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.648, 'num': 210},
 'Pharmacy': {'acc': 0.9, 'num': 30},
 'Physics': {'acc': 0.933, 'num': 30},
 'Psychology': {'acc': 0.767, 'num': 30},
 'Public_Health': {'acc': 0.9, 'num': 30},
 'Sociology': {'acc': 0.667, 'num': 30}}
eval out saved to ./val_sglang.json
Overall accuracy: 0.732
```


# GLM-4.6
Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-4.6



## 1. Model Introduction

[GLM-4.6](https://huggingface.co/zai-org/GLM-4.6) is a powerful language model developed by Zhipu AI, featuring advanced capabilities in reasoning, function calling, and multi-modal understanding.

As the latest iteration in the GLM series, GLM-4.6 achieves comprehensive enhancements across multiple domains, including real-world coding, long-context processing, reasoning, searching, writing, and agentic applications. Details are as follows:

* **Longer context window**: The context window has been expanded from 128K to 200K tokens, enabling the model to handle more complex agentic tasks.
* **Superior coding performance**: The model achieves higher scores on code benchmarks and demonstrates better real-world performance in applications such as Claude Code, Cline, Roo Code and Kilo Code, including improvements in generating visually polished front-end pages.
* **Advanced reasoning**: GLM-4.6 shows a clear improvement in reasoning performance and supports tool use during inference, leading to stronger overall capability.
* **More capable agents**: GLM-4.6 exhibits stronger performance in tool use and search-based agents, and integrates more effectively within agent frameworks.
* **Refined writing**: Better aligns with human preferences in style and readability, and performs more naturally in role-playing scenarios.

For more details, please refer to the [official GLM-4.6 documentation](https://docs.z.ai/guides/llm/glm-4.6).

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, deployment strategy, and thinking capabilities.

Run this Command:


### 3.2 Configuration Tips

* **EAGLE Speculative Decoding:** Supported for GLM-4.5/4.6. Add `--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. The spec-v2 overlap scheduler is enabled by default; pass `--disable-overlap-schedule` to disable.
* **Thinking Budget:** Use `--enable-custom-logit-processor` flag and pass `Glm4MoeThinkingBudgetLogitProcessor` in requests to cap the model's thinking token count (see section 4.2.3).

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

GLM-4.6 supports Thinking mode by default. Enable the reasoning parser during deployment to separate the thinking and the content sections:

```shell Command theme={null}
python -m sglang.launch_server \
  --model zai-org/GLM-4.6 \
  --reasoning-parser glm45 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="zai-org/GLM-4.6",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
To solve this problem, I need to calculate 15% of 240.
Step 1: Convert 15% to decimal: 15% = 0.15
Step 2: Multiply 240 by 0.15
Step 3: 240 × 0.15 = 36
=============== Content =================

The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36.
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.2 Tool Calling

> [!NOTE]
>
> **Parser names by model:** GLM-4.5 and GLM-4.6 use `--tool-call-parser glm45`. GLM-4.7 and GLM-4.7-Flash use `--tool-call-parser glm47`. All GLM models use `--reasoning-parser glm45` regardless of generation.

GLM-4.6 supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model zai-org/GLM-4.6 \
  --reasoning-parser glm45 \
  --tool-call-parser glm45 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="zai-org/GLM-4.6",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                if tool_call.function:
                    print(f"🔧 Tool Call: {tool_call.function.name}")
                    print(f"   Arguments: {tool_call.function.arguments}")

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information.
I should call the function with location="Beijing".
=============== Content =================

🔧 Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="zai-org/GLM-4.6",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The weather in Beijing is currently 22°C and sunny."
```

#### 4.2.3 Thinking Budget

Limit the number of thinking tokens using `CustomLogitProcessor`. Launch with `--enable-custom-logit-processor`:

```python Example theme={null}
import openai
from sglang.srt.sampling.custom_logit_processor import Glm4MoeThinkingBudgetLogitProcessor

client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="*")
response = client.chat.completions.create(
    model="zai-org/GLM-4.6",
    messages=[{"role": "user", "content": "Is Paris the Capital of France?"}],
    max_tokens=1024,
    extra_body={
        "custom_logit_processor": Glm4MoeThinkingBudgetLogitProcessor().to_str(),
        "custom_params": {"thinking_budget": 512},
    },
)
print(response)
```

## 5. Benchmark

This section uses **industry-standard configurations** for comparable benchmark results.

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8x), AMD MI300X (8x), AMD MI325X (8x), AMD MI355X (8x)
* Model: GLM-4.6
* Tensor Parallelism: 8
* SGLang Version: 0.5.6.post1

**Benchmark Methodology:**

We use industry-standard benchmark configurations to ensure results are comparable across frameworks and hardware platforms.

#### 5.1.1 Standard Test Scenarios

Three core scenarios reflect real-world usage patterns:

Scenario Input Length Output Length Use Case
**Chat** 1K 1K Most common conversational AI workload
**Reasoning** 1K 8K Long-form generation, complex reasoning tasks
**Summarization** 8K 1K Document summarization, RAG retrieval
#### 5.1.2 Concurrency Levels Test each scenario at three concurrency levels to capture the throughput vs. latency tradeoff (Pareto frontier): * **Low Concurrency**: `--max-concurrency 1` (Latency-optimized) * **Medium Concurrency**: `--max-concurrency 16` (Balanced) * **High Concurrency**: `--max-concurrency 100` (Throughput-optimized) #### 5.1.3 Number of Prompts For each concurrency level, configure `num_prompts` to simulate realistic user loads: * **Quick Test**: `num_prompts = concurrency × 1` (minimal test) * **Recommended**: `num_prompts = concurrency × 5` (standard benchmark) * **Stable Measurements**: `num_prompts = concurrency × 10` (production-grade) *** #### 5.1.4 Benchmark Commands **Scenario 1: Chat (1K/1K) - Most Important** * **Model Deployment** ```bash Command theme={null} python -m sglang.launch_server \ --model zai-org/GLM-4.6 \ --tp 8 ``` * Low Concurrency (Latency-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 63.82 Total input tokens: 6101 Total input text tokens: 6101 Total input vision tokens: 0 Total generated tokens: 4210 Total generated tokens (retokenized): 4209 Request throughput (req/s): 0.16 Input token throughput (tok/s): 95.60 Output token throughput (tok/s): 65.97 Peak output token throughput (tok/s): 68.00 Peak concurrent requests: 2 Total token throughput (tok/s): 161.57 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 6379.24 Median E2E Latency (ms): 5085.00 ---------------Time to First Token---------------- Mean TTFT (ms): 155.57 Median TTFT (ms): 149.79 P99 TTFT (ms): 207.69 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 14.81 Median TPOT (ms): 14.80 P99 TPOT (ms): 14.84 ---------------Inter-Token Latency---------------- Mean ITL (ms): 14.82 Median ITL (ms): 14.82 P95 ITL (ms): 15.17 P99 ITL (ms): 15.36 Max ITL (ms): 25.05 ================================================== ``` * Medium Concurrency (Balanced) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 72.06 Total input tokens: 39668 Total input text tokens: 39668 Total input vision tokens: 0 Total generated tokens: 40725 Total generated tokens (retokenized): 40672 Request throughput (req/s): 1.11 Input token throughput (tok/s): 550.47 Output token throughput (tok/s): 565.14 Peak output token throughput (tok/s): 752.00 Peak concurrent requests: 20 Total token throughput (tok/s): 1115.61 Concurrency: 13.71 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 12348.93 Median E2E Latency (ms): 13164.81 ---------------Time to First Token---------------- Mean TTFT (ms): 196.08 Median TTFT (ms): 155.22 P99 TTFT (ms): 377.98 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 24.24 Median TPOT (ms): 24.55 P99 TPOT (ms): 30.42 ---------------Inter-Token Latency---------------- Mean ITL (ms): 23.92 Median ITL (ms): 21.40 P95 ITL (ms): 22.49 P99 ITL (ms): 123.83 Max ITL (ms): 486.54 ================================================== ``` * High Concurrency (Throughput-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 138.50 Total input tokens: 249831 Total input text tokens: 249831 Total input vision tokens: 0 Total generated tokens: 252162 Total generated tokens (retokenized): 251841 Request throughput (req/s): 3.61 Input token throughput (tok/s): 1803.78 Output token throughput (tok/s): 1820.61 Peak output token throughput (tok/s): 2900.00 Peak concurrent requests: 107 Total token throughput (tok/s): 3624.40 Concurrency: 90.91 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 25183.97 Median E2E Latency (ms): 23968.49 ---------------Time to First Token---------------- Mean TTFT (ms): 337.77 Median TTFT (ms): 180.65 P99 TTFT (ms): 906.14 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 49.97 Median TPOT (ms): 52.20 P99 TPOT (ms): 61.81 ---------------Inter-Token Latency---------------- Mean ITL (ms): 49.36 Median ITL (ms): 35.05 P95 ITL (ms): 124.91 P99 ITL (ms): 187.69 Max ITL (ms): 440.34 ================================================== ``` **Scenario 2: Reasoning (1K/8K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 666.64 Total input tokens: 6101 Total input text tokens: 6101 Total input vision tokens: 0 Total generated tokens: 44452 Total generated tokens (retokenized): 44387 Request throughput (req/s): 0.02 Input token throughput (tok/s): 9.15 Output token throughput (tok/s): 66.68 Peak output token throughput (tok/s): 68.00 Peak concurrent requests: 2 Total token throughput (tok/s): 75.83 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 66661.35 Median E2E Latency (ms): 71902.36 ---------------Time to First Token---------------- Mean TTFT (ms): 160.21 Median TTFT (ms): 140.32 P99 TTFT (ms): 295.56 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 14.92 Median TPOT (ms): 14.94 P99 TPOT (ms): 15.02 ---------------Inter-Token Latency---------------- Mean ITL (ms): 14.96 Median ITL (ms): 14.96 P95 ITL (ms): 15.36 P99 ITL (ms): 15.57 Max ITL (ms): 19.06 ================================================== ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 503.30 Total input tokens: 39668 Total input text tokens: 39668 Total input vision tokens: 0 Total generated tokens: 318226 Total generated tokens (retokenized): 318025 Request throughput (req/s): 0.16 Input token throughput (tok/s): 78.82 Output token throughput (tok/s): 632.28 Peak output token throughput (tok/s): 752.00 Peak concurrent requests: 19 Total token throughput (tok/s): 711.09 Concurrency: 13.88 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 87349.22 Median E2E Latency (ms): 88248.04 ---------------Time to First Token---------------- Mean TTFT (ms): 228.54 Median TTFT (ms): 142.78 P99 TTFT (ms): 569.84 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 21.97 Median TPOT (ms): 22.14 P99 TPOT (ms): 22.47 ---------------Inter-Token Latency---------------- Mean ITL (ms): 21.91 Median ITL (ms): 21.80 P95 ITL (ms): 22.30 P99 ITL (ms): 22.78 Max ITL (ms): 137.19 ================================================== ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 772.28 Total input tokens: 158939 Total input text tokens: 158939 Total input vision tokens: 0 Total generated tokens: 1300705 Total generated tokens (retokenized): 1299924 Request throughput (req/s): 0.41 Input token throughput (tok/s): 205.80 Output token throughput (tok/s): 1684.24 Peak output token throughput (tok/s): 2112.00 Peak concurrent requests: 68 Total token throughput (tok/s): 1890.05 Concurrency: 56.17 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 135563.36 Median E2E Latency (ms): 140888.88 ---------------Time to First Token---------------- Mean TTFT (ms): 232.45 Median TTFT (ms): 145.59 P99 TTFT (ms): 576.49 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 33.47 Median TPOT (ms): 34.02 P99 TPOT (ms): 35.10 ---------------Inter-Token Latency---------------- Mean ITL (ms): 33.30 Median ITL (ms): 32.63 P95 ITL (ms): 34.27 P99 ITL (ms): 104.39 Max ITL (ms): 155.65 ================================================== ``` **Scenario 3: Summarization (8K/1K)** * Low ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 65.11 Total input tokens: 41941 Total input text tokens: 41941 Total input vision tokens: 0 Total generated tokens: 4210 Total generated tokens (retokenized): 4210 Request throughput (req/s): 0.15 Input token throughput (tok/s): 644.17 Output token throughput (tok/s): 64.66 Peak output token throughput (tok/s): 68.00 Peak concurrent requests: 2 Total token throughput (tok/s): 708.83 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 6508.31 Median E2E Latency (ms): 5263.36 ---------------Time to First Token---------------- Mean TTFT (ms): 189.48 Median TTFT (ms): 159.23 P99 TTFT (ms): 304.09 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 15.02 Median TPOT (ms): 15.03 P99 TPOT (ms): 15.27 ---------------Inter-Token Latency---------------- Mean ITL (ms): 15.04 Median ITL (ms): 15.03 P95 ITL (ms): 15.46 P99 ITL (ms): 15.65 Max ITL (ms): 24.20 ================================================== ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 76.43 Total input tokens: 300020 Total input text tokens: 300020 Total input vision tokens: 0 Total generated tokens: 41589 Total generated tokens (retokenized): 41577 Request throughput (req/s): 1.05 Input token throughput (tok/s): 3925.47 Output token throughput (tok/s): 544.15 Peak output token throughput (tok/s): 752.00 Peak concurrent requests: 19 Total token throughput (tok/s): 4469.62 Concurrency: 13.95 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 13329.63 Median E2E Latency (ms): 14141.09 ---------------Time to First Token---------------- Mean TTFT (ms): 339.88 Median TTFT (ms): 252.75 P99 TTFT (ms): 906.54 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 25.37 Median TPOT (ms): 25.73 P99 TPOT (ms): 30.94 ---------------Inter-Token Latency---------------- Mean ITL (ms): 25.04 Median ITL (ms): 21.68 P95 ITL (ms): 22.69 P99 ITL (ms): 146.98 Max ITL (ms): 483.14 ================================================== ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.6 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 136.24 Total input tokens: 1273893 Total input text tokens: 1273893 Total input vision tokens: 0 Total generated tokens: 169680 Total generated tokens (retokenized): 169452 Request throughput (req/s): 2.35 Input token throughput (tok/s): 9350.32 Output token throughput (tok/s): 1245.44 Peak output token throughput (tok/s): 1984.00 Peak concurrent requests: 69 Total token throughput (tok/s): 10595.77 Concurrency: 58.46 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 24889.40 Median E2E Latency (ms): 25123.37 ---------------Time to First Token---------------- Mean TTFT (ms): 355.82 Median TTFT (ms): 268.84 P99 TTFT (ms): 858.64 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 46.62 Median TPOT (ms): 49.04 P99 TPOT (ms): 58.88 ---------------Inter-Token Latency---------------- Mean ITL (ms): 46.36 Median ITL (ms): 32.46 P95 ITL (ms): 135.23 P99 ITL (ms): 204.27 Max ITL (ms): 508.14 ================================================== ``` #### 5.1.5 Understanding the Results **Key Metrics:** * **Request Throughput (req/s)**: Number of requests processed per second * **Output Token Throughput (tok/s)**: Total tokens generated per second * **Mean TTFT (ms)**: Time to First Token - measures responsiveness * **Mean TPOT (ms)**: Time Per Output Token - measures generation speed * **Mean ITL (ms)**: Inter-Token Latency - measures streaming consistency **Why These Configurations Matter:** * **1K/1K (Chat)**: Represents the most common conversational AI workload. This is the highest priority scenario for most deployments. * **1K/8K (Reasoning)**: Tests long-form generation capabilities crucial for complex reasoning, code generation, and detailed explanations. * **8K/1K (Summarization)**: Evaluates performance with large context inputs, essential for RAG systems, document Q\&A, and summarization tasks. * **Variable Concurrency**: Captures the Pareto frontier - the optimal tradeoff between throughput and latency at different load levels. Low concurrency shows best-case latency, high concurrency shows maximum throughput. **Interpreting Results:** * Compare your results against baseline numbers for your hardware * Higher throughput at same latency = better performance * Lower TTFT = more responsive user experience * Lower TPOT = faster generation speed ### 5.2 Accuracy Benchmark Document model accuracy on standard benchmarks: #### 5.2.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. * Test Result ```text Output theme={null} Accuracy: 0.975 Invalid: 0.000 Latency: 16.574 s Output throughput: 1194.637 token/s ``` # GLM-4.6V Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-4.6V ## 1. Model Introduction GLM-4.6V series model includes two versions: GLM-4.6V (106B), a foundation model designed for cloud and high-performance cluster scenarios, and GLM-4.6V-Flash (9B), a lightweight model optimized for local deployment and low-latency applications. GLM-4.6V scales its context window to 128k tokens in training, and achieves SoTA performance in visual understanding among models of similar parameter scales. Crucially, GLM team integrated native Function Calling capabilities for the first time. This effectively bridges the gap between "visual perception" and "executable action" providing a unified technical foundation for multimodal agents in real-world business scenarios. Beyond achieves SoTA performance across major multimodal benchmarks at comparable model scales. GLM-4.6V introduces several key features: * **Native Multimodal Function Calling** Enables native vision-driven tool use. Images, screenshots, and document pages can be passed directly as tool inputs without text conversion, while visual outputs (charts, search images, rendered pages) are interpreted and integrated into the reasoning chain. This closes the loop from perception to understanding to execution. Please refer to this [example](#4-2-3-tool-calling). * **Interleaved Image-Text Content Generation** Supports high-quality mixed media creation from complex multimodal inputs. GLM-4.6V takes a multimodal context—spanning documents, user inputs, and tool-retrieved images—and synthesizes coherent, interleaved image-text content tailored to the task. During generation it can actively call search and retrieval tools to gather and curate additional text and visuals, producing rich, visually grounded content. * **Multimodal Document Understanding** GLM-4.6V can process up to 128K tokens of multi-document or long-document input, directly interpreting richly formatted pages as images. It understands text, layout, charts, tables, and figures jointly, enabling accurate comprehension of complex, image-heavy documents without requiring prior conversion to plain text. * **Frontend Replication & Visual Editing** Reconstructs pixel-accurate HTML/CSS from UI screenshots and supports natural-language-driven edits. It detects layout, components, and styles visually, generates clean code, and applies iterative visual modifications through simple user instructions. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. ### 2.1 Docker Installation (Recommended) ```shell Command theme={null} docker pull lmsysorg/sglang:latest ``` **Advantages:** * Ready to use out of the box, no manual environment configuration needed * Avoids dependency conflict issues * Easy to migrate between different environments ### 2.2 Build from Source If you need to use the latest development version or require custom modifications, you can build from source: ```bash Command theme={null} # Install SGLang using UV (recommended) git clone https://github.com/sgl-project/sglang.git cd sglang uv venv source .venv/bin/activate uv pip install --prerelease=allow -e "python[all]" --index-url=https://pypi.org/simple pip install nvidia-cudnn-cu12==9.16.0.29 # Install ffmpeg to support video input sudo apt update sudo apt install ffmpeg ``` **Use Cases:** * Need to customize and modify SGLang source code * Want to use the latest development features * Participate in SGLang project development For general installation instructions, you can also refer to the [official SGLang installation guide](../../../docs/get-started/install). ## 3. Model Deployment ### 3.1 Basic Configuration **Interactive Command Generator**: Use the interactive configuration generator below to customize your deployment settings. Select your hardware platform, model size, quantization method, and other options to generate the appropriate launch command. Run this Command:

### 3.2 Configuration Tips

* **TTFT Optimization** : Set `SGLANG_USE_CUDA_IPC_TRANSPORT=1` to use CUDA IPC for transferring multimodal features, which significantly improves TTFT. This consumes additional memory and may require adjusting `--mem-fraction-static` and/or `--max-running-requests`. (additional memory is proportional to image size \* number of images in current running requests.)
* **TP=8 Configuration**: When using Tensor Parallelism (TP) of 8, the vision attention's 12 heads cannot be evenly divided. You can resolve this by adding `--mm-enable-dp-encoder` (which the generator above handles automatically).
* **Fast Model Loading**: For large models (like the 106B version), you can speed up model loading by using `--model-loader-extra-config='{"enable_multithread_load": "true","num_threads": 64}'`.
* **Hardware Notes:**
  * **H100 (FP8):** Use the FP8 checkpoint for best memory efficiency.
  * **A100 / H100 (BF16):** Use standard multimodal parameters to manage throughput and GPU memory usage.
  * **H200 / B200:** Runs out of the box, supporting full context length plus concurrent image + video processing.
* **Additional Multimodal Parameters:**
  * `--mm-attention-backend fa3`: Specify multimodal attention backend (Flash Attention 3).
  * `--mm-feature-transport=cuda_ipc`: Use CUDA IPC shared memory for multimodal data transport to avoid D2H memory copies and significantly improve E2E latency.

**Example with full multimodal optimizations:**

```bash Command theme={null}
SGLANG_USE_CUDA_IPC_TRANSPORT=1 \
SGLANG_VLM_CACHE_SIZE_MB=0 \
python -m sglang.launch_server \
  --model-path zai-org/GLM-4.6V \
  --host 0.0.0.0 \
  --port 30000 \
  --trust-remote-code \
  --tp-size 8 \
  --enable-cache-report \
  --log-level info \
  --max-running-requests 64 \
  --mem-fraction-static 0.65 \
  --chunked-prefill-size 8192 \
  --attention-backend fa3 \
  --mm-attention-backend fa3 \
  --mm-enable-dp-encoder \
  --enable-metrics
```

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Multi-Modal Inputs

GLM-4.6V supports image and video inputs via the OpenAI-compatible API.

**Image Input:**

```python Example theme={null}
import subprocess

curl_command = f"""
curl -s http://localhost:{30000}/v1/chat/completions \\
  -H "Content-Type: application/json" \\
  -d '{{
    "model": "default",
    "messages": [
      {{
        "role": "user",
        "content": [
          {{
            "type": "image_url",
            "image_url": {{
              "url": "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true"
            }}
          }},
          {{
            "type": "text",
            "text": "What is the image"
          }}
        ]
      }}
    ],
    "temperature": "0",
    "max_completion_tokens": "1000",
    "max_tokens": "1000"
  }}'
"""

response = subprocess.check_output(curl_command, shell=True).decode()
print(response)
```

```text Output theme={null}
{"id":"b61596ca71394dd699fd8abd4f650c44","object":"chat.completion","created":1765259019,"model":"default","choices":[{"index":0,"message":{"role":"assistant","content":"The image is a logo featuring the text \"SGL\" (in a bold, orange-brown font) alongside a stylized icon. The icon includes a network-like structure with circular nodes (suggesting connectivity or a tree/graph structure) and a tag with \"\" (a common symbol for coding, web development, or software). The color scheme uses warm orange-brown tones with a black background, giving it a tech-focused, modern aesthetic (likely representing a company, project, or tool related to software, web development, or digital technology).<|begin_of_box|>SGL logo (stylized text + network/coding icon)<|end_of_box|>","reasoning_content":"Okay, let's see. The image has a logo with the text \"SGL\" and a little icon on the left. The icon looks like a network or a tree structure with circles, and there's a tag with \"\" which is a common symbol for coding or web development. The colors are orange and brown tones, with a black background. So probably a logo for a company or project named SGL, maybe related to software, web development, or a tech company.","tool_calls":null},"logprobs":null,"finish_reason":"stop","matched_stop":151336}],"usage":{"prompt_tokens":2222,"total_tokens":2448,"completion_tokens":226,"prompt_tokens_details":null,"reasoning_tokens":0},"metadata":{"weight_version":"default"}}
```

**Video Input:**

```python Example theme={null}
import subprocess

curl_command = f"""
curl -s http://localhost:{30000}/v1/chat/completions \\
  -H "Content-Type: application/json" \\
  -d '{{
    "model": "default",
    "messages": [
      {{
        "role": "user",
        "content": [
          {{
            "type": "video_url",
            "video_url": {{
              "url": "https://github.com/sgl-project/sgl-test-files/raw/refs/heads/main/videos/jobs_presenting_ipod.mp4"
            }}
          }},
          {{
            "type": "text",
            "text": "What is in the video"
          }}
        ]
      }}
    ],
    "temperature": "0",
    "max_completion_tokens": "1000",
    "max_tokens": "1000"
  }}'
"""

response = subprocess.check_output(curl_command, shell=True).decode()
print(response)
```

```text Output theme={null}
{"id":"520e0a079e5d4b17b82a6af619315a97","object":"chat.completion","created":1765259029,"model":"default","choices":[{"index":0,"message":{"role":"assistant","content":"The image is a still from a presentation by a man on a stage. He is pointing to a small pocket on his jeans and asking the audience what the pocket is for. The video is being shared by Evan Carmichael. The man then reveals that the pocket is for an iPod Nano.","reasoning_content":"Based on the visual evidence in the video, here is a breakdown of what is being shown:\n\n*   **Subject:** The video features a man on a stage, giving a presentation. He is wearing a black t-shirt and dark jeans.\n*   **Action:** The man is pointing to a pocket on his jeans. He is asking the audience a question about the purpose of this pocket.\n*   **Context:** The presentation is being filmed, and the video is being shared by \"Evan Carmichael,\" a well-known motivational speaker and content creator. The source of the clip is credited to \"JoshuaG.\"\n*   **Reveal:** The man then reveals the answer to his question. He pulls a small, white, rectangular device out of the pocket. He identifies this device as an \"iPod Nano.\"\n\nIn summary, the image is a still from a presentation where a speaker is explaining the purpose of the small pocket found on many pairs of jeans.","tool_calls":null},"logprobs":null,"finish_reason":"stop","matched_stop":151336}],"usage":{"prompt_tokens":30276,"total_tokens":30532,"completion_tokens":256,"prompt_tokens_details":null,"reasoning_tokens":0},"metadata":{"weight_version":"default"}}
```

#### 4.2.2 Thinking Mode

GLM-4.6V supports Thinking mode. Enable the reasoning parser during deployment:

```shell Command theme={null}
python -m sglang.launch_server \
  --model zai-org/GLM-4.6V \
  --reasoning-parser glm45 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="zai-org/GLM-4.6V",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
To solve this problem, I need to calculate 15% of 240.
Step 1: Convert 15% to decimal: 15% = 0.15
Step 2: Multiply 240 by 0.15
Step 3: 240 × 0.15 = 36
=============== Content =================

The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36.
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.3 Tool Calling

GLM-4.6V supports tool calling with vision capabilities. Pass tools in your API request:

```python Example theme={null}
from openai import OpenAI

openai_api_key = "EMPTY"
openai_api_base = "http://127.0.0.1:30000/v1"
client = OpenAI(api_key=openai_api_key, base_url=openai_api_base)



tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current temperature for a given location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City and country e.g. Beijing, China",
                    }
                },
                "required": ["location"],
                "additionalProperties": False,
            },
        },
    }
]


messages = [
    {
        "role": "user",
        "content": "Please help me check today's weather in Beijing, and tell me whether the tool returned an image."
    },
    {
        "role": "assistant",
        "tool_calls": [
            {
                "id": "call_bk32t88BGpSdbtDgzT044Rh4",
                "type": "function",
                "function": {
                    "name": 'get_weather',
                    "arguments": '{"location":"Beijing, China"}'
                }
            }
        ]
    },
    {
        "role": "tool",
        "tool_call_id": "call_bk32t88BGpSdbtDgzT044Rh4",
        "content": [
            {
                "type": "text",
                "text": "Weather report generated: Beijing, November 7, 2025, sunny, temperature 2°C."
            },
            {
                "type": "image_url",
                "image_url": {
                     "url": "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true"
                }
            }
        ]
    },
]

response = client.chat.completions.create(
    model="zai-org/GLM-4.6V",
    messages=messages,
    timeout=900,
    tools=tools
)
print(response.choices[0].message.content.strip())
```

**Output Example:**

```text Output theme={null}
The weather in Beijing today (November 7, 2025) is sunny with a temperature of 2°C.

Yes, the tool returned an image (the SGL logo).
```

#### 4.2.4 Thinking Budget

Beyond the reasoning parser, you can cap the number of thinking tokens using `CustomLogitProcessor`. Launch with `--enable-custom-logit-processor` and pass `Glm4MoeThinkingBudgetLogitProcessor` in the request — same as the [GLM-4.6 text model approach](./GLM-4.6#4-2-3-thinking-budget):

```python Example theme={null}
import openai
from sglang.srt.sampling.custom_logit_processor import Glm4MoeThinkingBudgetLogitProcessor

client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="*")
response = client.chat.completions.create(
    model="zai-org/GLM-4.6V",
    messages=[{"role": "user", "content": "Describe this image briefly."}],
    max_tokens=1024,
    extra_body={
        "custom_logit_processor": Glm4MoeThinkingBudgetLogitProcessor().to_str(),
        "custom_params": {"thinking_budget": 512},
    },
)
print(response)
```

## 5. Benchmark

### 5.1. Text Benchmark: Latency, Throughput and Accuracy

#### Command

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

#### Result Output

```text Output theme={null}
Accuracy: 0.925
Invalid: 0.000
Latency: 15.327 s
Output throughput: 1788.375 token/s
```

### 5.2. Multimodal Benchmark - Latency and Throughput

#### Command

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --port 30000 \
  --model zai-org/GLM-4.6V \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 128 \
  --max-concurrency 8
```

#### Result Output

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 8
Successful requests:                     128
Benchmark duration (s):                  89.27
Total input tokens:                      315390
Total input text tokens:                 8702
Total input vision tokens:               306688
Total generated tokens:                  66020
Total generated tokens (retokenized):    31037
Request throughput (req/s):              1.43
Input token throughput (tok/s):          3533.17
Output token throughput (tok/s):         739.59
Peak output token throughput (tok/s):    823.00
Peak concurrent requests:                12
Total token throughput (tok/s):          4272.76
Concurrency:                             7.67
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5349.20
Median E2E Latency (ms):                 5380.98
---------------Time to First Token----------------
Mean TTFT (ms):                          1724.04
Median TTFT (ms):                        1688.16
P99 TTFT (ms):                           6152.34
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          8.15
Median TPOT (ms):                        7.77
P99 TPOT (ms):                           23.97
---------------Inter-Token Latency----------------
Mean ITL (ms):                           10.00
Median ITL (ms):                         8.44
P95 ITL (ms):                            9.23
P99 ITL (ms):                            116.02
Max ITL (ms):                            173.48
==================================================
```

### 5.3. Multimodal Accuracy Benchmark - MMMU

#### Command

```shell Command theme={null}
python3 benchmark/mmmu/bench_sglang.py --response-answer-regex "<\|begin_of_box\|>(.*)<\|end_of_box\|>" --port 30000 --concurrency 64 --extra-request-body '{"max_tokens": 4096}'
```

#### Result Output

```text Output theme={null}
Benchmark time: 487.2229107860476
answers saved to: ./answer_sglang.json
Evaluating...
answers saved to: ./answer_sglang.json
{'Accounting': {'acc': 0.962, 'num': 26},
 'Agriculture': {'acc': 0.5, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.733, 'num': 15},
 'Art': {'acc': 0.833, 'num': 30},
 'Art_Theory': {'acc': 0.9, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.733, 'num': 30},
 'Biology': {'acc': 0.586, 'num': 29},
 'Chemistry': {'acc': 0.654, 'num': 26},
 'Clinical_Medicine': {'acc': 0.633, 'num': 30},
 'Computer_Science': {'acc': 0.76, 'num': 25},
 'Design': {'acc': 0.867, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.633, 'num': 30},
 'Economics': {'acc': 0.862, 'num': 29},
 'Electronics': {'acc': 0.5, 'num': 18},
 'Energy_and_Power': {'acc': 0.875, 'num': 16},
 'Finance': {'acc': 0.857, 'num': 28},
 'Geography': {'acc': 0.714, 'num': 28},
 'History': {'acc': 0.767, 'num': 30},
 'Literature': {'acc': 0.897, 'num': 29},
 'Manage': {'acc': 0.759, 'num': 29},
 'Marketing': {'acc': 1.0, 'num': 26},
 'Materials': {'acc': 0.833, 'num': 18},
 'Math': {'acc': 0.76, 'num': 25},
 'Mechanical_Engineering': {'acc': 0.619, 'num': 21},
 'Music': {'acc': 0.286, 'num': 28},
 'Overall': {'acc': 0.761, 'num': 803},
 'Overall-Art and Design': {'acc': 0.729, 'num': 118},
 'Overall-Business': {'acc': 0.884, 'num': 138},
 'Overall-Health and Medicine': {'acc': 0.773, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.78, 'num': 118},
 'Overall-Science': {'acc': 0.728, 'num': 136},
 'Overall-Tech and Engineering': {'acc': 0.671, 'num': 143},
 'Pharmacy': {'acc': 0.933, 'num': 30},
 'Physics': {'acc': 0.929, 'num': 28},
 'Psychology': {'acc': 0.733, 'num': 30},
 'Public_Health': {'acc': 0.933, 'num': 30},
 'Sociology': {'acc': 0.724, 'num': 29}}
eval out saved to ./val_sglang.json
Overall accuracy: 0.761
```


# GLM-4.7
Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-4.7



## 1. Model Introduction

[GLM-4.7](https://huggingface.co/zai-org/GLM-4.7) is a powerful language model developed by Zhipu AI, featuring advanced capabilities in reasoning, function calling, and agent workflows.

GLM-4.7 brings improvements across all major domains:

* **Extended Context Window**: Expanded context window supporting even longer documents and complex multi-turn conversations
* **Enhanced Reasoning**: Improved reasoning capabilities with better chain-of-thought processing
* **Superior Coding**: Significantly improved code generation and understanding, with better real-world application performance
* **Advanced Tool Use**: More robust tool calling and agent capabilities for complex workflows
* **Optimized Performance**: Better throughput and latency characteristics across all hardware platforms

For more details, please refer to the [official GLM-4.7 documentation](https://docs.z.ai/guides/llm/glm-4.7).

**Key Features:**

* **State-of-the-Art Reasoning**: Enhanced reasoning capabilities for the most complex problem-solving tasks
* **Multiple Quantizations**: BF16, FP8, and NVFP4 variants for different performance/memory trade-offs
* **Hardware Optimization**: Tuned for NVIDIA Blackwell (B200, GB200) and AMD MI300X/MI325X/MI355X GPUs
* **High Performance**: Optimized for both throughput and latency scenarios

**Available Models:**

* **BF16 (Full precision)**: [zai-org/GLM-4.7](https://huggingface.co/zai-org/GLM-4.7)
* **FP8 (8-bit quantized)**: [zai-org/GLM-4.7-FP8](https://huggingface.co/zai-org/GLM-4.7-FP8)
* **NVFP4 (4-bit, NVIDIA Blackwell)**: [nvidia/GLM-4.7-NVFP4](https://huggingface.co/nvidia/GLM-4.7-NVFP4)

**License:**

Please refer to the [official GLM-4.7 model card](https://huggingface.co/zai-org/GLM-4.7) for license details.

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

**Docker Images by Hardware Platform:**

Hardware Platform Docker Image
NVIDIA H100 / H200 / B200 `lmsysorg/sglang:v0.5.12`
NVIDIA GB200 / B300 / GB300 (aarch64) `lmsysorg/sglang:v0.5.12-cu130`
AMD MI300X / MI325X `lmsysorg/sglang:v0.5.12-rocm720-mi30x`
AMD MI355X `lmsysorg/sglang:v0.5.12-rocm720-mi35x`
## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, deployment strategy, and thinking capabilities. Run this Command:

### 3.2 Configuration Tips

Pick a weight format by hardware: **NVFP4** on NVIDIA Blackwell (B200, GB200), **FP8** on H100/H200/AMD, **BF16** as the full-precision fallback. The recommended tensor-parallel size per platform:

Hardware NVFP4 FP8 BF16
B200 (8×, single node) tp=2 / 4 / 8 tp=4 / 8 tp=8
GB200 (NVL72, 4× per tray) tp=2 / 4 tp=4 —
H200 (8×) — tp=8 tp=8
AMD MI300X / MI325X / MI355X — tp=2 / 4 / 8 tp=4 / 8
* **EAGLE Speculative Decoding:** Supported for GLM-4.7. Add `--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. The spec-v2 overlap scheduler is enabled by default; pass `--disable-overlap-schedule` to disable. Enable via the interactive command generator above. * **Thinking Budget:** Use `--enable-custom-logit-processor` flag and pass `Glm4MoeThinkingBudgetLogitProcessor` in requests to cap the model's thinking token count (see section 4.2.3). For general GLM-4.x family launch guidance (AMD ROCm notes and more), see [Launch GLM-4.5 / GLM-4.6 / GLM-4.7 with SGLang](/cookbook/autoregressive/GLM/GLM-4.5). Per-hardware bench commands and flags are inline in §5.1 below. ## 4. Model Invocation ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) ### 4.2 Advanced Usage #### 4.2.1 Reasoning Parser GLM-4.7 supports Thinking mode by default. Enable the reasoning parser during deployment to separate the thinking and the content sections: ```shell Command theme={null} python -m sglang.launch_server \ --model zai-org/GLM-4.7 \ --reasoning-parser glm45 \ --tp 8 \ --host 0.0.0.0 \ --port 8000 ``` **Streaming with Thinking Process:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) # Enable streaming to see the thinking process in real-time response = client.chat.completions.create( model="zai-org/GLM-4.7", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], temperature=0.7, max_tokens=2048, stream=True ) # Process the stream has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: # Close thinking section and add content header if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= To solve this problem, I need to calculate 15% of 240. Step 1: Convert 15% to decimal: 15% = 0.15 Step 2: Multiply 240 by 0.15 Step 3: 240 × 0.15 = 36 =============== Content ================= The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36. ``` **Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions. #### 4.2.2 Tool Calling > [!NOTE] > > **Parser names by model:** GLM-4.5 and GLM-4.6 use `--tool-call-parser glm45`. GLM-4.7 and GLM-4.7-Flash use `--tool-call-parser glm47`. All GLM models use `--reasoning-parser glm45` regardless of generation. GLM-4.7 supports tool calling capabilities. Enable the tool call parser: ```shell Command theme={null} python -m sglang.launch_server \ --model zai-org/GLM-4.7 \ --reasoning-parser glm45 \ --tool-call-parser glm47 \ --tp 8 \ --host 0.0.0.0 \ --port 8000 ``` **Python Example (with Thinking Process):** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Make request with streaming to see thinking process response = client.chat.completions.create( model="zai-org/GLM-4.7", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, temperature=0.7, stream=True ) # Process streaming response thinking_started = False has_thinking = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print tool calls if hasattr(delta, 'tool_calls') and delta.tool_calls: # Close thinking section if needed if has_thinking and thinking_started: print("\n=============== Content =================", flush=True) thinking_started = False for tool_call in delta.tool_calls: if tool_call.function: print(f"Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") # Print content if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information. I should call the function with location="Beijing". =============== Content ================= Tool Call: get_weather Arguments: {"location": "Beijing", "unit": "celsius"} ``` **Note:** * The reasoning parser shows how the model decides to use a tool * Tool calls are clearly marked with the function name and arguments * You can then execute the function and send the result back to continue the conversation **Handling Tool Call Results:** ```python Example theme={null} # After getting the tool call, execute the function def get_weather(location, unit="celsius"): # Your actual weather API call here return f"The weather in {location} is 22°{unit[0].upper()} and sunny." # Send tool result back to the model messages = [ {"role": "user", "content": "What's the weather in Beijing?"}, { "role": "assistant", "content": None, "tool_calls": [{ "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": '{"location": "Beijing", "unit": "celsius"}' } }] }, { "role": "tool", "tool_call_id": "call_123", "content": get_weather("Beijing", "celsius") } ] final_response = client.chat.completions.create( model="zai-org/GLM-4.7", messages=messages, temperature=0.7 ) print(final_response.choices[0].message.content) # Output: "The weather in Beijing is currently 22°C and sunny." ``` #### 4.2.3 Thinking Budget Limit the number of thinking tokens using `CustomLogitProcessor`. Launch with `--enable-custom-logit-processor`: ```python Example theme={null} import openai from sglang.srt.sampling.custom_logit_processor import Glm4MoeThinkingBudgetLogitProcessor client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="*") response = client.chat.completions.create( model="zai-org/GLM-4.7", messages=[{"role": "user", "content": "Is Paris the Capital of France?"}], max_tokens=1024, extra_body={ "custom_logit_processor": Glm4MoeThinkingBudgetLogitProcessor().to_str(), "custom_params": {"thinking_budget": 512}, }, ) print(response) ``` ## 5. Benchmark This section uses **industry-standard configurations** for comparable benchmark results. ### 5.1 Speed Benchmark **Test Environment:** * Hardware: NVIDIA B200, NVIDIA GB200, AMD MI300X/MI325X/MI355X (8x) * Model: GLM-4.7-NVFP4 on NVIDIA Blackwell; GLM-4.7-FP8 or GLM-4.7 (BF16) on AMD * SGLang Version: 0.5.12 (NVIDIA Blackwell), 0.5.6.post1 (AMD) * Best per-GPU throughput config on B200: **TP=2 NVFP4 bf16-KV** (NVFP4 weights, no EP). Numbers below come from this config. **Benchmark Methodology:** We use industry-standard benchmark configurations to ensure results are comparable across frameworks and hardware platforms. #### 5.1.1 Standard Test Scenarios Four core scenarios reflect real-world usage patterns:
Scenario Input Length Output Length Use Case
**Chat** 1K 1K Most common conversational AI workload
**Reasoning** 1K 8K Long-form generation, complex reasoning tasks
**Summarization** 8K 1K Document summarization, RAG retrieval
**Throughput** 4K 1K Mixed RAG / agent / multi-turn conversation (used for the inline B200 / GB200 results below)
#### 5.1.2 Concurrency Levels Test each scenario at three concurrency levels to capture the throughput vs. latency tradeoff (Pareto frontier): * **Low Concurrency**: `--max-concurrency 1` (Latency-optimized) * **Medium Concurrency**: `--max-concurrency 16` (Balanced) * **High Concurrency**: `--max-concurrency 100` (Throughput-optimized) — the Throughput (4K/1K) scenario uses `--max-concurrency 128` to match the inline B200/GB200 results below. #### 5.1.3 Number of Prompts For each concurrency level, configure `num_prompts` to simulate realistic user loads: * **Quick Test**: `num_prompts = concurrency × 1` (minimal test) * **Recommended**: `num_prompts = concurrency × 5` (standard benchmark) * **Stable Measurements**: `num_prompts = concurrency × 10` (production-grade) *** #### 5.1.4 Benchmark Commands **Scenario 1: Chat (1K/1K) - Most Important** * **Model Deployment** ```bash Command theme={null} python -m sglang.launch_server \ --model zai-org/GLM-4.7 \ --tp 8 ``` * Low Concurrency (Latency-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * Medium Concurrency (Balanced) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` * High Concurrency (Throughput-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` **Scenario 2: Reasoning (1K/8K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` **Scenario 3: Summarization (8K/1K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` **Scenario 4: Throughput (4K/1K) — NVIDIA Blackwell with NVFP4** The remaining sub-sections (§5.1.4.1 NVIDIA B200, §5.1.4.2 NVIDIA GB200) measure this scenario with `nvidia/GLM-4.7-NVFP4` weights and report the full `bench_serving` output verbatim. The same commands apply to other NVIDIA hardware after substituting the deployment line from §3.1. > **Note**: These runs use EOS-enabled generation (no `--disable-ignore-eos`), so generated-token counts reflect natural model behavior rather than a strict fixed-OSL pin. Compare against other EOS-enabled runs at the same workload, not against fixed-output-length benchmarks. #### 5.1.4.1 NVIDIA B200 **Model Deployment (NVIDIA B200, TP=2 NVFP4 — max tok/s/gpu config):** ```bash Command theme={null} python -m sglang.launch_server \ --model nvidia/GLM-4.7-NVFP4 \ --tp-size 2 \ --mem-fraction-static 0.85 \ --reasoning-parser glm45 \ --tool-call-parser glm47 ``` * Low Concurrency (Latency-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model nvidia/GLM-4.7-NVFP4 \ --dataset-name random \ --random-input-len 4096 \ --random-output-len 1024 \ --num-prompts 5 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 1 Successful requests: 5 Benchmark duration (s): 25.07 Total input tokens: 8105 Total generated tokens: 2674 Request throughput (req/s): 0.20 Input token throughput (tok/s): 323.25 Output token throughput (tok/s): 106.65 Total token throughput (tok/s): 429.90 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 5011.93 Median E2E Latency (ms): 6441.44 ---------------Time to First Token---------------- Mean TTFT (ms): 179.61 Median TTFT (ms): 169.05 P99 TTFT (ms): 238.01 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 9.05 Median TPOT (ms): 9.03 P99 TPOT (ms): 9.16 ---------------Inter-Token Latency---------------- Mean ITL (ms): 9.05 Median ITL (ms): 9.05 ================================================== ``` * Medium Concurrency (Balanced) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model nvidia/GLM-4.7-NVFP4 \ --dataset-name random \ --random-input-len 4096 \ --random-output-len 1024 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 60.60 Total input tokens: 179772 Total generated tokens: 39657 Request throughput (req/s): 1.32 Input token throughput (tok/s): 2966.39 Output token throughput (tok/s): 654.37 Total token throughput (tok/s): 3620.76 Concurrency: 14.01 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 10615.87 Median E2E Latency (ms): 9985.45 ---------------Time to First Token---------------- Mean TTFT (ms): 267.39 Median TTFT (ms): 177.26 P99 TTFT (ms): 584.29 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 20.98 Median TPOT (ms): 21.06 P99 TPOT (ms): 24.88 ---------------Inter-Token Latency---------------- Mean ITL (ms): 20.92 Median ITL (ms): 17.93 ================================================== ``` * High Concurrency (Throughput-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model nvidia/GLM-4.7-NVFP4 \ --dataset-name random \ --random-input-len 4096 \ --random-output-len 1024 \ --num-prompts 640 \ --max-concurrency 128 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 128 Successful requests: 640 Benchmark duration (s): 172.95 Total input tokens: 1453591 Total generated tokens: 308740 Request throughput (req/s): 3.70 Input token throughput (tok/s): 8404.67 Output token throughput (tok/s): 1785.14 Total token throughput (tok/s): 10189.80 Concurrency: 117.85 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 31848.20 Median E2E Latency (ms): 28554.42 ---------------Time to First Token---------------- Mean TTFT (ms): 1598.40 Median TTFT (ms): 298.88 P99 TTFT (ms): 11015.96 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 65.94 Median TPOT (ms): 65.81 P99 TPOT (ms): 137.73 ---------------Inter-Token Latency---------------- Mean ITL (ms): 62.99 Median ITL (ms): 35.44 ================================================== ``` #### 5.1.4.2 NVIDIA GB200 **Model Deployment (NVIDIA GB200, TP=2 NVFP4 — max tok/s/gpu config):** ```bash Command theme={null} python -m sglang.launch_server \ --model nvidia/GLM-4.7-NVFP4 \ --tp-size 2 \ --mem-fraction-static 0.85 \ --reasoning-parser glm45 \ --tool-call-parser glm47 ``` * Low Concurrency (Latency-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model nvidia/GLM-4.7-NVFP4 \ --dataset-name random \ --random-input-len 4096 \ --random-output-len 1024 \ --num-prompts 5 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 1 Successful requests: 5 Benchmark duration (s): 24.74 Total input tokens: 8105 Total generated tokens: 2674 Request throughput (req/s): 0.20 Input token throughput (tok/s): 327.65 Output token throughput (tok/s): 108.10 Total token throughput (tok/s): 435.75 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 4944.47 Median E2E Latency (ms): 6347.31 ---------------Time to First Token---------------- Mean TTFT (ms): 211.41 Median TTFT (ms): 207.25 P99 TTFT (ms): 226.46 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 8.86 Median TPOT (ms): 8.84 P99 TPOT (ms): 8.96 ---------------Inter-Token Latency---------------- Mean ITL (ms): 8.87 Median ITL (ms): 8.85 ================================================== ``` * Medium Concurrency (Balanced) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model nvidia/GLM-4.7-NVFP4 \ --dataset-name random \ --random-input-len 4096 \ --random-output-len 1024 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 60.40 Total input tokens: 179772 Total generated tokens: 39657 Request throughput (req/s): 1.32 Input token throughput (tok/s): 2976.52 Output token throughput (tok/s): 656.61 Total token throughput (tok/s): 3633.13 Concurrency: 13.97 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 10611.51 Median E2E Latency (ms): 9956.84 ---------------Time to First Token---------------- Mean TTFT (ms): 338.14 Median TTFT (ms): 215.25 P99 TTFT (ms): 915.40 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 20.87 Median TPOT (ms): 21.36 P99 TPOT (ms): 27.05 ---------------Inter-Token Latency---------------- Mean ITL (ms): 20.77 Median ITL (ms): 16.53 ================================================== ``` * High Concurrency (Throughput-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model nvidia/GLM-4.7-NVFP4 \ --dataset-name random \ --random-input-len 4096 \ --random-output-len 1024 \ --num-prompts 640 \ --max-concurrency 128 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 128 Successful requests: 640 Benchmark duration (s): 181.89 Total input tokens: 1453591 Total generated tokens: 309221 Request throughput (req/s): 3.52 Input token throughput (tok/s): 7991.59 Output token throughput (tok/s): 1700.04 Total token throughput (tok/s): 9691.63 Concurrency: 118.86 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 33690.47 Median E2E Latency (ms): 30421.55 ---------------Time to First Token---------------- Mean TTFT (ms): 1353.16 Median TTFT (ms): 383.52 P99 TTFT (ms): 8940.53 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 69.88 Median TPOT (ms): 71.77 P99 TPOT (ms): 131.75 ---------------Inter-Token Latency---------------- Mean ITL (ms): 67.23 Median ITL (ms): 33.46 ================================================== ``` #### 5.1.5 Understanding the Results **Key Metrics:** * **Request Throughput (req/s)**: Number of requests processed per second * **Output Token Throughput (tok/s)**: Total tokens generated per second * **Mean TTFT (ms)**: Time to First Token - measures responsiveness * **Mean TPOT (ms)**: Time Per Output Token - measures generation speed * **Mean ITL (ms)**: Inter-Token Latency - measures streaming consistency **Why These Configurations Matter:** * **1K/1K (Chat)**: Represents the most common conversational AI workload. This is the highest priority scenario for most deployments. * **1K/8K (Reasoning)**: Tests long-form generation capabilities crucial for complex reasoning, code generation, and detailed explanations. * **8K/1K (Summarization)**: Evaluates performance with large context inputs, essential for RAG systems, document Q\&A, and summarization tasks. * **4K/1K (Throughput)**: Realistic mixed workload typical of production deployments (RAG context + medium response). Long enough input that prefill matters, long enough output that decode steady-state dominates. Used for the inline B200 / GB200 results above. * **Variable Concurrency**: Captures the Pareto frontier - the optimal tradeoff between throughput and latency at different load levels. Low concurrency shows best-case latency, high concurrency shows maximum throughput. **Interpreting Results:** * Compare your results against baseline numbers for your hardware * Higher throughput at same latency = better performance * Lower TTFT = more responsive user experience * Lower TPOT = faster generation speed ### 5.2 Accuracy Benchmark Document model accuracy on standard benchmarks: #### 5.2.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 1319 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. * Test Result (NVIDIA B200, TP=2 NVFP4) ```text Output theme={null} Accuracy: 0.946 Latency: 178.284 s Output throughput: 769.204 token/s ``` * Test Result (NVIDIA GB200, TP=2 NVFP4) ```text Output theme={null} Accuracy: 0.951 Latency: 175.190 s Invalid: 0.000 ``` # GLM-4.7-Flash Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-4.7-Flash ## 1. Model Introduction [GLM-4.7-Flash](https://huggingface.co/zai-org/GLM-4.7-Flash) is a lightweight and high-speed model in the GLM-4.7 series developed by Zhipu AI, featuring state-of-the-art capabilities in reasoning, function calling, and efficient local deployment. As a compact variant in the GLM-4.7 family, GLM-4.7-Flash is a **30B-A3B MoE** model designed to balance performance and efficiency: * **Lightweight Architecture**: 30B total parameters with only 3B active parameters, enabling efficient inference * **Enhanced Reasoning**: Inherits the reasoning capabilities from GLM-4.7 with optimized performance * **Superior Coding**: Strong code generation and understanding capabilities * **Advanced Tool Use**: Robust tool calling and agent capabilities for complex workflows * **Optimized for Local Deployment**: Designed for single-GPU deployment scenarios For more details, please refer to the [official GLM-4.7 documentation](https://docs.z.ai/guides/llm/glm-4.7). **Key Features:** * **Efficient MoE Architecture**: 30B-A3B sparse activation for optimal performance/efficiency trade-off * **Multiple Quantizations**: BF16 and FP8 variants for different performance/memory trade-offs * **Hardware Optimization**: Specifically tuned for NVIDIA H100/H200/B200 GPUs * **High Performance**: Optimized for both throughput and latency scenarios **Available Models:** * **BF16 (Full precision)**: [zai-org/GLM-4.7-Flash](https://huggingface.co/zai-org/GLM-4.7-Flash) **License:** Please refer to the [official GLM-4.7-Flash model card](https://huggingface.co/zai-org/GLM-4.7-Flash) for license details. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, deployment strategy, and thinking capabilities. Run this Command:

### 3.2 Configuration Tips

* **EAGLE Speculative Decoding:** Supported for GLM-4.7-Flash. Add `--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. The spec-v2 overlap scheduler is enabled by default; pass `--disable-overlap-schedule` to disable. Enable via the interactive command generator above.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

GLM-4.7-Flash supports Thinking mode by default. Enable the reasoning parser during deployment to separate the thinking and the content sections:

```shell Command theme={null}
python -m sglang.launch_server \
  --model zai-org/GLM-4.7-Flash \
  --reasoning-parser glm45 \
  --attention-backend triton \
  --tp 1 \
  --host 0.0.0.0 \
  --port 8000
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="zai-org/GLM-4.7-Flash",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
To solve this problem, I need to calculate 15% of 240.
Step 1: Convert 15% to decimal: 15% = 0.15
Step 2: Multiply 240 by 0.15
Step 3: 240 × 0.15 = 36
=============== Content =================

The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36.
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.2 Tool Calling

> [!NOTE]
>
> **Parser names by model:** GLM-4.5 and GLM-4.6 use `--tool-call-parser glm45`. GLM-4.7 and GLM-4.7-Flash use `--tool-call-parser glm47`. All GLM models use `--reasoning-parser glm45` regardless of generation.

GLM-4.7-Flash supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model zai-org/GLM-4.7-Flash \
  --reasoning-parser glm45 \
  --tool-call-parser glm47 \
  --attention-backend triton \
  --tp 1 \
  --host 0.0.0.0 \
  --port 8000
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="zai-org/GLM-4.7-Flash",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Accumulate tool calls (tool call deltas may stream in multiple chunks)
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
if tool_calls_accumulator:
    print("\n=============== Tool Calls =================", flush=True)
    for index, tool_call in sorted(tool_calls_accumulator.items()):
        print(f"Tool Call: {tool_call['name']}")
        print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
The user is asking for the weather in Beijing. I have the get_weather function available which can provide weather information for a location. The required parameter is "location" and the
 user has provided "Beijing". There's an optional parameter "unit" for temperature unit, but the user hasn't specified which unit they prefer, and since it's optional, I should not ask about it or make up a value for it. I'll call the function with just the location parameter.I'll check the current weather in Beijing for you.
=============== Tool Calls =================
Tool Call: get_weather
   Arguments: {"location": "Beijing"}

```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="zai-org/GLM-4.7-Flash",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The weather in Beijing is currently 22°C and sunny."
```

## 5. Benchmark

This section uses **industry-standard configurations** for comparable benchmark results.

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 (1x)
* Model: GLM-4.7-Flash
* Tensor Parallelism: 1
* SGLang Version: 0.5.7

**Benchmark Methodology:**

We use industry-standard benchmark configurations to ensure results are comparable across frameworks and hardware platforms.

#### 5.1.1 Standard Test Scenarios

Three core scenarios reflect real-world usage patterns:

Scenario Input Length Output Length Use Case
**Chat** 1K 1K Most common conversational AI workload
**Reasoning** 1K 8K Long-form generation, complex reasoning tasks
**Summarization** 8K 1K Document summarization, RAG retrieval
#### 5.1.2 Concurrency Levels Test each scenario at three concurrency levels to capture the throughput vs. latency tradeoff (Pareto frontier): * **Low Concurrency**: `--max-concurrency 1` (Latency-optimized) * **Medium Concurrency**: `--max-concurrency 16` (Balanced) * **High Concurrency**: `--max-concurrency 100` (Throughput-optimized) #### 5.1.3 Number of Prompts For each concurrency level, configure `num_prompts` to simulate realistic user loads: * **Quick Test**: `num_prompts = concurrency × 1` (minimal test) * **Recommended**: `num_prompts = concurrency × 5` (standard benchmark) * **Stable Measurements**: `num_prompts = concurrency × 10` (production-grade) *** #### 5.1.4 Benchmark Commands **Scenario 1: Chat (1K/1K) - Most Important** * **Model Deployment** ```bash Command theme={null} python -m sglang.launch_server \ --model zai-org/GLM-4.7-Flash \ --attention-backend triton \ --tp 1 ``` * Low Concurrency (Latency-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 38.94 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 4220 Request throughput (req/s): 0.26 Input token throughput (tok/s): 156.67 Output token throughput (tok/s): 108.37 Peak output token throughput (tok/s): 125.00 Peak concurrent requests: 2 Total token throughput (tok/s): 265.03 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 3891.12 Median E2E Latency (ms): 3061.48 P90 E2E Latency (ms): 7172.25 P99 E2E Latency (ms): 9042.62 ---------------Time to First Token---------------- Mean TTFT (ms): 131.36 Median TTFT (ms): 94.55 P99 TTFT (ms): 435.93 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 8.75 Median TPOT (ms): 8.82 P99 TPOT (ms): 9.39 ---------------Inter-Token Latency---------------- Mean ITL (ms): 8.93 Median ITL (ms): 8.98 P95 ITL (ms): 9.83 P99 ITL (ms): 10.20 Max ITL (ms): 18.50 ================================================== ``` * Medium Concurrency (Balanced) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 52.73 Total input tokens: 39668 Total input text tokens: 39668 Total generated tokens: 40805 Total generated tokens (retokenized): 40775 Request throughput (req/s): 1.52 Input token throughput (tok/s): 752.27 Output token throughput (tok/s): 773.83 Peak output token throughput (tok/s): 1040.00 Peak concurrent requests: 21 Total token throughput (tok/s): 1526.10 Concurrency: 13.98 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 9217.90 Median E2E Latency (ms): 9642.50 P90 E2E Latency (ms): 15147.02 P99 E2E Latency (ms): 18237.06 ---------------Time to First Token---------------- Mean TTFT (ms): 299.02 Median TTFT (ms): 105.98 P99 TTFT (ms): 1109.29 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 18.03 Median TPOT (ms): 18.00 P99 TPOT (ms): 26.51 ---------------Inter-Token Latency---------------- Mean ITL (ms): 17.52 Median ITL (ms): 16.07 P95 ITL (ms): 18.14 P99 ITL (ms): 89.43 Max ITL (ms): 763.13 ================================================== ``` * High Concurrency (Throughput-Optimized) ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 91.48 Total input tokens: 249831 Total input text tokens: 249831 Total generated tokens: 252662 Total generated tokens (retokenized): 250941 Request throughput (req/s): 5.47 Input token throughput (tok/s): 2730.87 Output token throughput (tok/s): 2761.82 Peak output token throughput (tok/s): 4199.00 Peak concurrent requests: 109 Total token throughput (tok/s): 5492.69 Concurrency: 90.54 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 16566.04 Median E2E Latency (ms): 16134.36 P90 E2E Latency (ms): 30167.60 P99 E2E Latency (ms): 34034.04 ---------------Time to First Token---------------- Mean TTFT (ms): 433.94 Median TTFT (ms): 123.26 P99 TTFT (ms): 1760.09 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 32.26 Median TPOT (ms): 33.56 P99 TPOT (ms): 38.78 ---------------Inter-Token Latency---------------- Mean ITL (ms): 31.99 Median ITL (ms): 24.06 P95 ITL (ms): 79.62 P99 ITL (ms): 103.03 Max ITL (ms): 1369.20 ================================================== ``` **Scenario 2: Reasoning (1K/8K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 525.43 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 44462 Total generated tokens (retokenized): 44451 Request throughput (req/s): 0.02 Input token throughput (tok/s): 11.61 Output token throughput (tok/s): 84.62 Peak output token throughput (tok/s): 125.00 Peak concurrent requests: 2 Total token throughput (tok/s): 96.23 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 52540.19 Median E2E Latency (ms): 53694.45 P90 E2E Latency (ms): 94742.08 P99 E2E Latency (ms): 101224.18 ---------------Time to First Token---------------- Mean TTFT (ms): 97.45 Median TTFT (ms): 95.28 P99 TTFT (ms): 105.64 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 10.94 Median TPOT (ms): 11.25 P99 TPOT (ms): 13.09 ---------------Inter-Token Latency---------------- Mean ITL (ms): 11.80 Median ITL (ms): 11.51 P95 ITL (ms): 15.83 P99 ITL (ms): 16.86 Max ITL (ms): 19.96 ================================================== ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 473.92 Total input tokens: 39668 Total input text tokens: 39668 Total generated tokens: 318306 Total generated tokens (retokenized): 317860 Request throughput (req/s): 0.17 Input token throughput (tok/s): 83.70 Output token throughput (tok/s): 671.65 Peak output token throughput (tok/s): 1040.00 Peak concurrent requests: 19 Total token throughput (tok/s): 755.35 Concurrency: 13.80 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 81746.73 Median E2E Latency (ms): 78508.54 P90 E2E Latency (ms): 155292.49 P99 E2E Latency (ms): 166769.99 ---------------Time to First Token---------------- Mean TTFT (ms): 117.50 Median TTFT (ms): 101.97 P99 TTFT (ms): 182.88 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 20.36 Median TPOT (ms): 20.48 P99 TPOT (ms): 22.63 ---------------Inter-Token Latency---------------- Mean ITL (ms): 20.52 Median ITL (ms): 20.42 P95 ITL (ms): 23.41 P99 ITL (ms): 26.29 Max ITL (ms): 90.48 ================================================== ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 714.72 Total input tokens: 158939 Total input text tokens: 158939 Total generated tokens: 1301025 Total generated tokens (retokenized): 1289431 Request throughput (req/s): 0.45 Input token throughput (tok/s): 222.38 Output token throughput (tok/s): 1820.33 Peak output token throughput (tok/s): 3200.00 Peak concurrent requests: 68 Total token throughput (tok/s): 2042.71 Concurrency: 55.68 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 124364.58 Median E2E Latency (ms): 129250.98 P90 E2E Latency (ms): 219175.80 P99 E2E Latency (ms): 247741.77 ---------------Time to First Token---------------- Mean TTFT (ms): 149.40 Median TTFT (ms): 114.78 P99 TTFT (ms): 288.60 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 30.51 Median TPOT (ms): 31.75 P99 TPOT (ms): 33.32 ---------------Inter-Token Latency---------------- Mean ITL (ms): 30.56 Median ITL (ms): 30.82 P95 ITL (ms): 33.20 P99 ITL (ms): 80.54 Max ITL (ms): 117.72 ================================================== ``` **Scenario 3: Summarization (8K/1K)** * Low Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 58.27 Total input tokens: 41941 Total input text tokens: 41941 Total generated tokens: 4220 Total generated tokens (retokenized): 4220 Request throughput (req/s): 0.17 Input token throughput (tok/s): 719.73 Output token throughput (tok/s): 72.42 Peak output token throughput (tok/s): 112.00 Peak concurrent requests: 2 Total token throughput (tok/s): 792.15 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 5825.08 Median E2E Latency (ms): 4624.26 P90 E2E Latency (ms): 12690.22 P99 E2E Latency (ms): 13177.96 ---------------Time to First Token---------------- Mean TTFT (ms): 296.01 Median TTFT (ms): 195.59 P99 TTFT (ms): 717.88 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 12.63 Median TPOT (ms): 13.07 P99 TPOT (ms): 16.68 ---------------Inter-Token Latency---------------- Mean ITL (ms): 13.13 Median ITL (ms): 13.17 P95 ITL (ms): 17.02 P99 ITL (ms): 17.47 Max ITL (ms): 19.84 ================================================== ``` * Medium Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 89.59 Total input tokens: 300020 Total input text tokens: 300020 Total generated tokens: 41669 Total generated tokens (retokenized): 41656 Request throughput (req/s): 0.89 Input token throughput (tok/s): 3348.77 Output token throughput (tok/s): 465.10 Peak output token throughput (tok/s): 752.00 Peak concurrent requests: 19 Total token throughput (tok/s): 3813.87 Concurrency: 14.39 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 16120.74 Median E2E Latency (ms): 16246.55 P90 E2E Latency (ms): 27279.72 P99 E2E Latency (ms): 34577.93 ---------------Time to First Token---------------- Mean TTFT (ms): 1943.94 Median TTFT (ms): 382.19 P99 TTFT (ms): 8980.41 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 27.87 Median TPOT (ms): 28.26 P99 TPOT (ms): 40.55 ---------------Inter-Token Latency---------------- Mean ITL (ms): 27.27 Median ITL (ms): 21.74 P95 ITL (ms): 23.32 P99 ITL (ms): 232.65 Max ITL (ms): 4282.01 ================================================== ``` * High Concurrency ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-4.7-Flash \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 167.01 Total input tokens: 1273893 Total input text tokens: 1273893 Total generated tokens: 170000 Total generated tokens (retokenized): 169226 Request throughput (req/s): 1.92 Input token throughput (tok/s): 7627.82 Output token throughput (tok/s): 1017.93 Peak output token throughput (tok/s): 1984.00 Peak concurrent requests: 69 Total token throughput (tok/s): 8645.75 Concurrency: 59.68 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 31147.52 Median E2E Latency (ms): 30603.34 P90 E2E Latency (ms): 54889.44 P99 E2E Latency (ms): 67665.30 ---------------Time to First Token---------------- Mean TTFT (ms): 428.87 Median TTFT (ms): 441.69 P99 TTFT (ms): 1232.68 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 58.06 Median TPOT (ms): 62.79 P99 TPOT (ms): 82.23 ---------------Inter-Token Latency---------------- Mean ITL (ms): 57.93 Median ITL (ms): 33.30 P95 ITL (ms): 247.98 P99 ITL (ms): 409.63 Max ITL (ms): 1421.21 ================================================== ``` #### 5.1.5 Understanding the Results **Key Metrics:** * **Request Throughput (req/s)**: Number of requests processed per second * **Output Token Throughput (tok/s)**: Total tokens generated per second * **Mean TTFT (ms)**: Time to First Token - measures responsiveness * **Mean TPOT (ms)**: Time Per Output Token - measures generation speed * **Mean ITL (ms)**: Inter-Token Latency - measures streaming consistency **Why These Configurations Matter:** * **1K/1K (Chat)**: Represents the most common conversational AI workload. This is the highest priority scenario for most deployments. * **1K/8K (Reasoning)**: Tests long-form generation capabilities crucial for complex reasoning, code generation, and detailed explanations. * **8K/1K (Summarization)**: Evaluates performance with large context inputs, essential for RAG systems, document Q\&A, and summarization tasks. * **Variable Concurrency**: Captures the Pareto frontier - the optimal tradeoff between throughput and latency at different load levels. Low concurrency shows best-case latency, high concurrency shows maximum throughput. **Interpreting Results:** * Compare your results against baseline numbers for your hardware * Higher throughput at same latency = better performance * Lower TTFT = more responsive user experience * Lower TPOT = faster generation speed ### 5.2 Accuracy Benchmark Document model accuracy on standard benchmarks: #### 5.2.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. * Result ```text Output theme={null} Accuracy: 0.845 Invalid: 0.000 Latency: 8.431 s Output throughput: 2195.387 token/s ``` # GLM-5 Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-5 ## 1. Model Introduction [GLM-5](https://huggingface.co/zai-org/GLM-5) is the most powerful language model in the GLM series developed by Zhipu AI, targeting complex systems engineering and long-horizon agentic tasks. Scaling from GLM-4.5's 355B parameters (32B active) to 744B parameters (40B active), GLM-5 integrates DeepSeek Sparse Attention (DSA) to largely reduce deployment cost while preserving long-context capacity. With advances in both pre-training (28.5T tokens) and post-training via [slime](https://github.com/THUDM/slime) (a novel asynchronous RL infrastructure), GLM-5 delivers significant improvements over GLM-4.7 and achieves best-in-class performance among open-source models on reasoning, coding, and agentic tasks. **Key Features:** * **Systems Engineering & Agentic Tasks**: Purpose-built for complex systems engineering and long-horizon agentic tasks * **State-of-the-Art Performance**: Best-in-class among open-source models on reasoning (HLE, AIME, GPQA), coding (SWE-bench, Terminal-Bench), and agentic tasks (BrowseComp, Vending Bench 2) * **DeepSeek Sparse Attention (DSA)**: Reduces deployment cost while preserving long-context capacity * **Multiple Quantizations**: BF16 and FP8 variants for different performance/memory trade-offs * **Speculative Decoding**: EAGLE-based speculative decoding support for lower latency **Available Models:** * **BF16 (Full precision)**: [zai-org/GLM-5](https://huggingface.co/zai-org/GLM-5) * **FP8 (8-bit quantized)**: [zai-org/GLM-5-FP8](https://huggingface.co/zai-org/GLM-5-FP8) **License:** MIT ## 2. SGLang Installation Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, and capabilities. SGLang supports serving GLM-5 on NVIDIA H100, H200, B200, and AMD MI300X/MI325X/MI355X GPUs. Run this Command:

> [!WARNING]
>
> All recipes here run the DSA indexer top-k on the default `--dsa-topk-backend sgl-kernel`. Other top-k backend choices have not been fully validated on GLM-5.

### 3.2 Configuration Tips

* Speculative decoding (MTP) can significantly reduce latency for interactive use cases.
* **DP Attention**: Enables data parallel attention for higher throughput under high concurrency. Note that DP attention trades off low-concurrency latency for high-concurrency throughput — disable it if your workload is latency-sensitive with few concurrent requests.
* The `--mem-fraction-static` flag is recommended for optimal memory utilization, adjust it based on your hardware and workload.
* BF16 model always requires **2x GPUs** compared to FP8 on NVIDIA hardware.

Hardware FP8 BF16
H100 tp=16 tp=32
H200 tp=8 tp=16
B200 tp=8 tp=16
MI300X/MI325X — tp=8
MI355X — tp=8
* **B200 (FP8)**: Use `--ep 1 --attention-backend dsa --dsa-decode-backend trtllm --dsa-prefill-backend trtllm --moe-runner-backend flashinfer_trtllm --enable-flashinfer-allreduce-fusion` for optimized DSA and MoE backends on Blackwell. Also add `--quantization fp8` for FP8 weight quantization. * **AMD GPUs**: Use `--dsa-prefill-backend tilelang --dsa-decode-backend tilelang` for the DSA attention backend. Add `--chunked-prefill-size 131072` and `--watchdog-timeout 1200` (20 minutes for weight loading). EAGLE speculative decoding is not currently supported on AMD for GLM-5. * For other configuration tips (MTP, DSA kernel, Context Parallel, HiSparse, NVFP4, Index Cache), see the [DeepSeek-V3.2 cookbook page](../DeepSeek/DeepSeek-V3_2). GLM-5 and DeepSeek-V3.2 share the same model structure, so the optimization techniques are common. * **Prefill CP on CUDA**: Zigzag (`--cp-strategy zigzag`) is temporarily unavailable for GLM-5. Use `--enable-prefill-cp --cp-strategy interleave` with `--attn-dp-size 1`. * Use `--json-model-override-args '{"index_topk_pattern": "FFSFSSSFSSFFFSSSFFFSFSSSSSSFFSFFSFFSSFFFFFFSFFFFFSFFSSSSSSFSFFFSFSSSFSFFSFFSSS"}'` for GLM-5-FP8 if you want to enable the [IndexCache](https://github.com/THUDM/IndexCache) method. This feature is supported through [this PR](https://github.com/sgl-project/sglang/pull/21405) and introduces only a small accuracy loss. However, if you are running rigorous accuracy evaluations, it is not recommended to enable this feature. ## 4. Model Invocation Deploy GLM-5 with the following command (FP8 on H200, all features enabled): ```shell Command theme={null} sglang serve \ --model-path zai-org/GLM-5-FP8 \ --tp 8 \ --tool-call-parser glm47 \ --reasoning-parser glm45 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --enable-flashinfer-allreduce-fusion \ --mem-fraction-static 0.85 \ --host 0.0.0.0 \ --port 30000 ``` ### 4.1 MI300X/MI325X/MI355X (ROCm) Server Command The following ROCm command is an additional option for AMD GPUs and does not replace the NVIDIA instructions above. ```shell Command theme={null} sglang serve \ --model-path zai-org/GLM-5 \ --tp 8 \ --trust-remote-code \ --dsa-prefill-backend tilelang \ --dsa-decode-backend tilelang \ --chunked-prefill-size 131072 \ --mem-fraction-static 0.80 \ --watchdog-timeout 1200 \ --host 0.0.0.0 \ --port 30000 ``` ### 4.2 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) ### 4.3 Advanced Usage #### 4.3.1 Reasoning Parser GLM-5 supports Thinking mode **by default**. Enable the reasoning parser during deployment to separate the thinking and content sections. The thinking process is returned via `reasoning_content` in the streaming response. To disable thinking and use Instruct mode, pass `chat_template_kwargs` at request time: * **Thinking mode** (default): The model performs step-by-step reasoning before answering. No extra parameters needed. * **Instruct mode** (`{"enable_thinking": false}`): The model responds directly without a thinking process. **Example 1: Thinking Mode (Default)** Thinking mode is enabled by default. The model will reason step-by-step before answering, and the thinking process is returned via `reasoning_content`: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Thinking mode is enabled by default, no extra parameters needed response = client.chat.completions.create( model="zai-org/GLM-5-FP8", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], max_tokens=2048, stream=True ) # Process the stream has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: # Close thinking section and add content header if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user wants me to solve a math problem: "What is 15% of 240?". Step 1: Understand the problem. I need to calculate a percentage of a number. Formula: Percentage × Number = Result. Step 2: Convert the percentage to a decimal or fraction. 15% = 15/100 or 0.15. Step 3: Perform the multiplication. Method A: Decimal multiplication. 0.15 × 240. Break it down: 10% of 240 = 24. 5% is half of 10%, so 12. 15% = 10% + 5% = 24 + 12 = 36. Method B: Fraction multiplication. 15/100 × 240. Simplify 240/100 = 2.4. 15 × 2.4. 10 × 2.4 = 24. 5 × 2.4 = 12. 24 + 12 = 36. Method C: Direct multiplication. 240 × 0.15. 240 × 0.10 = 24. 240 × 0.05 = 12. 24 + 12 = 36. Step 4: Final Verification. Is 36 reasonable? 10% is 24. 20% is 48. 15% is halfway between 10% and 20%. Halfway between 24 and 48 is 36. The result is correct. Step 5: Structure the final response. I will present the calculation clearly, perhaps showing the fractional or decimal method, or the mental math shortcut (10% + 5%). =============== Content ================= Here is the step-by-step solution: **Step 1: Convert the percentage to a decimal.** To convert 15% to a decimal, divide by 100. $$15\% = \frac{15}{100} = 0.15$$ **Step 2: Multiply the decimal by the number.** Now, multiply 0.15 by 240. $$0.15 \times 240$$ **Step 3: Perform the calculation.** You can break this down to make it easier: $$0.15 = 0.10 + 0.05$$ * First, find 10% of 240: $$0.10 \times 240 = 24$$ * Next, find 5% (which is half of 10%): $$\frac{24}{2} = 12$$ * Add the two results together: $$24 + 12 = 36$$ **Answer:** 15% of 240 is **36**. ``` **Example 2: Instruct Mode (Thinking Off)** To disable thinking and get a direct response, pass `{"enable_thinking": false}` via `chat_template_kwargs`: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Disable thinking mode via chat_template_kwargs response = client.chat.completions.create( model="zai-org/GLM-5-FP8", messages=[ {"role": "user", "content": "What is 15% of 240?"} ], extra_body={"chat_template_kwargs": {"enable_thinking": False}}, max_tokens=2048, stream=True ) # In Instruct mode, the model responds directly without reasoning_content for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} To find **15% of 240**, follow these steps: ### Step 1: Convert the Percentage to a Decimal First, convert the percentage to a decimal by dividing by 100. \[ 15\% = \frac{15}{100} = 0.15 \] ### Step 2: Multiply by the Number Next, multiply the decimal by the number you want to find the percentage of. \[ 0.15 \times 240 \] ### Step 3: Perform the Multiplication Calculate the multiplication: \[ 0.15 \times 240 = 36 \] ### Final Answer \[ \boxed{36} \] ``` #### 4.3.2 Tool Calling GLM-5 supports tool calling capabilities. Enable the tool call parser during deployment. Thinking mode is on by default; to disable it for tool calling requests, pass `extra_body={"chat_template_kwargs": {"enable_thinking": False}}`. **Python Example (with Thinking Process):** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Make request with streaming to see thinking process response = client.chat.completions.create( model="zai-org/GLM-5-FP8", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, stream=True ) # Process streaming response thinking_started = False has_thinking = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print tool calls if hasattr(delta, 'tool_calls') and delta.tool_calls: # Close thinking section if needed if has_thinking and thinking_started: print("\n=============== Content =================", flush=True) thinking_started = False for tool_call in delta.tool_calls: if tool_call.function: print(f"Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") # Print content if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user is asking for the weather in Beijing. I have access to a get_weather function that can provide current weather information. Let me check what parameters are required: - location: required, should be "Beijing" - unit: optional (not in required array), can be "celsius" or "fahrenheit" Since the user didn't specify a unit preference and it's optional, I should not ask about it or make up a value. I'll just call the function with the required location parameter.I'll get the current weather in Beijing for you. =============== Content ================= Tool Call: get_weather Arguments: Tool Call: None Arguments: { Tool Call: None Arguments: "location": "Be Tool Call: None Arguments: ijing" Tool Call: None Arguments: } ``` ## 5. Benchmark ### 5.1 Speed Benchmark **Test Environment:** * Hardware: H200 (8x) * Model: GLM-5-FP8 * Tensor Parallelism: 8 * SGLang Version: commit 947927bdb #### 5.1.1 Latency Benchmark ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-5-FP8 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 35.78 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 4213 Request throughput (req/s): 0.28 Input token throughput (tok/s): 170.54 Output token throughput (tok/s): 117.96 Peak output token throughput (tok/s): 148.00 Peak concurrent requests: 2 Total token throughput (tok/s): 288.50 Concurrency: 1.00 Accept length: 3.48 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 3576.31 Median E2E Latency (ms): 2935.97 P90 E2E Latency (ms): 5908.97 P99 E2E Latency (ms): 8588.08 ---------------Time to First Token---------------- Mean TTFT (ms): 290.88 Median TTFT (ms): 282.34 P99 TTFT (ms): 332.27 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 7.54 Median TPOT (ms): 6.97 P99 TPOT (ms): 9.04 ---------------Inter-Token Latency---------------- Mean ITL (ms): 7.80 Median ITL (ms): 6.81 P95 ITL (ms): 13.51 P99 ITL (ms): 26.99 Max ITL (ms): 29.50 ================================================== ``` #### 5.1.2 Throughput Benchmark ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-5-FP8 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 1000 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 411.74 Total input tokens: 502493 Total input text tokens: 502493 Total generated tokens: 500251 Total generated tokens (retokenized): 499614 Request throughput (req/s): 2.43 Input token throughput (tok/s): 1220.41 Output token throughput (tok/s): 1214.97 Peak output token throughput (tok/s): 2648.00 Peak concurrent requests: 105 Total token throughput (tok/s): 2435.38 Concurrency: 96.30 Accept length: 3.50 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 39648.76 Median E2E Latency (ms): 39058.12 P90 E2E Latency (ms): 57009.82 P99 E2E Latency (ms): 68880.33 ---------------Time to First Token---------------- Mean TTFT (ms): 20613.80 Median TTFT (ms): 21429.21 P99 TTFT (ms): 29543.17 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 38.73 Median TPOT (ms): 36.52 P99 TPOT (ms): 67.09 ---------------Inter-Token Latency---------------- Mean ITL (ms): 38.13 Median ITL (ms): 16.57 P95 ITL (ms): 86.01 P99 ITL (ms): 164.88 Max ITL (ms): 1307.02 ================================================== ``` ### 5.2 Accuracy Benchmark > [!NOTE] > > The accuracy benchmark results below are shared with GLM-5.1, as GLM-5.1 was not independently benchmarked at the time of this writing. A separate GLM-5.1 benchmark run is planned. #### 5.2.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 \ --num-threads 64 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. * Test Result ```text Output theme={null} Accuracy: 0.955 Invalid: 0.000 Latency: 32.470 s Output throughput: 642.044 token/s ``` #### 5.2.2 MMLU Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run mmlu \ --base-url http://127.0.0.1:30000/v1 \ --num-threads 64 --max-tokens 2048 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. * Test Result ```text Output theme={null} subject: abstract_algebra, #q:100, acc: 0.860 subject: anatomy, #q:135, acc: 0.874 subject: astronomy, #q:152, acc: 0.941 subject: business_ethics, #q:100, acc: 0.880 subject: clinical_knowledge, #q:265, acc: 0.932 subject: college_biology, #q:144, acc: 0.972 subject: college_chemistry, #q:100, acc: 0.640 subject: college_computer_science, #q:100, acc: 0.900 subject: college_mathematics, #q:100, acc: 0.810 subject: college_medicine, #q:173, acc: 0.873 subject: college_physics, #q:102, acc: 0.912 subject: computer_security, #q:100, acc: 0.880 subject: conceptual_physics, #q:235, acc: 0.928 subject: econometrics, #q:114, acc: 0.807 subject: electrical_engineering, #q:145, acc: 0.897 subject: elementary_mathematics, #q:378, acc: 0.937 subject: formal_logic, #q:126, acc: 0.778 subject: global_facts, #q:100, acc: 0.710 subject: high_school_biology, #q:310, acc: 0.961 subject: high_school_chemistry, #q:203, acc: 0.847 subject: high_school_computer_science, #q:100, acc: 0.960 subject: high_school_european_history, #q:165, acc: 0.891 subject: high_school_geography, #q:198, acc: 0.960 subject: high_school_government_and_politics, #q:193, acc: 0.984 subject: high_school_macroeconomics, #q:390, acc: 0.923 subject: high_school_mathematics, #q:270, acc: 0.696 subject: high_school_microeconomics, #q:238, acc: 0.962 subject: high_school_physics, #q:151, acc: 0.821 subject: high_school_psychology, #q:545, acc: 0.956 subject: high_school_statistics, #q:216, acc: 0.889 subject: high_school_us_history, #q:204, acc: 0.941 subject: high_school_world_history, #q:237, acc: 0.945 subject: human_aging, #q:223, acc: 0.857 subject: human_sexuality, #q:131, acc: 0.908 subject: international_law, #q:121, acc: 0.934 subject: jurisprudence, #q:108, acc: 0.907 subject: logical_fallacies, #q:163, acc: 0.933 subject: machine_learning, #q:112, acc: 0.830 subject: management, #q:103, acc: 0.942 subject: marketing, #q:234, acc: 0.940 subject: medical_genetics, #q:100, acc: 0.990 subject: miscellaneous, #q:783, acc: 0.959 subject: moral_disputes, #q:346, acc: 0.873 subject: moral_scenarios, #q:895, acc: 0.837 subject: nutrition, #q:306, acc: 0.922 subject: philosophy, #q:311, acc: 0.897 subject: prehistory, #q:324, acc: 0.929 subject: professional_accounting, #q:282, acc: 0.844 subject: professional_law, #q:1534, acc: 0.714 subject: professional_medicine, #q:272, acc: 0.941 subject: professional_psychology, #q:612, acc: 0.913 subject: public_relations, #q:110, acc: 0.791 subject: security_studies, #q:245, acc: 0.878 subject: sociology, #q:201, acc: 0.940 subject: us_foreign_policy, #q:100, acc: 0.920 subject: virology, #q:166, acc: 0.596 subject: world_religions, #q:171, acc: 0.936 Total latency: 165.275 Average accuracy: 0.877 ``` ### 5.3 AMD GPU Benchmarks #### 5.3.1 GSM8K Benchmark (MI325/MI35x) * MI325/MI35x Test (GLM-5 BF16, `tp=8`, TileLang DSA backends) ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 \ --num-threads 64 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. ```text Output theme={null} Accuracy: 0.970 Invalid: 0.000 ``` Results from [AMD nightly CI](https://github.com/sgl-project/sglang/actions/runs/22556197510/attempts/2#summary-65346783629). See also [sglang#18911](https://github.com/sgl-project/sglang/pull/18911). # GLM-5.1 Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-5.1 ## 1. Model Introduction **Available Models:** * **BF16 (Full precision)**: [zai-org/GLM-5.1](https://huggingface.co/zai-org/GLM-5.1) * **FP8 (8-bit quantized)**: [zai-org/GLM-5.1-FP8](https://huggingface.co/zai-org/GLM-5.1-FP8) * **NVFP4 (4-bit quantized)**: [nvidia/GLM-5.1-NVFP4](https://huggingface.co/nvidia/GLM-5.1-NVFP4) **License:** MIT ## 2. SGLang Installation Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, and capabilities. SGLang supports serving GLM-5.1 on NVIDIA H100, H200, B300, GB300, and AMD MI300X/MI325X/MI355X GPUs. Run this Command:

> [!WARNING]
>
> All recipes here run the DSA indexer top-k on the default `--dsa-topk-backend sgl-kernel`. Other top-k backend choices have not been fully validated on GLM-5.1.

### 3.2 Configuration Tips

* Speculative decoding (MTP) can significantly reduce latency for interactive use cases.
* **DP Attention**: Enables data parallel attention for higher throughput under high concurrency. Note that DP attention trades off low-concurrency latency for high-concurrency throughput — disable it if your workload is latency-sensitive with few concurrent requests.
* The `--mem-fraction-static` flag is recommended for optimal memory utilization, adjust it based on your hardware and workload.

Hardware NVFP4 FP8 BF16 MXFP4
H100 — tp=16 — —
H200 — tp=8 — —
B300 tp=8 — — —
GB300 tp=4 — — —
MI300X/MI325X — tp=8 tp=8 —
MI355X — tp=8 tp=8 tp=4
* **H100 and H200**: FP8 is the recommended deployment path. * **B300 and GB300**: NVFP4 is the recommended deployment path. Use `nvidia/GLM-5.1-NVFP4` with `--quantization modelopt_fp4`. Use `tp=8` on B300 and `tp=4` on GB300. The CUDA 13 image variant is required for B300 and GB300. * **AMD GPUs**: BF16 and FP8 checkpoints run on MI300X/MI325X/MI355X at tp=8. On MI355X (gfx950), the MXFP4 checkpoint `amd/GLM-5.1-MXFP4` is also supported at tp=4 with `--kv-cache-dtype fp8_e4m3`. All AMD paths pass `--dsa-prefill-backend tilelang --dsa-decode-backend tilelang`, `--chunked-prefill-size 131072`, and `--watchdog-timeout 1200` (20 minutes for weight loading). FP8 uses approximately half the memory of BF16 (\~89 GB/GPU vs \~175 GB/GPU). EAGLE speculative decoding is supported on AMD GPUs: MI300X/MI325X (gfx942) and MI355X (gfx950), but it **requires `--disable-custom-all-reduce`** — the aiter custom all-reduce kernel deadlocks during EAGLE verify at high concurrency, so without this flag the server will hang. * For other configuration tips (MTP, DSA kernel, Context Parallel, HiSparse, NVFP4, Index Cache), see the [DeepSeek-V3.2 cookbook page](../DeepSeek/DeepSeek-V3_2). GLM-5.1 and DeepSeek-V3.2 share the same model structure, so the optimization techniques are common. * **Prefill CP on CUDA**: Zigzag (`--cp-strategy zigzag`) is temporarily unavailable for GLM-5.1. Use `--enable-prefill-cp --cp-strategy interleave`. Attention DP is supported, with `tp_size / attn_dp_size` CP ranks in each DP group. Dense FFNs retain their configured TP width. * Use `--json-model-override-args '{"index_topk_pattern": "FFSFSSSFSSFFFSSSFFFSFSSSSSSFFSFFSFFSSFFFFFFSFFFFFSFFSSSSSSFSFFFSFSSSFSFFSFFSSS"}'` to enable the [IndexCache](https://github.com/THUDM/IndexCache) method for GLM-5.1. This can improve serving efficiency with only a small accuracy loss. If you are running rigorous accuracy evaluations, do not enable this feature. ## 4. Model Invocation Deploy GLM-5.1 with the following command (FP8 on H200, all features enabled): ```shell Command theme={null} sglang serve \ --model-path zai-org/GLM-5.1-FP8 \ --tp 8 \ --tool-call-parser glm47 \ --reasoning-parser glm45 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --mem-fraction-static 0.85 \ --host 0.0.0.0 \ --port 30000 ``` ### 4.1 B300/GB300 (NVFP4) Server Command #### B300 ```shell Command theme={null} sglang serve \ --model-path nvidia/GLM-5.1-NVFP4 \ --tp 8 \ --quantization modelopt_fp4 \ --tool-call-parser glm47 \ --reasoning-parser glm45 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --trust-remote-code \ --mem-fraction-static 0.80 \ --host 0.0.0.0 \ --port 30000 ``` #### GB300 ```shell Command theme={null} sglang serve \ --model-path nvidia/GLM-5.1-NVFP4 \ --tp 4 \ --quantization modelopt_fp4 \ --tool-call-parser glm47 \ --reasoning-parser glm45 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --trust-remote-code \ --mem-fraction-static 0.80 \ --host 0.0.0.0 \ --port 30000 ``` ### 4.2 MI300X/MI325X/MI355X (ROCm) Server Command The following ROCm commands are additional options for AMD GPUs and do not replace the NVIDIA instructions above. #### MXFP4 (MI355X / gfx950) On MI355X (gfx950), set `SGLANG_DSA_TRITON_PREFILL=1` to enable a faster Triton attention kernel for the prefill phase (opt-in, off by default). Keep `--dsa-prefill-backend tilelang` as shown. The EAGLE speculative-decoding flags below are optional but recommended on gfx950. ```shell Command theme={null} # SGLANG_DSA_TRITON_PREFILL=1 is optional; it enables a faster Triton prefill kernel on gfx950 SGLANG_DSA_TRITON_PREFILL=1 sglang serve \ --model-path amd/GLM-5.1-MXFP4 \ --tp 4 \ --trust-remote-code \ --kv-cache-dtype fp8_e4m3 \ --tool-call-parser glm47 \ --reasoning-parser glm45 \ --dsa-prefill-backend tilelang \ --dsa-decode-backend tilelang \ --chunked-prefill-size 131072 \ --mem-fraction-static 0.85 \ --watchdog-timeout 1200 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --disable-custom-all-reduce \ --host 0.0.0.0 \ --port 30000 ``` #### FP8 (Recommended) ```shell Command theme={null} sglang serve \ --model-path zai-org/GLM-5.1-FP8 \ --tp 8 \ --trust-remote-code \ --tool-call-parser glm47 \ --reasoning-parser glm45 \ --dsa-prefill-backend tilelang \ --dsa-decode-backend tilelang \ --chunked-prefill-size 131072 \ --mem-fraction-static 0.80 \ --watchdog-timeout 1200 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --disable-custom-all-reduce \ --host 0.0.0.0 \ --port 30000 ``` #### BF16 ```shell Command theme={null} sglang serve \ --model-path zai-org/GLM-5.1 \ --tp 8 \ --trust-remote-code \ --dsa-prefill-backend tilelang \ --dsa-decode-backend tilelang \ --chunked-prefill-size 131072 \ --mem-fraction-static 0.80 \ --watchdog-timeout 1200 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --disable-custom-all-reduce \ --host 0.0.0.0 \ --port 30000 ``` ### 4.3 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) ### 4.4 Advanced Usage #### 4.4.1 Reasoning Parser GLM-5.1 supports Thinking mode **by default**. Enable the reasoning parser during deployment to separate the thinking and content sections. The thinking process is returned via `reasoning_content` in the streaming response. To disable thinking and use Instruct mode, pass `chat_template_kwargs` at request time: * **Thinking mode** (default): The model performs step-by-step reasoning before answering. No extra parameters needed. * **Instruct mode** (`{"enable_thinking": false}`): The model responds directly without a thinking process. **Example 1: Thinking Mode (Default)** Thinking mode is enabled by default. The model will reason step-by-step before answering, and the thinking process is returned via `reasoning_content`: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Thinking mode is enabled by default, no extra parameters needed response = client.chat.completions.create( model="zai-org/GLM-5.1-FP8", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], max_tokens=2048, stream=True ) # Process the stream has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: # Close thinking section and add content header if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= 1. **Understand the Goal:** The user wants to find 15% of 240, and they want the solution explained step-by-step. 2. **Identify the Core Mathematical Concept:** "Percent" means "per hundred" or "out of 100". Finding "X% of Y" translates to the mathematical operation: $(X / 100) \times Y$. 3. **Step-by-Step Breakdown:** * *Step 1: Convert the percentage to a decimal (or fraction).* 15% means 15 out of 100, which is $15/100$ or $0.15$. * *Step 2: Multiply the decimal by the given number.* Multiply $0.15$ by $240$. * *Step 3: Perform the calculation.* * $0.15 \times 240$ * I can break this down further to make it easy to follow: * $0.10 \times 240 = 24$ (which is 10%) * $0.05 \times 240 = 12$ (which is 5%, half of 10%) * $24 + 12 = 36$ * Alternatively, standard multiplication: * $240 \times 15 = 3600$ * Move decimal two places left -> $36$ * *Step 4: State the final answer clearly.* 4. **Draft the Response (incorporating the steps clearly):** * *Introduction:* State the problem clearly. * *Step 1:* Explain how to convert 15% to a decimal. * *Step 2:* Explain the multiplication step. * *Step 3:* Show the actual math (I'll provide the standard multiplication and the "mental math" trick as it adds value). * *Conclusion:* Give the final answer. 5. **Refine the Output (Self-Correction/Polishing during drafting):** * *Drafting Step 1:* To find 15% of 240, first convert 15% into a decimal. Since percent means "per hundred," you divide 15 by 100. 15 ÷ 100 = 0.15. * *Drafting Step 2:* Next, multiply this decimal by the number you are finding the percentage of (which is 240). So, calculate 0.15 × 240. * *Drafting Step 3 (Standard way):* 0.15 × 240 = 36. * *Adding the alternative mental math way:* It's often helpful to break it down into 10% and 5%. * 10% of 240 = 24 (move the decimal point one place to the left) * 5% is half of 10%, so half of 24 = 12 * Add them together: 24 + 12 = 36. * *Final Answer:* 15% of 240 is 36. 6. **Final Review against User Prompt:** Does it solve the problem? Yes. Is it step-by-step? Yes. Is it clear? Yes. (Proceed to generate output). =============== Content ================= Here is the step-by-step solution to find 15% of 240: **Step 1: Convert the percentage to a decimal.** To convert a percentage to a decimal, divide it by 100 (or simply move the decimal point two places to the left). * 15% = 15 ÷ 100 = **0.15** **Step 2: Multiply the decimal by the number.** Now, multiply the decimal (0.15) by the number you are finding the percentage of (240). * 0.15 × 240 = **36** *(Alternative mental math method for Step 2)*: If you don't want to multiply by 0.15 directly, you can break 15% down into 10% and 5%: * **10% of 240** = 24 (just move the decimal point one place to the left) * **5% of 240** = 12 (5% is half of 10%, so just divide 24 by 2) * **Add them together**: 24 + 12 = **36** **Answer:** 15% of 240 is **36**. ``` **Example 2: Instruct Mode (Thinking Off)** To disable thinking and get a direct response, pass `{"enable_thinking": false}` via `chat_template_kwargs`: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Disable thinking mode via chat_template_kwargs response = client.chat.completions.create( model="zai-org/GLM-5.1-FP8", messages=[ {"role": "user", "content": "What is 15% of 240?"} ], extra_body={"chat_template_kwargs": {"enable_thinking": False}}, max_tokens=2048, stream=True ) # In Instruct mode, the model responds directly without reasoning_content for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} 15% of 240 is 36. Here is how to calculate it: 1. Convert the percentage to a decimal: 15% = 0.15 2. Multiply the decimal by the number: 0.15 × 240 = 36 ``` #### 4.4.2 Tool Calling GLM-5.1 supports tool calling capabilities. Enable the tool call parser during deployment. Thinking mode is on by default; to disable it for tool calling requests, pass `extra_body={"chat_template_kwargs": {"enable_thinking": False}}`. **Python Example (with Thinking Process):** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Make request with streaming to see thinking process response = client.chat.completions.create( model="zai-org/GLM-5.1-FP8", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, stream=True ) # Process streaming response thinking_started = False has_thinking = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print tool calls if hasattr(delta, 'tool_calls') and delta.tool_calls: # Close thinking section if needed if has_thinking and thinking_started: print("\n=============== Content =================", flush=True) thinking_started = False for tool_call in delta.tool_calls: if tool_call.function: print(f"Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") # Print content if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user wants to know the weather in Beijing. I'll call the get_weather function with "Beijing" as the location. =============== Content ================= Tool Call: get_weather Arguments: Tool Call: None Arguments: { Tool Call: None Arguments: "location": "Be Tool Call: None Arguments: ijing" Tool Call: None Arguments: } ``` ## 5. Benchmark ### 5.1 Speed Benchmark **Test Environment:** * Hardware: H200 (8x) * Model: GLM-5.1-FP8 * Tensor Parallelism: 8 * SGLang Version: commit 947927bdb #### 5.1.1 Latency Benchmark ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-5.1-FP8 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 35.78 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 4213 Request throughput (req/s): 0.28 Input token throughput (tok/s): 170.54 Output token throughput (tok/s): 117.96 Peak output token throughput (tok/s): 148.00 Peak concurrent requests: 2 Total token throughput (tok/s): 288.50 Concurrency: 1.00 Accept length: 3.48 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 3576.31 Median E2E Latency (ms): 2935.97 P90 E2E Latency (ms): 5908.97 P99 E2E Latency (ms): 8588.08 ---------------Time to First Token---------------- Mean TTFT (ms): 290.88 Median TTFT (ms): 282.34 P99 TTFT (ms): 332.27 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 7.54 Median TPOT (ms): 6.97 P99 TPOT (ms): 9.04 ---------------Inter-Token Latency---------------- Mean ITL (ms): 7.80 Median ITL (ms): 6.81 P95 ITL (ms): 13.51 P99 ITL (ms): 26.99 Max ITL (ms): 29.50 ================================================== ``` #### 5.1.2 Throughput Benchmark ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model zai-org/GLM-5.1-FP8 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 1000 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 411.74 Total input tokens: 502493 Total input text tokens: 502493 Total generated tokens: 500251 Total generated tokens (retokenized): 499614 Request throughput (req/s): 2.43 Input token throughput (tok/s): 1220.41 Output token throughput (tok/s): 1214.97 Peak output token throughput (tok/s): 2648.00 Peak concurrent requests: 105 Total token throughput (tok/s): 2435.38 Concurrency: 96.30 Accept length: 3.50 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 39648.76 Median E2E Latency (ms): 39058.12 P90 E2E Latency (ms): 57009.82 P99 E2E Latency (ms): 68880.33 ---------------Time to First Token---------------- Mean TTFT (ms): 20613.80 Median TTFT (ms): 21429.21 P99 TTFT (ms): 29543.17 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 38.73 Median TPOT (ms): 36.52 P99 TPOT (ms): 67.09 ---------------Inter-Token Latency---------------- Mean ITL (ms): 38.13 Median ITL (ms): 16.57 P95 ITL (ms): 86.01 P99 ITL (ms): 164.88 Max ITL (ms): 1307.02 ================================================== ``` ### 5.2 Accuracy Benchmark > [!NOTE] > > The accuracy benchmark results below are shared with GLM-5, as GLM-5.1 was not independently benchmarked at the time of this writing. A separate benchmark run is planned. #### 5.2.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 \ --num-threads 64 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. * Test Result ```text Output theme={null} Accuracy: 0.955 Invalid: 0.000 Latency: 32.470 s Output throughput: 642.044 token/s ``` #### 5.2.2 MMLU Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run mmlu \ --base-url http://127.0.0.1:30000/v1 \ --num-threads 64 --max-tokens 2048 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. * Test Result ```text Output theme={null} subject: abstract_algebra, #q:100, acc: 0.860 subject: anatomy, #q:135, acc: 0.874 subject: astronomy, #q:152, acc: 0.941 subject: business_ethics, #q:100, acc: 0.880 subject: clinical_knowledge, #q:265, acc: 0.932 subject: college_biology, #q:144, acc: 0.972 subject: college_chemistry, #q:100, acc: 0.640 subject: college_computer_science, #q:100, acc: 0.900 subject: college_mathematics, #q:100, acc: 0.810 subject: college_medicine, #q:173, acc: 0.873 subject: college_physics, #q:102, acc: 0.912 subject: computer_security, #q:100, acc: 0.880 subject: conceptual_physics, #q:235, acc: 0.928 subject: econometrics, #q:114, acc: 0.807 subject: electrical_engineering, #q:145, acc: 0.897 subject: elementary_mathematics, #q:378, acc: 0.937 subject: formal_logic, #q:126, acc: 0.778 subject: global_facts, #q:100, acc: 0.710 subject: high_school_biology, #q:310, acc: 0.961 subject: high_school_chemistry, #q:203, acc: 0.847 subject: high_school_computer_science, #q:100, acc: 0.960 subject: high_school_european_history, #q:165, acc: 0.891 subject: high_school_geography, #q:198, acc: 0.960 subject: high_school_government_and_politics, #q:193, acc: 0.984 subject: high_school_macroeconomics, #q:390, acc: 0.923 subject: high_school_mathematics, #q:270, acc: 0.696 subject: high_school_microeconomics, #q:238, acc: 0.962 subject: high_school_physics, #q:151, acc: 0.821 subject: high_school_psychology, #q:545, acc: 0.956 subject: high_school_statistics, #q:216, acc: 0.889 subject: high_school_us_history, #q:204, acc: 0.941 subject: high_school_world_history, #q:237, acc: 0.945 subject: human_aging, #q:223, acc: 0.857 subject: human_sexuality, #q:131, acc: 0.908 subject: international_law, #q:121, acc: 0.934 subject: jurisprudence, #q:108, acc: 0.907 subject: logical_fallacies, #q:163, acc: 0.933 subject: machine_learning, #q:112, acc: 0.830 subject: management, #q:103, acc: 0.942 subject: marketing, #q:234, acc: 0.940 subject: medical_genetics, #q:100, acc: 0.990 subject: miscellaneous, #q:783, acc: 0.959 subject: moral_disputes, #q:346, acc: 0.873 subject: moral_scenarios, #q:895, acc: 0.837 subject: nutrition, #q:306, acc: 0.922 subject: philosophy, #q:311, acc: 0.897 subject: prehistory, #q:324, acc: 0.929 subject: professional_accounting, #q:282, acc: 0.844 subject: professional_law, #q:1534, acc: 0.714 subject: professional_medicine, #q:272, acc: 0.941 subject: professional_psychology, #q:612, acc: 0.913 subject: public_relations, #q:110, acc: 0.791 subject: security_studies, #q:245, acc: 0.878 subject: sociology, #q:201, acc: 0.940 subject: us_foreign_policy, #q:100, acc: 0.920 subject: virology, #q:166, acc: 0.596 subject: world_religions, #q:171, acc: 0.936 Total latency: 165.275 Average accuracy: 0.877 ``` ### 5.3 AMD GPU Benchmarks #### 5.3.1 GSM8K Benchmark (MI325/MI35x) * MI325/MI35x Test (GLM-5.1 BF16, `tp=8`, TileLang DSA backends) ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 \ --num-threads 64 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. ```text Output theme={null} Accuracy: 0.970 Invalid: 0.000 ``` Results from [AMD nightly CI](https://github.com/sgl-project/sglang/actions/runs/22556197510/attempts/2#summary-65346783629). See also [sglang#18911](https://github.com/sgl-project/sglang/pull/18911). # GLM-5.2 Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-5.2 Deploy GLM-5.2 with SGLang — Z.ai's DeepSeek-Sparse-Attention (DSA) Mixture-of-Experts model with MTP speculative decoding and 1M context, on H200, B200, B300, GB300, and AMD MI300X/MI325X/MI355X, plus Ascend NPU recipes. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. > **Install and prepare Ascend NPUs** > > Use a Linux host with the Ascend driver and a compatible CANN / TorchNPU environment. Follow the > [Ascend installation guide](/docs/hardware-platforms/ascend-npus/getting-started/installation) and the > [GLM-5.2 deployment tutorial](/docs/hardware-platforms/ascend-npus/model-deployment/tutorials/glm_5_2#installation) to start a container with the NPU devices, driver mounts, and checkpoint directory. Run the setup and the generated **Python** command inside that container. > > **A3** > > ```bash Command theme={null} > docker pull quay.io/ascend/sglang:cann9.0.0-a3-v0.5.16 > ``` > > Run the following setup before copying the generated command (CANN 9.0.0). CPU tuning requires host privileges. > > ```bash Command theme={null} > unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY ASCEND_LAUNCH_BLOCKING > echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor > sysctl -w vm.swappiness=0 > sysctl -w kernel.numa_balancing=0 > sysctl -w kernel.sched_migration_cost_ns=50000 > source /usr/local/Ascend/ascend-toolkit/set_env.sh > source /usr/local/Ascend/nnal/atb/set_env.sh > ``` > > **950PR/DT series** > > Use the compatible 950PR/DT series SGLang checkout, CANN environment, and custom operators used for your deployment. Set `SGLANG_ROOT` to that checkout; these recipes do not prescribe an image tag. > > ```bash Command theme={null} > unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY ASCEND_LAUNCH_BLOCKING > unset HCCL_IF_IP HCCL_SOCKET_FAMILY RANK_TABLE_FILE > SGLANG_ROOT=/path/to/sglang > export PYTHONPATH="${SGLANG_ROOT}/python:${PYTHONPATH:-}" > ``` > > Replace the model path in the generated command with your mounted ModelSlim checkpoint directory. Include its configuration, tokenizer, quantization metadata, and MTP weights. > > For A3, use the locally prepared **GLM-5.2-w8a8** checkpoint described in the [model-weight prerequisites](/docs/hardware-platforms/ascend-npus/model-deployment/tutorials/glm_5_2#model-weights). > For 950PR/DT series, use your locally prepared GLM-5.2 **W8A8C8\_MXFP8** checkpoint, including MTP weights, and replace the model path in the generated command with its mounted path. > > Replace network placeholders such as ``, ``, and `` in the generated NPU command with your cluster settings. Pick your hardware + recipe to generate the launch command. The three serving strategies cover the common operating points: * **Low-Latency** — fastest reply for a single user. Pick for chat. * **Balanced** — good speed with several users at once. Use for typical multi-user serving. * **High-Throughput** — most tokens per second across many users. Best for batch jobs. > [!WARNING] > > All recipes here run the DSA indexer top-k on the default `--dsa-topk-backend sgl-kernel`. Other top-k backend choices have not been fully validated on GLM-5.2. > [!NOTE] > > Speed numbers are measured with `--random-range-ratio 1.0`, `--flush-cache`, on `main @ 09ca4fc` (H200 FP8 cells: `v0.5.14 @ 49e384ce`). Spec cells pin the EAGLE acceptance length via the serve env `SGLANG_SIMULATE_ACC_LEN` (low-latency 5-1-6 = 3.5; FP8 balanced 1-1-2 = 2; NVFP4 balanced 2-1-3 = 2); high-throughput has no spec. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## Agentic Long-Context Deployment Agentic workloads, such as coding agents and other multi-turn, tool-using assistants, send long prompts whose prefixes grow and repeat from turn to turn. Serving them well depends on reusing the KV cache across turns, offloading it beyond GPU memory, and keeping each session on the workers that already hold its prefix. This section gives complete launch commands for such deployments, each benchmarked in [SemiAnalysis InferenceX](https://inferencex.semianalysis.com/) and linked to the run that measured it. Pick a hardware platform, checkpoint, deployment shape, concurrency, KV cache offloading mechanism and router to get every process of the deployment as a raw command, one tab per process in launch order. * **Router.** Each configuration was submitted behind one front door: Dynamo (`dynamo.frontend` with `dynamo.sglang` workers) or SGLang (`sglang.launch_server`, behind `sglang_router` when there are several workers or DP-attention ranks). * **KV offload.** Choose among these KV cache offloading mechanisms: none (GPU KV only), HiCache (host DRAM), or a Mooncake store attached through the external linker. The Mooncake option needs an image whose SGLang build includes `--enable-unified-cache-external-linker`. * **Container image.** Run the commands inside the image listed for each configuration. Several are SGLang nightly images, so flag names follow that image. ## 1. Model Introduction **GLM-5.2** is Z.ai's flagship Mixture-of-Experts model built on **DeepSeek Sparse Attention (DSA)**: a lightning indexer selects a sparse set of key tokens per query (top-2048), so attention cost stays near-constant as context grows. It ships in two precisions — **FP8** (`zai-org/GLM-5.2-FP8`) and full **BF16** (`zai-org/GLM-5.2`) — both with **78 transformer layers**, **256 routed experts** (8 active per token), a **1M-token context window**, and a single **MTP (Multi-Token Prediction)** layer for built-in EAGLE-style speculative decoding. FP8 is the recommended deployment; BF16 (\~1.5 TB) needs an 8×B300 node or a multi-node setup. For Blackwell, NVIDIA also publishes an **NVFP4** build (`nvidia/GLM-5.2-NVFP4`) that quantizes only the MoE experts' linear weights and activations to 4-bit (the shared expert stays unquantized), holding accuracy within \~1 point of the FP8 baseline on GPQA Diamond, SciCode, and IFBench. For AMD MI355X (gfx950), AMD publishes an **MXFP4** build (`amd/GLM-5.2-MXFP4`, Quark-quantized) — see the AMD GPUs configuration tip below; this recipe is inferred from the validated `amd/GLM-5.1-MXFP4` MI355X recipe and not yet benchmarked on GLM-5.2 (`verified: false`).
Model Architecture Context
**[GLM-5.2-FP8](https://huggingface.co/zai-org/GLM-5.2-FP8)** MoE · DSA · 256 experts (top-8) · MTP · FP8 1,048,576
**[GLM-5.2](https://huggingface.co/zai-org/GLM-5.2)** MoE · DSA · 256 experts (top-8) · MTP · BF16 1,048,576
**[GLM-5.2-NVFP4](https://huggingface.co/nvidia/GLM-5.2-NVFP4)** MoE · DSA · 256 experts (top-8) · MTP · NVFP4 1,048,576
**[GLM-5.2-MXFP4](https://huggingface.co/amd/GLM-5.2-MXFP4)** MoE · DSA · 256 experts (top-8) · MTP · MXFP4 1,048,576
**Recommended generation:** `temperature=1.0`, `top_p=0.95` (the checkpoint's `generation_config.json` defaults; informational — do not hardcode in client code). **Resources:** [GLM-5.2-FP8](https://huggingface.co/zai-org/GLM-5.2-FP8) · [GLM-5.2 (BF16)](https://huggingface.co/zai-org/GLM-5.2) · [GLM-5.2-NVFP4](https://huggingface.co/nvidia/GLM-5.2-NVFP4) · [GLM-5.2-MXFP4](https://huggingface.co/amd/GLM-5.2-MXFP4). ## 2. Configuration Tips * **DeepSeek Sparse Attention (DSA).** GLM-5.2 uses the `glm_moe_dsa` architecture; SGLang auto-selects the DSA attention backends (`flashmla_sparse` prefill, `fa3` decode, `sgl-kernel` indexer topk). No attention-backend flag is needed on the supported hardware. SGLang also auto-selects the KV-cache dtype for DSA models — `fp8_e4m3` on Blackwell (B200/GB300/B300, which then routes DSA through the TensorRT-LLM backend) and `bf16` on Hopper (H200) — so no `--kv-cache-dtype` flag is required. On Hopper, pairing `--kv-cache-dtype fp8_e4m3` with `--dsa-prefill-backend flashmla_sparse_q8 --dsa-decode-backend flashmla_kv` selects the native FP8 sparse prefill kernel (computes directly on the fp8 KV cache with no fp8→bf16 dequantization round-trip; GLM-5.2's 64 query heads match the kernel's native tile) — see the [DeepSeek-V3.2 page](../DeepSeek/DeepSeek-V3_2) for kernel details; the optional `SGLANG_ENABLE_DSA_Q8KV8_*` performance env vars are documented in `python/sglang/srt/environ.py`. * **MTP / speculative decoding.** The checkpoint ships one nextn layer. Enable EAGLE MTP for lower latency (`--speculative-algorithm EAGLE --speculative-num-steps 5 --speculative-eagle-topk 1 --speculative-num-draft-tokens 6` for low-latency; `1-1-2` for balanced). The config's `index_share_for_mtp_iteration` reuses the DSA indexer's topk across draft steps (effective only at `--speculative-eagle-topk 1`). **Tune the draft length to the accept length.** GLM-5.2's MTP head is strong — accept length runs high (4+ in many workloads, near-saturating at 5–6 in low-latency runs). Watch the server's reported **accept length** and adjust `--speculative-num-steps` / `--speculative-num-draft-tokens` accordingly: while accept length stays close to the draft-token count there is headroom to push them higher (more accepted tokens per step); if it falls well below, lower them — every rejected draft token is wasted verification compute. * **Memory.** The FP8 weights are large (MoE total, not active params). Start around `--mem-fraction-static 0.8` on H200 (TP8) and tune up; raise it for the 4-GPU GB300 single-node layout (TP4). * **DP-Attention + DeepEP** for the balanced/high-throughput strategies spreads attention across data-parallel ranks and routes MoE through DeepEP. * **BF16 weights need more GPUs.** The full-precision build (`zai-org/GLM-5.2`, \~1.5 TB) does not fit a single 8×H200 / 8×B200 / 4×GB300 node. It fits single-node on **8×B300** (TP8, \~2.1 TB HBM) — **verified**; on the smaller GPUs it needs a **multi-node** layout (e.g. 2×8×H200 or 2×8×B200 at TP16, 2×4×GB300 at TP8), and those **multi-node BF16 recipes are still proposed/inferred** (`verified: false`). FP8 is the recommended deployment. Use the same DSA / MTP / chunked-prefill guidance as FP8. On B300, BF16 low-latency matches FP8 (the sm103 FP8 path is not yet optimized), but FP8 wins at the balanced/high-throughput points. * **PD Disaggregation (prefill/decode).** GLM-5.2 is a DSA model and runs under prefill/decode disaggregation — toggle the **PD Disagg** card in the [Playground above](#playground) (pick a Prefill/Decode role + transfer backend, then front the roles with `sglang_router.launch_router --pd-disaggregation`). The Mooncake backend **auto-detects the InfiniBand HCA**, so no device flag is needed by default; only add `--disaggregation-ib-device mlx5_0` (your NIC) if auto-detection picks the wrong device or KV transfer fails to connect. On H200 Docker, expose the IB HCAs to the container (`--privileged --ulimit memlock=-1`, or `--device /dev/infiniband:/dev/infiniband --cap-add IPC_LOCK`) — without IB exposure Mooncake silently falls back to TCP. * **Chunked-prefill size is regime-dependent.** At long input (8K+) the default `--chunked-prefill-size 2048` is too small and leaves the balanced point prefill-bound (queueing dominates TTFT). Raising it to `--chunked-prefill-size 32768` on the balanced recipe gave roughly **+34–78% output throughput and −39–59% TTFT** on 8×H200 and 8×B200 (8K-in / 1K-out) in our testing. It is **neutral for high-throughput** (decode-bound there) — keep the default. `--max-running-requests` tracks KV capacity, not a tuning free-for-all: \~60–90 concurrent 8K+1K FP8 requests fit on a single 8-GPU node, so pin balanced near `--max-running-requests 80` and let high-throughput run wider. * **AMD GPUs (MI300X / MI325X / MI355X).** FP8 (`zai-org/GLM-5.2-FP8`) runs single-node at `tp=8` on all three. BF16 (`zai-org/GLM-5.2`, \~1.51 TB) only fits single-node on **MI325X** (2 TB HBM) and **MI355X** (2.3 TB); **MI300X** (1.5 TB) cannot hold the BF16 weights plus KV cache on one node, so use FP8 there (or a multi-node BF16 layout once validated). Use the DSA tilelang backend (`--dsa-prefill-backend tilelang --dsa-decode-backend tilelang`) and add `--chunked-prefill-size 131072` plus `--watchdog-timeout 1200` (20 min for weight loading). FP8 uses about half the memory of BF16 (\~89 GB/GPU vs \~175 GB/GPU). GLM-5.2 and DeepSeek-V3.2 share the same model structure; for other DSA / HiSparse tips see the [DeepSeek-V3.2 cookbook](../DeepSeek/DeepSeek-V3_2). * **MI355X MXFP4 (gfx950-only).** AMD publishes a Quark-quantized **`amd/GLM-5.2-MXFP4`** build for MI355X. It needs `--trust-remote-code` (Quark's custom quant config) and runs at `tp=4` (the 4-bit MoE weights fit a 4-GPU slice) with `--kv-cache-dtype fp8_e4m3`, the DSA triton backends (`--dsa-prefill-backend triton --dsa-decode-backend triton`, also SGLang's ROCm default), and the same `--chunked-prefill-size` and `--watchdog-timeout` as the FP8/BF16 recipes above. At `tp=4` this shape — 16 query heads per rank on an FP8 KV cache — is the one the gfx950 sparse-MLA kernels are tuned for; the `tp=8` recipes above stay on tilelang, which is what their published numbers were measured with. This recipe is carried over from the validated `amd/GLM-5.1-MXFP4` MI355X deployment (same DSA architecture family) and has not yet been benchmarked on GLM-5.2, so the Deploy panel marks it unverified. > [!NOTE] > > **gfx950 block-FP8 accuracy: fixed as of the pinned MI355X image (`v0.5.13.post1-rocm720-mi35x-20260618`).** Earlier SGLang ROCm images miscompiled AMD aiter's `gemm_a8w8_blockscale_bpreshuffle` GEMM on gfx950 (ROCm 7.2): the error was small per layer but compounded across all 78 layers and silently corrupted output — in-context reasoning broke (GSM8K ≈ 0) while short factual prompts still looked fine. The root cause was a gfx950/ROCm-7.2 miscompile of the CK kernel (a packed illegal-type FMA that relied on an LLVM coercion pass removed in ROCm 7.2; non-deterministic wrong rows near tile boundaries). This is resolved in the pinned image and newer: GLM-5.2-FP8 on MI350X/MI355X (gfx950) was re-validated at TP4 and TP8 — **GSM8K ≈ 0.96 (0% invalid)** and **15/15 needle-in-haystack retrieval to \~118K tokens**. **MI300X / MI325X (gfx942) were never affected.** If you must run an older image, treat gfx950 FP8 output as unverified. Background: [sgl-project/sglang#28685](https://github.com/sgl-project/sglang/issues/28685) (analysis) and the upstream CK fix [ROCm/rocm-libraries#8639](https://github.com/ROCm/rocm-libraries/pull/8639) (scalar FMA + accumulator anchor; restores correctness and determinism at -O3). * **MTP / EAGLE speculative decoding on AMD.** Five-step MTP is validated for `amd/GLM-5.2-MXFP4` on MI355X with `lmsysorg/sglang-rocm:v0.5.20-rocm720-mi35x-20260930`. Choose **Low-Latency** for TP8/EP1, or **High-Throughput** for TP4/EP4 with HiCache (`--enable-hierarchical-cache --hicache-ratio 1.0`). HiCache uses the default `kernel`, `page_first`, and `write_through` settings. MTP remains unvalidated for GLM-5.2 on MI300X/MI325X and for the other MI355X checkpoint precisions. ## 3. Advanced Usage ### 3.1 Reasoning GLM-5.2 is a hybrid-reasoning model. Enable the `glm45` reasoning parser (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to separate thinking from the final answer — thinking lands in `message.reasoning_content`, the answer in `message.content`. Thinking is on by default; turn it off with `chat_template_kwargs: {"enable_thinking": False}` (the template variable is `enable_thinking`, not `thinking`). **Reasoning effort.** Pass `chat_template_kwargs: {"reasoning_effort": ...}` to inject a `Reasoning Effort: ` system line (only while thinking is on). **The template wires only two effective levels — `Max` and `High` — and if you don't pass `reasoning_effort` at all you get `Max`, the highest.** `"high"` is the *only* value that lowers effort; every other value (including `"low"` and `"medium"`) falls through to `Max`: | `reasoning_effort` | Injected system line | Effect | | - | - | - | | *(not passed / unset)* | `Reasoning Effort: Max` | **default — highest reasoning** | | `"high"` | `Reasoning Effort: High` | dials reasoning **down** | | `"low"`, `"medium"`, any other value | `Reasoning Effort: Max` | falls through to `Max` (not a distinct level) | > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="zai-org/GLM-5.2-FP8", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > extra_body={"chat_template_kwargs": {"enable_thinking": True, "reasoning_effort": "high"}}, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: 1. **Identify the core question:** The user wants to find 15% of 240. > 2. **Convert the percentage to a decimal:** 15% = 0.15 > 3. **Multiply by the total:** 0.15 * 240 = 36 > (Quick mental math: 10% of 240 = 24; 5% = 12; 24 + 12 = 36.) > > Answer: 15% of 240 is **36**. > > Here is how you can calculate it: > 0.15 × 240 = 36 > ``` ### 3.2 Tool Calling Enable the `glm47` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. GLM-5.2 emits the newer `………` format, so it needs the **`glm47`** parser — the older `glm45` parser does not parse it (the call would be left as raw text in `content`). On thinking mode the turn also fills `reasoning_content`, so print both fields. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string"}}, > "required": ["city"], > }, > }, > }] > resp = client.chat.completions.create( > model="zai-org/GLM-5.2-FP8", > messages=[{"role": "user", "content": "What's the weather in Paris?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user wants to know the weather in Paris. I'll call the get_weather function with "Paris" as the city. > > Tool calls: [ > { > "id": "call_13fcd52146934b7781d06d4a", > "type": "function", > "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"} > } > ] > ``` ### 3.3 HiCache (Hierarchical KV Caching) For long-context, prefix-heavy workloads, enable hierarchical KV caching to spill cold KV blocks to host memory (toggle the **Hierarchical KV Cache** card in the [Playground above](#playground)). Useful given GLM-5.2's 1M-token window; pair `--hicache-ratio` with a write policy that matches your reuse pattern. ### 3.4 Claude Code Integration GLM-5.2's strong reasoning + tool-calling makes it a good backend for [Claude Code](https://code.claude.com/docs/en/overview), Anthropic's agentic CLI. SGLang exposes the Anthropic-compatible `/v1/messages` endpoint on every server, so Claude Code can talk to a GLM-5.2 server with only environment variables — no code change. Launch the server with `--reasoning-parser glm45 --tool-call-parser glm47` (any recipe from the Deployment panel above works), then: ```bash Command theme={null} export ANTHROPIC_BASE_URL="http://127.0.0.1:30000" export ANTHROPIC_AUTH_TOKEN="dummy" export API_TIMEOUT_MS="3000000" export CLAUDE_CODE_AUTO_COMPACT_WINDOW="1000000" export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 export CLAUDE_CODE_ATTRIBUTION_HEADER=0 export ANTHROPIC_DEFAULT_HAIKU_MODEL="glm-5.2[1m]" export ANTHROPIC_DEFAULT_SONNET_MODEL="glm-5.2[1m]" export ANTHROPIC_DEFAULT_OPUS_MODEL="glm-5.2[1m]" claude ``` Two of these matter specifically for GLM-5.2: * **`CLAUDE_CODE_ATTRIBUTION_HEADER=0`** — Claude Code prepends a per-request attribution block to the system prompt. GLM-5.2's chat template renders `tools` **before** `system`, so that per-request hash is the first token to diverge between turns and the radix prefix cache re-prefills the whole system + history every turn. This env removes the block and restores prefix-cache reuse. * **`glm-5.2[1m]`** as the model name — the `[1m]` suffix is the client-side hint that enables Claude Code's 1M-context beta, matching GLM-5.2's 1,048,576-token window. Without it, context is capped well below 1M. SGLang does not validate the `model` field, so any name is accepted server-side. For the full setup (streaming, tool-use, count\_tokens, persisting env in `~/.claude/settings.json`, troubleshooting), see [Anthropic-Compatible API](../../../docs/basic_usage/anthropic_api). ### 3.5 Context Parallelism > [!WARNING] > > Zigzag prefill CP (`--cp-strategy zigzag`) is temporarily unavailable for GLM-5.2. For prefill CP on CUDA, use `interleave` as shown below. Attention DP is supported: each DP group uses `tp_size / attn_dp_size` CP ranks. Dense FFNs retain the configured TP width; use `--moe-dense-tp-size 1` for local dense computation. Prefill context parallelism can help with reduction of TTFT under long context. To enable prefill context parallelism for GLM 5.2, please append the following arguments: ```bash theme={null} --attn-cp-size 8 \ --enable-prefill-cp \ --cp-strategy interleave \ ``` which splits the sequence equally across `--attn-cp-size` ranks during attention forward. The trade off for prefill CP is that it will introduce extra all-gather operation before indexer-topk and attention kernels, so it will increase latency for decode (in unified deployment) or short prefill. When deploying with PD Disaggregation, the prefill node can choose to enable [LayerSplit](https://z.ai/blog/scaling-pain) technique with ```bash theme={null} --enable-dsa-cache-layer-split \ --attn-cp-size 8 \ --cp-strategy interleave \ ``` With LayerSplit, the kv cache on each rank can be sharded over the CP attention group, and prefetched when necessary. This can reduce kv cache memory by up to 75%, thus increasing the throughput on prefill side. # GLM-5.3 Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-5.3 Deploy GLM-5.3 with SGLang — Z.ai's DeepSeek-Sparse-Attention (DSA) Mixture-of-Experts model with MTP speculative decoding and 1M context, on H200, B200, B300, GB300, and AMD MI300X/MI325X/MI355X, plus Ascend NPU recipes. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. > **Install and prepare Ascend NPUs** > > Use a Linux host with the Ascend driver and a compatible CANN / TorchNPU environment. Follow the > [Ascend installation guide](/docs/hardware-platforms/ascend-npus/getting-started/installation) and the > [GLM-5.3 deployment tutorial](/docs/hardware-platforms/ascend-npus/model-deployment/tutorials/glm_5_3#installation) to start a container with the NPU devices, driver mounts, and checkpoint directory. Run the setup and the generated **Python** command inside that container. > > **A3** > > ```bash Command theme={null} > docker pull quay.io/ascend/sglang:cann9.1.0-a3-B080 > ``` > > This CANN 9.1.0 image requires a compatible SGLang build, TorchNPU, ATB, and custom operators before serving. Set `SGLANG_ROOT` to that source checkout. > > Run the following setup before copying the generated command (CANN 9.1.0). CPU tuning requires host privileges. > > ```bash Command theme={null} > unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY ASCEND_LAUNCH_BLOCKING > echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor > sysctl -w vm.swappiness=0 > sysctl -w kernel.numa_balancing=0 > sysctl -w kernel.sched_migration_cost_ns=50000 > source /usr/local/Ascend/ascend-toolkit/set_env.sh > source /usr/local/Ascend/nnal/atb/set_env.sh > source /usr/local/Ascend/cann-9.1.0/opp/vendors/customize/bin/set_env.bash > SGLANG_ROOT=/path/to/sglang > export PYTHONPATH="${SGLANG_ROOT}/python:${PYTHONPATH:-}" > export LD_LIBRARY_PATH="/usr/local/Ascend/ascend-toolkit/latest/opp/vendors/customize/op_api/lib:${LD_LIBRARY_PATH:-}" > ``` > > **950PR/DT series** > > Use the compatible 950PR/DT series SGLang checkout, CANN environment, and custom operators used for your deployment. Set `SGLANG_ROOT` to that checkout; these recipes do not prescribe an image tag. > > ```bash Command theme={null} > unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY ASCEND_LAUNCH_BLOCKING > unset HCCL_IF_IP HCCL_SOCKET_FAMILY RANK_TABLE_FILE > SGLANG_ROOT=/path/to/sglang > export PYTHONPATH="${SGLANG_ROOT}/python:${PYTHONPATH:-}" > ``` > > Replace the model path in the generated command with your mounted ModelSlim checkpoint directory. Include its configuration, tokenizer, quantization metadata, and MTP weights. > > Use a locally prepared **W8A8** checkpoint for A3. On 950PR/DT series, both unified serving and PD disaggregation use the same **W8A8C8\_MXFP8** checkpoint. Both 950PR/DT series recipes explicitly use FP8 E4M3 KV cache and BF16 draft KV cache. > > Replace network placeholders such as ``, ``, and `` in the generated NPU command with your cluster settings. Pick your hardware + recipe to generate the launch command. The three serving strategies cover the common operating points: * **Low-Latency** — fastest reply for a single user. Pick for chat. * **Balanced** — good speed with several users at once. Use for typical multi-user serving. * **High-Throughput** — most tokens per second across many users. Best for batch jobs. > [!WARNING] > > All recipes here run the DSA indexer top-k on the default `--dsa-topk-backend sgl-kernel`. Other top-k backend choices have not been fully validated on GLM-5.3. ## Playground The Playground is where you experiment with **SGLang features beyond the deployment matrix**. It lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## Agentic Long-Context Deployment Agentic workloads, such as coding agents and other multi-turn, tool-using assistants, send long prompts whose prefixes grow and repeat from turn to turn. Serving them well depends on reusing the KV cache across turns, offloading it beyond GPU memory, and keeping each session on the workers that already hold its prefix. This section gives complete launch commands for such deployments, each benchmarked in [SemiAnalysis InferenceX](https://inferencex.semianalysis.com/) and linked to the run that measured it. Pick a hardware platform, checkpoint, deployment shape, concurrency, KV cache offloading mechanism and router to get every process of the deployment as a raw command, one tab per process in launch order. * **Router.** Each configuration was submitted behind one front door: Dynamo (`dynamo.frontend` with `dynamo.sglang` workers) or SGLang (`sglang.launch_server`, behind `sglang_router` when there are several workers or DP-attention ranks). * **KV offload.** Choose among these KV cache offloading mechanisms: none (GPU KV only), HiCache (host DRAM), or a Mooncake store attached through the external linker. The Mooncake option needs an image whose SGLang build includes `--enable-unified-cache-external-linker`. * **Container image.** Run the commands inside the image listed for each configuration. Several are SGLang nightly images, so flag names follow that image. ## 1. Model Introduction **GLM-5.3** is Z.ai's flagship Mixture-of-Experts model built on **DeepSeek Sparse Attention (DSA)**: a lightning indexer selects a sparse set of key tokens per query (top-2048), so attention cost stays near-constant as context grows. It keeps the same base architecture while updating post-training for complex coding and long-horizon tasks. It ships in two precisions — **FP8** (`zai-org/GLM-5.3`) and full **BF16** (`zai-org/GLM-5.3-BF16`) — both with **78 transformer layers**, **256 routed experts** (8 active per token), a **1M-token context window**, and a single **MTP (Multi-Token Prediction)** layer for built-in EAGLE-style speculative decoding. FP8 is the recommended deployment; BF16 (\~1.5 TB) needs an 8×B300 node or a multi-node setup. For Blackwell, RadixArk publishes an **experimental NVFP4** build (`RadixArk/GLM-5.3-NVFP4`, Model Optimizer) that quantizes only the routed experts' linear weights and activations to 4-bit (attention, shared experts, dense layers, MTP, embeddings, and the LM head stay unquantized), cutting the weight footprint to \~0.45 TB so a 4-GPU GB300 node can serve it with TP4. **The NVFP4 cells are experimental** — benchmark data (accuracy / throughput) is still pending; treat them as provisional until the benchmark cards fill in.
Model Architecture Context
**[GLM-5.3](https://huggingface.co/zai-org/GLM-5.3)** MoE · DSA · 256 experts (top-8) · MTP · FP8 1,048,576
**[GLM-5.3-BF16](https://huggingface.co/zai-org/GLM-5.3-BF16)** MoE · DSA · 256 experts (top-8) · MTP · BF16 1,048,576
**[GLM-5.3-NVFP4](https://huggingface.co/RadixArk/GLM-5.3-NVFP4)** MoE · DSA · 256 experts (top-8) · MTP · NVFP4 1,048,576
**Recommended generation:** `temperature=1.0`, `top_p=0.95` (the checkpoint's `generation_config.json` defaults; informational — do not hardcode in client code). **Resources:** [GLM-5.3](https://huggingface.co/zai-org/GLM-5.3) · [GLM-5.3-BF16](https://huggingface.co/zai-org/GLM-5.3-BF16) · [GLM-5.3-NVFP4](https://huggingface.co/RadixArk/GLM-5.3-NVFP4). ## 2. Configuration Tips * **DeepSeek Sparse Attention (DSA).** GLM-5.3 uses the `glm_moe_dsa` architecture; SGLang auto-selects the DSA attention backends (`flashmla_sparse` prefill, `fa3` decode, `sgl-kernel` indexer topk). No attention-backend flag is needed on the supported hardware. SGLang also auto-selects the KV-cache dtype for DSA models — `fp8_e4m3` on Blackwell (B200/GB300/B300, which then routes DSA through the TensorRT-LLM backend) and `bf16` on Hopper (H200) — so no `--kv-cache-dtype` flag is required. On Hopper, pairing `--kv-cache-dtype fp8_e4m3` with `--dsa-prefill-backend flashmla_sparse_q8 --dsa-decode-backend flashmla_kv` selects the native FP8 sparse prefill kernel (computes directly on the fp8 KV cache with no fp8→bf16 dequantization round-trip; GLM-5.3's 64 query heads match the kernel's native tile) — see the [DeepSeek-V3.2 page](../DeepSeek/DeepSeek-V3_2) for kernel details; the optional `SGLANG_ENABLE_DSA_Q8KV8_*` performance env vars are documented in `python/sglang/srt/environ.py`. * **MTP / speculative decoding.** The checkpoint ships one nextn layer. Enable EAGLE MTP for lower latency (`--speculative-algorithm EAGLE --speculative-num-steps 5 --speculative-eagle-topk 1 --speculative-num-draft-tokens 6` for low-latency; `1-1-2` for balanced). The config's `index_share_for_mtp_iteration` reuses the DSA indexer's topk across draft steps (effective only at `--speculative-eagle-topk 1`). Watch the server's reported **accept length** and adjust `--speculative-num-steps` / `--speculative-num-draft-tokens`: lower the draft length when rejected draft tokens create excess verification work. * **DFlash2 (block-diffusion draft).** The **Speculative** card in the [Playground above](#playground) also offers **DFlash2**, which replaces the in-checkpoint MTP layer with the separately trained block-diffusion drafter [`incoai/GLM-5.3-DFlash2`](https://huggingface.co/incoai/GLM-5.3-DFlash2). It proposes a whole block per step and the target verifies the block in one forward pass, so output quality stays the target's. The block size — 8, i.e. 7 draft tokens per verification step — comes from the draft checkpoint's own `dflash_config`, so no `--speculative-num-draft-tokens` is passed; the draft is a small dense model and runs on `fa4` instead of the target's DSA backends. Note that DFLASH runs on **CUDA/NPU only** and rejects **DP-Attention**, so turn DP-Attention off in the **Attention** card before selecting it on a high-throughput base. The draft repository is public but licensed CC BY-NC-ND 4.0 for research and evaluation. * **Memory.** The FP8 weights are large (MoE total, not active params). Start around `--mem-fraction-static 0.8` on H200 (TP8) and tune up; raise it for the 4-GPU GB300 single-node layout (TP4). * **DP-Attention + DeepEP** for the balanced/high-throughput strategies spreads attention across data-parallel ranks and routes MoE through DeepEP. * **BF16 weights need more GPUs.** The full-precision build (`zai-org/GLM-5.3-BF16`, \~1.5 TB) does not fit a single 8×H200 / 8×B200 / 4×GB300 node. It fits single-node on **8×B300** (TP8, \~2.1 TB HBM); on the smaller GPUs it needs a **multi-node** layout (e.g. 2×8×H200 or 2×8×B200 at TP16, 2×4×GB300 at TP8). FP8 is the recommended deployment. Use the same DSA / MTP / chunked-prefill guidance as FP8. * **PD Disaggregation (prefill/decode).** GLM-5.3 is a DSA model and runs under prefill/decode disaggregation — toggle the **PD Disagg** card in the [Playground above](#playground) (pick a Prefill/Decode role + transfer backend, then front the roles with `sglang_router.launch_router --pd-disaggregation`). The Mooncake backend **auto-detects the InfiniBand HCA**, so no device flag is needed by default; only add `--disaggregation-ib-device mlx5_0` (your NIC) if auto-detection picks the wrong device or KV transfer fails to connect. On H200 Docker, expose the IB HCAs to the container (`--privileged --ulimit memlock=-1`, or `--device /dev/infiniband:/dev/infiniband --cap-add IPC_LOCK`) — without IB exposure Mooncake silently falls back to TCP. * **Chunked-prefill size is regime-dependent.** For long-input balanced workloads, start with `--chunked-prefill-size 32768` and tune it together with `--max-running-requests` for your input length and KV capacity. Keep the default chunked-prefill size for the high-throughput recipe unless profiling shows that prefill is the bottleneck. * **AMD GPUs (MI300X / MI325X / MI355X).** FP8 (`zai-org/GLM-5.3`) runs single-node at `tp=8` on all three. BF16 (`zai-org/GLM-5.3-BF16`, \~1.51 TB) only fits single-node on **MI325X** (2 TB HBM) and **MI355X** (2.3 TB); **MI300X** (1.5 TB) cannot hold the BF16 weights plus KV cache on one node, so use FP8 there. Use the DSA tilelang backend (`--dsa-prefill-backend tilelang --dsa-decode-backend tilelang`) and add `--chunked-prefill-size 131072` plus `--watchdog-timeout 1200` (20 min for weight loading). GLM-5.3 and DeepSeek-V3.2 share the same model structure; for other DSA / HiSparse tips see the [DeepSeek-V3.2 cookbook](../DeepSeek/DeepSeek-V3_2). * **MTP / EAGLE speculative decoding** is disabled for AMD in the Deploy panel because the gfx950 spec-decode draft kernel is not yet validated on this hardware (and at `--speculative-num-steps > 3` hits a separate build issue). Until MTP is validated on gfx950, omit the `--speculative-*` flags and serve without MTP. ## 3. Advanced Usage ### 3.1 Reasoning GLM-5.3 is a reasoning model, and generated commands enable `--reasoning-parser auto` (which resolves to `glm45` for GLM-5.3) by default so thinking is separated from the final answer — thinking lands in `message.reasoning_content`, the answer in `message.content`. Without the parser the server returns the thinking and the answer as one `content` string with a stray `` between them, because the chat template opens `` in the generation prompt. You can disable **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground) when an integration needs that raw format. The chat template defaults `clear_thinking` to `false`; for multi-turn chat, pass `chat_template_kwargs: {"clear_thinking": True}` so previous reasoning is cleared before the next response. **Reasoning effort.** Pass `chat_template_kwargs: {"reasoning_effort": ...}` to select `low`, `high`, or `max`. If you omit it or pass another value, the template uses `max`. | `reasoning_effort` | Injected system line | Effect | | - | - | - | | *(not passed / unset)*, `"max"` | `Reasoning Effort: Max` | default — highest reasoning effort | | `"high"` | `Reasoning Effort: High` | high reasoning effort | | `"low"` | `Reasoning Effort: Low` | low reasoning effort | | any other value | `Reasoning Effort: Max` | falls back to the default | > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="zai-org/GLM-5.3", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > extra_body={"chat_template_kwargs": {"clear_thinking": True, "reasoning_effort": "high"}}, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: 1. **Identify the core question:** The user wants to find 15% of 240. > 2. **Convert the percentage to a decimal:** 15% = 0.15 > 3. **Multiply by the total:** 0.15 * 240 = 36 > (Quick mental math: 10% of 240 = 24; 5% = 12; 24 + 12 = 36.) > > Answer: 15% of 240 is **36**. > > Here is how you can calculate it: > 0.15 × 240 = 36 > ``` ### 3.2 Tool Calling Generated commands enable `--tool-call-parser auto` by default, so structured calls are returned in `message.tool_calls` with `finish_reason: "tool_calls"`. `auto` resolves to **`glm47`** for GLM-5.3: the model emits the newer `………` format, which the older `glm45` parser does not parse (the call would be left as raw text in `content`). Running with no tool-call parser fails the same way, and `finish_reason` stays `"stop"`, so an agent loop never sees the call. You can disable **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground) when tool calling is not needed. On thinking mode the turn also fills `reasoning_content`, so print both fields. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string"}}, > "required": ["city"], > }, > }, > }] > resp = client.chat.completions.create( > model="zai-org/GLM-5.3", > messages=[{"role": "user", "content": "What's the weather in Paris?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user wants to know the weather in Paris. I'll call the get_weather function with "Paris" as the city. > > Tool calls: [ > { > "id": "call_13fcd52146934b7781d06d4a", > "type": "function", > "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"} > } > ] > ``` ### 3.3 HiCache (Hierarchical KV Caching) For long-context, prefix-heavy workloads, enable hierarchical KV caching to spill cold KV blocks to host memory (toggle the **Hierarchical KV Cache** card in the [Playground above](#playground)). Useful given GLM-5.3's 1M-token window; pair `--hicache-ratio` with a write policy that matches your reuse pattern. ### 3.4 Claude Code Integration GLM-5.3's strong reasoning + tool-calling makes it a good backend for [Claude Code](https://code.claude.com/docs/en/overview), Anthropic's agentic CLI. SGLang exposes the Anthropic-compatible `/v1/messages` endpoint on every server, so Claude Code can talk to a GLM-5.3 server with only environment variables — no code change. Launch the server with `--reasoning-parser auto --tool-call-parser auto` (any recipe from the Deployment panel above works), then: ```bash Command theme={null} export ANTHROPIC_BASE_URL="http://127.0.0.1:30000" export ANTHROPIC_AUTH_TOKEN="dummy" export API_TIMEOUT_MS="3000000" export CLAUDE_CODE_AUTO_COMPACT_WINDOW="1000000" export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 export CLAUDE_CODE_ATTRIBUTION_HEADER=0 export ANTHROPIC_DEFAULT_HAIKU_MODEL="glm-5.3[1m]" export ANTHROPIC_DEFAULT_SONNET_MODEL="glm-5.3[1m]" export ANTHROPIC_DEFAULT_OPUS_MODEL="glm-5.3[1m]" claude ``` Two of these matter specifically for GLM-5.3: * **`CLAUDE_CODE_ATTRIBUTION_HEADER=0`** — Claude Code prepends a per-request attribution block to the system prompt. GLM-5.3's chat template renders `tools` **before** `system`, so that per-request hash is the first token to diverge between turns and the radix prefix cache re-prefills the whole system + history every turn. This env removes the block and restores prefix-cache reuse. * **`glm-5.3[1m]`** as the model name — the `[1m]` suffix is the client-side hint that enables Claude Code's 1M-context beta, matching GLM-5.3's 1,048,576-token window. Without it, context is capped well below 1M. SGLang does not validate the `model` field, so any name is accepted server-side. For the full setup (streaming, tool-use, count\_tokens, persisting env in `~/.claude/settings.json`, troubleshooting), see [Anthropic-Compatible API](../../../docs/basic_usage/anthropic_api). ### 3.5 Context Parallelism > [!WARNING] > > Zigzag prefill CP (`--cp-strategy zigzag`) is temporarily unavailable for GLM-5.3. For prefill CP on CUDA, use `interleave` as shown below. Prefill context parallelism can help with reduction of TTFT under long context. To enable prefill context parallelism for GLM 5.3, please append the following arguments: ```bash theme={null} --attn-cp-size 8 \ --enable-prefill-cp \ --cp-strategy interleave \ ``` which splits the sequence equally across `--attn-cp-size` ranks during attention forward. The trade off for prefill CP is that it will introduce extra all-gather operation before indexer-topk and attention kernels, so it will increase latency for decode (in unified deployment) or short prefill. You can combine interleave CP with attention DP. Each attention-DP group owns `tp_size / attn_dp_size` CP ranks; for example, `--tp 8 --attn-dp-size 2` uses CP4 within each DP group. Dense FFNs retain their configured TP width: the default runs them over the full TP group, while `--moe-dense-tp-size 1` runs them independently on local token shards. When deploying with PD Disaggregation, a **prefill worker using the Mooncake transfer backend** can enable the [LayerSplit](https://z.ai/blog/scaling-pain) technique with ```bash theme={null} --enable-dsa-cache-layer-split \ --enable-prefill-cp \ --attn-cp-size 8 \ --cp-strategy interleave \ ``` With LayerSplit, the kv cache on each rank can be sharded over the CP attention group, and prefetched when necessary. This can reduce kv cache memory by up to 75%, thus increasing the throughput on prefill side. # GLM-5.3-Flash Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-5.3-Flash Deploy GLM-5.3-Flash with SGLang using recipes for H100, H200, B200, B300, GB200, GB300, MI355X, and TPU7x, with MTP and multimodal serving, plus Ascend A3 and 950PR/DT series NPU recipes. ## Deployment > **Install SGLang** > > Use an SGLang build that includes GLM-5.3-Flash support (v0.5.20 or later). > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > For the listed NVIDIA hardware, the deployment panel can render a complete `docker run` command. See [Install SGLang with Docker](/docs/get-started/install#method-3-using-docker) for host setup. > > For MI355X, follow the [AMD GPU installation guide](/docs/hardware-platforms/amd_gpu) and run the generated **Python** command on four GPUs. Select FP8 or [MXFP4](https://huggingface.co/OneNexus/GLM-5.3-Flash-MXFP4); SGLang downloads the model and tokenizer automatically. > > For TPU7x, install [sglang-torchtpu](https://github.com/sgl-project/sglang-torchtpu) from source (its `main` branch; the `v0.1.0-tpu` image predates the GLM-5.3-Flash MTP fixes) and run the generated **Python** command on one TPU7x host with 4 chips: > > ```bash Command theme={null} > git clone https://github.com/sgl-project/sglang-torchtpu.git > cd sglang-torchtpu > cp python/pyproject_tpu.toml python/pyproject.toml > pip install --extra-index-url https://download.pytorch.org/whl/cpu -e python/ > pip install --no-deps -e . > ``` > **Install and prepare Ascend NPUs** > > Use a Linux host with the Ascend driver and a compatible CANN / TorchNPU environment. Follow the > [Ascend installation guide](/docs/hardware-platforms/ascend-npus/getting-started/installation) and the > [GLM-5.3-Flash deployment tutorial](/docs/hardware-platforms/ascend-npus/model-deployment/tutorials/glm_5_3_flash#installation) to start a container with the NPU devices, driver mounts, and checkpoint directory. Run the setup and the generated **Python** command inside that container. > > **A3** > > ```bash Command theme={null} > docker pull swr.cn-southwest-2.myhuaweicloud.com/base_image/dockerhub/lmsysorg/sglang:cann9.1.0-a3-glm5.3-flash > ``` > > Run the following setup before copying the generated command (CANN 9.1.0). CPU tuning requires host privileges. > > ```bash Command theme={null} > unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY ASCEND_LAUNCH_BLOCKING > source /usr/local/Ascend/ascend-toolkit/set_env.sh > source /usr/local/Ascend/nnal/atb/set_env.sh > source /usr/local/Ascend/cann-9.1.0/opp/vendors/customize/bin/set_env.bash > ``` > > **950PR/DT series** > > Use a CANN 9.1.0 SGLang image with the custom operators and MemFabric runtime required by the tutorial; PD mode also requires DP-attention support. The tutorial does not specify a 950PR/DT series image tag. > > ```bash Command theme={null} > NPU_IMAGE="" > docker pull "$NPU_IMAGE" > ``` > > ```bash Command theme={null} > unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY all_proxy ALL_PROXY ASCEND_LAUNCH_BLOCKING > source /usr/local/Ascend/ascend-toolkit/set_env.sh > source /usr/local/Ascend/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash > source /usr/local/Ascend/ascend-toolkit/latest/opp/vendors/custom_transformer/bin/set_env.bash > source /usr/local/memfabric_hybrid/set_env.sh > ``` > > Replace the model path in the generated command with your mounted ModelSlim checkpoint directory. Include its configuration, tokenizer, quantization metadata, and MTP weights. > > Use [W8A8](https://www.modelscope.cn/models/Eco-Tech/GLM-5.3-Flash-w8a8) for A3 and [W8A8\_MXFP8](https://www.modelscope.cn/models/Eco-Tech/GLM-5.3-Flash-w8a8-mxfp8) for 950PR/DT series. > > Replace network placeholders such as ``, ``, and `` in the generated NPU command with your cluster settings. The cookbook opens on **B300**. Choose your hardware, then choose the operating point that matches your workload: * **Low Latency** starts with MTP 5/1/6 speculative decoding and tensor parallelism to shorten interactive responses. * **High Throughput** starts with speculative decoding off, which avoids draft-and-verify overhead under sustained batches. Every listed GPU platform exposes both strategies; TPU7x has a Low Latency recipe only. A **Verified** badge means that exact hardware and command were tested. **Final Verification In Progress** means the recipe runs and is queued for measurement on the final weights. **Not Verified** means the command is a supported starting point that still needs workload validation. A choice is disabled only when the underlying runtime combination is known to be unsupported. The recommended selection is only a starting point. The same panel also lets you override the KV/DSA pairing, multimodal feature transport, Breakable Cuda Graph, and HiCache tiers. The MI355X commands are marked **Not Verified** because the selector defaults to HiCache off, whereas the measured AgentX configuration adds the host tier described in [Extend the cache hierarchy](#extend-the-cache-hierarchy). Do not treat the CUDA benchmark rows as MI355X measurements. **Breakable Cuda Graph** defaults to **Off**. On NVIDIA, select **On** to add `--cuda-graph-backend-prefill breakable` to the generated command. This requires a build that includes [PR #38522](https://github.com/sgl-project/sglang/pull/38522); the option is disabled on MI355X. > [!NOTE] > > Generated commands leave `--mamba-full-memory-ratio` at its `0.9` default, which is a generic starting point rather than a workload-tuned split: too low starves the KDA state pool and clamps `max_running_requests`, too high over-provisions it and shrinks the KV pool. Use the repo-local [`compute-mamba-ratio`](https://github.com/sgl-project/sglang/blob/main/.claude/skills/compute-mamba-ratio/SKILL.md) skill to compute the balanced ratio — or the `--max-mamba-cache-size` pin to use instead — from your average request length and the two pool sizes printed in one boot log. See [Size both memory pools](#size-both-memory-pools) for what each pool caps. ## Playground Use the Playground for lower-level tuning such as attention parallelism, MoE communication, PD disaggregation, speculative decoding, and reasoning or tool parsers. It inherits every selection from the deployment panel and shows only the command-line diff. The MoE backend defaults to `flashinfer_trtllm` on B300, B200, GB300 and GB200, to DeepGemm on Hopper, and to AITER on MI355X. ## 1. Model introduction GLM-5.3-Flash is a natively multimodal Mixture-of-Experts model built around a hybrid attention architecture — 320B total parameters with 18B active. Its 45 text layers combine MLA attention, DSA sparse attention, and KDA linear attention, and a 24-layer vision encoder handles image and video input. The checkpoint uses 288 routed experts with 8 active experts per token and includes a native MTP draft layer for speculative decoding. See the [GLM-5.3-Flash blog](https://z.ai/blog/glm-5.3-flash) and the [GLM-5 technical report](https://arxiv.org/abs/2602.15763) for training details.
Attribute Description
Architecture MoE with hybrid attention (MLA, DSA, KDA), mHC, and MTP — 320B total / 18B active parameters
Precision FP8 weights ([`zai-org/GLM-5.3-Flash`](https://huggingface.co/zai-org/GLM-5.3-Flash)); MXFP4 on MI355X ([`OneNexus/GLM-5.3-Flash-MXFP4`](https://huggingface.co/OneNexus/GLM-5.3-Flash-MXFP4)); NVFP4 on Blackwell from [`RadixArk/GLM-5.3-Flash-NVFP4`](https://huggingface.co/RadixArk/GLM-5.3-Flash-NVFP4) and [`nvidia/GLM-5.3-Flash-NVFP4`](https://huggingface.co/nvidia/GLM-5.3-Flash-NVFP4); FP8 KV cache by default on Blackwell and MI355X, BF16 KV cache on H100 and H200
Context 1M tokens
Inputs Text, image, and video
Generation defaults `temperature=1.0`, `top_p=0.95`, thinking enabled
The deployment recipes inherit the checkpoint's 1,048,576-token context limit and generation configuration. Override sampling only when your application has its own evaluated settings. ## 2. Configuration tips ### Choose a strategy Start with **Low Latency** for chat and agent workloads. It drafts from the checkpoint's MTP head at a fixed depth (5 steps, top-k 1, 6 draft tokens) with natural acceptance. Measure **High Throughput** for heavily batched traffic where disabling speculative decoding can be more efficient. SGLang serves MTP through `--speculative-algorithm EAGLE` (upstream folds the older NEXTN spelling into EAGLE), so generated commands use that flag value. Strategy labels describe the workload goal, not a hardware restriction. Both strategies stay available when you switch hardware; only the verification badge changes. On MI355X, the measured AgentX frontier used Low Latency (EAGLE 5/1/6); High Throughput is an unmeasured speculation-off starting point. ### Change the speculative algorithm The **Speculative** card in the Playground changes the algorithm without leaving the selected strategy: * **EAGLE / MTP 5-1-6** is exactly what Low Latency serves, so a Low Latency base starts on this chip. Pick it from a High Throughput base to keep that recipe's other settings and add the MTP head. * **Off (greedy)** strips the whole `--speculative-*` family, which is what High Throughput already starts from. * **DFlash2** swaps the in-checkpoint MTP head for the trained block-diffusion draft in [`incoai/GLM-5.3-Flash-DFlash2`](https://huggingface.co/incoai/GLM-5.3-Flash-DFlash2). The draft proposes a whole block per step and the target verifies it in one forward pass, so output quality stays the target's. Its block size comes from the draft checkpoint, and the draft runs on `fa4` rather than the target's DSA backends. The hidden-state capture it needs ([PR #36708](https://github.com/sgl-project/sglang/pull/36708)) shipped with the GLM-5.3-Flash support in v0.5.20, so the image pinned above is enough. The draft repository is access-gated: request access on its model page, then download it alongside the target before serving. This combination is not yet measured on the cookbook hardware, so treat it as a starting point. Neither algorithm runs with DP-Attention; the card disables the affected chips and names the reason. DFlash2's FA4 draft path is also disabled on MI355X. ### Serve on TPU7x The TPU7x recipe serves the language model with DeepSeek Sparse Attention on the Pallas sparse MLA kernels and MTP 3/1/4 on the experimental chain speculative worker (`SGLANG_TPU_ENABLE_EXPERIMENTAL_SPEC_WORKER=1`). On TPU7x, 3/1/4 decodes faster than 5/1/6 at the same accept length, because each extra draft row widens the target verify. It is sized for one request with 8K input and 1K output: `--context-length 10240`, `--max-running-requests 1`, and a 20,480-token KV pool. Raise `--context-length`, `--max-total-tokens`, `--max-running-requests` and `--max-mamba-cache-size` together for longer or concurrent requests; those settings are outside the verified command. The first start compiles every decode and prefill shape listed in `--tpu-compile-bs` and `--tpu-compile-tokens`, so it takes longer than later starts that reuse the compilation cache. ### Size both memory pools GLM-5.3-Flash maintains a paged KV pool for attention and a separate KDA state pool. The KDA state pool can limit concurrency before the KV pool is full. If startup reduces `max_running_requests` because of KDA state capacity, increase `--mamba-full-memory-ratio` or set `--max-mamba-cache-size` for the expected concurrency, then tune `--max-running-requests` to the workload. Keep the prefix cache enabled for every strategy. Keep the checkpoint's KDA lower-bound setting unchanged. In particular, do not override `linear_lower_bound` through `--json-model-override-args`. ### Keep the KV and DSA backends paired On Blackwell, the recipes default to an FP8 KV cache with TRT-LLM DSA: on GB300 this pairing measured 2.9–5.7% higher throughput and about 1.8x the KV token capacity at identical pool bytes, with GSM8K accuracy within noise of BF16. BF16 KV with TileLang DSA remains selectable in the deployment panel and is the default on H100 and H200, where FP8 KV with TRT-LLM DSA is disabled. MI355X instead uses FP8 KV with TileLang DSA in the recorded ROCm recipe. Switch the dtype and both DSA backends together; TileLang DSA with FP8 KV is not a valid CUDA combination, and TRT-LLM DSA is not the MI355X backend. On Hopper, BF16 KV can also run the sparse prefill in FP8 with `--dsa-prefill-backend flashmla_sparse_q8` (decode stays on `tilelang` and the cache stays BF16): on H200 this pairing measured 5.8–12.1% higher throughput on prefill-only requests, with GSM8K accuracy within noise of BF16 + TileLang. It is SM90-only and requires a build that includes [PR #41790](https://github.com/sgl-project/sglang/pull/41790); FP8 KV is not available with it for this model. ### Extend the cache hierarchy Keep **HiCache** off when GPU memory is sufficient. Select **L1 + L2** to spill reusable cache entries into host memory. Select **+ L3** only after configuring Mooncake on every serving node; the generated command exposes the required configuration path. These options remain selectable but are marked **Not Verified** until the resulting command is validated on the chosen hardware. For agentic MXFP4 serving on MI355X, select **Low Latency** with **L1 + L2**. The host tier uses `--hicache-size 180` (about 190 GB of host memory per rank once the KDA state and DSA indexer pools are included, 750 GB per node) and requires a build that includes [PR #42178](https://github.com/sgl-project/sglang/pull/42178). With less free host memory, keep HiCache off; the server does not start when the host tier does not fit. ### Multimodal memory All strategies enable multimodal serving. Image and video input use `Glm5NextProcessor`, which the pinned Transformers release ships (the MI355X checks predate that release and used commit `e4052f55`). On MI355X, text, image, and an image-bearing follow-up were qualified with that build; video was not evaluated. The processor samples video at 2 FPS and caps video input at 240,000 visual tokens. Install `torchcodec` in the serving environment before sending video requests. For very long videos on 4x GB300, use encoder disaggregation to isolate the vision encoder's memory spikes from language decoding. The default multimodal feature transport is automatic, and on a single CUDA node auto resolves to CPU transport. The MI355X selection explicitly emits CPU transport, matching its image-serving check. CUDA IPC is opt-in: pass `--mm-feature-transport cuda_ipc` when lower transfer latency matters more than the GPU memory the IPC pool reserves. CUDA VMM transport applies only to multi-node GB200/GB300 systems on the MNNVL fabric, where auto selects it. ## 3. Advanced usage ### 3.1 Reasoning Thinking is enabled by the checkpoint's generation configuration, and generated commands enable `--reasoning-parser auto` (which resolves to `glm45` for GLM-5.3-Flash) by default. The OpenAI-compatible API then places thinking in `message.reasoning_content` and the final answer in `message.content`. You can disable **Reasoning Parser** in the Playground when an integration needs the raw response format. To disable thinking for a request, pass `chat_template_kwargs: {"thinking": false}` in the request body. ### 3.2 Tool calling Generated commands enable `--tool-call-parser auto` (which resolves to `glm47` for GLM-5.3-Flash) by default, so structured calls are returned in `message.tool_calls`. You can disable **Tool Call Parser** in the Playground when tool calling is not needed. On follow-up turns, read both `reasoning_content` and `content` because a thinking model can use either field around tool execution. ### 3.3 Multimodal serving The base recipes accept image and video content through the OpenAI-compatible chat API. Keep the processor defaults unless you have measured a different sampling or resize policy. Inputs above the video token budget are clamped to the processor's limit rather than rejected. ### 3.4 Encoder disaggregation Encoder disaggregation separates vision preprocessing from language inference. The verified topology uses one 4x GB300 node shared by an encoder-only TP4 process on port 30001 and a language-only TP4 process on port 30000. Start the encoder first. > **Encoder server (GB300)** > > ```bash Command theme={null} > sglang serve \ > --model-path zai-org/GLM-5.3-Flash \ > --tp-size 4 \ > --encoder-only \ > --host 0.0.0.0 \ > --port 30001 > ``` > **Language server (GB300)** > > ```bash Command theme={null} > sglang serve \ > --model-path zai-org/GLM-5.3-Flash \ > --tp-size 4 \ > --attention-backend dsa \ > --dsa-prefill-backend tilelang \ > --dsa-decode-backend tilelang \ > --linear-attn-backend triton \ > --kv-cache-dtype bfloat16 \ > --quantization fp8 \ > --moe-runner-backend flashinfer_trtllm \ > --max-running-requests 64 \ > --chunked-prefill-size 8192 \ > --max-prefill-tokens 8192 \ > --disable-prefill-cuda-graph \ > --speculative-algorithm EAGLE \ > --speculative-num-steps 3 \ > --speculative-eagle-topk 1 \ > --speculative-num-draft-tokens 4 \ > --language-only \ > --encoder-urls http://localhost:30001 \ > --mem-fraction-static 0.78 \ > --host 0.0.0.0 \ > --port 30000 > ``` This topology served image requests and videos up to 238,080 visual tokens. In a concurrent long-video workload, the largest observed decode gap fell from 5.53 seconds in unified serving to 1.79 seconds with encoder disaggregation. Keep `--mem-fraction-static 0.78` on the language process so the encoder retains room for vision workspaces. Install `torchcodec` for video and see the [encoder disaggregation guide](/docs/advanced_features/epd_disaggregation) for the generic architecture and operational model. ### 3.5 Prefill Context Parallelism Use prefill context parallelism (CP) to distribute DSA prefill computation for long prompts, including multimodal inputs. This hybrid model uses **interleave CP for DSA layers** and **head-wise tensor parallelism for KDA layers**, sharing the same communication group. Layer boundaries all-gather the context shards before KDA and reduce-scatter its output back onto those shards. The mHC residual streams and their coefficients stay local, with each output's reduction completed before the residual update. In the Playground's **Attention** card, select **TP=8** and **CP=8** on B300 or B200 to add `--attn-cp-size 8 --enable-prefill-cp --cp-strategy interleave`. For CP4, set TP=4 and CP=4. With CP enabled, the **MoE** card restricts EP to **1** or the CP size; an incompatible EP selection falls back to 1. Choosing EP=CP also adds `--moe-dense-tp-size` with the CP size. Prefill CP and PD disaggregation cannot be enabled together for this model. > **Example of launching with Prefill CP on Blackwell GPU** > > ```bash Command theme={null} > sglang serve \ > --model-path zai-org/GLM-5.3-Flash \ > --tp-size 4 \ > --attn-cp-size 4 \ > --enable-prefill-cp \ > --cp-strategy interleave \ > --moe-dense-tp-size 4 \ > --ep-size 1 \ > --speculative-algorithm EAGLE \ > --speculative-num-steps 5 \ > --speculative-eagle-topk 1 \ > --speculative-num-draft-tokens 6 \ > --dsa-prefill-backend trtllm \ > --dsa-decode-backend trtllm \ > --kv-cache-dtype fp8_e4m3 \ > --moe-runner-backend flashinfer_trtllm \ > --reasoning-parser auto \ > --tool-call-parser auto \ > --host 0.0.0.0 \ > --port 30000 > ``` ### 3.6 PD disaggregation (preview) PD splits prefill and decode into separate server groups behind a router. For this hybrid model, the transfer moves both the paged DSA KV and the KDA recurrent state. The Playground's **PD Disagg** card defaults to **Off**, with **Mooncake** as its only transfer backend. Select **Prefill** or **Decode** to add `--disaggregation-mode prefill` or `--disaggregation-mode decode`, respectively, together with `--disaggregation-transfer-backend mooncake`. Selecting either role disables prefill CP. The generated prefill and decode commands use ports 30000 and 30100, respectively. > [!WARNING] > > PD serving is mechanically validated with dummy weights only — startup, bootstrap, state transfer, and request flow all work on 4x GB300. It has not been load- or accuracy-tested. Treat it as a preview until the real-weight gate completes. > **PD serving on 4x GB300 (single node)** > > ```bash Prefill (GPU 0-1) theme={null} > sglang serve \ > --model-path zai-org/GLM-5.3-Flash \ > --tp-size 2 \ > --dsa-prefill-backend tilelang \ > --dsa-decode-backend tilelang \ > --kv-cache-dtype bfloat16 \ > --moe-runner-backend triton \ > --disaggregation-mode prefill \ > --disaggregation-bootstrap-port 8998 \ > --disaggregation-transfer-backend nixl \ > --host 0.0.0.0 \ > --port 31000 > ``` > > ```bash Decode (GPU 2-3) theme={null} > sglang serve \ > --model-path zai-org/GLM-5.3-Flash \ > --tp-size 2 \ > --base-gpu-id 2 \ > --dsa-prefill-backend tilelang \ > --dsa-decode-backend tilelang \ > --kv-cache-dtype bfloat16 \ > --moe-runner-backend triton \ > --disaggregation-mode decode \ > --disaggregation-transfer-backend nixl \ > --host 0.0.0.0 \ > --port 32000 > ``` > > ```bash Router theme={null} > python -m sglang_router.launch_router \ > --pd-disaggregation \ > --mini-lb \ > --prefill http://127.0.0.1:31000 8998 \ > --decode http://127.0.0.1:32000 \ > --host 0.0.0.0 \ > --port 30000 > ``` > > The positional `8998` after `--prefill` must equal the prefill server's `--disaggregation-bootstrap-port`. Operational notes: * Give each role a distinct `--nccl-port` when both share one node. * Single-node NIXL needs `UCX_NET_DEVICES=lo` and `UCX_TLS=tcp,cuda_copy,cuda_ipc,self,sm` in both server environments. * The validated arm used the triton MoE runner; the flashinfer\_trtllm runner from the deployment recipes is untested under PD. Known limitations: * Speculative decoding does not start under PD at the current cut (draft-graph capture width assert on the prefill role; decode-side memory pressure at TP2). Run PD without speculative flags. * Prefill and decode with different TP sizes transfer state through slice paths, but numeric correctness is unverified. Keep both roles at the same TP size. # GLM Glyph Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-Glyph ## 1. Model Introduction [Glyph](https://huggingface.co/zai-org/Glyph) is a powerful language model developed by Zhipu AI, featuring advanced capabilities in reasoning, function calling, and multi-modal understanding. **Hardware Support:** NVIDIA B200/H100/H200, AMD MI300X/MI325X/MI355X **Key Features:** * **Advanced Reasoning**: Built-in reasoning capabilities for complex problem-solving * **Multiple Quantizations**: BF16 and FP8 variants for different performance/memory trade-offs * **High Performance**: Optimized for both throughput and latency scenarios **Available Models:** * **BF16 (Full precision)**: [zai-org/Glyph](https://huggingface.co/zai-org/Glyph) * **FP8 (8-bit quantized)**: [zai-org/Glyph-FP8](https://huggingface.co/zai-org/Glyph-FP8) **License:** Please refer to the [official Glyph model card](https://huggingface.co/zai-org/Glyph) for license details. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, and other options. Run this Command:

### 3.2 Configuration Tips

* **Thinking Budget:** Use `--enable-custom-logit-processor` flag and pass `Glm4MoeThinkingBudgetLogitProcessor` in requests to cap the model's thinking token count. See the [GLM-4.5 cookbook page](/cookbook/autoregressive/GLM/GLM-4.5) for the full Thinking Budget usage example.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Thinking Mode

Glyph supports thinking mode for enhanced reasoning. Enable the reasoning parser during deployment to separate the thinking and content sections:

```shell Command theme={null}
python -m sglang.launch_server \
  --model-path zai-org/Glyph \
  --reasoning-parser glm45 \
  --tp 4
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="zai-org/Glyph",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

**Disable Thinking Mode:**

To disable thinking mode for a specific request:

```python Example theme={null}
response = client.chat.completions.create(
    model="zai-org/Glyph",
    messages=[{"role": "user", "content": "What is the capital of France?"}],
    extra_body={"chat_template_kwargs": {"enable_thinking": False}}
)
```

#### 4.2.2 Tool Calling

Glyph supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model-path zai-org/Glyph \
  --reasoning-parser glm45 \
  --tool-call-parser glm45 \
  --tp 4
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="zai-org/Glyph",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information.
I should call the function with location="Beijing".
=============== Content =================

Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="zai-org/Glyph",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The weather in Beijing is currently 22°C and sunny."
```

## 5. Benchmark

This section uses **industry-standard configurations** for comparable benchmark results.

### 5.1 Speed Benchmark

**Test Environment:**

* Model: Glyph
* SGLang Version: 0.5.6.post1

**Benchmark Methodology:**

We use industry-standard benchmark configurations to ensure results are comparable across frameworks and hardware platforms.

#### 5.1.1 Standard Scenario Benchmark

* **Model Deployment**

```bash Command theme={null}
python -m sglang.launch_server \
  --model zai-org/Glyph \
  --tp 2
```

##### 5.1.1.1 Low Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  17.03
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4220
Request throughput (req/s):              0.59
Input token throughput (tok/s):          358.17
Output token throughput (tok/s):         247.74
Peak output token throughput (tok/s):    251.00
Peak concurrent requests:                3
Total token throughput (tok/s):          605.91
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   1702.14
Median E2E Latency (ms):                 1361.72
---------------Time to First Token----------------
Mean TTFT (ms):                          22.35
Median TTFT (ms):                        22.61
P99 TTFT (ms):                           23.76
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          3.99
Median TPOT (ms):                        3.99
P99 TPOT (ms):                           4.01
---------------Inter-Token Latency----------------
Mean ITL (ms):                           3.99
Median ITL (ms):                         3.99
P95 ITL (ms):                            4.03
P99 ITL (ms):                            4.12
Max ITL (ms):                            7.46
==================================================
```

##### 5.1.1.2 Medium Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  16.27
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    40804
Request throughput (req/s):              4.92
Input token throughput (tok/s):          2438.06
Output token throughput (tok/s):         2507.94
Peak output token throughput (tok/s):    3069.00
Peak concurrent requests:                26
Total token throughput (tok/s):          4946.00
Concurrency:                             13.44
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2733.43
Median E2E Latency (ms):                 2892.98
---------------Time to First Token----------------
Mean TTFT (ms):                          33.10
Median TTFT (ms):                        27.73
P99 TTFT (ms):                           49.34
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          5.33
Median TPOT (ms):                        5.39
P99 TPOT (ms):                           5.86
---------------Inter-Token Latency----------------
Mean ITL (ms):                           5.30
Median ITL (ms):                         4.89
P95 ITL (ms):                            5.54
P99 ITL (ms):                            21.17
Max ITL (ms):                            25.14
==================================================
```

##### 5.1.1.3 High Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  25.67
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    252657
Request throughput (req/s):              19.48
Input token throughput (tok/s):          9733.69
Output token throughput (tok/s):         9843.99
Peak output token throughput (tok/s):    13398.00
Peak concurrent requests:                127
Total token throughput (tok/s):          19577.68
Concurrency:                             89.49
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   4593.75
Median E2E Latency (ms):                 4431.03
---------------Time to First Token----------------
Mean TTFT (ms):                          48.66
Median TTFT (ms):                        35.88
P99 TTFT (ms):                           120.61
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          9.10
Median TPOT (ms):                        9.55
P99 TPOT (ms):                           11.00
---------------Inter-Token Latency----------------
Mean ITL (ms):                           9.01
Median ITL (ms):                         6.51
P95 ITL (ms):                            23.19
P99 ITL (ms):                            25.54
Max ITL (ms):                            52.93
==================================================
```

#### 5.1.2 Reasoning Scenario Benchmark

##### 5.1.2.1 Low Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  201.53
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  44462
Total generated tokens (retokenized):    44455
Request throughput (req/s):              0.05
Input token throughput (tok/s):          30.27
Output token throughput (tok/s):         220.63
Peak output token throughput (tok/s):    251.00
Peak concurrent requests:                2
Total token throughput (tok/s):          250.90
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   20151.45
Median E2E Latency (ms):                 21576.31
---------------Time to First Token----------------
Mean TTFT (ms):                          2362.23
Median TTFT (ms):                        23.03
P99 TTFT (ms):                           21310.14
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          4.00
Median TPOT (ms):                        4.00
P99 TPOT (ms):                           4.01
---------------Inter-Token Latency----------------
Mean ITL (ms):                           4.00
Median ITL (ms):                         4.00
P95 ITL (ms):                            4.05
P99 ITL (ms):                            4.08
Max ITL (ms):                            5.67
==================================================
```

##### 5.1.2.2 Medium Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  118.67
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  318306
Total generated tokens (retokenized):    318270
Request throughput (req/s):              0.67
Input token throughput (tok/s):          334.27
Output token throughput (tok/s):         2682.26
Peak output token throughput (tok/s):    3264.00
Peak concurrent requests:                19
Total token throughput (tok/s):          3016.53
Concurrency:                             13.74
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   20387.23
Median E2E Latency (ms):                 20466.09
---------------Time to First Token----------------
Mean TTFT (ms):                          132.47
Median TTFT (ms):                        27.19
P99 TTFT (ms):                           583.15
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          5.09
Median TPOT (ms):                        5.13
P99 TPOT (ms):                           5.19
---------------Inter-Token Latency----------------
Mean ITL (ms):                           5.09
Median ITL (ms):                         5.08
P95 ITL (ms):                            5.18
P99 ITL (ms):                            5.57
Max ITL (ms):                            522.26
==================================================
```

##### 5.1.2.3 High Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 320 \
  --max-concurrency 64 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  150.00
Total input tokens:                      158939
Total input text tokens:                 158939
Total input vision tokens:               0
Total generated tokens:                  1301025
Total generated tokens (retokenized):    1300901
Request throughput (req/s):              2.13
Input token throughput (tok/s):          1059.59
Output token throughput (tok/s):         8673.49
Peak output token throughput (tok/s):    11899.00
Peak concurrent requests:                71
Total token throughput (tok/s):          9733.09
Concurrency:                             54.71
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   25645.42
Median E2E Latency (ms):                 26913.26
---------------Time to First Token----------------
Mean TTFT (ms):                          163.75
Median TTFT (ms):                        93.67
P99 TTFT (ms):                           426.19
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          6.27
Median TPOT (ms):                        6.39
P99 TPOT (ms):                           6.59
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.27
Median ITL (ms):                         0.17
P95 ITL (ms):                            32.94
P99 ITL (ms):                            67.89
Max ITL (ms):                            136.00
==================================================
```

#### 5.1.3 Summarization Scenario Benchmark

#### 5.1.3.1 Low Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  17.44
Total input tokens:                      41941
Total input text tokens:                 41941
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4220
Request throughput (req/s):              0.57
Input token throughput (tok/s):          2405.19
Output token throughput (tok/s):         242.00
Peak output token throughput (tok/s):    250.00
Peak concurrent requests:                2
Total token throughput (tok/s):          2647.19
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   1742.54
Median E2E Latency (ms):                 1412.47
---------------Time to First Token----------------
Mean TTFT (ms):                          53.48
Median TTFT (ms):                        45.05
P99 TTFT (ms):                           98.57
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          4.01
Median TPOT (ms):                        4.01
P99 TPOT (ms):                           4.03
---------------Inter-Token Latency----------------
Mean ITL (ms):                           4.01
Median ITL (ms):                         4.01
P95 ITL (ms):                            4.06
P99 ITL (ms):                            4.09
Max ITL (ms):                            4.95
==================================================
```

##### 5.1.3.2 Medium Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  16.90
Total input tokens:                      300020
Total input text tokens:                 300020
Total input vision tokens:               0
Total generated tokens:                  41669
Total generated tokens (retokenized):    41668
Request throughput (req/s):              4.73
Input token throughput (tok/s):          17753.58
Output token throughput (tok/s):         2465.75
Peak output token throughput (tok/s):    3005.00
Peak concurrent requests:                25
Total token throughput (tok/s):          20219.33
Concurrency:                             13.68
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2890.33
Median E2E Latency (ms):                 3069.55
---------------Time to First Token----------------
Mean TTFT (ms):                          41.46
Median TTFT (ms):                        31.75
P99 TTFT (ms):                           93.18
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          5.52
Median TPOT (ms):                        5.58
P99 TPOT (ms):                           6.14
---------------Inter-Token Latency----------------
Mean ITL (ms):                           5.48
Median ITL (ms):                         5.13
P95 ITL (ms):                            5.93
P99 ITL (ms):                            20.76
Max ITL (ms):                            36.01
==================================================
```

##### 5.1.3.3 High Concurrency

* **Benchmark Command**:

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model zai-org/Glyph \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 320 \
  --max-concurrency 64 \
  --request-rate inf
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  35.54
Total input tokens:                      1273893
Total input text tokens:                 1273893
Total input vision tokens:               0
Total generated tokens:                  170000
Total generated tokens (retokenized):    169994
Request throughput (req/s):              9.01
Input token throughput (tok/s):          35848.57
Output token throughput (tok/s):         4783.96
Peak output token throughput (tok/s):    8396.00
Peak concurrent requests:                80
Total token throughput (tok/s):          40632.53
Concurrency:                             59.26
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   6580.96
Median E2E Latency (ms):                 6248.74
---------------Time to First Token----------------
Mean TTFT (ms):                          345.27
Median TTFT (ms):                        96.06
P99 TTFT (ms):                           2823.92
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          12.26
Median TPOT (ms):                        12.53
P99 TPOT (ms):                           23.58
---------------Inter-Token Latency----------------
Mean ITL (ms):                           11.76
Median ITL (ms):                         6.57
P95 ITL (ms):                            27.66
P99 ITL (ms):                            91.24
Max ITL (ms):                            2609.64
==================================================
```

### 5.2 Accuracy Benchmark

Document model accuracy on standard benchmarks:

#### 5.2.1 GSM8K Benchmark

* Benchmark Command

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* Test Result

```text Output theme={null}
Accuracy: 0.890
Invalid: 0.000
Latency: 3.718 s
Output throughput: 5245.606 token/s
```


# GLM-OCR
Source: https://docs.sglang.io/cookbook/autoregressive/GLM/GLM-OCR



## 1. Model Introduction

[GLM-OCR](https://huggingface.co/zai-org/GLM-OCR) is a multimodal OCR model for complex document understanding, built on the GLM-V encoder–decoder architecture. It introduces Multi-Token Prediction (MTP) loss and stable full-task reinforcement learning to improve training efficiency, recognition accuracy, and generalization.

The model integrates the CogViT visual encoder pre-trained on large-scale image–text data, a lightweight cross-modal connector with efficient token downsampling, and a GLM-0.5B language decoder. Combined with a two-stage pipeline of layout analysis and parallel recognition based on PP-DocLayout-V3, GLM-OCR delivers robust and high-quality OCR performance across diverse document layouts.

**Hardware Support:** NVIDIA B200/H100/H200

**Key Features:**

* **State-of-the-Art Performance**: Achieves 94.62 on OmniDocBench V1.5, ranking #1, and delivers SOTA results across major document understanding benchmarks, including formula recognition, table recognition, and information extraction.
* **Optimized for Real-World Scenarios**: Specifically optimized for practical business cases, maintaining stable and accurate performance on complex tables, code documents, seals, and other challenging layouts.
* **Efficient Inference**: With only 0.9B parameters, GLM-OCR supports deployment via vLLM and SGLang, significantly reducing inference latency and compute cost—well suited for high-concurrency and edge deployments.
* **Easy to Use**: Fully open-sourced with a complete SDK and inference toolchain, enabling one-line invocation and seamless integration into existing systems.

For more details, please refer to the [official GLM-OCR model card](https://huggingface.co/zai-org/GLM-OCR).

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and deployment options. You can optionally enable MTP (Multi-Token Prediction) for faster inference using EAGLE speculative decoding.

Run this Command:


### 3.2 Configuration Tips

* **CUDA IPC Transport**: The `SGLANG_USE_CUDA_IPC_TRANSPORT=1` environment variable enables CUDA IPC for transferring multimodal features, which significantly improves TTFT.
* **MTP (Multi-Token Prediction)**: Enable MTP to use EAGLE speculative decoding for faster inference. This feature predicts multiple tokens at once to reduce latency.
* **Memory Management**: For memory-constrained environments, you may need to adjust `--mem-fraction-static` and/or `--max-running-requests`.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 OCR Image Processing

GLM-OCR supports OCR tasks on various document types. Here's a basic example:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                }
            },
            {
                "type": "text",
                "text": "Please extract all text from this image."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="zai-org/GLM-OCR",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example Output:**

```text Output theme={null}
Response costs: 2.29s
Generated text: CINNAMON SUGAR
1 x 17,000 17,000

SUB TOTAL 17,000

GRAND TOTAL 17,000

CASH IDR 20,000

CHANGE DUE 3,000

```

#### 4.2.2 Complex Document Processing

GLM-OCR excels at processing complex documents including:

* **Tables**: Accurate extraction of tabular data with structure preservation
* **Formulas**: Mathematical formula recognition
* **Code Documents**: Source code extraction from screenshots
* **Seals and Stamps**: Recognition of seals and stamps in documents
* **Multi-layout Documents**: Mixed content with text, images, and tables

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

# Example: Processing a document with tables
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "YOUR_DOCUMENT_IMAGE_URL"
                }
            },
            {
                "type": "text",
                "text": "Please extract the table content from this document and format it as markdown."
            }
        ]
    }
]

response = client.chat.completions.create(
    model="zai-org/GLM-OCR",
    messages=messages,
    max_tokens=4096
)
print(response.choices[0].message.content)
```

## 5. Benchmark

### 5.1 Accuracy Benchmark

Document model accuracy on standard benchmarks:

#### 5.1.1 OCRBench Benchmark

* Benchmark Command

```bash Command theme={null}
python3 -m lmms_eval \
  --model openai_compatible \
  --model_args "model_version=zai-org/GLM-OCR" \
  --tasks ocrbench \
  --batch_size 128 \
  --log_samples \
  --log_samples_suffix "openai_compatible" \
  --output_path ./logs
```

* Test Result

Tasks Version Filter n-shot Metric Value Stderr
ocrbench Yaml none 0 ocrbench\_accuracy ↑ 0.806 N/A
#### 5.1.2 OmniDocBench V1.5 GLM-OCR achieves **94.62** on OmniDocBench V1.5, ranking #1 among all models, demonstrating state-of-the-art performance across major document understanding benchmarks. # GigaChat 3.5 Source: https://docs.sglang.io/cookbook/autoregressive/GigaChat/GigaChat3.5 Deploy GigaChat 3.5 with SGLang — the 432B-A28B hybrid MLA + GDN Mixture-of-Experts instant model with MTP speculative decoding and tool calling, on H100 and H200 in FP8. ## Deployment > **Install SGLang** > > For all install methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). > > **Python (pip / uv)** > > GigaChat 3.5 support is on `main` ([PR #29189](https://github.com/sgl-project/sglang/pull/29189), merged 2026-09-21) and not yet in a `pip` release — install from source: > > ```bash Command theme={null} > pip install --upgrade pip > pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' > ``` > > Then run the **Python** output of the command panel below. > > **Docker** > > > [!NOTE] > > > > No released `lmsysorg/sglang` tag carries GigaChat 3.5 yet. The nightly `lmsysorg/sglang:dev` is rebuilt from `main` and carries the model in builds after 2026-09-21, but that path has not been run end-to-end, so the command panel shows only the Python run mode. Run the Python command inside the nightly image; the Docker tab returns to the panel after a verified run. > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. This page covers the **instant** checkpoint (direct answers, no thinking). For the thinking checkpoint, see [GigaChat 3.5 Reasoning](/cookbook/autoregressive/GigaChat/GigaChat3.5-Reasoning). Pick your hardware and recipe to generate the launch command. Two serving strategies cover the operating points: * **Low-Latency** — MTP speculative decoding on, Mamba state pool pinned. Fastest reply per user; pick for chat and agent loops. * **High-Throughput** — MTP off. At saturation the draft + verify overhead outweighs the speedup, so this is the recipe for batch jobs and many concurrent users. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations that have been run end-to-end; the Playground lets you turn on additional knobs — the tool-call parser, the MTP preset, parallelism — on top of whichever cell the Deploy panel is currently showing. Any change flips the badge to **Not Verified** until the new configuration is run end-to-end. ## 1. Model Introduction **GigaChat 3.5** is a hybrid Mixture-of-Experts model from GigaChat — **432B** total parameters, **28B** active per token, **256K** context (YaRN, factor 8 over a 32K base), released under the **MIT** license. Its **40** layers interleave two attention types: **10** full-attention **MLA** layers (DeepSeek-style latent attention, every 4th layer) and **30** **GDN** linear-attention layers (Qwen3-Next gated delta-net, constant-size state). Only the MLA layers hold a KV cache; the linear layers keep their state in a Mamba-style pool. The MoE block routes to **8 of 256** experts plus **1** shared expert. The checkpoint ships **2** stacked **MTP** draft heads for speculative decoding, and tool calls are emitted in GigaChat's **GCML** format. This is the **instant** release: it answers directly, without a thinking block. The separately trained **Reasoning** release always thinks first and ships 3 MTP heads — it has [its own page](/cookbook/autoregressive/GigaChat/GigaChat3.5-Reasoning). **Resources:** HuggingFace — [GigaChat3.5-432B-A28B](https://huggingface.co/ai-sage/GigaChat3.5-432B-A28B) (FP8, served here) · [GigaChat3.5-432B-A28B-bf16](https://huggingface.co/ai-sage/GigaChat3.5-432B-A28B-bf16) (BF16, for fine-tuning; no single-node recipe). ## 2. Configuration Tips **Two pools.** GDN layers keep per-request state in a Mamba-style pool, MLA layers use a paged KV pool; `--mamba-full-memory-ratio` (default 0.9) splits the post-weight budget. On 8×H100 at `--mem-fraction-static 0.8` that is \~51 GB of weights per GPU, 347 state slots and 542k KV tokens. The resolver forces `--mamba-radix-cache-strategy no_buffer` (3 slots per request, overlap scheduler off), so the unpinned server admits 115 concurrent requests. **MTP needs a pinned pool.** Each running request holds extra state copies under speculative decoding, and the default ratio then admits only a few dozen. The Low-Latency recipe pins `--max-mamba-cache-size 240` with `--max-running-requests 80`; the KV pool drops to 185k tokens. Keep `--mem-fraction-static 0.8` on 80 GB — it is already tight in eager prefill at 16 concurrent 8k-token prompts. **Capacity levers** (toggles in the [Playground](#playground)). `--mamba-ssm-dtype bfloat16` halves every state slot at no cost in accuracy or speed. `--kv-cache-dtype fp8_e4m3` doubles the KV pool but decodes \~2.3× slower on H100 and cannot be combined with MTP on 80 GB. **MTP flags.** `--speculative-algorithm EAGLE` uses GigaChat's own NextN heads through the multi-layer EAGLE worker, selected automatically. This checkpoint has **2** heads: `--speculative-num-steps 2`, `--speculative-num-draft-tokens 3`. **Parsers.** `--tool-call-parser gigachat35` for structured tool calls (§3.1). No reasoning parser, not even `auto`: the checkpoint never emits ``, and the forced `gigachat35` splitter would move the whole answer into `reasoning_content`. ## 3. Advanced Usage ### 3.1 Tool Calling Enable the `gigachat35` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured calls via `message.tool_calls`. GigaChat emits tool calls in its **GCML** format — a `<|GCML|tool_calls>` … `` block holding one `<|GCML|invoke name="…">` per call — inside the assistant turn; the parser reads them out and strips the block from `content`. `--tool-call-parser auto` also resolves to `gigachat35` for this checkpoint, since its chat template carries the GCML marker. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string", "description": "The city name"}}, > "required": ["city"], > }, > }, > } > ] > > resp = client.chat.completions.create( > model="ai-sage/GigaChat3.5-432B-A28B", > messages=[{"role": "user", "content": "What's the weather in Paris?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Content:", msg.content) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Content: > Tool calls: [ChatCompletionMessageFunctionToolCall(id='call_aa689732d4884654a1f76762', function=Function(arguments='{"city": "Paris"}', name='get_weather'), type='function', index=0)] > ``` > > Appending a `tool` message with `{"city": "Paris", "temp_c": 9, "condition": "light rain"}` and re-requesting returns the final answer with no further tool call: > > ```text Output theme={null} > Content: The current weather in Paris is light rain with a temperature of 9°C. > Tool calls: None > ``` > [!NOTE] > > GigaChat tends to call tools **sequentially** — one hop, then the next — so a multi-tool request may come back with a single call. Drive it with an agent loop that appends each `tool` result and re-requests until `finish_reason` is no longer `tool_calls`. Parallel calls (several invokes in one block) are supported by the format when the model chooses them. ### 3.2 MTP (Speculative Decoding) GigaChat 3.5 ships its own NextN draft heads, so speculative decoding needs no separate draft model: `--speculative-algorithm EAGLE` runs the stacked heads through SGLang's multi-layer EAGLE worker, which is selected automatically for this architecture. The **Low-Latency** recipe has it on; in the [Playground](#playground) the **Speculative** card adds the same preset to any other cell. ```bash Flags theme={null} --speculative-algorithm EAGLE \ --speculative-num-steps 2 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 3 \ --max-running-requests 80 \ --max-mamba-cache-size 240 ``` * **Steps follow the checkpoint.** This checkpoint has 2 draft heads, so use `--speculative-num-steps 2` and `--speculative-num-draft-tokens 3` (steps + 1); the worker rejects other values at startup. * **Pin the state pool.** Under MTP every running request holds extra GDN state copies for verification. Without `--max-mamba-cache-size` and `--max-running-requests` the resolver clamps concurrency to a few dozen requests; §2 explains what the pin costs in context. The panel shows an amber callout whenever a speculative command lacks `--max-running-requests`. * **Where it pays off.** Low concurrency: accepted draft tokens skip target forwards, so single-request decode runs about 2× faster with the output distribution unchanged. At high concurrency the verify work and the smaller KV pool eat the gain, which is why the High-Throughput recipe leaves MTP off. Measured numbers are in the benchmark card above. # GigaChat 3.5 Reasoning Source: https://docs.sglang.io/cookbook/autoregressive/GigaChat/GigaChat3.5-Reasoning Deploy GigaChat 3.5 Reasoning with SGLang — the 432B-A28B hybrid MLA + GDN Mixture-of-Experts thinking model with reasoning parsing, MTP speculative decoding and tool calling, on H100 and H200 in FP8. ## Deployment > **Install SGLang** > > For all install methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). > > **Python (pip / uv)** > > GigaChat 3.5 support is on `main` ([PR #29189](https://github.com/sgl-project/sglang/pull/29189), merged 2026-09-21) and not yet in a `pip` release — install from source: > > ```bash Command theme={null} > pip install --upgrade pip > pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' > ``` > > Then run the **Python** output of the command panel below. > > **Docker** > > > [!NOTE] > > > > No released `lmsysorg/sglang` tag carries GigaChat 3.5 yet. The nightly `lmsysorg/sglang:dev` is rebuilt from `main` and carries the model in builds after 2026-09-21, but that path has not been run end-to-end, so the command panel shows only the Python run mode. Run the Python command inside the nightly image; the Docker tab returns to the panel after a verified run. > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. This page covers the **Reasoning** checkpoint (always thinks before answering). For the direct-answer checkpoint, see [GigaChat 3.5](/cookbook/autoregressive/GigaChat/GigaChat3.5). Pick your hardware and recipe to generate the launch command. Two serving strategies cover the operating points: * **Low-Latency** — MTP speculative decoding on, Mamba state pool pinned to 80 requests. Fastest reply per user: measured 2× decode speed at batch 1 and 1.5× at 16 concurrent 8k-token requests. Pick for chat and agent loops. * **High-Throughput** — MTP off, pools left to the default ratio, so the KV pool is \~2.7× larger. Past a few dozen concurrent long-context requests the pinned recipe starts queueing prompts on KV space, and at saturation the draft + verify overhead no longer pays; this is the recipe for batch jobs and many concurrent users. > [!NOTE] > > H100 numbers were measured on 8×H100 SXM at `b63f8416b3` (the PR #29189 merge on `main`) with `bench_serving`, random > ISL 8192 / OSL 1024, `--random-range-ratio 1.0`, `--warmup-requests 4`, `--flush-cache`; latencies are > P50. GSM8K was measured with the 5-shot chat harness `sglang.test.run_eval --eval-name gsm8k --api chat` (1314 scored questions, > `max_tokens` 8192), so the model thinks before every answer exactly as in production. That harness was > deprecated upstream after these runs; the **Reproduce** button emits its successor, `sgl-eval run gsm8k` > (single-shot), which can land a point or two away from the numbers shown. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations that have been run end-to-end; the Playground lets you turn on additional knobs — the reasoning and tool-call parsers, the MTP preset, parallelism — on top of whichever cell the Deploy panel is currently showing. Any change flips the badge to **Not Verified** until the new configuration is run end-to-end. ## 1. Model Introduction **GigaChat 3.5 Reasoning** is the thinking release of GigaChat's hybrid Mixture-of-Experts model — **432B** total parameters, **28B** active per token, **256K** context (YaRN, factor 8 over a 32K base), released under the **MIT** license. It shares the base architecture with [GigaChat 3.5](/cookbook/autoregressive/GigaChat/GigaChat3.5): **40** layers interleaving **10** full-attention **MLA** layers (DeepSeek-style latent attention, every 4th layer) with **30** **GDN** linear-attention layers (Qwen3-Next gated delta-net, constant-size state), and an MoE block routing to **8 of 256** experts plus **1** shared expert. Only the MLA layers hold a KV cache; the linear layers keep their state in a Mamba-style pool. What differs: the chat template opens every assistant turn with ``, so the model always reasons before answering (there is no template switch to turn it off), and the checkpoint ships **3** stacked **MTP** draft heads instead of 2. Tool calls use the same **GCML** format. The model card reports the largest gains over the instant release in mathematics, code, instruction following and structured output. **Recommended generation:** the model card suggests `temperature=0.6` with a generous `max_tokens` (thinking alone can run to thousands of tokens). Informational only — the sample code below relies on the checkpoint's `generation_config.json` defaults. **Resources:** HuggingFace — [GigaChat3.5-432B-A28B-Reasoning](https://huggingface.co/ai-sage/GigaChat3.5-432B-A28B-Reasoning) (FP8, served here) · [GigaChat3.5-432B-A28B-Reasoning-bf16](https://huggingface.co/ai-sage/GigaChat3.5-432B-A28B-Reasoning-bf16) (BF16, for fine-tuning; no single-node recipe). ## 2. Configuration Tips **Two pools.** GDN layers keep per-request state in a Mamba-style pool, MLA layers use a paged KV pool; `--mamba-full-memory-ratio` (default 0.9) splits the post-weight budget. On 8×H100 at `--mem-fraction-static 0.8` that is \~51 GB of weights per GPU, 348 state slots and 542k KV tokens. The resolver forces `--mamba-radix-cache-strategy no_buffer` (3 slots per request, overlap scheduler off), so the unpinned server admits 116 concurrent requests. **MTP needs a pinned pool and 0.83.** Each running request holds extra state copies under speculative decoding, and the default ratio then admits only a few dozen. The Low-Latency recipe pins `--max-mamba-cache-size 240` with `--max-running-requests 80` and runs at `--mem-fraction-static 0.83` (KV pool 199k tokens); at 0.85 the server ran out of memory in eager prefill at 16 concurrent 8k-token prompts. To size by workload instead of a pin: `r = (3 + draft_tokens) × 16 MB / (11.5 KB × L)` for an average request length `L`, and with MTP keep running 8k-token requests under \~20, since the EAGLE worker holds each prompt's hidden states outside both pools. **Capacity levers** (toggles in the [Playground](#playground)). `--mamba-ssm-dtype bfloat16` halves every state slot at no cost in accuracy or accept length — on the Low-Latency recipe the KV pool grows from 199k to 496k tokens. `--kv-cache-dtype fp8_e4m3` doubles the KV pool but decodes \~2.3× slower on H100 and cannot be combined with MTP on 80 GB. **MTP flags.** `--speculative-algorithm EAGLE` uses GigaChat's own NextN heads through the multi-layer EAGLE worker, selected automatically. This checkpoint has **3** heads: `--speculative-num-steps 3`, `--speculative-num-draft-tokens 4`. **Parsers.** `--reasoning-parser gigachat35` splits thinking from the answer (§3.1), `--tool-call-parser gigachat35` gives structured tool calls (§3.2); `auto` resolves to `gigachat35` for both. Do not use the reasoning parser on the Instant checkpoint. ## 3. Advanced Usage ### 3.1 Reasoning The chat template opens every assistant turn with ``, and there is no template switch to turn thinking off. Enable the `gigachat35` reasoning parser (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to split the thinking from the final answer into `reasoning_content` vs `content`. Without the parser, the raw think block is returned inline in `content`. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > resp = client.chat.completions.create( > model="ai-sage/GigaChat3.5-432B-A28B-Reasoning", > messages=[{"role": "user", "content": "What is 17 times 24?"}], > max_tokens=4096, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: I need to calculate 17 times 24. I can do this by breaking it down into smaller parts. First, I know that 10 times 24 is 240, and 7 times 24 is... let me figure that out. 7 times 20 is 140, and 7 times 4 is 28, so 140 plus 28 is 168. Then, I add the two results: 240 plus 168. > > 240 plus 168: 240 plus 100 is 340, plus 60 is 400, plus 8 is 408. Wait, that doesn't seem right. Let me add them properly. 240 + 168: 0 + 8 is 8, 4 + 6 is 10, carry over the 1, so 2 + 1 is 3, plus the carried over 1 is 4, so it should be 408. But I think I remember that 17 times 24 is 408, but let me double-check. > [... ~1,400 more thinking tokens ...] > Answer: > > 17 multiplied by 24 equals 408. This can be calculated in several ways: > > ### Method 1: Breaking Down the Numbers > - $17 \times 24 = 17 \times (20 + 4)$ > - First, $17 \times 20 = 340$ > - Then, $17 \times 4 = 68$ > - Add the results: $340 + 68 = 408$ > > ### Method 2: Using the Distributive Property > - $17 \times 24 = (10 + 7) \times 24$ > - $10 \times 24 = 240$ > - $7 \times 24 = 168$ > - Add the results: $240 + 168 = 408$ > [...] > ``` > > The full response was 1,641 completion tokens, 24.6 s at batch size 1 on 8×H100 without MTP. > [!NOTE] > > The model can spend hundreds of tokens thinking, so keep `max_tokens` generous. A response with an empty `content` and `finish_reason: "length"` means the think block was cut off before it closed — raise the limit. ### 3.2 Tool Calling Enable the `gigachat35` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured calls via `message.tool_calls`. GigaChat emits tool calls in its **GCML** format — a `<|GCML|tool_calls>` … `` block holding one `<|GCML|invoke name="…">` per call — inside the assistant turn; the parser reads them out and strips the block from `content`. `--tool-call-parser auto` also resolves to `gigachat35` for this checkpoint, since its chat template carries the GCML marker. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string", "description": "The city name"}}, > "required": ["city"], > }, > }, > } > ] > > resp = client.chat.completions.create( > model="ai-sage/GigaChat3.5-432B-A28B-Reasoning", > messages=[{"role": "user", "content": "What's the weather in Paris?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Content:", msg.content) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: Okay, the user is asking about the weather in Paris. Let me check what tools I have available. There's the get_weather function which requires the city name. Since the user provided "Paris" directly, I can use that function. I just need to make sure to format the tool call correctly with the city parameter. No other information is needed here, so I'll call get_weather with city set to Paris. > Content: > Tool calls: [ChatCompletionMessageFunctionToolCall(id='call_ef4e35b959c648fbaeab9afd', function=Function(arguments='{"city": "Paris"}', name='get_weather'), type='function', index=0)] > ``` > > Appending a `tool` message with `{"city": "Paris", "temp_c": 9, "condition": "light rain"}` and re-requesting returns the final answer with no further tool call: > > ```text Output theme={null} > Reasoning: > Content: The current weather in Paris is **9°C** with **light rain**. > Tool calls: None > ``` > [!NOTE] > > The tool-call turn carries the model's thinking in `reasoning_content`, so print it alongside `content` and `tool_calls`. GigaChat tends to call tools **sequentially** — one hop, then the next — so a multi-tool request may come back with a single call. Drive it with an agent loop that appends each `tool` result and re-requests until `finish_reason` is no longer `tool_calls`. Parallel calls (several invokes in one block) are supported by the format when the model chooses them. ### 3.3 MTP (Speculative Decoding) GigaChat 3.5 ships its own NextN draft heads, so speculative decoding needs no separate draft model: `--speculative-algorithm EAGLE` runs the stacked heads through SGLang's multi-layer EAGLE worker, which is selected automatically for this architecture. The **Low-Latency** recipe has it on; in the [Playground](#playground) the **Speculative** card adds the same preset to any other cell. ```bash Flags theme={null} --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --max-running-requests 80 \ --max-mamba-cache-size 240 ``` * **Steps follow the checkpoint.** This checkpoint has 3 draft heads, so use `--speculative-num-steps 3` and `--speculative-num-draft-tokens 4` (steps + 1); the worker rejects other values at startup. * **Pin the state pool.** Under MTP every running request holds extra GDN state copies for verification. Without `--max-mamba-cache-size` and `--max-running-requests` the resolver clamps concurrency to a few dozen requests; §2 explains what the pin costs in context and why the recipe runs at `--mem-fraction-static 0.83`. The panel shows an amber callout whenever a speculative command lacks `--max-running-requests`. * **Where it pays off.** Long think blocks are long, low-entropy decode, exactly what draft heads predict well: on 8×H100 single-request decode runs about 2× faster and 16 concurrent 8k-token requests about 1.5× faster, with GSM8K unchanged. At 64 concurrent requests the verify work and the smaller KV pool make it slower than the plain recipe, which is why the High-Throughput recipe leaves MTP off. Measured numbers are in the benchmark card above. # DiffusionGemma Source: https://docs.sglang.io/cookbook/autoregressive/Google/DiffusionGemma ## 1. Model Introduction DiffusionGemma is a uniform-state (renoising) block-diffusion language model from Google. An encoder builds causal context, and a decoder denoises a fixed-length bidirectional canvas of `canvas_length` tokens. The `Gemma4Renoise` sampler runs `max_denoising_steps` reverse steps over the canvas, feeding the previous step's logits back as self-conditioning and emitting the greedy argmax of the processed logits. **Key Features:** * **Uniform-State Renoising**: The canvas starts from random tokens and is refined each step by accepting confident positions and re-noising the rest, with no mask token. * **Encoder / Decoder Canvas**: The encoder produces causal context KV, the decoder attends bidirectionally over the canvas. * **Self-Conditioning**: Each step conditions on the previous step's logits. * **EntropyBound Acceptance**: Each step accepts the lowest-entropy canvas positions within an entropy budget and re-noises the rest. * **StableAndConfident Stopping**: A canvas stops early once it is stable and confident. * **MoE Architecture**: The 26B-A4B model uses a Mixture-of-Experts architecture for efficient inference. * **Multimodal Input**: Accepts text and image inputs (via a \~550M vision encoder) and generates text output. **Available Models:**
Model Architecture Parameters
[google/diffusiongemma-26B-A4B-it](https://huggingface.co/google/diffusiongemma-26B-A4B-it) MoE, uniform-state diffusion (text + image) 25.2B total / 3.8B active
**Architecture Specifications:** | Spec | Value | | - | - | | Total Parameters | 25.2B | | Active Parameters | 3.8B | | Layers | 30 | | Sliding Window | 1024 tokens | | Context Length | Up to 256K tokens | | Canvas Length | 256 | | Vocabulary Size | 262K | | Experts | 8 active / 128 total + 1 shared | | Supported Modalities | Text, Image | | Vision Encoder | \~550M parameters | **License:** Refer to the model card for license details. ## 2. SGLang Installation Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. The checkpoint ships its own modeling code, so `--trust-remote-code` is required when serving. ## 3. Model Deployment ### 3.1 Basic Configuration The required runtime settings are applied automatically for `Gemma4Renoise` (the Triton attention backend, eager mode, and unchunked prefill, needed because the full-attention head\_dim is 512 and the canvas uses bidirectional attention), so a default launch works: ```bash Command theme={null} sglang serve \ --model-path google/diffusiongemma-26B-A4B-it \ --dllm-algorithm Gemma4Renoise \ --trust-remote-code \ --host 0.0.0.0 \ --port 30000 ``` ### 3.2 Configuration Tips **dLLM-Specific Parameters:**
Parameter Description Recommended Value
`--dllm-algorithm` Diffusion decoding algorithm `Gemma4Renoise`
`--trust-remote-code` Required to load the checkpoint's modeling code Always enabled
`--dllm-algorithm-config` Optional YAML overriding the renoise schedule Checkpoint defaults
The attention backend, eager mode, and unchunked prefill are selected automatically for `Gemma4Renoise`, so they do not need to be passed on the command line. Sampling is governed by the renoise schedule. Request-level `logprobs`, penalties, `logit_bias`, and grammar / structured output (`json_schema` / `regex` / `ebnf` / `structural_tag`) are not applied and are rejected with a 400. Core sampling controls (`temperature`, `top_k`, `top_p`) are accepted but have no effect. Streaming is block-level: one fully-denoised canvas per chunk. **Gemma4Renoise Config** (defaults follow the checkpoint's `generation_config.json`): ```yaml Config theme={null} # Number of reverse denoising steps per canvas. max_denoising_steps: 48 # Optional. Makes the renoise sampling reproducible (also shared across TP ranks). seed: 1234 sampler_config: # Entropy budget. Accept the lowest-entropy canvas positions within this bound each step (the rest are re-noised). entropy_bound: 0.1 # Linear temperature schedule applied over the denoising steps. temperature_schedule: t_min: 0.4 t_max: 0.8 # Stop early once the canvas is stable and confident. stopping_config: confidence_threshold: 0.005 stability_threshold: 1 ``` ## 4. Model Invocation ### 4.1 Deployment Start the server with the command from [Section 3.1](#3-1-basic-configuration). ### 4.2 Basic Usage ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="google/diffusiongemma-26B-A4B-it", messages=[ {"role": "user", "content": "What are the key differences between TCP and UDP?"} ], max_tokens=1024 ) print(response.choices[0].message.content) ``` ### 4.3 Streaming Streaming emits one fully-denoised canvas per chunk. ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="google/diffusiongemma-26B-A4B-it", messages=[ {"role": "user", "content": "Write a Python function to compute the Fibonacci sequence."} ], max_tokens=2048, stream=True ) for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) print() ``` ## 5. Benchmark ### 5.1 Speed Benchmark Not benchmarked for speed. ### 5.2 Accuracy Benchmark Full test splits, every item scored (no failed-request exclusions). Text MCQ benchmarks use greedy generate-and-parse, MATH uses boxed-answer extraction plus sympy equivalence. MMLU, ARC-Challenge, and MATH-500 are the mean of two independent server launches.
Benchmark Score
GSM8K 95.4%
ARC-Challenge 91.6%
HumanEval 92.7% pass\@1
MMLU 76.2%
MMLU-Pro 73.7%
GSM-Symbolic 92.2%
MATH-500 72.1%
AIME-2026 10.0%
HMMT-Feb-2025 10.0%
GPQA-main 59.2%
Multimodal, full standard split per task (MMMU / MMMU-Pro / MMStar / AI2D as multiple-choice, MathVista testmini, DocVQA by ANLS, ChartQA by relaxed accuracy):
Multimodal benchmark Score
MMMU (val, MC) 64.9%
MMMU-Pro (standard 10-opt, MC) 57.3%
MathVista (testmini) 68.4%
DocVQA (val) 85.9%
ChartQA (test) 61.7%
AI2D (test) 78.7%
MMStar (val) 65.9%
# EmbeddingGemma Source: https://docs.sglang.io/cookbook/autoregressive/Google/EmbeddingGemma Serve Google's EmbeddingGemma text embedding model with SGLang. ## Overview [EmbeddingGemma](https://huggingface.co/google/embeddinggemma-300m) is Google's 300M-parameter text embedding model. SGLang detects its bidirectional Gemma 3 encoder, applies normalized mean pooling, and serves embeddings through the OpenAI-compatible `/v1/embeddings` endpoint. On NVIDIA CUDA, SGLang uses breakable CUDA graph (BCG) for its complete prefill by default. It also disables prefix caching and chunked prefill, which are incompatible with this bidirectional encoder. ## Prerequisites * NVIDIA CUDA GPU. * A Hugging Face account that has accepted the [EmbeddingGemma license](https://huggingface.co/google/embeddinggemma-300m). * A Hugging Face access token. Export it before starting the server so it can download the gated checkpoint: ```bash theme={null} export HF_TOKEN= ``` Install an SGLang build that includes EmbeddingGemma support: ```bash theme={null} pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' ``` ## Start the server The standard configuration detects EmbeddingGemma and enables embedding mode, BCG, and the checkpoint's BF16 dtype automatically: ```bash theme={null} sglang serve \ --model-path google/embeddinggemma-300m \ --host 0.0.0.0 ``` ### Hopper performance defaults On H100 and H200, SGLang automatically selects FA3 and captures BCG through 16,384 tokens, covering eight 2K embedding requests in one replay. No extra performance flags are required for this workload. To capture larger aggregate prefills, raise the BCG tier explicitly: ```bash theme={null} sglang serve \ --model-path google/embeddinggemma-300m \ --cuda-graph-max-bs-prefill 32768 \ --host 0.0.0.0 ``` EmbeddingGemma automatically enables batch tokenization for list-valued embedding requests, so do not add a separate tokenizer batching flag. ## Create embeddings Send one string or a batch of strings to the OpenAI-compatible endpoint: ```bash theme={null} curl http://127.0.0.1:30000/v1/embeddings \ -H 'Content-Type: application/json' \ -d '{ "model": "google/embeddinggemma-300m", "input": [ "A short guide to serving text embeddings.", "Vector search retrieves semantically similar documents." ], "encoding_format": "float" }' ``` See [OpenAI-compatible embedding APIs](/docs/basic_usage/openai_api_embeddings) for Python and OpenAI client examples. ## Deployment behavior EmbeddingGemma performs bidirectional attention over the complete input, so reusing a prefix KV cache or splitting the input into chunked prefills would produce incorrect attention states. SGLang applies the required settings automatically: * disables RadixAttention prefix caching; * disables chunked prefill; * disables the decode CUDA graph because this is an embedding-only model; * uses BCG for CUDA prefill; * uses the FlashAttention raw-K/V path when the prefill backend is FA3 or FA4 on supported Hopper and Blackwell CUDA GPUs. No prefill CUDA-graph override is required for this recipe. Keep BCG enabled to use the optimized EmbeddingGemma path. # EmbeddingGemma 2 Source: https://docs.sglang.io/cookbook/autoregressive/Google/EmbeddingGemma2 Serve Google's multimodal EmbeddingGemma 2 model (text, image, video, audio) with SGLang. ## Overview [EmbeddingGemma 2](https://huggingface.co/google/embeddinggemma-2) is Google's multimodal embedding model. It maps text (including code), images, video, audio, and interleaved combinations of them into one shared, L2-normalized 768-dimensional vector space. | Property | Value | | :- | :- | | Parameters | 740M total: 270M text backbone, 170M vision encoder, 300M audio encoder | | Architecture | 24-layer bidirectional Gemma 4 encoder, 5:1 local:global attention, local window radius 512 | | Context | 8,192 tokens shared by all modalities in a request | | Output | 768 dimensions; Matryoshka truncation to 512, 256, or 128 | | Pooling | Mean pooling over all tokens, then L2 normalization | SGLang detects the `EmbeddingGemma2Model` architecture and configures it automatically: * enables embedding mode, so `--is-embedding` is not needed; * selects the Triton attention backend, which implements the bidirectional sliding window; * disables RadixAttention prefix caching and chunked prefill, because bidirectional attention makes every token depend on the whole input; * caps the context length at 8,192 tokens. ## Prerequisites * An NVIDIA CUDA GPU. The model weighs about 1.5 GB in BF16, so any data-center GPU works. * A Transformers build that includes EmbeddingGemma 2 (`model_type: embedding_gemma2`). Older releases fail at startup with `Transformers does not recognize this architecture`. * An SGLang build that includes EmbeddingGemma 2 support: ```bash theme={null} pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' ``` Run the model in BF16 (the checkpoint default) or FP32. Do not use FP16: the model's activations exceed its range and produce NaN or degraded embeddings. ## Start the server ```bash theme={null} sglang serve \ --model-path google/embeddinggemma-2 \ --host 0.0.0.0 ``` ### Load only the encoders you need The vision and audio encoders load only when their modality is allowed. Set a modality's per-request limit to `0` to skip loading its encoder. Images and video share the vision encoder. | Serving | `--limit-mm-data-per-request` | Parameters loaded | | :- | :- | :- | | Text only | `'{"image": 0, "video": 0, "audio": 0}'` | 270M | | Text and images/video | `'{"audio": 0}'` | 440M | | Text and audio | `'{"image": 0, "video": 0}'` | 570M | | All modalities | (default) | 740M | ```bash theme={null} sglang serve \ --model-path google/embeddinggemma-2 \ --limit-mm-data-per-request '{"image": 0, "video": 0, "audio": 0}' \ --host 0.0.0.0 ``` A request for a disabled modality fails with HTTP 400, for example `Image count 1 exceeds limit 0 per request.` ### Enable Matryoshka dimensions To let clients request shorter vectors through the `dimensions` field, declare the supported sizes when starting the server: ```bash theme={null} sglang serve \ --model-path google/embeddinggemma-2 \ --json-model-override-args '{"matryoshka_dimensions": [128, 256, 512, 768]}' \ --host 0.0.0.0 ``` SGLang truncates the pooled vector and then re-normalizes it, as the model card requires. Other sizes are rejected with HTTP 400. Queries and documents must use the same dimension. ## Task prompts EmbeddingGemma 2 is trained with short task prefixes on text inputs. Prepend them yourself; images, video, and audio take no prefix. For documents without a title, use `title: none`. | Use case | Query | Document | | :- | :- | :- | | Retrieval | `task: search result \| query: {content}` | `title: {title} \| text: {content}` | | Question answering | `task: question answering \| query: {content}` | `title: {title} \| text: {content}` | | Fact checking | `task: fact checking \| query: {content}` | `title: {title} \| text: {content}` | | Code retrieval | `task: code retrieval \| query: {content}` | `title: {title} \| text: {content}` | | Classification | `task: classification \| query: {content}` | | | Clustering | `task: clustering \| query: {content}` | | | Semantic similarity | `task: sentence similarity \| query: {content}` | | ## Create embeddings ### Native `/encode` API `/encode` supports every modality, including several media items in one embedding. Text, one embedding per string: ```bash theme={null} curl http://127.0.0.1:30000/encode \ -H 'Content-Type: application/json' \ -d '{ "text": [ "task: search result | query: What causes the aurora borealis?", "title: none | text: The aurora is caused by solar wind particles colliding with the upper atmosphere." ] }' ``` An image, video, or audio clip on its own. SGLang inserts the placeholder for you: ```bash theme={null} curl http://127.0.0.1:30000/encode \ -H 'Content-Type: application/json' \ -d '{"image_data": "https://example.com/cat.jpg"}' ``` Use `video_data` or `audio_data` the same way. Audio should be mono at 16 kHz. Interleaved input, one embedding for the whole sequence. Mark each item's position with `<|image|>`, `<|video|>`, or `<|audio|>`, and pass the items in the same order: ```bash theme={null} curl http://127.0.0.1:30000/encode \ -H 'Content-Type: application/json' \ -d '{ "text": "Waterproof running shoes. <|image|> Breathable mesh upper. <|image|> Narration: <|audio|>", "image_data": ["https://example.com/shoe.jpg", "https://example.com/mesh.jpg"], "audio_data": "https://example.com/narration.wav" }' ``` #### How requests map to embeddings | Request shape | Result | | :- | :- | | `text` is a string, media is a list | 1 embedding containing all the media | | `text` is a list of N strings, media is a list of N entries | N embeddings, paired by position; an entry may be `null` or a list of several items | | `text` is a list, media is a single item (not a list) | the item is attached to every request, so every string needs its placeholder | | No `text`, media is a flat list `[a, b]` | 1 embedding of `a` and `b` together | | No `text`, media is a list of lists `[[a], [b]]` | 2 embeddings | Requests are rejected with HTTP 400 instead of being silently changed when: * the number of `<|image|>`, `<|video|>`, or `<|audio|>` placeholders differs from the number of items of that modality (text without any placeholder plus an image is also a mismatch); * a batched media list has a different length than the `text` list. ### OpenAI-compatible `/v1/embeddings` ```bash theme={null} curl http://127.0.0.1:30000/v1/embeddings \ -H 'Content-Type: application/json' \ -d '{ "model": "google/embeddinggemma-2", "input": [ {"text": "a product photo: <|image|>", "image": "https://example.com/shoe.jpg"}, {"image": "https://example.com/mesh.jpg"}, {"text": "task: search result | query: waterproof trail shoes"} ] }' ``` Each input item produces one embedding. In this API, an item carries at most one `image` or `video` and no audio. For several media items in one embedding, or for audio, use `/encode`. ## Input limits All modalities share the 8,192-token context. Requests that exceed it fail with HTTP 400 (`The input (N tokens) is longer than the model's context length (8192 tokens).`). | Modality | Cost | Max, single modality | | :- | :- | :- | | Text | 1 token per subword | 8,192 tokens | | Image | up to 280 tokens per image | about 29 images | | Video | up to 140 tokens per sampled frame | about 58 frames | | Audio | 25 tokens per second | about 327 seconds | Video is sampled at 1 frame per second and capped at 32 frames by default, spread uniformly over longer clips, so a video of any length fits by default. A 2-minute 720p clip, for example, uses 3,906 tokens. Only the sampled frames are decoded. To change the sampling rate or frame cap for every request, use `--mm-process-config`: ```bash theme={null} sglang serve \ --model-path google/embeddinggemma-2 \ --mm-process-config '{"video": {"fps": 2, "max_frames": 48}}' \ --host 0.0.0.0 ``` The number of frames that fit depends on resolution. At 720p, 64 frames fit; 70 frames exceed the context. # Gemma 4 Source: https://docs.sglang.io/cookbook/autoregressive/Google/Gemma4 ## 1. Model Introduction Gemma 4 is Google's next-generation family of open models, building on the Gemma 3 architecture with improved performance, MoE variants, and multimodal support for text, vision, and audio. **Key Features:** * **Hybrid Attention**: Combines sliding window and full attention layers for efficient long-context processing * **Multimodal**: Supports text, image, and audio inputs via dedicated vision and audio encoders * **MoE Variant**: The 26B-A4B model uses a Mixture-of-Experts architecture for efficient inference * **Per-Layer Embeddings (PLE)**: Layer-specific token embeddings for enhanced representations * **Reasoning**: Built-in thinking mode with `gemma4` reasoning parser * **Tool Calling**: Function call support with streaming via `gemma4` tool call parser * **Fused Operations**: Triton-optimized RMSNorm + residual + scalar kernels **Available Models:**
Model Architecture Parameters
[google/gemma-4-E2B-it](https://huggingface.co/google/gemma-4-E2B-it) Dense \~2B
[google/gemma-4-E4B-it](https://huggingface.co/google/gemma-4-E4B-it) Dense \~4B
[google/gemma-4-12B-it](https://huggingface.co/google/gemma-4-12B-it) Dense 12B
[google/gemma-4-31B-it](https://huggingface.co/google/gemma-4-31B-it) Dense 31B
[google/gemma-4-26B-A4B-it](https://huggingface.co/google/gemma-4-26B-A4B-it) MoE 26B total / 4B active
## 2. SGLang Installation Gemma 4 (including the encoder-free unified 12B, [sgl-project/sglang#27167](https://github.com/sgl-project/sglang/pull/27167)) is supported on SGLang main. Install it together with the matching transformers commit: ```bash Command theme={null} # Install SGLang from main pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' # Install transformers with Gemma 4 support (encoder-free unified family included) pip install 'git+https://github.com/huggingface/transformers.git@1423d22f7a3b62e8c70ad67b58ec25cd9b675897' ``` ### Docker `lmsysorg/sglang:latest` (CUDA 13.0, multi-arch `amd64` + `arm64`) runs on both Hopper (H200) and Blackwell (B200 / GB200 / GB300): ```bash Command theme={null} docker run --gpus all --ipc=host --shm-size 32g \ -v ~/.cache/huggingface:/root/.cache/huggingface \ -p 30000:30000 \ lmsysorg/sglang:latest \ sglang serve --model-path google/gemma-4-12B-it \ --reasoning-parser gemma4 --tool-call-parser gemma4 \ --host 0.0.0.0 --port 30000 ``` For other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/install). ## 3. Model Deployment ### 3.1 Basic Configuration The Gemma 4 series offers models in various sizes and architectures, optimized for different hardware platforms including NVIDIA GPUs, AMD GPUs, and Intel Arc Pro B-Series GPUs(codename: BMG (Battlemage)), Xeon CPUs. The recommended launch configurations vary by hardware and model size. **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and model variant. Run this Command:

### 3.2 Configuration Tips

* SGLang automatically selects the Triton attention backend for Gemma 4 models (required for bidirectional image-token attention during prefill).
* **Attention backend on Blackwell (B200/sm100)**: SGLang defaults to the `trtllm_mha` backend on sm100, which is fastest for text but applies *causal* attention to image tokens. For multimodal (image) workloads on B200, pass `--attention-backend triton` to restore bidirectional image-token attention and full vision quality. Text-only and audio workloads are unaffected by the default.
* **Gemma 4 26B-A4B on B200**: Use `--mem-fraction-static 0.75` to leave workspace headroom for the Triton MoE path.
* For the 26B-A4B MoE model, consider `--tp 2` for high-throughput workloads.
* **Speculative Decoding (MTP)**: Each Gemma 4 variant ships with a paired `*-assistant` draft model that enables NEXTN multi-token prediction. Enable it via the selector above, or pass `--speculative-algorithm NEXTN --speculative-draft-model-path google/gemma-4--it-assistant --speculative-num-steps 5 --speculative-num-draft-tokens 6 --speculative-eagle-topk 1`. MTP can significantly reduce latency for interactive use cases. The 26B-A4B MoE model requires `--tp 2` when MTP is enabled.
* **QAT checkpoints**: Toggle **Checkpoint → QAT** in the selector to target the `qat-q4_0-unquantized` releases. These keep bf16 weights, so memory and TP requirements match the standard checkpoints, and each has a matching `*-qat-q4_0-unquantized-assistant` draft model for MTP.
* Hardware requirements:

Model Hardware TP
gemma-4-E2B-it 1x H200 / 1x B200 / 1x B300 / 1x MI300X / 1x MI325X / 1x MI355X 1
gemma-4-E4B-it 1x H200 / 1x B200 / 1x B300 / 1x MI300X / 1x MI325X / 1x MI355X 1
gemma-4-12B-it 1x H200 / 1x B200 / 1x B300 1
gemma-4-31B-it 2x H200 / 1x B200 / 1x B300 / 1x MI300X / 1x MI325X / 1x MI355X 2 (H200) / 1 (B200/B300/AMD)
gemma-4-26B-A4B-it 1x H200 / 1x B200 / 1x B300 / 1x MI300X / 1x MI325X / 1x MI355X 1
### 3.3 AMD GPU Deployment (MI300X / MI325X / MI355X) SGLang automatically selects the correct attention backend on AMD GPUs. For the small E-models (`gemma-4-E2B-it`, `gemma-4-E4B-it`), disable AITER on AMD GPUs and use the same command line otherwise: ```bash Command theme={null} SGLANG_USE_AITER=0 sglang serve --model-path google/gemma-4-E4B-it \ --reasoning-parser gemma4 \ --tool-call-parser gemma4 \ --host 0.0.0.0 --port 30000 ``` For `gemma-4-31B-it` and `gemma-4-26B-A4B-it`, the same commands above work on MI300X, MI325X, and MI355X without additional command-line changes. > **Status**: AMD benchmarks are available in [Section 5.1](#5-1-speed-benchmark). ## 4. Model Invocation Deploy gemma-4-26B-A4B-it (MoE) with all features enabled: ```bash Command theme={null} sglang serve --model-path google/gemma-4-26B-A4B-it \ --reasoning-parser gemma4 \ --tool-call-parser gemma4 \ --host 0.0.0.0 --port 30000 ``` #### Speculative Decoding (MTP) Server Commands Each Gemma 4 variant ships with a paired `*-assistant` draft model for NEXTN multi-token prediction. Use the commands below to enable MTP for the corresponding target model. These match the configuration generated when you toggle **Speculative Decoding (MTP) → Enabled** in the [interactive selector](#3-1-basic-configuration). ```bash Command theme={null} # Gemma 4 E2B + MTP sglang serve \ --model-path google/gemma-4-E2B-it \ --speculative-algorithm NEXTN \ --speculative-draft-model-path google/gemma-4-E2B-it-assistant \ --speculative-num-steps 5 \ --speculative-num-draft-tokens 6 \ --speculative-eagle-topk 1 \ --mem-fraction-static 0.85 ``` ```bash Command theme={null} # Gemma 4 E4B + MTP sglang serve \ --model-path google/gemma-4-E4B-it \ --speculative-algorithm NEXTN \ --speculative-draft-model-path google/gemma-4-E4B-it-assistant \ --speculative-num-steps 5 \ --speculative-num-draft-tokens 6 \ --speculative-eagle-topk 1 \ --mem-fraction-static 0.85 ``` ```bash Command theme={null} # Gemma 4 12B + MTP (~35% faster single-stream decode on H200) sglang serve \ --model-path google/gemma-4-12B-it \ --speculative-algorithm NEXTN \ --speculative-draft-model-path google/gemma-4-12B-it-assistant \ --speculative-num-steps 5 \ --speculative-num-draft-tokens 6 \ --speculative-eagle-topk 1 \ --mem-fraction-static 0.85 ``` ```bash Command theme={null} # Gemma 4 31B + MTP sglang serve \ --model-path google/gemma-4-31B-it \ --tp-size 2 \ --speculative-algorithm NEXTN \ --speculative-draft-model-path google/gemma-4-31B-it-assistant \ --speculative-num-steps 5 \ --speculative-num-draft-tokens 6 \ --speculative-eagle-topk 1 \ --mem-fraction-static 0.85 ``` ```bash Command theme={null} # Gemma 4 26B-A4B + MTP sglang serve \ --model-path google/gemma-4-26B-A4B-it \ --tp-size 2 \ --speculative-algorithm NEXTN \ --speculative-draft-model-path google/gemma-4-26B-A4B-it-assistant \ --speculative-num-steps 5 \ --speculative-num-draft-tokens 6 \ --speculative-eagle-topk 1 \ --mem-fraction-static 0.85 ``` ### 4.1 Basic Usage ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="google/gemma-4-26B-A4B-it", messages=[ {"role": "user", "content": "What are the key differences between TCP and UDP?"} ], max_tokens=1024 ) print(response.choices[0].message.content) ```
Example Output ```text Output theme={null} The fundamental difference between **TCP (Transmission Control Protocol)** and **UDP (User Datagram Protocol)** lies in how they prioritize data integrity versus speed. ### 1. Connection Type * **TCP (Connection-Oriented):** Before any data is sent, TCP performs a "three-way handshake." The sender and receiver exchange signals to establish a formal connection. * **UDP (Connectionless):** UDP does not establish a connection. It simply starts blasting packets to the destination IP address without checking if the receiver is ready. ### 2. Reliability and Error Checking * **TCP (Reliable):** If a packet is lost or arrives corrupted, TCP detects the error and retransmits the missing data. * **UDP (Unreliable):** If a packet is lost or corrupted, it is simply discarded. There is no mechanism to ask for a retransmission. ### 3. Ordering of Data * **TCP (Ordered):** Segments are assigned sequence numbers and reassembled in the correct order. * **UDP (Unordered):** Packets may arrive in a different order than sent. ### 4. Speed and Overhead * **TCP (Slower):** Managing connections, tracking, and retransmissions adds significant overhead. * **UDP (Faster):** No handshake, no tracking — extremely fast and ideal for real-time needs. | Feature | TCP | UDP | | :--- | :--- | :--- | | **Connection** | Connection-oriented | Connectionless | | **Reliability** | Guaranteed delivery | Best-effort | | **Ordering** | Maintains strict order | No guaranteed order | | **Speed** | Slower (High overhead) | Faster (Low overhead) | ```
### 4.2 Vision Input Gemma 4 multimodal variants accept images alongside text: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="google/gemma-4-26B-A4B-it", messages=[ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://farm4.staticflickr.com/3175/2653711032_804ff86d81_z.jpg" } }, { "type": "text", "text": "Describe this image in detail." } ] } ], max_tokens=1024 ) print(response.choices[0].message.content) ```
Example Output ```text Output theme={null} A vertical, full shot shows a girl and a boy standing in front of a giant teddy bear. The boy, who is on the left, is of South Asian descent, has short dark hair, and is smiling at the camera. He is wearing a navy blue sweatshirt with a white collar, blue jeans, and white, black, and red sneakers. The girl, on the right, is also of South Asian descent and has long, dark hair. She is smiling at the camera and is wearing a pink t-shirt, a white long-sleeve shirt underneath, blue jeans, and pink sneakers. The giant teddy bear is light brown and is standing behind the two children. The bear has large, dark eyes and a black nose. In the background, on the left, there is a large wooden basket filled with small teddy bears. To the left of the basket, an American flag is hanging on the wall. On the right side of the image, there is a green leafy plant. The floor is a dark purple carpet. The lighting is bright and even. ```
### 4.3 Reasoning (Thinking Mode) Gemma 4 supports hybrid reasoning. Thinking is **not enabled by default** — pass `chat_template_kwargs: {"enable_thinking": true}` via `extra_body` to activate it. The reasoning parser separates thinking and content, returning the thinking process via `reasoning_content` in the streaming response. ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="google/gemma-4-26B-A4B-it", messages=[ {"role": "user", "content": "Solve step by step: If a train travels at 60 km/h for 2.5 hours, how far does it go?"} ], max_tokens=4096, stream=True, extra_body={"chat_template_kwargs": {"enable_thinking": True}} ) thinking_started = False has_thinking = False has_answer = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ```
Example Output ```text Output theme={null} =============== Thinking ================= * Input: Speed = 60 km/h, Time = 2.5 hours. * Goal: Find the distance traveled. * Distance = Speed × Time. * Step 1: Identify given values. Speed = 60 km/h, Time = 2.5 hours * Step 2: Formula. Distance = Speed × Time * Step 3: Calculation. 60 × 2.5 Mental math: 60 × 2 = 120; 60 × 0.5 = 30; 120 + 30 = 150. * Step 4: Final Result. 150 km. =============== Content ================= To find the distance traveled, you can follow these steps: ### 1. Identify the given information: * **Speed:** 60 km/h * **Time:** 2.5 hours ### 2. Use the distance formula: Distance = Speed × Time ### 3. Substitute the values: Distance = 60 km/h × 2.5 hours ### 4. Perform the calculation: * 60 × 2 = 120 * 60 × 0.5 = 30 * 120 + 30 = 150 **Final Answer: The train travels 150 km.** ```
### 4.4 Tool Calling Gemma 4 supports function calling with the `gemma4` tool call parser. Enable it during deployment with `--tool-call-parser gemma4`. ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] response = client.chat.completions.create( model="google/gemma-4-26B-A4B-it", messages=[ {"role": "user", "content": "What's the weather in Tokyo?"} ], tools=tools, stream=True ) thinking_started = False has_thinking = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) if hasattr(delta, 'tool_calls') and delta.tool_calls: if has_thinking and thinking_started: print("\n=============== Tool Calls ================", flush=True) thinking_started = False for tool_call in delta.tool_calls: if tool_call.function: print(f"Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") if delta.content: print(delta.content, end="", flush=True) print() ```
Example Output ```text Output theme={null} =============== Tool Calls ================ Tool Call: get_weather Arguments: {"location": "Tokyo"} ```
### 4.5 Audio Input The audio-capable Gemma 4 variants (`gemma-4-E2B-it`, `gemma-4-E4B-it`, `gemma-4-12B-it`) accept raw audio alongside text. Pass the waveform as a base64 `audio_url` data URI (16 kHz mono WAV works well), or as OpenAI's `input_audio` part with the base64 bytes in `data` and a `format` of `wav`: ```python Example theme={null} import base64 from openai import OpenAI client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") with open("sample.wav", "rb") as f: audio_b64 = base64.b64encode(f.read()).decode() response = client.chat.completions.create( model="google/gemma-4-12B-it", messages=[ { "role": "user", "content": [ {"type": "audio_url", "audio_url": {"url": f"data:audio/wav;base64,{audio_b64}"}}, {"type": "text", "text": "Transcribe the speech in this audio exactly."}, ], } ], max_tokens=256, temperature=0, ) print(response.choices[0].message.content) ```
Example Output ```text Output theme={null} Mr. Quilter is the apostle of the middle classes, and we are glad to welcome his gospel. ```
For best ASR quality, use the recommended transcription prompt structure: ```text Prompt theme={null} Transcribe the following speech segment in {LANGUAGE} into {LANGUAGE} text. Follow these specific instructions for formatting the answer: * Only output the transcription, with no newlines. * When transcribing numbers, write the digits, i.e. write 1.7 and not one point seven, and write 3 instead of three. ``` For speech translation (AST), ask for the transcription in the source language first, then the translation: *"Transcribe the following speech segment in , then translate it into . ..."* ## 5. Benchmark ### 5.1 Speed Benchmark **Test Environment:** * Hardware: H200 * SGLang Version: gemma4 branch #### gemma-4-E2B-it (1x H200, TP=1) Server Launch Command: ```bash Command theme={null} sglang serve --model-path google/gemma-4-E2B-it ``` **Latency Benchmark (Text)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang \ --host 0.0.0.0 --port 30000 \ --dataset-name random --num-prompts 10 --max-concurrency 1 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 17.44 Total input tokens: 6101 Total generated tokens: 4220 Request throughput (req/s): 0.57 Output token throughput (tok/s): 242.03 Total token throughput (tok/s): 591.94 Mean TTFT (ms): 50.19 Median TTFT (ms): 54.22 Mean TPOT (ms): 3.99 Median ITL (ms): 4.05 ================================================== ``` **Latency Benchmark (Image)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang-oai-chat \ --host 0.0.0.0 --port 30000 \ --dataset-name image --image-count 2 --image-resolution 720p \ --random-input-len 128 --random-output-len 1024 \ --num-prompts 10 --max-concurrency 1 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 18.05 Total input tokens: 6097 Total input vision tokens: 5340 Total generated tokens: 4220 Request throughput (req/s): 0.55 Output token throughput (tok/s): 233.84 Total token throughput (tok/s): 571.69 Mean TTFT (ms): 109.59 Median TTFT (ms): 112.62 Mean TPOT (ms): 4.01 Median ITL (ms): 4.04 ================================================== ``` **Throughput Benchmark (Text)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang \ --host 0.0.0.0 --port 30000 \ --dataset-name random --num-prompts 1000 --max-concurrency 100 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 51.73 Total input tokens: 512842 Total generated tokens: 510855 Request throughput (req/s): 19.33 Output token throughput (tok/s): 9876.36 Peak output token throughput (tok/s): 13863.00 Total token throughput (tok/s): 19791.14 Mean TTFT (ms): 86.57 Mean TPOT (ms): 9.56 Median ITL (ms): 5.99 ================================================== ``` **Throughput Benchmark (Image)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang-oai-chat \ --host 0.0.0.0 --port 30000 \ --dataset-name image --image-count 2 --image-resolution 720p \ --random-input-len 128 --random-output-len 1024 \ --num-prompts 1000 --max-concurrency 100 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 89.07 Total input tokens: 617799 Total input vision tokens: 534000 Total generated tokens: 510855 Request throughput (req/s): 11.23 Output token throughput (tok/s): 5735.75 Peak output token throughput (tok/s): 12823.00 Total token throughput (tok/s): 12672.23 Mean TTFT (ms): 636.46 Mean TPOT (ms): 16.34 Median ITL (ms): 5.68 ================================================== ``` #### gemma-4-E4B-it (1x H200, TP=1) Server Launch Command: ```bash Command theme={null} sglang serve --model-path google/gemma-4-E4B-it ``` **Latency Benchmark (Text)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 24.49 Total input tokens: 6101 Total generated tokens: 4220 Request throughput (req/s): 0.41 Output token throughput (tok/s): 172.32 Total token throughput (tok/s): 421.45 Mean TTFT (ms): 52.76 Median TTFT (ms): 53.66 Mean TPOT (ms): 5.64 Median ITL (ms): 5.74 ================================================== ``` **Latency Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 25.04 Total input tokens: 6124 Total input vision tokens: 5340 Total generated tokens: 4220 Request throughput (req/s): 0.40 Output token throughput (tok/s): 168.54 Total token throughput (tok/s): 413.13 Mean TTFT (ms): 110.15 Median TTFT (ms): 108.24 Mean TPOT (ms): 5.66 Median ITL (ms): 5.73 ================================================== ``` **Throughput Benchmark (Text)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 72.95 Total input tokens: 512842 Total generated tokens: 510855 Request throughput (req/s): 13.71 Output token throughput (tok/s): 7002.68 Peak output token throughput (tok/s): 9878.00 Total token throughput (tok/s): 14032.60 Mean TTFT (ms): 166.33 Mean TPOT (ms): 13.36 Median ITL (ms): 8.88 ================================================== ``` **Throughput Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 108.99 Total input tokens: 616952 Total input vision tokens: 534000 Total generated tokens: 510855 Request throughput (req/s): 9.18 Output token throughput (tok/s): 4687.38 Peak output token throughput (tok/s): 9277.00 Total token throughput (tok/s): 10348.25 Mean TTFT (ms): 626.17 Mean TPOT (ms): 20.00 Median ITL (ms): 8.64 ================================================== ``` #### gemma-4-31B-it (2x H200, TP=2) Server Launch Command: ```bash Command theme={null} sglang serve --model-path google/gemma-4-31B-it --tp 2 ``` **Latency Benchmark (Text)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 53.05 Total input tokens: 6101 Total generated tokens: 4220 Request throughput (req/s): 0.19 Output token throughput (tok/s): 79.55 Total token throughput (tok/s): 194.55 Mean TTFT (ms): 72.77 Median TTFT (ms): 75.05 Mean TPOT (ms): 12.32 Median ITL (ms): 12.53 ================================================== ``` **Latency Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 53.78 Total input tokens: 6162 Total input vision tokens: 5340 Total generated tokens: 4220 Request throughput (req/s): 0.19 Output token throughput (tok/s): 78.46 Total token throughput (tok/s): 193.03 Mean TTFT (ms): 143.35 Median TTFT (ms): 146.85 Mean TPOT (ms): 12.37 Median ITL (ms): 12.48 ================================================== ``` **Throughput Benchmark (Text)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 182.00 Total input tokens: 512842 Total generated tokens: 510855 Request throughput (req/s): 5.49 Output token throughput (tok/s): 2806.82 Peak output token throughput (tok/s): 3798.00 Total token throughput (tok/s): 5624.56 Mean TTFT (ms): 324.67 Mean TPOT (ms): 33.95 Median ITL (ms): 25.44 ================================================== ``` **Throughput Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 236.46 Total input tokens: 621630 Total input vision tokens: 534000 Total generated tokens: 510855 Request throughput (req/s): 4.23 Output token throughput (tok/s): 2160.42 Peak output token throughput (tok/s): 3745.00 Total token throughput (tok/s): 4789.30 Mean TTFT (ms): 952.02 Mean TPOT (ms): 44.17 Median ITL (ms): 26.81 ================================================== ``` #### gemma-4-26B-A4B-it (MoE, 1x H200, TP=1) Server Launch Command: ```bash Command theme={null} sglang serve --model-path google/gemma-4-26B-A4B-it ``` > **Tip**: Consider `--tp 2` for high-throughput workloads. **Latency Benchmark (Text)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 25.00 Total input tokens: 6101 Total generated tokens: 4220 Request throughput (req/s): 0.40 Output token throughput (tok/s): 168.81 Total token throughput (tok/s): 412.85 Mean TTFT (ms): 103.74 Median TTFT (ms): 46.57 Mean TPOT (ms): 5.60 Median ITL (ms): 5.78 ================================================== ``` **Latency Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 25.31 Total input tokens: 6164 Total input vision tokens: 5340 Total generated tokens: 4220 Request throughput (req/s): 0.40 Output token throughput (tok/s): 166.70 Total token throughput (tok/s): 410.20 Mean TTFT (ms): 129.22 Median TTFT (ms): 132.54 Mean TPOT (ms): 5.68 Median ITL (ms): 5.75 ================================================== ``` **Throughput Benchmark (Text)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 138.98 Total input tokens: 512842 Total generated tokens: 510855 Request throughput (req/s): 7.20 Output token throughput (tok/s): 3675.81 Peak output token throughput (tok/s): 4799.00 Total token throughput (tok/s): 7365.91 Mean TTFT (ms): 153.77 Mean TPOT (ms): 25.95 Median ITL (ms): 20.23 ================================================== ``` **Throughput Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 186.38 Total input tokens: 621146 Total input vision tokens: 534000 Total generated tokens: 510855 Request throughput (req/s): 5.37 Output token throughput (tok/s): 2740.86 Peak output token throughput (tok/s): 4962.00 Total token throughput (tok/s): 6073.47 Mean TTFT (ms): 854.71 Mean TPOT (ms): 34.64 Median ITL (ms): 19.08 ================================================== ``` #### gemma-4-31B-it (1x MI300X, TP=1) Server Launch Command: ```bash Command theme={null} sglang serve --model-path google/gemma-4-31B-it ``` > **Note**: The 31B dense model fits on a single MI300X (192 GB VRAM) at TP=1, unlike H200 (141 GB) which requires TP=2. **Latency Benchmark (Text)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang \ --host 0.0.0.0 --port 30000 \ --dataset-name random --num-prompts 10 --max-concurrency 1 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 103.55 Total input tokens: 6101 Total generated tokens: 4220 Request throughput (req/s): 0.10 Output token throughput (tok/s): 40.75 Total token throughput (tok/s): 99.67 Mean TTFT (ms): 152.35 Median TTFT (ms): 169.66 Mean TPOT (ms): 24.13 Median ITL (ms): 24.23 ================================================== ``` **Throughput Benchmark (Text)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang \ --host 0.0.0.0 --port 30000 \ --dataset-name random --num-prompts 1000 --max-concurrency 100 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 441.59 Total input tokens: 512842 Total generated tokens: 510855 Request throughput (req/s): 2.26 Output token throughput (tok/s): 1156.85 Peak output token throughput (tok/s): 1759.00 Total token throughput (tok/s): 2318.19 Mean TTFT (ms): 819.22 Mean TPOT (ms): 82.51 Median ITL (ms): 63.45 ================================================== ``` #### gemma-4-26B-A4B-it (MoE, 1x MI300X, TP=1) Server Launch Command: ```bash Command theme={null} sglang serve --model-path google/gemma-4-26B-A4B-it ``` **Latency Benchmark (Text)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang \ --host 0.0.0.0 --port 30000 \ --dataset-name random --num-prompts 10 --max-concurrency 1 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 43.73 Total input tokens: 6101 Total generated tokens: 4220 Request throughput (req/s): 0.23 Output token throughput (tok/s): 96.49 Total token throughput (tok/s): 236.00 Mean TTFT (ms): 185.58 Median TTFT (ms): 90.18 Mean TPOT (ms): 9.78 Median ITL (ms): 9.57 ================================================== ``` **Throughput Benchmark (Text)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang \ --host 0.0.0.0 --port 30000 \ --dataset-name random --num-prompts 1000 --max-concurrency 100 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 219.43 Total input tokens: 512842 Total generated tokens: 510855 Request throughput (req/s): 4.56 Output token throughput (tok/s): 2328.05 Peak output token throughput (tok/s): 3500.00 Total token throughput (tok/s): 4665.16 Mean TTFT (ms): 168.44 Mean TPOT (ms): 41.23 Median ITL (ms): 29.31 ================================================== ``` #### gemma-4-12B-it (1x H200, TP=1) Server Launch Command: ```bash Command theme={null} sglang serve --model-path google/gemma-4-12B-it ``` **Latency Benchmark (Text)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang \ --host 0.0.0.0 --port 30000 \ --dataset-name random --num-prompts 10 --max-concurrency 1 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 38.66 Total input tokens: 6101 Total generated tokens: 4220 Request throughput (req/s): 0.26 Output token throughput (tok/s): 109.15 Total token throughput (tok/s): 266.94 Mean TTFT (ms): 33.08 Median TTFT (ms): 33.71 Mean TPOT (ms): 9.02 Median ITL (ms): 9.19 ================================================== ``` **Latency Benchmark (Image)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang-oai-chat \ --host 0.0.0.0 --port 30000 \ --dataset-name image --image-count 2 --image-resolution 720p \ --random-input-len 128 --random-output-len 1024 \ --num-prompts 10 --max-concurrency 1 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 39.36 Total input vision tokens: 5320 Total generated tokens: 4220 Request throughput (req/s): 0.25 Output token throughput (tok/s): 107.23 Total token throughput (tok/s): 263.62 Mean TTFT (ms): 94.98 Median TTFT (ms): 97.33 Mean TPOT (ms): 9.08 Median ITL (ms): 9.17 ================================================== ``` **Throughput Benchmark (Text)** ```bash Command theme={null} python3 -m sglang.bench_serving --backend sglang \ --host 0.0.0.0 --port 30000 \ --dataset-name random --num-prompts 1000 --max-concurrency 100 ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 130.44 Total input tokens: 512842 Total generated tokens: 510855 Request throughput (req/s): 7.67 Output token throughput (tok/s): 3916.46 Total token throughput (tok/s): 7848.15 Mean TTFT (ms): 207.49 Median TTFT (ms): 76.95 Mean TPOT (ms): 24.38 Median ITL (ms): 17.89 ================================================== ``` **Throughput Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 147.57 Total input tokens: 619609 Total input vision tokens: 532000 Total generated tokens: 510855 Request throughput (req/s): 6.78 Output token throughput (tok/s): 3461.79 Total token throughput (tok/s): 7660.54 Mean TTFT (ms): 438.40 Median TTFT (ms): 129.83 Mean TPOT (ms): 27.12 Median ITL (ms): 19.16 ================================================== ``` #### gemma-4-12B-it (1x B200, TP=1) Server Launch Command: ```bash Command theme={null} # Text/audio: the sm100 default (trtllm_mha) is fastest. # For image workloads add --attention-backend triton (bidirectional image attention). sglang serve --model-path google/gemma-4-12B-it --attention-backend triton ``` **Latency Benchmark (Text)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 30.46 Output token throughput (tok/s): 138.55 Total token throughput (tok/s): 338.85 Mean TTFT (ms): 28.14 Median TTFT (ms): 29.74 Mean TPOT (ms): 7.08 Median ITL (ms): 7.26 ================================================== ``` **Latency Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 31.43 Total input vision tokens: 5320 Total generated tokens: 4220 Request throughput (req/s): 0.32 Output token throughput (tok/s): 134.26 Total token throughput (tok/s): 329.57 Mean TTFT (ms): 115.51 Median TTFT (ms): 74.27 Mean TPOT (ms): 7.14 Median ITL (ms): 7.24 ================================================== ``` **Throughput Benchmark (Text)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 92.94 Request throughput (req/s): 10.76 Output token throughput (tok/s): 5496.55 Total token throughput (tok/s): 11014.49 Mean TTFT (ms): 120.89 Median TTFT (ms): 45.00 Mean TPOT (ms): 17.23 Median ITL (ms): 14.30 ================================================== ``` **Throughput Benchmark (Image)** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang-oai-chat Max request concurrency: 100 Successful requests: 998 Benchmark duration (s): 107.82 Total input tokens: 617971 Total input vision tokens: 530936 Total generated tokens: 508951 Request throughput (req/s): 9.26 Output token throughput (tok/s): 4720.29 Total token throughput (tok/s): 10451.68 Mean TTFT (ms): 425.89 Median TTFT (ms): 109.57 Mean TPOT (ms): 19.45 Median ITL (ms): 15.11 ================================================== ``` > **Performance tuning**: On B200, raising `--scheduler-recv-interval` to 16 lifted text throughput from 5497 to 5673 tok/s output (≈ +3%) at concurrency 100 with no accuracy change, by reducing the scheduler's per-step Python overhead. It is a safe, low-risk knob for high-concurrency serving. ### 5.2 Accuracy Benchmark **Test Environment:** * Hardware: H200 * SGLang Version: gemma4 branch #### MMLU
Model Humanities Social Sciences STEM Other Overall
gemma-4-E2B-it 0.621 0.739 0.830 0.736 **0.720**
gemma-4-E4B-it 0.703 0.862 0.902 0.825 **0.810**
gemma-4-12B-it 0.784 0.888 0.946 0.861 **0.859**
gemma-4-31B-it 0.878 0.921 0.884 0.911 **0.896**
gemma-4-26B-A4B-it 0.853 0.906 0.938 0.886 **0.891**
#### GSM8K
Model Accuracy Invalid Latency (s) Output Throughput (tok/s)
gemma-4-E2B-it 0.170 0.000 3.990 8041.739
gemma-4-E4B-it 0.745 0.000 4.174 4672.030
gemma-4-12B-it 0.431 0.052 55.105 6580.229
gemma-4-31B-it 0.805 0.005 16.148 1559.914
gemma-4-26B-A4B-it 0.450 0.010 13.001 4089.457
> **Note**: These GSM8K numbers use the raw few-shot completion harness (now removed). `gemma-4-12B-it` is reasoning-oriented and is under-elicited by raw few-shot prompting; with the chat template it scores **0.950** on the same 1319 GSM8K test questions (also measured before the sgl-eval migration). #### gemma-4-12B-it with sgl-eval `gemma-4-12B-it` is reasoning-oriented and answers verbosely (step-by-step) rather than emitting a terse final line. Strict last-line `Answer: $LETTER` extraction (as in `sglang.test.run_eval`) therefore undercounts its correct answers. [sgl-eval](https://github.com/sgl-project/sgl-eval) — sgl-project's evaluation CLI, which uses robust answer extraction — gives a faithful score on the served model: | Benchmark | Examples | Accuracy | | - | - | - | | MMLU | 2000 | **0.878** | | GSM8K | 1319 | **0.960** | Reproduce against a running server (`--base-url` points at your endpoint): ```bash Command theme={null} pip install sgl-eval # Sanity-check the endpoint sgl-eval ping --base-url http://localhost:30000/v1 # Run the benchmarks (greedy, single-shot) sgl-eval run gsm8k --base-url http://localhost:30000/v1 sgl-eval run mmlu --base-url http://localhost:30000/v1 --num-examples 2000 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. #### MMMU
Model Overall
gemma-4-E2B-it **0.307**
gemma-4-E4B-it **0.396**
gemma-4-12B-it **0.683**
gemma-4-31B-it **0.589**
gemma-4-26B-A4B-it **0.549**
MMMU detailed scores (per domain) **gemma-4-E2B-it** ```json Config theme={null} {"Overall-Art and Design": {"num": 120, "acc": 0.45}, "Art": {"num": 30, "acc": 0.5}, "Art_Theory": {"num": 30, "acc": 0.467}, "Design": {"num": 30, "acc": 0.5}, "Music": {"num": 30, "acc": 0.333}, "Overall-Business": {"num": 150, "acc": 0.26}, "Accounting": {"num": 30, "acc": 0.367}, "Economics": {"num": 30, "acc": 0.233}, "Finance": {"num": 30, "acc": 0.2}, "Manage": {"num": 30, "acc": 0.233}, "Marketing": {"num": 30, "acc": 0.267}, "Overall-Science": {"num": 150, "acc": 0.273}, "Biology": {"num": 30, "acc": 0.233}, "Chemistry": {"num": 30, "acc": 0.267}, "Geography": {"num": 30, "acc": 0.367}, "Math": {"num": 30, "acc": 0.233}, "Physics": {"num": 30, "acc": 0.267}, "Overall-Health and Medicine": {"num": 150, "acc": 0.273}, "Basic_Medical_Science": {"num": 30, "acc": 0.5}, "Clinical_Medicine": {"num": 30, "acc": 0.233}, "Diagnostics_and_Laboratory_Medicine": {"num": 30, "acc": 0.233}, "Pharmacy": {"num": 30, "acc": 0.3}, "Public_Health": {"num": 30, "acc": 0.1}, "Overall-Humanities and Social Science": {"num": 120, "acc": 0.4}, "History": {"num": 30, "acc": 0.4}, "Literature": {"num": 30, "acc": 0.567}, "Sociology": {"num": 30, "acc": 0.333}, "Psychology": {"num": 30, "acc": 0.3}, "Overall-Tech and Engineering": {"num": 210, "acc": 0.252}, "Agriculture": {"num": 30, "acc": 0.333}, "Architecture_and_Engineering": {"num": 30, "acc": 0.267}, "Computer_Science": {"num": 30, "acc": 0.233}, "Electronics": {"num": 30, "acc": 0.1}, "Energy_and_Power": {"num": 30, "acc": 0.3}, "Materials": {"num": 30, "acc": 0.2}, "Mechanical_Engineering": {"num": 30, "acc": 0.333}, "Overall": {"num": 900, "acc": 0.307}} ``` **gemma-4-E4B-it** ```json Config theme={null} {"Overall-Art and Design": {"num": 120, "acc": 0.458}, "Art": {"num": 30, "acc": 0.433}, "Art_Theory": {"num": 30, "acc": 0.567}, "Design": {"num": 30, "acc": 0.667}, "Music": {"num": 30, "acc": 0.167}, "Overall-Business": {"num": 150, "acc": 0.287}, "Accounting": {"num": 30, "acc": 0.233}, "Economics": {"num": 30, "acc": 0.467}, "Finance": {"num": 30, "acc": 0.133}, "Manage": {"num": 30, "acc": 0.3}, "Marketing": {"num": 30, "acc": 0.3}, "Overall-Science": {"num": 150, "acc": 0.28}, "Biology": {"num": 30, "acc": 0.333}, "Chemistry": {"num": 30, "acc": 0.133}, "Geography": {"num": 30, "acc": 0.4}, "Math": {"num": 30, "acc": 0.2}, "Physics": {"num": 30, "acc": 0.333}, "Overall-Health and Medicine": {"num": 150, "acc": 0.427}, "Basic_Medical_Science": {"num": 30, "acc": 0.4}, "Clinical_Medicine": {"num": 30, "acc": 0.533}, "Diagnostics_and_Laboratory_Medicine": {"num": 30, "acc": 0.4}, "Pharmacy": {"num": 30, "acc": 0.4}, "Public_Health": {"num": 30, "acc": 0.4}, "Overall-Humanities and Social Science": {"num": 120, "acc": 0.7}, "History": {"num": 30, "acc": 0.633}, "Literature": {"num": 30, "acc": 0.867}, "Sociology": {"num": 30, "acc": 0.733}, "Psychology": {"num": 30, "acc": 0.567}, "Overall-Tech and Engineering": {"num": 210, "acc": 0.324}, "Agriculture": {"num": 30, "acc": 0.533}, "Architecture_and_Engineering": {"num": 30, "acc": 0.3}, "Computer_Science": {"num": 30, "acc": 0.367}, "Electronics": {"num": 30, "acc": 0.133}, "Energy_and_Power": {"num": 30, "acc": 0.4}, "Materials": {"num": 30, "acc": 0.2}, "Mechanical_Engineering": {"num": 30, "acc": 0.333}, "Overall": {"num": 900, "acc": 0.396}} ``` **gemma-4-12B-it** ```json Config theme={null} {"Overall-Art and Design": {"num": 120, "acc": 0.667}, "Art": {"num": 30, "acc": 0.7}, "Art_Theory": {"num": 30, "acc": 0.867}, "Design": {"num": 30, "acc": 0.767}, "Music": {"num": 30, "acc": 0.333}, "Overall-Business": {"num": 150, "acc": 0.747}, "Accounting": {"num": 30, "acc": 0.767}, "Economics": {"num": 30, "acc": 0.767}, "Finance": {"num": 30, "acc": 0.633}, "Manage": {"num": 30, "acc": 0.7}, "Marketing": {"num": 30, "acc": 0.867}, "Overall-Science": {"num": 150, "acc": 0.647}, "Biology": {"num": 30, "acc": 0.6}, "Chemistry": {"num": 30, "acc": 0.633}, "Geography": {"num": 30, "acc": 0.567}, "Math": {"num": 30, "acc": 0.6}, "Physics": {"num": 30, "acc": 0.833}, "Overall-Health and Medicine": {"num": 150, "acc": 0.68}, "Basic_Medical_Science": {"num": 30, "acc": 0.667}, "Clinical_Medicine": {"num": 30, "acc": 0.633}, "Diagnostics_and_Laboratory_Medicine": {"num": 30, "acc": 0.267}, "Pharmacy": {"num": 30, "acc": 0.833}, "Public_Health": {"num": 30, "acc": 1.0}, "Overall-Humanities and Social Science": {"num": 120, "acc": 0.817}, "History": {"num": 30, "acc": 0.8}, "Literature": {"num": 30, "acc": 0.9}, "Sociology": {"num": 30, "acc": 0.8}, "Psychology": {"num": 30, "acc": 0.767}, "Overall-Tech and Engineering": {"num": 210, "acc": 0.6}, "Agriculture": {"num": 30, "acc": 0.467}, "Architecture_and_Engineering": {"num": 30, "acc": 0.667}, "Computer_Science": {"num": 30, "acc": 0.733}, "Electronics": {"num": 30, "acc": 0.567}, "Energy_and_Power": {"num": 30, "acc": 0.667}, "Materials": {"num": 30, "acc": 0.567}, "Mechanical_Engineering": {"num": 30, "acc": 0.533}, "Overall": {"num": 900, "acc": 0.683}} ``` **gemma-4-31B-it** ```json Config theme={null} {"Overall-Art and Design": {"num": 120, "acc": 0.667}, "Art": {"num": 30, "acc": 0.667}, "Art_Theory": {"num": 30, "acc": 0.867}, "Design": {"num": 30, "acc": 0.8}, "Music": {"num": 30, "acc": 0.333}, "Overall-Business": {"num": 150, "acc": 0.573}, "Accounting": {"num": 30, "acc": 0.633}, "Economics": {"num": 30, "acc": 0.733}, "Finance": {"num": 30, "acc": 0.433}, "Manage": {"num": 30, "acc": 0.533}, "Marketing": {"num": 30, "acc": 0.533}, "Overall-Science": {"num": 150, "acc": 0.527}, "Biology": {"num": 30, "acc": 0.667}, "Chemistry": {"num": 30, "acc": 0.567}, "Geography": {"num": 30, "acc": 0.5}, "Math": {"num": 30, "acc": 0.267}, "Physics": {"num": 30, "acc": 0.633}, "Overall-Health and Medicine": {"num": 150, "acc": 0.673}, "Basic_Medical_Science": {"num": 30, "acc": 0.733}, "Clinical_Medicine": {"num": 30, "acc": 0.533}, "Diagnostics_and_Laboratory_Medicine": {"num": 30, "acc": 0.467}, "Pharmacy": {"num": 30, "acc": 0.8}, "Public_Health": {"num": 30, "acc": 0.833}, "Overall-Humanities and Social Science": {"num": 120, "acc": 0.825}, "History": {"num": 30, "acc": 0.833}, "Literature": {"num": 30, "acc": 0.867}, "Sociology": {"num": 30, "acc": 0.767}, "Psychology": {"num": 30, "acc": 0.833}, "Overall-Tech and Engineering": {"num": 210, "acc": 0.405}, "Agriculture": {"num": 30, "acc": 0.667}, "Architecture_and_Engineering": {"num": 30, "acc": 0.2}, "Computer_Science": {"num": 30, "acc": 0.567}, "Electronics": {"num": 30, "acc": 0.333}, "Energy_and_Power": {"num": 30, "acc": 0.533}, "Materials": {"num": 30, "acc": 0.3}, "Mechanical_Engineering": {"num": 30, "acc": 0.233}, "Overall": {"num": 900, "acc": 0.589}} ``` **gemma-4-26B-A4B-it** ```json Config theme={null} {"Overall-Art and Design": {"num": 120, "acc": 0.717}, "Art": {"num": 30, "acc": 0.733}, "Art_Theory": {"num": 30, "acc": 0.833}, "Design": {"num": 30, "acc": 0.867}, "Music": {"num": 30, "acc": 0.433}, "Overall-Business": {"num": 150, "acc": 0.493}, "Accounting": {"num": 30, "acc": 0.533}, "Economics": {"num": 30, "acc": 0.533}, "Finance": {"num": 30, "acc": 0.333}, "Manage": {"num": 30, "acc": 0.5}, "Marketing": {"num": 30, "acc": 0.567}, "Overall-Science": {"num": 150, "acc": 0.473}, "Biology": {"num": 30, "acc": 0.633}, "Chemistry": {"num": 30, "acc": 0.367}, "Geography": {"num": 30, "acc": 0.533}, "Math": {"num": 30, "acc": 0.267}, "Physics": {"num": 30, "acc": 0.567}, "Overall-Health and Medicine": {"num": 150, "acc": 0.62}, "Basic_Medical_Science": {"num": 30, "acc": 0.767}, "Clinical_Medicine": {"num": 30, "acc": 0.533}, "Diagnostics_and_Laboratory_Medicine": {"num": 30, "acc": 0.433}, "Pharmacy": {"num": 30, "acc": 0.7}, "Public_Health": {"num": 30, "acc": 0.667}, "Overall-Humanities and Social Science": {"num": 120, "acc": 0.758}, "History": {"num": 30, "acc": 0.8}, "Literature": {"num": 30, "acc": 0.833}, "Sociology": {"num": 30, "acc": 0.733}, "Psychology": {"num": 30, "acc": 0.667}, "Overall-Tech and Engineering": {"num": 210, "acc": 0.376}, "Agriculture": {"num": 30, "acc": 0.633}, "Architecture_and_Engineering": {"num": 30, "acc": 0.367}, "Computer_Science": {"num": 30, "acc": 0.533}, "Electronics": {"num": 30, "acc": 0.167}, "Energy_and_Power": {"num": 30, "acc": 0.367}, "Materials": {"num": 30, "acc": 0.367}, "Mechanical_Engineering": {"num": 30, "acc": 0.2}, "Overall": {"num": 900, "acc": 0.549}} ``` #### ASR
Model WER Avg Latency (s) Throughput (req/s)
gemma-4-E2B-it 23.86% 0.212 2.99
gemma-4-E4B-it 29.55% 0.366 2.46
gemma-4-12B-it Supported (see §4.5) — —
gemma-4-31B-it Not Supported — —
gemma-4-26B-A4B-it Not Supported — —
#### FLEUR (EN\_US)
Model WER Avg Latency (s) Throughput (req/s)
gemma-4-E2B-it 7.37% 0.8963s 16.25
gemma-4-E4B-it 6.08% 0.8707s 16.20
gemma-4-12B-it Supported (see §4.5) — —
gemma-4-31B-it Not Supported — —
gemma-4-26B-A4B-it Not Supported — —
### 5.3 Logits correctness validation **gemma-4-E2B-it** ```shell Command theme={null} $ python -m sglang.benchmark.one_batch --correct --model google/gemma-4-E2B-it .... prefill logits (final): tensor([[-25.3063, -2.5718, -10.3674, ..., -25.3779, -25.5181, -25.2337]], device='cuda:0') .... $ python scripts/playground/reference_hf.py --model-path google/gemma-4-E2B-it .... prefill logits (final) tensor([-25.3281, -2.1367, -10.2266, ..., -25.4375, -25.5000, -25.2500], device='cuda:0', dtype=torch.float16) .... ``` **gemma-4-E4B-it** ```shell Command theme={null} $ python -m sglang.benchmark.one_batch --correct --model google/gemma-4-E4B-it .... prefill logits (final): tensor([[-17.6478, 7.9901, -5.6505, ..., -17.5658, -17.6478, -17.7293]], device='cuda:0') .... $ python scripts/playground/reference_hf.py --model-path google/gemma-4-E4B-it .... prefill logits (final) tensor([-17.5625, 8.0469, -5.5742, ..., -17.4688, -17.5625, -17.6719], device='cuda:0', dtype=torch.float16) .... ``` **gemma-4-31B-it** ```shell Command theme={null} $ python -m sglang.benchmark.one_batch --correct --model google/gemma-4-31B-it .... prefill logits (final): tensor([[-2.0748, 1.1245, -7.4356, ..., -2.1059, -2.1525, -2.2303]], device='cuda:0') .... $ python scripts/playground/reference_hf.py --model-path google/gemma-4-31B-it .... prefill logits (final) tensor([-2.1133, 1.2656, -7.4766, ..., -2.1523, -2.2012, -2.2695], device='cuda:0', dtype=torch.float16) .... ```
# Granite 4.2 Source: https://docs.sglang.io/cookbook/autoregressive/IBM/Granite-4.2 Deploy Granite 4.2 3B, 8B, and 30B dense models with SGLang on NVIDIA H200 and B200, including thinking modes and structured tool calling. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick a Granite 4.2 checkpoint to generate the launch command. The verified matrix covers BF16 serving on one NVIDIA H200 or B200 with tensor parallelism 1. > [!NOTE] > > The H200 speed results use `lmsysorg/sglang:dev` at SGLang commit `d59c1ddf7` and the B200 results at commit `d10a656ad8`; the launch recipes were verified end to end on both GPUs against the release checkpoints. Each speed point uses 80 fixed-length random requests at 8,192 input and 1,024 output tokens, 8 warmup requests, a flushed cache, greedy sampling, and ignore-EOS. ## Playground The Playground layers SGLang features on top of the verified recipe. Any override changes the badge to **Not Verified** until that exact configuration is tested end to end. ## 1. Model introduction **Granite 4.2** is IBM's dense decoder-only language model family with 3B, 8B, and 30B checkpoints. Each checkpoint uses BF16 weights, has a configured context length of 131,072 tokens, and supports default thinking, non-thinking, low-effort thinking, and structured tool calls through its chat template. The repositories declare the Apache-2.0 license.
Variant Total params Position in family
**[Granite 4.2 3B](https://huggingface.co/ibm-granite/granite-4.2-3b)** 3B Smallest checkpoint
**[Granite 4.2 8B](https://huggingface.co/ibm-granite/granite-4.2-8b)** 8B Mid-size checkpoint
**[Granite 4.2 30B](https://huggingface.co/ibm-granite/granite-4.2-30b)** 30B Largest checkpoint
**Recommended generation:** IBM recommends `temperature=1.0` and `top_p=0.95` for general chat, reasoning, and tool calling. The release checkpoints ship these values in `generation_config.json`; send them per request when you want to be explicit. **Resources:** [Granite 4.2 3B](https://huggingface.co/ibm-granite/granite-4.2-3b) · [Granite 4.2 8B](https://huggingface.co/ibm-granite/granite-4.2-8b) · [Granite 4.2 30B](https://huggingface.co/ibm-granite/granite-4.2-30b). ## 2. Configuration tips * **Thinking is enabled by default.** Set `chat_template_kwargs.enable_thinking` to `false` for a direct answer. Set `enable_thinking` and `low_effort` to `true` for a shorter reasoning trace. * **Give thinking enough tokens.** At `temperature=1.0` the default thinking mode can run past 1,000 tokens on multi-step problems. Use a `max_tokens` of at least 2,048 for thinking requests so the answer is not cut off. * **Reasoning parser.** Launch with `--reasoning-parser auto`, which resolves to `nemotron_3` for these checkpoints, so OpenAI-compatible responses separate the trace into `message.reasoning_content` and the answer into `message.content`. Without a parser flag the reasoning markup stays inline in `message.content`. * **Tool-call parser.** Launch with `--tool-call-parser auto`, which resolves to `qwen3_coder` for these checkpoints, so tool requests are returned through `message.tool_calls`. Without it, raw `` markup stays in `message.content`. * **Single-GPU sizing.** All three BF16 checkpoints loaded and completed chat requests with `--tp 1 --mem-fraction-static 0.8` on one H200 and on one B200. Increase TP only after validating the new topology. * **Image selection.** The validated path uses `lmsysorg/sglang:dev`. A stable image tested during validation had an incompatible dependency set before model loading, so use the recipe's image until a newer tagged release is confirmed. ## 3. Advanced usage The outputs below are verbatim captures from Granite 4.2 3B on the verified server. Sampling is stochastic, so a repeated request can produce different wording. ### 3.1 Thinking modes The `nemotron_3` reasoning parser keeps reasoning and final content in separate fields. Granite 4.2 accepts three chat-template modes: default thinking, non-thinking, and low-effort thinking. > **Thinking modes example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > model = "ibm-granite/granite-4.2-3b" > > modes = { > "thinking": {"enable_thinking": True}, > "non-thinking": {"enable_thinking": False}, > "low-effort": {"enable_thinking": True, "low_effort": True}, > } > > for name, chat_template_kwargs in modes.items(): > response = client.chat.completions.create( > model=model, > messages=[ > {"role": "user", "content": "What is 17 * 23? Answer briefly."} > ], > extra_body={"chat_template_kwargs": chat_template_kwargs}, > ) > message = response.choices[0].message > print(f"[{name}]") > print("Reasoning:", getattr(message, "reasoning_content", None)) > print("Answer:", message.content) > ``` > **Example output** > > ```text Output theme={null} > [thinking] > Reasoning: Okay, the user asked "What is 17 * 23? Answer briefly." I need to calculate 17 multiplied by 23. > > Let me do the multiplication. 17 times 23. > > I can break it down: 17 * 20 = 340, and 17 * 3 = 51. Then add them: 340 + 51 = 391. > > Alternatively, 23 * 17: 23*10=230, 23*7=161, 230+161=391. Same result. > > So the answer is 391. > > The user wants a brief answer, so just state the number. > > Answer: > 391 > [non-thinking] > Reasoning: None > Answer: 391 > [low-effort] > Reasoning: Compute 17*23 = 17*20=340, plus 17*3=51 => 391. > > Answer: > 391 > ``` ### 3.2 Tool calling The `qwen3_coder` parser converts the model's tool markup into OpenAI-compatible structured calls. > **Tool calling example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city.", > "parameters": { > "type": "object", > "properties": { > "city": {"type": "string", "description": "The city name"}, > }, > "required": ["city"], > }, > }, > }] > > response = client.chat.completions.create( > model="ibm-granite/granite-4.2-3b", > messages=[{"role": "user", "content": "What is the weather in Boston right now?"}], > tools=tools, > tool_choice="auto", > ) > > choice = response.choices[0] > message = choice.message > print("Reasoning:", getattr(message, "reasoning_content", None)) > print("Content:", message.content) > for call in message.tool_calls or []: > print("Tool:", call.function.name) > print("Arguments:", call.function.arguments) > print("Finish reason:", choice.finish_reason) > ``` > **Example output** > > ```text Output theme={null} > Reasoning: Okay, the user is asking for the weather in Boston right now. I need to use the available tool called get_weather. The tool requires the city parameter. Since the user specified Boston, I'll call get_weather with city set to Boston. > > Content: None > Tool: get_weather > Arguments: {"city": "Boston"} > Finish reason: tool_calls > ``` # Jais 3 Source: https://docs.sglang.io/cookbook/autoregressive/IFM/Jais-3 Deploy the IFM Jais 3 family with SGLang — BF16 recipes for six dense and Mixture-of-Experts checkpoints on NVIDIA H100 GPUs. ## Deployment > **Install SGLang** > > Jais 3 is supported from SGLang 0.5.20: > > ```bash Command theme={null} > pip install --upgrade pip > pip install "sglang>=0.5.20" > ``` > > For other install methods, see [Install](/docs/get-started/install). Choose a model size to generate its H100 launch command. Five checkpoints run on a single node; 375B-A23B needs two. The recipes serve each repository's `main` branch. Each accuracy value in the benchmark cards is the arithmetic mean of two full evaluation runs. Speed values come from a single run. ## Playground The base recipes enable the `k2_horizon` reasoning parser. Use the Playground to configure the `k2_horizon` tool-call parser, TP and MoE expert-parallel overrides, NGRAM speculative decoding, PD disaggregation, and HiCache. A separate validation pass functionally exercised the tool-call parser on all six checkpoints; every other Playground override remains unverified. ## 1. Model introduction **Jais 3** is an IFM model family spanning six checkpoints from **0.9B** to **375B** parameters. The family includes dense models, Mixture-of-Experts models, and the MoVA-36B-A4B checkpoint's routed Mixture-of-Value-Attention path. This page provides native SGLang serving recipes for the family.
Checkpoint Architecture Context length H100 recipe
**[0.9B](https://huggingface.co/IFM/Jais-3-0.9B)** Dense 131,072 BF16 · TP1
**[3.7B](https://huggingface.co/IFM/Jais-3-3.7B)** Dense 524,288 BF16 · TP1
**[7B](https://huggingface.co/IFM/Jais-3-7B)** Dense 524,288 BF16 · TP1
**[32B](https://huggingface.co/IFM/Jais-3-32B)** Dense 524,288 BF16 · TP2
**[MoVA-36B-A4B](https://huggingface.co/IFM/Jais-3-MoVA-36B-A4B)** MoE + MoVA 524,288 BF16 · TP2 · EP2
**[375B-A23B](https://huggingface.co/IFM/Jais-3-375B-A23B)** MoE 524,288 BF16 · TP16 · EP16 · 2 nodes
**Resources:** [Jais 3 collection](https://huggingface.co/collections/IFM/jais-3) · [Jais 3 375B-A23B model card](https://huggingface.co/IFM/Jais-3-375B-A23B). ## 2. Configuration tips * **Hardware and precision:** The current matrix covers NVIDIA H100 GPUs and BF16 checkpoints only. * **Parallelism:** Use TP1 for 0.9B, 3.7B, and 7B; TP2 for 32B; TP2 with expert parallelism (`--ep 2`) for MoVA-36B-A4B; and TP16 with `--ep 16` across two eight-GPU nodes for 375B-A23B. Every other recipe stays within one node. * **Attention:** The verified base recipes select FlashAttention-3 with `--attention-backend fa3`. * **Parsers:** The base recipes enable reasoning with `--reasoning-parser k2_horizon`. Enable `--tool-call-parser k2_horizon` from the **Parsers** card in the [Playground](#playground) when you need tool calling. * **MoVA-36B-A4B router provenance:** The MoVA-36B-A4B checkpoint's source xLLM router used two GEMM partitions. `--json-model-override-args '{"xllm_source_router_gemm_partitions":2}'` preserves its BF16 partial-GEMM rounding and FP32 reduction order; SGLang does not infer this source topology from runtime TP. * **375B-A23B memory:** The BF16 weights take about 760 GB. One node of eight H100 80 GB GPUs holds 640 GB, so the checkpoint does not fit on a single node; the recipe uses two nodes (16 GPUs, 1,280 GB). Run the generated command on both nodes, with node rank 0 on the head node and 1 on the other. * **375B-A23B loading:** The 375B-A23B recipe disables multithreaded weight loading with `--model-loader-extra-config '{"enable_multithread_load":false}'`. * **Playground features:** TP and EP settings other than the base recipes', NGRAM, PD disaggregation, and HiCache are optional, unverified command overrides. The tool-call parser was functionally exercised separately. * **Deliberate omissions:** Context parallelism is unsupported or unvalidated for xLLM. DP-attention and alternate MoE backend selectors are not exposed until they are validated. * **Validation:** All six recipes completed two full GSM8K evaluation runs on H100; see [Benchmark results](#3-benchmark-results). ## 3. Benchmark results Speed was measured with native `sglang.benchmark.serving` using fixed random token IDs: 8,192 input tokens, 1,024 output tokens, 64 warmup requests, a cache flush, and seed `20260901`. The latency run uses 32 prompts at concurrency 1. The throughput run uses 256 prompts at concurrency 64 for the single-GPU checkpoints, 32 for the two-GPU checkpoints, and 8 for the two-node 375B-A23B. Each speed value comes from a single run, with the load generator on a separate client node; TTFT and TPOT are medians. Throughput per GPU is `(total input tokens + total output tokens) / duration / TP`. Checkpoints and workloads not yet measured show a dash in the benchmark cards. GSM8K used the full 1,319-example test split with `sgl-eval`, 32 client threads, a 32,768-token output limit, temperature 0, top-p 0.95, seed 0, and high reasoning effort. Each server ran on H100 from the repository's `main` branch, with no pinned revision. The evaluation is zero-shot: each question is sent as a single user message with the `math` prompt, which asks for the final answer inside `\boxed{}`, and no worked examples. Scoring is rule-based accuracy with no LLM judge: `sgl-eval` extracts the last `\boxed{}` from the final answer and checks it against the reference by symbolic equivalence, so `\$57{,}500` matches `57500`. A response with no boxed answer counts as incorrect, so these scores can be lower than LLM-as-a-judge results on the same outputs. Each checkpoint was evaluated twice, and the table shows both runs and their mean. The 0.9B and 3.7B runs were issued one after the other; from 7B onward both were issued together with `--n-repeats 2` against one running server. All requests completed without errors. Responses that reached the output limit stay in the score and count as incorrect; the Truncated column gives the share of such responses in run 1 and run 2. | Checkpoint | Run 1 | Run 2 | Mean | Truncated | | - | -: | -: | -: | -: | | 0.9B | 83.62% | 83.78% | 83.70% | 0.68% / 0.61% | | 3.7B | 96.36% | 96.13% | 96.25% | 0.00% / 0.15% | | 7B | 95.91% | 95.83% | 95.87% | 0.00% / 0.08% | | 32B | 96.51% | 96.74% | 96.63% | 0.00% / 0.00% | | MoVA-36B-A4B | 95.98% | 96.44% | 96.21% | 0.00% / 0.00% | | 375B-A23B | 96.44% | 96.21% | 96.32% | 0.00% / 0.00% | ## 4. Advanced usage ### 4.1 Reasoning The base recipes include `--reasoning-parser k2_horizon`. The parser returns thinking in `reasoning_content` and the final answer in `content`. The example output below was captured with the MoVA-36B-A4B checkpoint and both parser flags enabled. > **Reasoning example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > response = client.chat.completions.create( > model="IFM/Jais-3-MoVA-36B-A4B", > messages=[{"role": "user", "content": "Hello"}], > ) > > message = response.choices[0].message > reasoning = getattr(message, "reasoning_content", None) > if reasoning is None: > reasoning = (message.model_extra or {}).get("reasoning_content") > print("Reasoning:", reasoning) > print("Answer:", message.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user says "Hello". As a helpful AI, we should greet them back, maybe ask how we can assist. > > We need to respond with a friendly greeting. Probably something like "Hello! How can I help you today?" > > That's straightforward. > > We should consider any policies for greeting. No issues. > > Let's proceed. > Answer: Hello! How can I help you today? > ``` ### 4.2 Tool calling Enable **Tool Call Parser** in the **Parsers** card of the [Playground](#playground) to add `--tool-call-parser k2_horizon`. The parser exposes K2 tool output as OpenAI-compatible `message.tool_calls`. The example output below was captured with the MoVA-36B-A4B checkpoint and both parser flags enabled. > **Tool-calling example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Return weather for a city.", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string"}}, > "required": ["city"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="IFM/Jais-3-MoVA-36B-A4B", > messages=[{"role": "user", "content": "Call get_weather for Paris."}], > tools=tools, > tool_choice={"type": "function", "function": {"name": "get_weather"}}, > max_tokens=1024, > ) > > message = response.choices[0].message > reasoning = getattr(message, "reasoning_content", None) > if reasoning is None: > reasoning = (message.model_extra or {}).get("reasoning_content") > print("Reasoning:", reasoning) > print("Content:", message.content or "") > for tool_call in message.tool_calls or []: > print(f"Tool call: {tool_call.function.name}({tool_call.function.arguments})") > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user wants the weather for Paris, using the get_weather function. We'll call the function. > Content: [{"name":"get_weather", "parameters": {"city": "Paris"}}] > ``` ### 4.3 HiCache For large checkpoints or repeated long-context prefixes, enable **HiCache** in the [Playground](#playground), then choose a storage backend and write policy. Treat the generated override as unverified until it is exercised on your storage stack. # K2 Horizon Source: https://docs.sglang.io/cookbook/autoregressive/IFM/K2-Horizon Deploy the IFM K2 Horizon family with SGLang — BF16 recipes for six dense and Mixture-of-Experts checkpoints on NVIDIA H200 GPUs. ## Deployment > **Install SGLang** > > Install from a source checkout that includes the K2 Horizon runtime support in [PR #37654](https://github.com/sgl-project/sglang/pull/37654) before using the generated commands: > > ```bash Command theme={null} > pip install --upgrade pip > pip install -e "python" > ``` > > For general source-install guidance, see [Install → Method 2: From source](/docs/get-started/install#method-2-from-source). Choose a model size to generate its validated single-node H200 launch command. The serving settings in all six base recipes completed two independent H200 benchmark launches at the pinned model revisions using the K2 Horizon runtime support in [PR #37654](https://github.com/sgl-project/sglang/pull/37654). Each speed and accuracy value in the benchmark cards is the arithmetic mean of two independent server launches. ## Playground The base recipes enable the `k2_horizon` reasoning parser. Use the Playground to configure the `k2_horizon` tool-call parser, TP and MoE expert-parallel overrides, NGRAM speculative decoding, PD disaggregation, and HiCache. A separate validation pass functionally exercised the tool-call parser on all six checkpoints; every other Playground override remains unverified. ## 1. Model introduction **K2 Horizon** is an IFM model family spanning six checkpoints from **0.9B** to **375B** parameters. The family includes dense models, Mixture-of-Experts models, and the MoVA-36B-A4B checkpoint's routed Mixture-of-Value-Attention path. This page provides native SGLang serving recipes for the family.
Checkpoint Architecture Context length H200 recipe
**[0.9B](https://huggingface.co/IFM/K2-Horizon-0.9B)** Dense 131,072 BF16 · TP1
**[3.7B](https://huggingface.co/IFM/K2-Horizon-3.7B)** Dense 524,288 BF16 · TP1
**[7B](https://huggingface.co/IFM/K2-Horizon-7B)** Dense 524,288 BF16 · TP1
**[32B](https://huggingface.co/IFM/K2-Horizon-32B)** Dense 524,288 BF16 · TP2
**[MoVA-36B-A4B](https://huggingface.co/IFM/K2-Horizon-MoVA-36B-A4B)** MoE + MoVA 524,288 BF16 · TP2
**[375B-A23B](https://huggingface.co/IFM/K2-Horizon-375B-A23B)** MoE 524,288 BF16 · TP8
> [!NOTE] > > All six checkpoints use the Apache License 2.0. **Resources:** [K2 Horizon collection](https://huggingface.co/collections/IFM/k2-horizon) · [K2 Horizon 375B-A23B model card](https://huggingface.co/IFM/K2-Horizon-375B-A23B). ## 2. Configuration tips * **Hardware and precision:** The current matrix covers NVIDIA H200 GPUs and BF16 checkpoints only. * **Parallelism:** Use TP1 for 0.9B, 3.7B, and 7B; TP2 for 32B and MoVA-36B-A4B; and TP8 for 375B-A23B. Each recipe stays within one node. * **Attention:** The verified base recipes select FlashAttention-3 with `--attention-backend fa3`. * **Revisions:** The recipes pin revisions `6fbc54f7e4dc9d9cd671351f51498a1958dd2a01` (0.9B), `fe504ef19c7efa3120a9352bcfa180aa133946de` (3.7B), `85d46bbaf6ecd844a8ef61991f6e492d4faf4179` (7B), `eff3d24a3a40360c6fd1a1dd5723ce6329d93484` (32B), `e5c131d4d0ae196f5041284a0f9262d713083901` (MoVA-36B-A4B), and `70d7c58c1f8a2fc523c861c2cf7d2d339d7a8a0c` (375B-A23B). * **Parsers:** The base recipes enable reasoning with `--reasoning-parser k2_horizon`. Enable `--tool-call-parser k2_horizon` from the **Parsers** card in the [Playground](#playground) when you need tool calling. * **MoVA-36B-A4B router provenance:** The MoVA-36B-A4B checkpoint's source xLLM router used two GEMM partitions. `--json-model-override-args '{"xllm_source_router_gemm_partitions":2}'` preserves its BF16 partial-GEMM rounding and FP32 reduction order; SGLang does not infer this source topology from runtime TP. * **375B-A23B loading:** The 375B-A23B recipe disables multithreaded weight loading with `--model-loader-extra-config '{"enable_multithread_load":false}'`. * **Playground features:** TP, EP, NGRAM, PD disaggregation, and HiCache are optional, unverified command overrides. The tool-call parser was functionally exercised separately. * **Deliberate omissions:** Context parallelism is unsupported or unvalidated for xLLM. DP-attention and alternate MoE backend selectors are not exposed until they are validated. * **Validation:** The serving configuration for all six recipes completed native speed and full GSM8K evaluation on H200 using the K2 Horizon runtime support in [PR #37654](https://github.com/sgl-project/sglang/pull/37654). * **Benchmark provenance:** The results below were collected at revisions `9b9ec1f7e17f62ed218df542687a144116219d84` (0.9B), `c177771836a4c460743c00002c22483f6f18d1eb` (3.7B), `69ada542b68fe13d767479db2ab9421baff88681` (7B), `e1fd0277713e4eefcd3416348fd6fedacf7f2392` (32B), `16d20c739c687c08423422d1a2fbba6c529014cd` (MoVA-36B-A4B), and `12812264242a14dce44aa7ae27f931ff4584bcbf` (375B-A23B). The 375B-A23B benchmark launched a directly mounted checkpoint; the other five launches used materialized Hugging Face snapshots. ## 3. Benchmark results Speed was measured with native `sglang.benchmark.serving` using fixed random token IDs: 8,192 input tokens, 1,024 output tokens, 64 warmup requests, a cache flush, and seed `20260901`. The latency run used 32 prompts at concurrency 1. The throughput run used 256 prompts at concurrency 64 for TP1, 32 for TP2, and 8 for TP8. TTFT and TPOT are medians within each launch; the benchmark cards show the arithmetic mean across the two launches. Throughput per GPU is `(total input tokens + total output tokens) / duration / TP`. GSM8K used the full 1,319-example test split with `sgl-eval`, 32 client threads, a 32,768-token output limit, temperature 0, top-p 0.95, seed 0, and high reasoning effort. The mean and both independent server-launch scores are shown below. All requests completed without errors. Responses that reached the output limit remain in the score: truncation was 6.90% in both 0.9B launches, 4.09% and 4.70% for 3.7B, and at most 1.14% for the other checkpoints. | Checkpoint | Launch 1 | Launch 2 | Mean | | - | -: | -: | -: | | 0.9B | 85.22% | 85.29% | 85.25% | | 3.7B | 92.12% | 91.89% | 92.00% | | 7B | 95.30% | 94.47% | 94.88% | | 32B | 95.75% | 96.21% | 95.98% | | MoVA-36B-A4B | 95.45% | 94.84% | 95.15% | | 375B-A23B | 95.53% | 95.60% | 95.56% | ## 4. Advanced usage ### 4.1 Reasoning The base recipes include `--reasoning-parser k2_horizon`. The parser returns thinking in `reasoning_content` and the final answer in `content`. The example output below was captured with the 3.7B checkpoint and both parser flags enabled. > **Reasoning example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > response = client.chat.completions.create( > model="IFM/K2-Horizon-3.7B", > messages=[{"role": "user", "content": "Hello"}], > ) > > message = response.choices[0].message > reasoning = getattr(message, "reasoning_content", None) > if reasoning is None: > reasoning = (message.model_extra or {}).get("reasoning_content") > print("Reasoning:", reasoning) > print("Answer:", message.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: We have a user who just said "Hello". We need to respond. As an AI, we should be friendly, perhaps ask how can we help. If says "Hello" alone, respond with greeting and offer assistance. Potentially ask what they need. There's no special instruction; just typical. > > But maybe we must think about the context: The user gave just a greeting; we should respond with a greeting and ask how we can help. Could also ask if they want anything specific. > > We should be concise but friendly: "Hello! How can I assist you today?" Provide some content. > > But maybe the user expects something else. But in this scenario, we just reply with a greeting. > > Thus answer: "Hello! What can I do for you?" Etc. > > Check any style guidelines: We want to keep it short or perhaps ask follow-up. The user didn't ask any question, just saying hello. Could also respond: "Hello! ..." > > Thus arguably the answer: "Hi there! How can I help you today?" Let's do that. > > But also maybe we could ask if they need help with something specific. That's appropriate. > > Thus the final answer: "Hello! How can I assist you today?" Possibly add friendly banter. > > We'll respond. > > Answer: > Hello! 👋 How can I help you today? > ``` ### 4.2 Tool calling Enable **Tool Call Parser** in the **Parsers** card of the [Playground](#playground) to add `--tool-call-parser k2_horizon`. The parser exposes K2 tool output as OpenAI-compatible `message.tool_calls`. The example output below was captured with the 32B checkpoint and both parser flags enabled. > **Tool-calling example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Return weather for a city.", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string"}}, > "required": ["city"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="IFM/K2-Horizon-32B", > messages=[{"role": "user", "content": "Call get_weather for Paris."}], > tools=tools, > tool_choice={"type": "function", "function": {"name": "get_weather"}}, > max_tokens=1024, > ) > > message = response.choices[0].message > reasoning = getattr(message, "reasoning_content", None) > if reasoning is None: > reasoning = (message.model_extra or {}).get("reasoning_content") > print("Reasoning:", reasoning) > print("Content:", message.content or "") > for tool_call in message.tool_calls or []: > print(f"Tool call: {tool_call.function.name}({tool_call.function.arguments})") > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: Okay, the user wants me to call the get_weather function for Paris. Let me check the tools available. There's a function called get_weather that takes a city parameter. The required parameter is city, and it's a string. So I need to make sure to pass "Paris" as the city. I don't see any other parameters needed. The user didn't mention any other details, so I'll just use the city name. Let me structure the tool call correctly. The function name is get_weather, and the arguments should be a JSON object with "city": "Paris". I need to make sure the JSON is properly formatted. Alright, that should do it. > > Content: > Tool call: get_weather({"city": "Paris"}) > ``` ### 4.3 HiCache For large checkpoints or repeated long-context prefixes, enable **HiCache** in the [Playground](#playground), then choose a storage backend and write policy. Treat the generated override as unverified until it is exercised on your storage stack. # IQuest-Q1 Source: https://docs.sglang.io/cookbook/autoregressive/IQuestLab/IQuest-Q1 Deploy IQuest-Q1 with SGLang — BF16 recipes for the 320B Mixture-of-Experts model on 8× NVIDIA H200, with optional MTP speculative decoding. ## Deployment > **Install SGLang** > > IQuest-Q1 needs an SGLang build that includes IQuest-Q1 support. The nightly image carries it: > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > For other methods, see the [official SGLang installation guide](../../../docs/get-started/install). Download the checkpoint first; the MTP draft lives in its `mtp/` subdirectory: ```bash Command theme={null} hf download IQuestLab/IQuest-Q1 --local-dir /model/IQuest-Q1 ``` Pick a recipe to generate the launch command. **Low-Latency** enables MTP speculative decoding; **High-Throughput** serves the target model alone. ## 1. Model Introduction **IQuest-Q1** is a Mixture-of-Experts language model from IQuestLab with about 320B total parameters and 15B active per token. It has 88 layers that interleave three sliding-window attention layers (4,096-token window) with one full-attention layer, uses learned attention sinks, and routes each token to 8 of 256 experts. It ships with a single-layer MTP draft that SGLang applies recursively for speculative decoding. **Resources:** [HuggingFace](https://huggingface.co/IQuestLab/IQuest-Q1). ## 2. Configuration Tips * **Hardware.** IQuest-Q1 requires the FA3 attention backend for both the target and the MTP draft, because the attention sink is applied from the FA3 softmax LSE. SGLang builds FA3 for Hopper, so Blackwell GPUs are not supported. The BF16 weights take about 640 GB, which fits 8× H200 with tensor parallelism 8. * **Reasoning.** Thinking is on by default. Pass `"chat_template_kwargs": {"thinking": false}` to turn it off for a request. The `iquest_q1` reasoning parser returns the thinking in `reasoning_content`. * **Tool calling.** The `iquest_q1` tool-call parser supports `tool_choice` values `auto`, `required`, and a named function. * **MTP depth.** The single draft layer runs 5 sequential steps, one token each, and each round verifies 6 tokens. Keep `--speculative-num-draft-tokens` equal to `--speculative-num-steps` + 1. # LLaDA 2.1 Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/LLaDA-2.1 ## 1. Model Introduction [LLaDA 2.1](https://github.com/inclusionAI/LLaDA2.X) is a series of large-scale discrete diffusion language models (dLLMs) developed by the InclusionAI team at Ant Group. Unlike traditional autoregressive models that generate text left-to-right one token at a time, LLaDA 2.1 uses a diffusion-based approach — drafting tokens in parallel and refining them through iterative denoising, enabling self-correction during generation. **Key Features:** * **Token Editing (T2T + M2T)**: Combines Mask-to-Token (M2T) and Token-to-Token (T2T) editing, allowing the model to not only unmask tokens but also revise already-generated tokens mid-flight * **Dual Decoding Modes**: Speed Mode (S) for maximum throughput with T2T refinement, and Quality Mode (Q) for conservative thresholds and higher benchmark scores * **MoE Architecture**: Both variants use Mixture-of-Experts architecture for efficient scaling * **First Large-Scale RL for dLLMs**: Implements the first reinforcement learning framework specifically designed for diffusion language models, improving reasoning and instruction-following * **Lightning-Fast Decoding**: Up to 892 tokens/s on HumanEval+ for the 100B model **Available Models:**
Model Parameters Architecture Context Length HuggingFace
**LLaDA2.1-mini** 16B MoE (20 layers, 16 attention heads) 32,768 tokens [inclusionAI/LLaDA2.1-mini](https://huggingface.co/inclusionAI/LLaDA2.1-mini)
**LLaDA2.1-flash** 100B MoE 32,768 tokens [inclusionAI/LLaDA2.1-flash](https://huggingface.co/inclusionAI/LLaDA2.1-flash)
**License:** Apache 2.0. Please refer to the [official LLaDA2.X repository](https://github.com/inclusionAI/LLaDA2.X) for details. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model size, and decoding mode. SGLang supports serving LLaDA-2.1 on NVIDIA H100, H200, B200, and AMD MI300X, MI325X, MI355X GPUs. Run this Command:

### 3.2 Configuration Tips

**dLLM-Specific Parameters:**

Parameter Description Recommended Value
`--dllm-algorithm` Diffusion decoding algorithm `JointThreshold`
`--trust-remote-code` Required for LLaDA model loading Always enabled
`--mem-fraction-static` Static memory fraction for KV cache `0.8`
`--max-running-requests` Maximum concurrent requests `1` (for best quality)
`--attention-backend` Attention computation backend `flashinfer`
**Decoding Mode Comparison:**
Mode Threshold Speed Quality Best For
**Quality Mode (Q)** Conservative Moderate Higher benchmark scores Accuracy-critical tasks
**Speed Mode (S)** Aggressive Very fast, relies on T2T editing Slightly lower Throughput-critical tasks
**Hardware Requirements:** * **LLaDA2.1-mini (16B)**: \~47 GB VRAM, runs on a single GPU (TP=1) * **LLaDA2.1-flash (100B)**: Requires multi-GPU setup (TP=4 on H100/H200, TP=2 on B200) ## 4. Model Invocation ### 4.1 Deployment Start the server using the command generated above, for example: ```shell Command theme={null} python -m sglang.launch_server \ --model-path inclusionAI/LLaDA2.1-mini \ --dllm-algorithm JointThreshold \ --tp 1 \ --trust-remote-code \ --mem-fraction-static 0.8 \ --max-running-requests 1 \ --attention-backend flashinfer \ --host 0.0.0.0 \ --port 8000 ``` ### 4.2 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) **Simple Completion Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="inclusionAI/LLaDA2.1-mini", messages=[ {"role": "user", "content": "Explain what a diffusion language model is in simple terms."} ], max_tokens=1024 ) print(response.choices[0].message.content) ``` **Output Example:** ```text Output theme={null} Sure! Let's break it down in simple terms. A **diffusion language model** is a type of artificial intelligence that learns to generate text—like sentences, stories, or emails—by studying a lot of written text. Here’s how it works, using a simple real-life analogy: Imagine you have a big book full of stories. A diffusion language model is trying to learn how to write a new story. Instead of being told the rules, it starts by looking at all the words in the book and trying to understand how words usually go together. Now, think of the process like this: 1. **Start with random noise**: The model begins with a completely random set of words (like a scribble on paper). 2. ** ** "clean up" the noise**: It gradually "denoises" the noise by turning it into meaningful text, word by word, based on what it learned learned from the book. 3. **Learn from patterns**: As it does this, it learns patterns—like how words often follow each other, or how sentences start. 4. **Generate new text**: Once it’s learned the patterns, it can create new, coherent sentences or stories by starting from a and and building it up word by word. So, the "diffusion" part comes from the idea of going from random noise to clear, meaningful text—like turning a scribble into a full story. In short: A diffusion language model is an AI that learns to write text by reading lots of books and gradually turning random noise into coherent, meaningful sentences based on what it learned. ``` ### 4.3 Advanced Usage #### 4.3.1 Streaming ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="inclusionAI/LLaDA2.1-mini", messages=[ {"role": "user", "content": "Write a Python function to compute the Fibonacci sequence."} ], max_tokens=2048, stream=True ) for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ````text Output theme={null} Here are several ways to implement the Fibonacci sequence in Python: ## 1. Recursive Approach (Simple but Inefficient) ```python def fibonacci_recursive(n): """ Compute the nth Fibonacci number using recursion. Args: n (int): The position in the Fibonacci sequence (0-indexed) Returns: int: The nth Fibonacci number Raises: ValueError: If n is negative """ if n < 0: raise ValueError("n must be non-negative") if n <= 1: return n return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2) # Example usage print(fibonacci_recursive(10)) # Output: 55 ``` ## 2. Iterative Approach (Efficient) ... ```` #### 4.3.2 Code Generation ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="inclusionAI/LLaDA2.1-mini", messages=[ {"role": "user", "content": "Write a Python function that checks if a string is a palindrome. Include docstring and test cases."} ], max_tokens=2048 ) print(response.choices[0].message.content) ``` **Output Example:** ````text Output theme={null} ```python def is_palindrome(s): """ Check if a string is a palindrome. A palindrome is a word, phrase, or sequence that reads the same backward as forward. This function ignores case, spaces, punctuation, and non characters characters. Args: s (str): The string to check Returns: bool: True if the string is a palindrome, False otherwise Examples: >>> is_palindrome("racecar") True >>> is_palindrome("A man a plan a canal Panama") True >>> is_palindrome("race a car") False >>> is_palindrome("") True >>> is_palindrome("a") True """ # Remove non-alphanumeric characters and convert to lowercase cleaned = ''.join(char.lower() for char in s if char.isalnum()) # Check if the cleaned string reads the same forwards and backwards return cleaned == cleaned[::-1] # Test cases def test_is_palindrome(): """Test the is_palindrome function with various inputs.""" # Test basic palindromes assert is_palindrome("racecar") == True assert is_palindrome("level") == True assert is_palindrome("madam") == True assert is_palindrome("radar") == True # Test palindromes with spaces and punctuation assert is_palindrome("A man a plan a canal Panama") == True assert is_palindrome("race a car") == False assert is_palindrome("Was it a car or a cat I saw?") == True assert is_palindrome("Madam, I'm Adam") == True # Test edge cases assert is_palindrome("") == True assert is_palindrome("a") == True assert is_palindrome("A") == True assert is_palindrome("Aa") == True # Test non-palindromes assert is_palindrome("hello") == False assert is_palindrome("world") == False assert is_palindrome("python") == False # Test single characters assert is_palindrome("1") == True assert is_palindrome("1") == True print("All tests passed!") # Run the tests if __name__ == "__main__": # Example usage print("Testing isalindrome function:") print(f"'racecar' {is_palindrome('racecar')}") print(f"'A man a plan a canal Panama': {is_palindrome('A man a plan a canal Panama')}") print(f"'race a car': {is_palindrome('race a car')}") print(f"'hello': {is_palindrome('hello')}") # Run tests test_is_palindrome() ``` This implementation includes: 1. **Comprehensive function** `is_palindrome()` that: - Ignores case by converting to lowercase - Removes all non-alphanumeric characters (spaces, punctuation, etc.) - Uses string slicing (`[::-1]`) to reverse the string 2. **Detailed docstring** explaining: - What the function does - How it works - Return value - Examples of usage 3. **Extensive test cases** covering: - Basic palindromes - Palindromes with spaces and punctuation - Edge cases (empty string, single character) - Non-palindromes - Mixed case scenarios 4. **Test function** that uses assertions to verify the function works correctly The function efficiently handles real-world palindrome checking by ignoring case, spaces, and punctuation, making it suitable for phrases like "A man a plan a canal Panama". ```` ## 5. Benchmark This section uses **industry-standard configurations** for comparable benchmark results. ### 5.1 Speed Benchmark **Test Environment:** * Hardware: NVIDIA B200 (4x) * SGLang Version: 0.5.8+ #### 5.1.1 LLaDA2.1-mini **Model Deployment:** ```bash Command theme={null} python -m sglang.launch_server \ --model-path inclusionAI/LLaDA2.1-mini \ --dllm-algorithm JointThreshold \ --tp 1 \ --trust-remote-code \ --mem-fraction-static 0.8 \ --max-running-requests 1 \ --attention-backend flashinfer ``` * Latency Benchmark ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model inclusionAI/LLaDA2.1-mini \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * **Latency Result**: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 9.90 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 3433 Request throughput (req/s): 1.01 Input token throughput (tok/s): 616.26 Output token throughput (tok/s): 426.26 Peak output token throughput (tok/s): 1010.00 Peak concurrent requests: 3 Total token throughput (tok/s): 1042.53 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 988.87 Median E2E Latency (ms): 655.27 P90 E2E Latency (ms): 1952.50 P99 E2E Latency (ms): 2932.19 ---------------Time to First Token---------------- Mean TTFT (ms): 152.74 Median TTFT (ms): 150.37 P99 TTFT (ms): 229.78 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 2.16 Median TPOT (ms): 2.08 P99 TPOT (ms): 3.72 ---------------Inter-Token Latency---------------- Mean ITL (ms): 2.10 Median ITL (ms): 1.99 P95 ITL (ms): 4.03 P99 ITL (ms): 6.34 Max ITL (ms): 26.59 ================================================== ``` * Throughput Benchmark ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model inclusionAI/LLaDA2.1-mini \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` * **Throughput Result**: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 467.74 Total input tokens: 249831 Total input text tokens: 249831 Total generated tokens: 252662 Total generated tokens (retokenized): 189717 Request throughput (req/s): 1.07 Input token throughput (tok/s): 534.12 Output token throughput (tok/s): 540.17 Peak output token throughput (tok/s): 1753.00 Peak concurrent requests: 105 Total token throughput (tok/s): 1074.30 Concurrency: 90.77 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 84912.27 Median E2E Latency (ms): 86564.26 P90 E2E Latency (ms): 110567.26 P99 E2E Latency (ms): 114303.38 ---------------Time to First Token---------------- Mean TTFT (ms): 83920.39 Median TTFT (ms): 85669.54 P99 TTFT (ms): 112969.91 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 2.67 Median TPOT (ms): 1.65 P99 TPOT (ms): 4.43 ---------------Inter-Token Latency---------------- Mean ITL (ms): 1.69 Median ITL (ms): 1.46 P95 ITL (ms): 3.96 P99 ITL (ms): 4.84 Max ITL (ms): 92.08 ================================================== ``` #### 5.1.2 LLaDA2.1-flash **Model Deployment:** ```bash Command theme={null} python -m sglang.launch_server \ --model-path inclusionAI/LLaDA2.1-flash \ --dllm-algorithm JointThreshold \ --tp 4 \ --trust-remote-code \ --mem-fraction-static 0.8 \ --max-running-requests 1 \ --attention-backend flashinfer ``` * Latency Benchmark ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model inclusionAI/LLaDA2.1-flash \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * **Latency Result**: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 14.46 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 3276 Request throughput (req/s): 0.69 Input token throughput (tok/s): 421.79 Output token throughput (tok/s): 291.75 Peak output token throughput (tok/s): 676.00 Peak concurrent requests: 3 Total token throughput (tok/s): 713.53 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 1445.16 Median E2E Latency (ms): 968.06 P90 E2E Latency (ms): 3101.86 P99 E2E Latency (ms): 4208.49 ---------------Time to First Token---------------- Mean TTFT (ms): 231.63 Median TTFT (ms): 242.67 P99 TTFT (ms): 341.33 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 3.04 Median TPOT (ms): 2.79 P99 TPOT (ms): 5.33 ---------------Inter-Token Latency---------------- Mean ITL (ms): 3.05 Median ITL (ms): 2.41 P95 ITL (ms): 7.25 P99 ITL (ms): 8.27 Max ITL (ms): 29.27 ================================================== ``` * Throughput Benchmark ```bash Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --model inclusionAI/LLaDA2.1-flash \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` * **Throughput Result**: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 671.85 Total input tokens: 249831 Total input text tokens: 249831 Total generated tokens: 252662 Total generated tokens (retokenized): 177961 Request throughput (req/s): 0.74 Input token throughput (tok/s): 371.85 Output token throughput (tok/s): 376.07 Peak output token throughput (tok/s): 1521.00 Peak concurrent requests: 103 Total token throughput (tok/s): 747.92 Concurrency: 91.28 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 122658.36 Median E2E Latency (ms): 125265.55 P90 E2E Latency (ms): 159554.07 P99 E2E Latency (ms): 165174.88 ---------------Time to First Token---------------- Mean TTFT (ms): 121009.17 Median TTFT (ms): 124437.80 P99 TTFT (ms): 163579.29 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 4.73 Median TPOT (ms): 2.16 P99 TPOT (ms): 7.13 ---------------Inter-Token Latency---------------- Mean ITL (ms): 2.38 Median ITL (ms): 1.40 P95 ITL (ms): 6.89 P99 ITL (ms): 8.60 Max ITL (ms): 176.78 ================================================== ``` ### 5.2 Accuracy Benchmark #### 5.2.1 GSM8K Benchmark ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:8000/v1 \ --num-examples 200 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. **Results:** ```text Output theme={null} Accuracy: 0.895 Invalid: 0.000 Latency: 100.552 s Output throughput: 262.094 token/s ``` # Ling-2.5-1T Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/Ling-2.5-1T ## 1. Model Introduction [Ling-2.5-1T](https://huggingface.co/inclusionAI/Ling-2.5-1T) is the latest flagship instant model in the Ling family. Thinking models raise the ceiling of intelligence, while instant models expand its reach by balancing efficiency and performance—making AGI not only more powerful, but also more accessible. Ling-2.5-1T delivers comprehensive upgrades across model architecture, token efficiency, and preference alignment, designed to bring universally accessible AI to a new level of quality. **Key Features:** * **Trillion-Scale Model**: 1T total parameters with 63B active parameters (up from 51B in the previous generation). Pre-training corpus expanded from 20T to 29T tokens. Leveraging an efficient hybrid linear attention architecture (1:7 MLA + Lightning Linear Attention), the model delivers exceptionally high throughput while processing context lengths of up to 1M tokens. * **Token Efficiency**: By introducing a composite reward mechanism combining "Correctness" and "Process Redundancy", Ling-2.5-1T further pushes the frontier of efficiency-performance balance in instant models. At comparable token efficiency levels, Ling-2.5-1T's reasoning capabilities significantly outperform its predecessor, approaching the level of frontier "thinking models" that typically consume \~4x the output tokens. * **Preference Alignment**: Through refined alignment strategies—such as bidirectional RL feedback and Agent-based instruction constraint verification—Ling-2.5-1T achieves substantial improvements over the previous generation in preference alignment tasks, including creative writing and instruction following. * **Agentic Capabilities**: Trained with Agentic RL in large-scale high-fidelity interactive environments, Ling-2.5-1T is compatible with mainstream agent platforms such as Claude Code, OpenCode, and OpenClaw. It achieves leading open-source performance on the general tool-calling benchmark, BFCL-V4. * **Context Length**: 256K -> 1M (YaRN) **Available Models:** * **BF16**: [inclusionAI/Ling-2.5-1T](https://huggingface.co/inclusionAI/Ling-2.5-1T) **License:** MIT ## 2. SGLang Installation Ling-2.5-1T runs on the standard SGLang Docker image: ```bash Command theme={null} # NVIDIA (H200 / B200 / GB200 / GB300) docker pull lmsysorg/sglang:latest ``` For other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/install). Ling-2.5-1T is also supported via the **nightly PyPI builds**. See the [SGLang Installation (PyPI)](../../../docs/get-started/install) guide for setup instructions. ## 3. Model Deployment Ling-2.5-1T is a trillion-parameter BF16 model that requires multi-node deployment (at least 2 nodes). Use the configuration selector below to generate the deployment command for your hardware platform. Run this Command:

### Configuration Tips

* The `--trust-remote-code` flag is required for this model due to custom modeling code.
* `--tp-size` can be set to a maximum of 8 for this model. If you have more GPUs available, increase `--pp-size` to scale across additional nodes.
* Adding `--model-loader-extra-config '{"enable_multithread_load": "true","num_threads": 64}'` enables faster model loading.
* On H200/GB200/GB300 with 2-node deployment, `--mem-frac 0.95` is required to avoid OOM since the model occupies most of the GPU memory. For better throughput, consider 4-node deployment (ref [model card](https://huggingface.co/inclusionAI/Ling-2.5-1T#run-inference) for more details).

## 4. Model Invocation

### 4.1 Basic Usage

For example, launch the server on 2 H200 nodes:

```bash Command theme={null}
export MASTER_IP=10.10.0.1 # The IP of Node 0
export PORT=30000
export DIST_PORT=50000

# Node 0:
python3 -m sglang.launch_server \
--model-path inclusionAI/Ling-2.5-1T \
--trust-remote-code \
--tp-size 8 \
--pp-size 2 \
--nnodes 2 \
--node-rank 0 \
--host 0.0.0.0 \
--port ${PORT} \
--dist-init-addr ${MASTER_IP}:${DIST_PORT} \
--tool-call-parser qwen \
--model-loader-extra-config '{"enable_multithread_load": "true","num_threads": 64}' \
--mem-frac 0.95


# Node 1:
python3 -m sglang.launch_server \
--model-path inclusionAI/Ling-2.5-1T \
--trust-remote-code \
--tp-size 8 \
--pp-size 2 \
--nnodes 2 \
--node-rank 1 \
--dist-init-addr ${MASTER_IP}:${DIST_PORT} \
--tool-call-parser qwen \
--model-loader-extra-config '{"enable_multithread_load": "true","num_threads": 64}' \
--mem-frac 0.95
```

Once the server is running, send requests to the master node:

```bash Command theme={null}
curl -s http://${MASTER_IP}:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "auto", "messages": [{"role": "user", "content": "What is the capital of France?"}]}'
```

Output:

```json Config theme={null}
{
  "id": "e82af153da844ee6aed7a27a3187f2f4",
  "object": "chat.completion",
  "created": 1771216764,
  "model": "auto",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is **Paris**.\n\n**Additional details:**\n*   It is the largest city in France.\n*   It is located in the north-central part of the country along the Seine River.\n*   Paris is often referred to as \"The City of Light\" (*La Ville Lumière*).",
        "reasoning_content": null,
        "tool_calls": null
      },
      "logprobs": null,
      "finish_reason": "stop",
      "matched_stop": 156895
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "total_tokens": 93,
    "completion_tokens": 68,
    "prompt_tokens_details": null,
    "reasoning_tokens": 0
  }
}
```

For more API usage examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Tool Calling Example

```bash Command theme={null}
curl -s http://${MASTER_IP}:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "inclusionAI/Ling-2.5-1T",
    "messages": [{"role": "user", "content": "Search for the latest news about AI"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "search",
        "description": "Search for information on the internet",
        "parameters": {
          "type": "object",
          "properties": {
            "query": {"type": "string", "description": "The search query"}
          },
          "required": ["query"]
        }
      }
    }],
    "tool_choice": "auto"
  }'
```

Output:

```json Config theme={null}
{
  "id": "b968e45c7d414f7482c8ffc0f9c6b688",
  "object": "chat.completion",
  "created": 1771216520,
  "model": "inclusionAI/Ling-2.5-1T",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "reasoning_content": null,
        "tool_calls": [
          {
            "id": "call_e75f711d8ad840ed9d382c9e",
            "index": 0,
            "type": "function",
            "function": {
              "name": "search",
              "arguments": "{\"query\": \"latest news about AI\"}"
            }
          }
        ]
      },
      "logprobs": null,
      "finish_reason": "tool_calls",
      "matched_stop": null
    }
  ],
  "usage": {
    "prompt_tokens": 173,
    "total_tokens": 196,
    "completion_tokens": 23,
    "prompt_tokens_details": null,
    "reasoning_tokens": 0
  }
}
```

## 5. Benchmark

### GSM8K

* Benchmark Command

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

* Test Result

```text Output theme={null}
Accuracy: 0.960
Invalid: 0.000
Latency: 45.410 s
Output throughput: 560.642 token/s
```


# Ling-2.6
Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/Ling-2.6



## 1. Model Introduction

The **Ling-2.6** family from inclusionAI is the next iteration of the Ling instant-model series. Continuing the architectural direction set by Ling-2.5, Ling-2.6 doubles down on **inference efficiency**, **token efficiency**, and **agent performance** — staying competitive with frontier instant models while being faster, leaner, and better suited for production agent workloads.

**Key Features:**

* **Hybrid Linear Attention**: A `1:7 MLA + Lightning Linear` hybrid built on top of a highly sparse MoE backbone. Compared with same-class SOTA models, Ling-2.6-flash shows up to \~4× higher prefill and decode throughput in long-context scenarios; Ling-2.6-1T is shipped in FP8 so it fits a single GB300 node with `--tp 4`.
* **Token Efficiency**: Trained with explicit token-efficiency objectives. On the full Artificial Analysis suite, Ling-2.6-flash uses only \~15M output tokens while remaining competitive — a meaningfully stronger intelligence-per-token profile than long-reasoning peers.
* **Agentic Capabilities**: Refined for tool use, multi-step planning, and long-horizon execution. Reaches SOTA-class results on **BFCL-V4**, **TAU2-bench**, **SWE-bench Verified**, **Claw-Eval**, and **PinchBench**, and is validated against Claude Code, Kilo Code, Qwen Code, Hermes Agent, and OpenClaw.
* **Long Context**: Native 128K, extendable to **256K (Ling-2.6-flash)** and **256K → 1M (Ling-2.6-1T via YaRN)**.

**Available Models:**

* **BF16**: [inclusionAI/Ling-2.6-flash](https://huggingface.co/inclusionAI/Ling-2.6-flash) — 104B total / 7.4B active
* **FP8 (E4M3)**: [inclusionAI/Ling-2.6-1T](https://huggingface.co/inclusionAI/Ling-2.6-1T) — \~1T total

**License:** MIT

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

### 3.1 Ling-2.6-flash

Ling-2.6-flash is a 104B/7.4B-active MoE that runs comfortably on a single 4-GPU node. Use the selector below to generate the launch command for your hardware.

Run this Command:


#### Configuration Tips

* `--trust-remote-code` is required (custom `BailingMoeV2_5ForCausalLM` modeling code).
* `--tp-size 4` is the reference layout. On 4× H20-3e the model reaches \~340 tokens/s decode at TP=4, batch 32.
* Native context is 128K. Enable YaRN (`--json-model-override-args '{"rope_scaling": {"rope_type": "yarn", "factor": 2.0, ...}}'`) to extend to 256K — the snippet does this for you.
* `--tool-call-parser qwen25` matches the model's `...` schema.
* The recommended baseline does **not** include `--reasoning-parser qwen3`. Ling-2.6 is a controllable-reasoning model whose chat template defaults to `detailed thinking off`; the SGLang `qwen3` reasoning parser, in contrast, assumes default-thinking semantics and would mis-route normal output into `reasoning_content`. Only enable it if you specifically want `...` blocks split out — see [§4.3 Thinking Mode](#4-3-thinking-mode).
* **MTP (multi-token prediction)** is supported. Add `--speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 --mamba-radix-cache-strategy extra_buffer` to enable it — see the [model card](https://huggingface.co/inclusionAI/Ling-2.6-flash#run-inference) for the full example.

### 3.2 Ling-2.6-1T

Ling-2.6-1T ships in **FP8 (E4M3)**, so unlike Ling-2.5-1T it fits a **single GB300 node with `--tp 4`**. On smaller GPUs (H200/B200), a 2-node deployment with `--pp-size 2` is required.

Run this Command:


#### Configuration Tips

* `--trust-remote-code` is required for the custom modeling code.
* `--model-loader-extra-config '{"enable_multithread_load":"true","num_threads":64}'` significantly speeds up the multi-shard FP8 weight load (26 safetensors shards + an MTP layer).
* Use `--tool-call-parser qwen` for tool calling.
* The recommended baseline does **not** include `--reasoning-parser qwen3`. Ling-2.6's chat template defaults to `detailed thinking off`, while SGLang's `qwen3` reasoning parser assumes default-thinking semantics — combining the two requires a per-request workaround for tool calls (see [§4.3 Thinking Mode](#4-3-thinking-mode)). Only enable `--reasoning-parser qwen3` if you specifically want `...` blocks split into `reasoning_content`.
* For 2-node deployments, set `MASTER_IP`, `PORT`, and `DIST_PORT` consistently across both nodes.

## 4. Model Invocation

For example, launch a Ling-2.6-1T server on a single GB300 node:

```bash Command theme={null}
sglang serve \
  --model-path inclusionAI/Ling-2.6-1T \
  --tp-size 4 \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000 \
  --tool-call-parser qwen \
  --model-loader-extra-config '{"enable_multithread_load":"true","num_threads":64}'
```

### 4.1 Basic Usage

```bash Command theme={null}
curl -s http://${MASTER_IP}:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "auto", "messages": [{"role": "user", "content": "What is the capital of France?"}]}'
```

Output:

```json Config theme={null}
{
  "id": "...",
  "object": "chat.completion",
  "model": "auto",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The capital of France is **Paris**.",
        "reasoning_content": null,
        "tool_calls": null
      },
      "finish_reason": "stop"
    }
  ]
}
```

### 4.2 Tool Calling Example

```bash Command theme={null}
curl -s http://${MASTER_IP}:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [{"role": "user", "content": "Search for the latest news about AI"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "search",
        "description": "Search for information on the internet",
        "parameters": {
          "type": "object",
          "properties": {
            "query": {"type": "string", "description": "The search query"}
          },
          "required": ["query"]
        }
      }
    }],
    "tool_choice": "auto"
  }'
```

Output:

```json Config theme={null}
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_...",
            "type": "function",
            "function": {
              "name": "search",
              "arguments": "{\"query\": \"latest news about AI\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}
```

### 4.3 Thinking Mode

Both Ling-2.6-flash and Ling-2.6-1T are **controllable-reasoning** models. Their chat template uses textual directives in the system message — `detailed thinking on` or `detailed thinking off` — to toggle thinking. The template **defaults to `detailed thinking off`** when neither phrase is present, and it does **not** read the Qwen3-style `enable_thinking` template variable.

#### Enabling thinking

Include `detailed thinking on` in the first system message:

```bash Command theme={null}
curl -s http://${MASTER_IP}:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [
      {"role": "system", "content": "detailed thinking on"},
      {"role": "user", "content": "If a box has 12 red balls and 8 blue balls, then 5 red balls are removed, how many balls remain?"}
    ]
  }'
```

If you already have a system prompt, append the directive on its own line:

```json theme={null}
{"role": "system", "content": "You are a helpful assistant.\ndetailed thinking on"}
```

When thinking is on, the model emits `...` blocks before its final answer. To get those split into `message.reasoning_content` automatically, also launch the server with `--reasoning-parser qwen3`.

#### Caveat: `--reasoning-parser qwen3` + tool calling

The SGLang `qwen3` reasoning parser was written for Qwen3, where models are **default-thinking** and clients opt out via `chat_template_kwargs.enable_thinking=false`. Ling-2.6 is the opposite — default-non-thinking, with toggling done in the system message. As a result, when the server is launched with **both** `--tool-call-parser qwen` and `--reasoning-parser qwen3`, every tool-call request must include `chat_template_kwargs.enable_thinking=false`, otherwise the parser routes the `...` block into `reasoning_content` instead of `message.tool_calls`:

```bash Command theme={null}
curl -s http://${MASTER_IP}:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [{"role": "user", "content": "Search for the latest news about AI"}],
    "tools": [...],
    "tool_choice": "auto",
    "chat_template_kwargs": {"enable_thinking": false}
  }'
```

`enable_thinking` here is consumed by the SGLang reasoning parser, **not** by the chat template — Ling-2.6's template ignores it. For the simplest configuration, just omit `--reasoning-parser qwen3` and toggle thinking via the system message.

For more API examples, see the [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request).

## 5. Benchmark

### GSM8K (Ling-2.6-1T, GB300 × 4)

Reference run on a single GB300 node with `--tp 4`:

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

```text Output theme={null}
Accuracy: 0.9621 (1269 / 1319)
```

For Ling-2.6-flash, see the official numbers on the [model card](https://huggingface.co/inclusionAI/Ling-2.6-flash) (BFCL-V4, TAU2-bench, SWE-bench Verified, Claw-Eval, PinchBench, Artificial Analysis).


# Ling-3.0-flash
Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/Ling-3.0-flash

Deploy Ling-3.0-flash with SGLang — a 124B hybrid KDA + MLA MoE in BF16, FP8, INT4, or MXFP4 on Hopper and Blackwell GPUs.

## Deployment

> **Install SGLang**
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev-Ling-3.0-flash
> ```
>
> For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces.

Pick your hardware + recipe to generate the launch command. Three serving strategies are covered:

* **Low-Latency** — fastest reply for a single user. Pick for chat. These recipes run speculative decoding: pick **NEXTN** (built-in MTP layer, no extra checkpoint) or **DSPARK** (external draft model) in the **Spec Decode** selector of the Deploy panel.
* **High-Throughput** — most tokens per second across many users. Best for batch jobs. These recipes turn speculative decoding off, since at saturation the draft/verify overhead outweighs the speedup.
* **HiCache + Mooncake** — writes reusable prefixes to Mooncake L3 storage. Start the Mooncake services in §3.3 before launching the generated server command.

## Playground

The Playground is where you experiment with **SGLang features beyond the documented matrix**. The Deploy panel above only emits the curated recipe combinations on this page; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing.

## 1. Model Introduction

Ling-3.0-flash is a hybrid-attention Mixture-of-Experts (MoE) language model from the BailingMoeV3 family. It interleaves Kimi Delta Attention (KDA) linear-attention layers with gated Multi-head Latent Attention (MLA) full-attention layers, on top of a fine-grained MoE feed-forward network. This keeps per-token inference cost close to a small model — **124B total parameters with only 5.1B active** — while retaining large-model capacity.

It is a hybrid-reasoning model with thinking enabled by default, and it supports structured tool calling. Native context length is 256K.

**Available Models:**

* **BF16**: [inclusionAI/Ling-3.0-flash](https://huggingface.co/inclusionAI/Ling-3.0-flash) — 124B total / 5.1B active
* **FP8** (blockwise E4M3): [inclusionAI/Ling-3.0-flash-fp8](https://huggingface.co/inclusionAI/Ling-3.0-flash-fp8)
* **INT4** (compressed-tensors W4A16): [inclusionAI/Ling-3.0-flash-int4](https://huggingface.co/inclusionAI/Ling-3.0-flash-int4)
* **MXFP4**: [inclusionAI/Ling-3.0-flash-fp4](https://huggingface.co/inclusionAI/Ling-3.0-flash-fp4)
* **DSPARK draft**: [inclusionAI/Ling-3.0-flash-dspark](https://huggingface.co/inclusionAI/Ling-3.0-flash-dspark) — 5-layer DSpark draft checkpoint for DSPARK speculative decoding

**License:** MIT

**Resources:** [HuggingFace](https://huggingface.co/inclusionAI/Ling-3.0-flash).

## 2. Configuration Tips

* BF16 tensor parallelism follows the GPU: `--tp 4` on 141 GB-class cards (H20-3e, H200) and 4-GPU Blackwell nodes (B200, GB300); `--tp 8` on 80 GB cards (H100, H800).
* The FP8 recipes pair `--tp` with a matching `--ep-size` (`--tp 4 --ep-size 4` on 4-GPU nodes, `--tp 8 --ep-size 8` on H100/H800). The checkpoint uses blockwise (128×128) E4M3 expert weights, so a pure tensor-parallel shard must satisfy `(768 / TP) % 128 == 0` — only TP2 qualifies; expert parallelism splits experts whole instead of by column, which lifts that restriction and uses the full node. SGLang detects the quantization format from the checkpoint's `quantization_config`, so no explicit quantization flag is needed.
* INT4 uses compressed-tensors W4A16 experts. With the default MoE runner, SGLang selects Marlin on H200 and the graph-compatible Triton implementation on Blackwell; do not force a backend in the launch command.
* MXFP4 uses the native FlashInfer runner on H200 and B200. The checkpoint mixes MXFP4 routed experts with block-FP8 dense and shared projections; on B200, `--fp8-gemm-backend triton` avoids an unsupported FlashInfer FP8 tactic while the routed experts remain native MXFP4.
* `--reasoning-parser ling3` and `--tool-call-parser ling3` enable Ling-3.0-specific reasoning and structured tool-call parsing; toggle them in the **Parsers** card of the [Playground](#playground).
* Both the chat template and the `ling3` reasoning parser default to thinking on. A single request can turn it off with `"chat_template_kwargs": {"enable_thinking": false}` (see §3.1).
* The BF16/FP8 recipes use `--mem-fraction-static 0.8`; INT4/MXFP4 use `0.85`. These values reserve the headroom used by the validated graph-enabled runs.
* The checkpoint ships a built-in MTP layer (`num_nextn_predict_layers: 1`); enable it with `--speculative-algorithm NEXTN` — no separate draft model is needed. The Low-Latency recipes default to it via the **Spec Decode** selector; toggle it in the **Speculative Decoding** card of the [Playground](#playground).
* DSPARK is the alternative speculative path: it drafts with the external [inclusionAI/Ling-3.0-flash-dspark](https://huggingface.co/inclusionAI/Ling-3.0-flash-dspark) checkpoint instead of the built-in MTP layer. Pick **DSPARK** in the Deploy panel's **Spec Decode** selector (also available in the [Playground](#playground)); it composes `--speculative-algorithm DSPARK`, the draft path, and `--enable-linear-replayssm-spec`, the KDA verify path that folds per-draft intermediate states onto a fixed ring instead of snapshotting full states. The draft block size auto-infers from the checkpoint; tune it with `--speculative-dspark-block-size`. The draft's block size of 8 makes the verify window 9 tokens, and the KDA ReplaySSM ring must be a power of two at least twice the window — the recipe therefore pins `--linear-replayssm-cache-len 32`, since the 16 default fails startup validation. MXFP4 requires `--moe-runner-backend flashinfer_mxfp4`; the mixed checkpoint does not auto-select it.
* Native context is 256K; SGLang reads it from the checkpoint's `max_position_embeddings`, so no `--context-length` flag is needed.
* The **HiCache** card in the [Playground](#playground) exposes the validated Mooncake L3 path. It adds the hybrid-KDA scheduler and prefix-key settings together; see §3.3 for the required services.

## 3. Advanced Usage

### 3.1 Reasoning

Ling-3.0-flash thinks by default. With `--reasoning-parser ling3` (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)), the chain-of-thought is returned in `message.reasoning_content` and the final answer in `message.content`:

> **Thinking-mode request**
>
> ```bash Command theme={null}
> curl -s http://localhost:30000/v1/chat/completions \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "inclusionAI/Ling-3.0-flash",
>     "messages": [{"role": "user", "content": "What is 15% of 240?"}]
>   }'
> ```

> **Example Output**
>
> ```json Output theme={null}
> {
>   "choices": [
>     {
>       "message": {
>         "role": "assistant",
>         "content": "15% of 240 = **36**",
>         "reasoning_content": "The user is asking a simple percentage calculation: 15% of 240. This is straightforward: 0.15 × 240 = 36.",
>         "tool_calls": null
>       },
>       "finish_reason": "stop"
>     }
>   ]
> }
> ```

> [!NOTE]
>
> Thinking is controlled by the chat template's `enable_thinking` kwarg and is on by default. Disable it per request with `"chat_template_kwargs": {"enable_thinking": false}`.

### 3.2 Tool Calling

With `--tool-call-parser ling3` (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)), structured calls are parsed into `message.tool_calls` and `finish_reason` is `tool_calls`:

> **Tool-calling request**
>
> ```bash Command theme={null}
> curl -s http://localhost:30000/v1/chat/completions \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "inclusionAI/Ling-3.0-flash",
>     "messages": [{"role": "user", "content": "Search for the latest news about AI"}],
>     "tools": [{
>       "type": "function",
>       "function": {
>         "name": "search",
>         "description": "Search for information on the internet",
>         "parameters": {
>           "type": "object",
>           "properties": {
>             "query": {"type": "string", "description": "The search query"}
>           },
>           "required": ["query"]
>         }
>       }
>     }],
>     "tool_choice": "auto"
>   }'
> ```

> **Example Output**
>
> ```json Output theme={null}
> {
>   "choices": [
>     {
>       "message": {
>         "role": "assistant",
>         "content": "",
>         "reasoning_content": "The user wants me to search for the latest news about AI. I'll use the search tool with a query about the latest AI news.",
>         "tool_calls": [
>           {
>             "id": "call_0822dd418aa34254aa5b19e1",
>             "index": 0,
>             "type": "function",
>             "function": { "name": "search", "arguments": "{\"query\": \"latest news about AI 2025\"}" }
>           }
>         ]
>       },
>       "finish_reason": "tool_calls"
>     }
>   ]
> }
> ```

For more API examples, see the [SGLang Basic Usage Guide](/docs/basic_usage/send_request).

### 3.3 HiCache with Mooncake

The HiCache recipes use Mooncake as L3 prefix storage. Start the metadata server, master, and storage client before you launch SGLang. The following command runs all three services from the same image in a separate container:

```bash Command theme={null}
docker run --rm --network host --ipc=host \
  lmsysorg/sglang:dev-Ling-3.0-flash \
  bash -lc '
    python3 -m mooncake.http_metadata_server --port 8290 &
    mooncake_master --port 50171 --metrics_port 9024 &
    exec mooncake_client \
      --host=127.0.0.1 \
      --port=50172 \
      --master_server_address=127.0.0.1:50171 \
      --metadata_server=http://127.0.0.1:8290/metadata \
      --protocol=tcp \
      --device_names= \
      --global_segment_size=4294967296 \
      --enable_http_server=true \
      --http_port=8291
  '
```

Then select **HiCache + Mooncake** in Deployment, or enable **HiCache** in the Playground. Docker commands use host networking so the SGLang container can reach these localhost services. You can change the master and metadata endpoints in the **Env** dialog.

This validated setup uses TCP, so `MOONCAKE_DEVICE=` and the client's `--device_names=` are intentionally empty. Set both to your actual device list only when you configure an RDMA deployment.

> [!NOTE]
>
> With the default `chunked_prefill_size` of 8192, a cold request writes through only when its uncached extend length fits in one chunk. A longer cold first request skips write-through for that influx; a repeat with the same prefix can hit the device radix cache and proceed normally.

> [!WARNING]
>
> For this hybrid KDA model, use the Mooncake L3 recipe shown here. Host-memory L2 eviction is not exposed because the KDA cache path is not currently compatible with it. Track the limitation in [issue #33713](https://github.com/sgl-project/sglang/issues/33713).

For storage sizing and backend details, see [HiCache best practices](/docs/advanced_features/hicache_best_practices).


# Ling-3.0-flash-VL
Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/Ling-3.0-flash-VL

Deploy Ling-3.0-flash-VL with SGLang — a ~125B hybrid KDA + MLA MoE vision-language model (5.1B active) with image and video input, thinking mode, and 128K context on Blackwell and Hopper GPUs.

## Deployment

> **Install SGLang**
>
> For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel.
>
> **Python (pip / uv)**
>
> ```bash Command theme={null}
> pip install --upgrade pip
> pip install uv
> uv pip install --prerelease=allow sglang
> ```
>
> Then run the **Python** output of the command panel below in that environment. Ling-3.0-flash-VL support requires sglang with sgl-project/sglang#38526 (or newer); until it merges, install directly from the PR head:
>
> ```bash Command theme={null}
> pip install --upgrade pip
> pip install uv
> uv pip install "sglang @ git+https://github.com/sgl-project/sglang.git@refs/pull/38526/head#subdirectory=python"
> uv pip install torchcodec==0.16.0  # optional, preferred video-decode backend
> ```
>
> Video input needs `decord` or `torchcodec` in the environment; audio is not supported. Downloading the checkpoint requires `HF_TOKEN`.
>
> **Docker**
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev-Ling-3.0-flash-VL
> ```
>
> For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces.

Pick your hardware and quantization to generate the launch command. The checkpoint ships in BF16 with FP8, INT4, and FP4 variants, and each combination carries one **Balanced** recipe: BF16 uses `--tp 4` on 288 GB-class (GB300, B300) and 141 GB-class (B200, H200) GPUs and `--tp 8` on H100 (sized so the \~250 GB of BF16 weights fit with KV-cache headroom); FP8 uses `--tp 1` on GB300/B300/B200 and `--tp 2` on H200/H100; INT4 and FP4 use `--tp 1` everywhere. DGX Spark offers INT4 and FP4 only.

## Playground

The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits the recipes on this page; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing.

## 1. Model Introduction

Ling-3.0-flash-VL is the vision-language member of the BailingMoeV3 family. Its language backbone is the [Ling-3.0-flash](/cookbook/autoregressive/InclusionAI/Ling-3.0-flash) hybrid-attention Mixture-of-Experts (MoE) model: 42 layers that interleave Kimi Delta Attention (KDA) linear-attention layers with gated Multi-head Latent Attention (MLA) full-attention layers, on top of a fine-grained MoE feed-forward network with 512 routed experts (8 active per token) plus a shared expert. A 27-layer vision encoder (0.4B parameters, 16-pixel patches with 2×2 spatial merging and paired frames for video) feeds image and video tokens into that backbone through a small MLP projector. In total the checkpoint holds **\~125B parameters with \~5.1B active per token**, so per-token inference cost stays close to a small model.

It is a thinking model: the chat template turns chain-of-thought on by default and exposes an `enable_thinking` switch. It supports structured tool calling. Inputs are text, images, and video; audio is not supported. Native context length is 128K tokens. Unlike Ling-3.0-flash, the VL checkpoint ships no built-in MTP draft layer, so there is no speculative-decoding recipe.

**Available Models:**

* **BF16**: [inclusionAI/Ling-3.0-flash-VL](https://huggingface.co/inclusionAI/Ling-3.0-flash-VL) — \~125B total / \~5.1B active
* **FP8**: [inclusionAI/Ling-3.0-flash-VL-FP8](https://huggingface.co/inclusionAI/Ling-3.0-flash-VL-FP8) — 128×128 block quantization
* **INT4 (GPTQ)**: [inclusionAI/Ling-3.0-flash-VL-int4](https://huggingface.co/inclusionAI/Ling-3.0-flash-VL-int4) — compressed-tensors, group size 32
* **FP4 (MXFP4)**: [inclusionAI/Ling-3.0-flash-VL-fp4](https://huggingface.co/inclusionAI/Ling-3.0-flash-VL-fp4) — e2m1 experts + FP8 e4m3 activations, Blackwell only

**License:** MIT

**Recommended generation:** `temperature=1.0`, `top_p=0.95`, `top_k=20` (from the checkpoint's `generation_config.json`; SGLang applies these defaults, so the samples below do not set them).

**Resources:** [HuggingFace](https://huggingface.co/inclusionAI/Ling-3.0-flash-VL).

## 2. Configuration Tips

* `--trust-remote-code` is required. The checkpoint declares its config and multimodal processor through `auto_map`, and SGLang's native implementation loads the image/video preprocessing and the chat template from those files. Serving from the Hub repo or from a local snapshot needs no extra environment setup.
* BF16 weights take \~250 GB. The recipes use `--tp 4` on 288 GB-class (GB300, B300) and 141 GB-class (B200, H200) GPUs and `--tp 8` on H100, with the default memory pool. The 4×GB300 and 4×H200 cells are validated end to end; the rest are sized by the same rule and carry the unverified badge. Adjust TP in the **Attention Parallelism** card of the [Playground](#playground).
* HiCache is supported: `--enable-hierarchical-cache` attaches the hierarchical cache to the hybrid SSM state (verified with CPU offload; L3 storage backends such as Mooncake are untested). On shared hosts, set an explicit `--hicache-size ` — the default ratio can request more host RAM than is free.
* Vision token budget: the encoder emits one token per 32×32-pixel block after merging, so a 1280×720 image costs about 880 tokens and the processor's `max_pixels` of 4,194,304 caps a single image at roughly 4,100 tokens. Video frames are paired before patching; the sample clip in §3.2 costs 4,224 tokens. Size `--chunked-prefill-size` and `--max-running-requests` with these counts in mind for image-heavy traffic.
* Parsers: the generated recipes include `--reasoning-parser auto --tool-call-parser auto` by default. Both resolve to `ling3` from the chat template (the server logs `Auto-detected --reasoning-parser as ling3 from chat template` and the same for the tool-call parser), so no model-specific parser name is needed; the explicit form `--reasoning-parser ling3 --tool-call-parser ling3` is equivalent. With the parsers on, reasoning is returned in `message.reasoning_content` and structured tool calls in `message.tool_calls`; without them, `message.content` carries the reasoning followed by `` and the answer (the opening `` tag sits in the prompt and is not echoed).
* Thinking is on by default (`enable_thinking` defaults to true in the chat template, and the `ling3` reasoning parser follows that default). Turn it off per request with `"chat_template_kwargs": {"enable_thinking": false}` (§3.3).
* Native context is 128K, and the generated recipes default to the 256K YaRN variant (`--context-length 262144` plus the `rope_scaling` override and `SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1`), matching the model card. For the native 128K window, drop all three from the command.
* Audio content parts are rejected before preprocessing; send images as `image_url` and clips as `video_url` content parts (§3).
* The FP8 variant (`inclusionAI/Ling-3.0-flash-VL-FP8`) uses 128×128 block quantization, so plain TP must keep `768 ÷ tp` divisible by 128 (TP 1, 2, 3, or 6 — TP=4 fails to load). FP8 recipes default to a single GPU where the \~126 GB weights fit (`--tp 1` on 288 GB-class and B200, verified on GB300) or `--tp 2` on tighter cards. As a manual alternative on four GPUs, `--tp 4 --ep 4` keeps experts whole per rank (measured on 4×GB300). The BF16 checkpoint can also be quantized online with `--quantization fp8`; measured accuracy and speed for both paths are in the benchmark cards below.
* The INT4 variant (`inclusionAI/Ling-3.0-flash-VL-int4`) is a GPTQ 4-bit export (compressed-tensors, group size 32). It runs on all listed hardware with single-GPU (`--tp 1`) recipes; GB300, H200, and DGX Spark cells are verified, the rest carry the unverified badge. Shared-expert fusion is auto-disabled for the INT4 and FP4 checkpoints by the current dev image and by sglang main; older images need `--disable-shared-experts-fusion` explicitly.
* The FP4 variant (`inclusionAI/Ling-3.0-flash-VL-fp4`) is an MXFP4 export (e2m1 routed-expert weights with e8m0 scales, group 32, plus FP8 e4m3 dynamic activations) and runs on Hopper (SM90 CUTLASS W4A16) and Blackwell (SM100/SM120): H200, GB300, B300, B200, and DGX Spark. The `flashinfer_mxfp4` MoE backend is selected automatically on the `lmsysorg/sglang:dev-Ling-3.0-flash-VL` image and on sglang main; on builds that already include the VL integration but predate the auto-selection, add `--moe-runner-backend flashinfer_mxfp4` explicitly. GB300, H200, and DGX Spark cells are verified, the rest carry the unverified badge.

## 3. Advanced Usage

The examples below were run against a server launched with the recipe above plus `--reasoning-parser auto --tool-call-parser auto`, which resolves both parsers to `ling3` (§2). Reasoning therefore arrives in `message.reasoning_content` and the answer in `message.content`.

### 3.1 Image Understanding

Send images as OpenAI-style `image_url` content parts:

> **Image Example (Python)**
>
> ```python Example theme={null}
> from openai import OpenAI
>
> client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
> resp = client.chat.completions.create(
>     model="inclusionAI/Ling-3.0-flash-VL",
>     messages=[{
>         "role": "user",
>         "content": [
>             {"type": "image_url", "image_url": {"url": "https://raw.githubusercontent.com/sgl-project/sglang/main/examples/assets/example_image.png"}},
>             {"type": "text", "text": "Describe this image in one sentence."},
>         ],
>     }],
>     max_tokens=2048,
> )
> msg = resp.choices[0].message
> print("Reasoning:", getattr(msg, "reasoning_content", None))
> print("Content:", msg.content)
> ```

> **Example Output**
>
> ```text Output theme={null}
> Reasoning: The user wants a one-sentence description of this image. Let me look at the image carefully.
>
> The image shows a man wearing a yellow shirt (with some kind of text on it, probably "Sudsy" or similar) standing behind a yellow taxi SUV, ironing clothes on a portable ironing board set up at the rear of the vehicle. On the left side, another yellow taxi (sedan) is passing by on the street. The background is an urban streetscape with buildings lined up.
>
> I need to write this in one sentence. For example: "A man wearing a yellow shirt irons clothes on a portable ironing board attached to the back of a yellow taxi on a city street, while another taxi passes by."
>
> Let me make it concise yet descriptive. One sentence.
>
> "On a city street, a man in a yellow sweatshirt irons clothes on a portable ironing board mounted on the back of a yellow taxi SUV, while another yellow taxi drives past."
>
> This works. I'll return only the answer.
> Content: A man in a yellow shirt irons clothes on a portable ironing board set up at the back of a yellow taxi on a city street, while another yellow cab drives past.
> ```

### 3.2 Video Understanding

Clips go in as `video_url` content parts. The processor samples and pairs frames itself; no client-side frame extraction is needed:

> **Video Example (Python)**
>
> ```python Example theme={null}
> from openai import OpenAI
>
> client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY", timeout=900)
> resp = client.chat.completions.create(
>     model="inclusionAI/Ling-3.0-flash-VL",
>     messages=[{
>         "role": "user",
>         "content": [
>             {"type": "video_url", "video_url": {"url": "https://github.com/sgl-project/sgl-test-files/raw/refs/heads/main/videos/jobs_presenting_ipod.mp4"}},
>             {"type": "text", "text": "What is happening in this video? Answer in two sentences."},
>         ],
>     }],
>     max_tokens=2048,
> )
> msg = resp.choices[0].message
> print("Reasoning:", getattr(msg, "reasoning_content", None))
> print("Content:", msg.content)
> ```

> **Example Output**
>
> ```text Output theme={null}
> Reasoning: The user wants me to describe what is happening in this video in two sentences.
>
> Looking at the video, I can see:
> - A man on stage (appears to be Steve Jobs) presenting something
> - He's wearing a black shirt and jeans
> - There's a large screen behind him showing a close-up of a hand reaching toward a pocket on blue jeans
> - Text appears on screen asking "Anyone know what this pocket is for?"
> - He pulls out a small white device (iPod Nano) from his pocket
> - The text says "I've always wondered that" and "well now we know" and "is the new iPod Nano"
> - He holds up the white iPod Nano device
>
> This is clearly Steve Jobs presenting the new iPod Nano at an Apple event. The small white device is the iPod Nano.
>
> I need to summarize this in exactly two sentences.
> Content: A presenter on stage pulls a small white device from his pocket while a large screen behind him displays a close-up image of a hand reaching toward a jeans pocket. He holds the device up to reveal it is the new iPod Nano, answering the on-screen text that questioned what the small pocket was designed for.
> ```

### 3.3 Thinking Mode

Thinking is on by default. Disable it for a single request through the chat template's `enable_thinking` kwarg; the model then answers directly and `reasoning_content` stays empty:

> **Thinking-off Example (Python)**
>
> ```python Example theme={null}
> from openai import OpenAI
>
> client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
> resp = client.chat.completions.create(
>     model="inclusionAI/Ling-3.0-flash-VL",
>     messages=[{
>         "role": "user",
>         "content": [
>             {"type": "image_url", "image_url": {"url": "https://raw.githubusercontent.com/sgl-project/sglang/main/examples/assets/example_image.png"}},
>             {"type": "text", "text": "Describe this image in one sentence."},
>         ],
>     }],
>     max_tokens=512,
>     extra_body={"chat_template_kwargs": {"enable_thinking": False}},
> )
> msg = resp.choices[0].message
> print("Reasoning:", getattr(msg, "reasoning_content", None))
> print("Content:", msg.content)
> ```

> **Example Output**
>
> ```text Output theme={null}
> Reasoning: None
> Content: A man in a yellow sweatshirt irons a blue shirt on a folding board attached to the back of a parked yellow taxi SUV, while another yellow cab drives past on a city street.
> ```

### 3.4 Tool Calling

With the tool-call parser on, structured calls are parsed into `message.tool_calls` and `finish_reason` is `tool_calls`. Send the tool result back as a `tool` message to get the final answer; on this thinking model the follow-up turn may put text in `reasoning_content` as well as `content`, so print both:

> **Tool-calling Example (Python)**
>
> ```python Example theme={null}
> import json
> from openai import OpenAI
>
> client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
> tools = [{
>     "type": "function",
>     "function": {
>         "name": "get_weather",
>         "description": "Get the current weather for a city",
>         "parameters": {
>             "type": "object",
>             "properties": {"city": {"type": "string", "description": "City name"}},
>             "required": ["city"],
>         },
>     },
> }]
> messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]
>
> resp = client.chat.completions.create(
>     model="inclusionAI/Ling-3.0-flash-VL",
>     messages=messages,
>     tools=tools,
>     tool_choice="auto",
>     max_tokens=2048,
> )
> msg = resp.choices[0].message
> print("finish_reason:", resp.choices[0].finish_reason)
> print("Reasoning:", getattr(msg, "reasoning_content", None))
> print("Content:", msg.content)
> for call in msg.tool_calls:
>     print("Tool call:", call.function.name, call.function.arguments)
>
> messages.append({
>     "role": "assistant",
>     "content": msg.content or "",
>     "tool_calls": [{"id": c.id, "type": "function",
>                     "function": {"name": c.function.name, "arguments": c.function.arguments}}
>                    for c in msg.tool_calls],
> })
> messages.append({
>     "role": "tool",
>     "tool_call_id": msg.tool_calls[0].id,
>     "content": json.dumps({"city": "Paris", "temperature_c": 18, "condition": "light rain"}),
> })
> resp = client.chat.completions.create(
>     model="inclusionAI/Ling-3.0-flash-VL",
>     messages=messages,
>     tools=tools,
>     max_tokens=2048,
> )
> msg = resp.choices[0].message
> print("finish_reason:", resp.choices[0].finish_reason)
> print("Reasoning:", getattr(msg, "reasoning_content", None))
> print("Content:", msg.content)
> ```

> **Example Output**
>
> ```text Output theme={null}
> finish_reason: tool_calls
> Reasoning: The user wants to know the current weather in Paris. I'll call the get_weather function with the city "Paris".
> Content: Let me check the weather in Paris for you right away!
> Tool call: get_weather {"city": "Paris"}
> finish_reason: stop
> Reasoning: None
> Content: Here's the current weather in Paris:
>
> - 🌡️ **Temperature:** 18°C
> - 🌧️ **Condition:** Light rain
>
> It looks like a mild day with some light rain. You might want to bring an umbrella if you're heading out! ☂️
> ```

For more API examples, see the [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision) and the [Tool Parser guide](../../../docs/advanced_features/tool_parser).


# Ling-3.0-tiny
Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/Ling-3.0-tiny

Deploy Ling-3.0-tiny with SGLang — a compact ~7.9B total / ~1.2B active hybrid KDA + MLA MoE in BF16, FP8, or INT4, with thinking mode and tool calling.

## Deployment

> **Install SGLang**
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev-Ling-3.0-tiny
> ```
>
> For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces.

Pick your hardware + recipe to generate the launch command. One serving strategy is covered:

* **High-Throughput** — most tokens per second across many users. Best for batch jobs. Ling-3.0-tiny ships no built-in MTP draft layer (`num_nextn_predict_layers: 0`), so there is no NEXTN speculative-decoding recipe.

## Playground

The Playground is where you experiment with **SGLang features beyond the documented matrix**. The Deploy panel above only emits the curated recipe combinations on this page; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing.

## 1. Model Introduction

Ling-3.0-tiny is a compact hybrid-attention Mixture-of-Experts (MoE) language model from the BailingMoeV3 family — the small variant of [Ling-3.0-flash](/cookbook/autoregressive/InclusionAI/Ling-3.0-flash). It interleaves Kimi Delta Attention (KDA) linear-attention layers with gated Multi-head Latent Attention (MLA) full-attention layers on top of a fine-grained MoE feed-forward network, keeping per-token inference cost near a \~1B dense model — **\~7.9B total parameters with \~1.2B active** — while retaining large-model capacity.

It is a thinking model with chain-of-thought enabled by default, and it supports structured tool calling. Native context length is 128K. Unlike Ling-3.0-flash, it ships **no built-in MTP draft layer**, so it does not use NEXTN speculative decoding.

**Available Models:**

* **BF16**: [inclusionAI/Ling-3.0-tiny](https://huggingface.co/inclusionAI/Ling-3.0-tiny) — \~7.9B total / \~1.2B active
* **FP8** (blockwise E4M3): [inclusionAI/Ling-3.0-tiny-fp8](https://huggingface.co/inclusionAI/Ling-3.0-tiny-fp8)
* **INT4** (compressed-tensors W4A16): [inclusionAI/Ling-3.0-tiny-int4](https://huggingface.co/inclusionAI/Ling-3.0-tiny-int4)

**License:** MIT

**Resources:** [HuggingFace](https://huggingface.co/inclusionAI/Ling-3.0-tiny).

## 2. Configuration Tips

* At \~7.9B total / 15.8 GB in BF16 (\~7.9 GB in FP8 and \~5.8 GB in INT4), a single GPU is plenty on every supported card. Tensor parallelism is only useful to raise aggregate KV-cache capacity for many long-context concurrent requests — add `--tp 2`/`--tp 4` to a multi-GPU serve directly.
* Use the dedicated `lmsysorg/sglang:dev-Ling-3.0-tiny` runtime image; it includes the compressed-tensors Hopper and Blackwell backends that INT4 needs.
* The FP8 checkpoint uses blockwise (128×128) E4M3 weights with dynamic activations, quantized from the BF16 model with attention projections, the dense MoE gate, and the lm\_head left in higher precision. SGLang detects the format from the checkpoint's `quantization_config`, so no explicit quantization flag is needed, and the same single-GPU recipe serves it.
* The INT4 checkpoint uses symmetric group-32 W4A16 routed experts. SGLang selects Marlin on Hopper and Triton WNA16 on Blackwell automatically; no explicit quantization or MoE backend flag is needed.
* Unlike Ling-3.0-flash (which pairs `--reasoning-parser ling3` / `--tool-call-parser ling3`), Ling-3.0-tiny uses `--reasoning-parser deepseek-r1` and `--tool-call-parser glm45` (its auto-detected template pairing) — the template wraps tool calls in `` blocks and emits an inline `...` chain-of-thought. Toggle them in the **Parsers** card of the [Playground](#playground).
* Only `--model-path`, `--host`, and `--port` are needed. SGLang auto-resolves the context length (native 128K from `max_position_embeddings`), the attention backend, and `--mem-fraction-static` from the GPU and the CUDA-graph runtime, so the recipes leave them unset.
* The chat template defaults to thinking on. Turn it off per request with `"chat_template_kwargs": {"enable_thinking": false}` for direct answers without the `...` block.
* Ling-3.0-tiny ships no built-in MTP draft layer (`num_nextn_predict_layers: 0`), so `--speculative-algorithm NEXTN` is not applicable.

## 3. Advanced Usage

### 3.1 Reasoning

With `--reasoning-parser deepseek-r1` (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)), the chain-of-thought is returned in `message.reasoning_content` and the final answer in `message.content`:

> **Thinking-mode request**
>
> ```bash Command theme={null}
> curl -s http://localhost:30000/v1/chat/completions \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "inclusionAI/Ling-3.0-tiny",
>     "messages": [{"role": "user", "content": "What is 15% of 240?"}]
>   }'
> ```

> **Example Output**
>
> ```json Output theme={null}
> {
>   "choices": [
>     {
>       "message": {
>         "role": "assistant",
>         "content": "15% of 240 is **36**.\n\n**Calculation:** 0.15 × 240 = 36",
>         "reasoning_content": "The user is asking for 15% of 240. This is a simple percentage calculation.\n\n15% of 240 = 0.15 × 240 = 36\n\nLet me verify: 0.15 × 240 = 0.15 × 200 + 0.15 × 40 = 30 + 6 = 36. Yes, that's correct.",
>         "tool_calls": null
>       },
>       "finish_reason": "stop"
>     }
>   ]
> }
> ```

> [!NOTE]
>
> Thinking is controlled by the chat template's `enable_thinking` kwarg and is on by default. Disable it per request with `"chat_template_kwargs": {"enable_thinking": false}`.

### 3.2 Tool Calling

With `--tool-call-parser glm45` (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)), structured calls are parsed into `message.tool_calls` and `finish_reason` is `tool_calls`:

> **Tool-calling request**
>
> ```bash Command theme={null}
> curl -s http://localhost:30000/v1/chat/completions \
>   -H "Content-Type: application/json" \
>   -d '{
>     "model": "inclusionAI/Ling-3.0-tiny",
>     "messages": [{"role": "user", "content": "Search for the latest news about AI"}],
>     "tools": [{
>       "type": "function",
>       "function": {
>         "name": "search",
>         "description": "Search for information on the internet",
>         "parameters": {
>           "type": "object",
>           "properties": {
>             "query": {"type": "string", "description": "The search query"}
>           },
>           "required": ["query"]
>         }
>       }
>     }],
>     "tool_choice": "auto"
>   }'
> ```

> **Example Output**
>
> ```json Output theme={null}
> {
>   "choices": [
>     {
>       "message": {
>         "role": "assistant",
>         "content": "Let me search for the latest news about AI for you.",
>         "reasoning_content": "The user wants me to search for the latest news about AI. I'll use the search tool to find recent AI news.",
>         "tool_calls": [
>           {
>             "id": "call_79b73a89696d4544ac6dd724",
>             "index": 0,
>             "type": "function",
>             "function": { "name": "search", "arguments": "{\"query\": \"latest AI news 2025\"}" }
>           }
>         ]
>       },
>       "finish_reason": "tool_calls"
>     }
>   ]
> }
> ```

For more API examples, see the [SGLang Basic Usage Guide](/docs/basic_usage/send_request).


# Ling-3.1-flash
Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/Ling-3.1-flash

Deploy Ling-3.1-flash with SGLang — FP8 hybrid KDA + MLA MoE recipes for H200 and GB300 GPUs, measured accuracy and decode speed, and Mooncake prefix caching.

## Deployment

> **Install SGLang**
>
> Use the Ling-3.1-flash image, which includes model support and the decode optimizations used by these recipes. The image supports multiple CPU architectures:
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev-ling-3.1-flash
> ```
>
> Select **Docker** in the command panel to launch the matching image. The **Python** command requires an environment with the same Ling-3.1-flash build. See the [installation guide](/docs/get-started/install#method-3-using-docker) for Docker setup.
>
> > [!NOTE]
> >
> > The first launch in a fresh container spends about five extra minutes compiling JIT kernels for the speculative-decoding graphs (about 4–5 minutes once, then about 30 seconds). Mount a persistent cache volume, for example `-v ~/.cache:/root/.cache`, to skip it on later starts.
>
> > [!NOTE]
> >
> > **AMD MI325X / MI350X:** the published ROCm images predate the ROCm gated-MLA fix that Ling-3.1-flash needs; without it the server fails while capturing decode CUDA graphs. Until a ROCm image includes the fix, build a thin image that switches the nightly's editable SGLang source to the Ling-3.1-flash branch (use the `mi35x` base for MI350X), then substitute it for the image in the generated Docker command:
> >
> > ```dockerfile Dockerfile theme={null}
> > FROM lmsysorg/sglang-rocm:v0.5.21-rocm724-mi30x-20261013
> > RUN cd /sgl-workspace/sglang \
> >  && git fetch https://github.com/sgl-project/sglang.git bailing-v3-day0 \
> >  && git checkout FETCH_HEAD
> > ```

Pick your hardware to generate the launch command:

* **Low-Latency** — TP-only (EP=1) with NEXTN speculative decoding for single-user chat and interactive requests. Verified on H200.
* **High-Throughput** — expert-parallel (EP) serving for batch and multi-user traffic: TP8 + EP8 on H200/H800/H100/B200-class nodes, TP4 + EP4 on GB300, TP8 + EP8 with AITER on AMD MI300X/MI325X/MI350X/MI355X (without speculative decoding). Verified on H200 and GB300; other platforms are unverified. AMD MI325X and MI350X recipes (TP8 + EP8 with AITER, without speculative decoding) are provided unverified; the MI325X accuracy in the benchmark card was measured by AMD.

For prefix-heavy multi-turn workloads, enable **HiCache** in the Playground after starting the Mooncake services in §3.3. The combination is verified: prefix hits return from Mooncake L3 on every TP rank.

## Playground

Experiment with SGLang features on top of the selected deployment. The speculative-decoding options show the checkpoint requirements; the multi-turn prefix-cache preset adds the paired scheduler flags and environment setting.

## 1. Model introduction

[Ling-3.1-flash](https://huggingface.co/inclusionAI/Ling-3.1-flash) is a hybrid-attention Mixture-of-Experts language model using the `BailingMoeV3ForCausalLM` architecture. Its 72 layers combine Kimi Delta Attention (KDA) with Multi-head Latent Attention (MLA), with 512 routed experts. The checkpoint uses FP8 E4M3 weights in 128×128 blocks with dynamic activation quantization.

The model supports reasoning and structured tool calling, with a context limit of 262,144 tokens.

**Checkpoint:** [inclusionAI/Ling-3.1-flash](https://huggingface.co/inclusionAI/Ling-3.1-flash). **License:** MIT.

The model has about 560B total parameters (512 routed experts with 8 active plus one shared expert per token, about 17B active), 72 layers, and FP8 block-quantized weights.

## 2. Configuration tips

* Use eight H200 GPUs with `--tp 8 --ep 8`, or four GB300 GPUs with `--tp 4 --ep 4`. SGLang detects FP8 from the checkpoint.
* On H200, enable `SGLANG_ENABLE_FP8_BLOCK_GEMV=1` and `SGLANG_ENABLE_FUSED_KDA_OUTPUT_QUANT=1`. Both are included in the generated commands; they are no-ops on GB300 (SM10x).
* Leave `--mem-fraction-static` at its default. SGLang auto-selects the `ling3` reasoning and tool-call parsers for this architecture; you can change the parser settings in the Playground.
* **NEXTN:** add `--speculative-algorithm NEXTN` for built-in MTP speculative decoding. Measured acceptance length is 2.61 on random tokens and 2.13 on real-text probes.
* **Long context:** the checkpoint supports 262,144 tokens natively. For up to 1,048,576 tokens, add the YaRN override from §3.4.
* **Topology:** the Low-Latency recipe runs TP-only (no `--ep-size`) and is clearly faster at batch size 1 (about 9-13% lower TPOT on H200, verified on both 2048/512 and 8192/1024 workloads). At concurrency 16-32 the two recipes deliver the same throughput within \~2%. TP-only relies on the loader's TP-requant support; it fails loudly at startup on builds without it.
* For prefix-heavy, multi-turn workloads, select **Cache fork and tail** in the Playground. It combines `--mamba-radix-cache-strategy extra_buffer`, `--chunked-prefill-size 4096`, and `SGLANG_SPLIT_PREFILL_AT_MAMBA_FORK=1`. GPU checks confirmed both fork and tail states are cached, saving about 576 tokens per subsequent turn in the measured workload.

### Playground support

* **Attention:** BailingKDA shards its projections on attention TP; DP-attention size must divide TP. Prefill CP is disabled because BailingKDA does not implement the required sequence gather and recurrent-state handling.
* **MoE:** Auto, DeepGEMM, and Triton use the FP8 MoE runner paths. EP must divide TP.
* **PD disaggregation:** the Playground exposes separate prefill and decode roles with Mooncake transfer. The runtime has hybrid recurrent-state transfer support, but this model's PD deployment has not been verified. Provision separate workers and route requests through a PD-aware gateway; select the role-specific command for each worker.
* **HiCache:** enabling Mooncake on the H200 base preserves NEXTN and adds direct page-first I/O, hybrid-KDA prefix settings, and TCP storage endpoints.

### Performance

On H200 TP8 with NEXTN and the decode gates enabled, batch-size-1 output throughput measures **269.2 tokens/s** (TP8 + EP8: 239.5 tokens/s). GB300 TP4 with NEXTN measures **175.3 tokens/s** (`TPOT 5.22 ms, accept 2.60`; TP4 + EP4: 160.0 tokens/s).

Acceptance length is the mean number of tokens accepted per speculative verification step, including the target bonus token:

Workload Acceptance length
Random-token benchmark (bs=1)2.61
GSM8K smoke (HiCache serve)2.29
Full GSM8K (cumulative)2.43
Real-text probes (30 prompts)2.13
The image includes KDA normalization/quantization fusion, FP8 block GEMV, router-gate matrix-vector kernels, and a 512-expert top-k router. > **Reproduce the H200 speed workload** > > Launch the H200 **Low-Latency** recipe, then run: > > ```bash Command theme={null} > python3 -m sglang.bench_serving \ > --backend sglang \ > --host localhost --port 30000 \ > --model inclusionAI/Ling-3.1-flash \ > --dataset-name random \ > --random-input-len 2048 --random-output-len 512 \ > --random-range-ratio 1 \ > --num-prompts 16 --max-concurrency 1 \ > --flush-cache --seed 11 > ``` > > For the saturation row in the benchmark widget, launch the H200 **High-Throughput** recipe instead and run: > > ```bash Command theme={null} > python3 -m sglang.bench_serving \ > --backend sglang \ > --host localhost --port 30000 \ > --model inclusionAI/Ling-3.1-flash \ > --dataset-name random \ > --random-input-len 8192 --random-output-len 1024 \ > --random-range-ratio 1 \ > --num-prompts 256 --max-concurrency 48 \ > --flush-cache --seed 11 > ``` > **Reproduce GSM8K accuracy** > > ```bash Command theme={null} > pip install sgl-eval > sgl-eval run gsm8k \ > --base-url http://localhost:30000/v1 \ > --num-threads 32 > ``` > > Evaluate all 1,319 questions and inspect completion reasons as well as accuracy. For the H200 NEXTN recipes, compare the stop rate with the measured 99.77% (Low-Latency) or 99.92% (High-Throughput); accuracy alone can hide generations that reach the token limit. ## 3. Advanced usage ### 3.1 Reasoning The `ling3` parser returns reasoning in `message.reasoning_content` and the final answer in `message.content`. Thinking is enabled by default. To request a direct answer, pass `"chat_template_kwargs": {"enable_thinking": false}` in the request body, or `extra_body={"chat_template_kwargs": {"enable_thinking": False}}` with the OpenAI Python client. > **Thinking-on request (Python)** > > ```python Python theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="Ling-3.1-flash", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > ) > print(response.choices[0].message.reasoning_content) > print(response.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > 15% of 240 = 0.15 × 240 = 36. > > Quick check: 10% of 240 = 24, 5% = 12, total 36. Correct. > **36** > > Here's the calculation: > - 15% = 0.15 > - 0.15 × 240 = 36 > > Or break it down: 10% of 240 = 24, and 5% of 240 = 12, so 24 + 12 = **36** > ``` > > The first block is `reasoning_content` (59 tokens); the second is `content`. `finish_reason` is `stop`. > **Thinking-off request (Python)** > > ```python Python theme={null} > response = client.chat.completions.create( > model="Ling-3.1-flash", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > extra_body={"chat_template_kwargs": {"enable_thinking": False}}, > ) > print(response.choices[0].message.reasoning_content) # None > print(response.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > None > 15% of 240 is **36**. > > Calculation: > - 10% of 240 = 24 > - 5% of 240 = 12 > - 24 + 12 = **36** > > Or directly: 240 × 0.15 = **36** > ``` > > `reasoning_content` is `None` and `reasoning_tokens` is 0. ### 3.2 Tool calling The `ling3` tool-call parser returns structured calls in `message.tool_calls`, with `finish_reason` set to `tool_calls`. Send tools through the OpenAI-compatible `tools` field and return each tool result with its matching `tool_call_id`. Read both `reasoning_content` and `content` on the follow-up assistant turn. > **Tool-calling request and follow-up (Python)** > > ```python Python theme={null} > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": { > "city": {"type": "string", "description": "City name, e.g. Beijing"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["city"], > }, > }, > } > ] > > import json > > > def get_weather(city: str, unit: str = "celsius"): > # Stand-in for your real tool implementation. > return {"city": city, "temperature": 22, "condition": "sunny", "unit": unit} > > > response = client.chat.completions.create( > model="Ling-3.1-flash", > messages=[{"role": "user", "content": "What's the weather like in Hangzhou right now?"}], > tools=tools, > tool_choice="required", > ) > msg = response.choices[0].message > call = msg.tool_calls[0] > print(msg.model_dump_json(indent=2, exclude_none=True)) > print(response.choices[0].finish_reason) > > # Execute the tool yourself, then return its result on the matching tool_call_id > result = get_weather(**json.loads(call.function.arguments)) > > follow_up = client.chat.completions.create( > model="Ling-3.1-flash", > messages=[ > {"role": "user", "content": "What's the weather like in Hangzhou right now?"}, > msg, > {"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}, > ], > tools=tools, > ) > print(follow_up.choices[0].message.reasoning_content) > print(follow_up.choices[0].message.content) > ``` > **Example Output (first turn)** > > ```json Output theme={null} > { > "content": "", > "role": "assistant", > "tool_calls": [ > { > "id": "call_ecd286d7dccb4c70a8c9c586", > "function": { > "arguments": "{\"city\": \"Hangzhou\", \"unit\": \"celsius\"}", > "name": "get_weather" > }, > "type": "function", > "index": 0 > } > ], > "reasoning_content": "The user is asking about the current weather in Hangzhou. I need to call the get_weather function with the city parameter set to \"Hangzhou\". The unit parameter is optional - I'll default to celsius since that's commonly used in China." > } > ``` > **Example Output (follow-up)** > > ```text Output theme={null} > The user asked about the weather in Hangzhou and I got the result. Let me provide a natural response. > The weather in Hangzhou right now is sunny with a temperature of 22°C. It's a pleasant day! > ``` > > The first line is `reasoning_content`; the second is `content`. `finish_reason` is `stop`. ### 3.4 Long context with YaRN (up to 1M tokens) The model's native context is 262,144 tokens. Verified on H200 and GB300, YaRN extrapolation serves up to **1,048,576 tokens**: ```bash Command theme={null} --json-model-override-args '{"rope_scaling": {"rope_type": "yarn", "factor": 4.0, "original_max_position_embeddings": 262144, "rope_theta": 6000000, "partial_rotary_factor": 0.5}, "max_position_embeddings": 1048576}' ``` Add it to the Low-Latency serve command. All four keys are required: the override replaces the checkpoint's RoPE parameters, so omitting `rope_theta` or `partial_rotary_factor` silently changes the RoPE base, and omitting `max_position_embeddings` keeps the 262,144 limit. Only enable it for prompts beyond 256K. Verification on the current checkpoint: a fact planted at token 700,023 of a 900,022-token prompt is retrieved exactly, NEXTN acceptance stays about 2.1 at 900K, and a 300,101-token prompt is answered correctly (H200 TTFT 15.4 s, GB300 12.6 s). One 1M-token request fits alongside normal serving traffic on both platforms. ### 3.3 HiCache with Mooncake With HiCache enabled, prefix state is written through to Mooncake L3 and later requests prefetch it back: measured 5952 of 6000 tokens restored from storage on every TP rank. Mooncake runs as L3 prefix storage over TCP; start the metadata server, master, and storage client before launching SGLang. Run these services on the same host as the SGLang container: > **Start Mooncake services** > > ```bash Command theme={null} > docker run --rm --network host --ipc=host \ > lmsysorg/sglang:dev-ling-3.1-flash \ > bash -lc ' > python3 -m mooncake.http_metadata_server --port 8290 & > mooncake_master --port 50171 --metrics_port 9024 & > exec mooncake_client \ > --host=127.0.0.1 \ > --port=50172 \ > --master_server_address=127.0.0.1:50171 \ > --metadata_server=http://127.0.0.1:8290/metadata \ > --protocol=tcp \ > --device_names= \ > --global_segment_size=4294967296 \ > --enable_http_server=true \ > --http_port=8291 > ' > ``` > **Example Output** > > ```text Output theme={null} > I1014 11:47:24.542050 328820 master.cpp:1522] Master service started on port 50171, max_threads=16, enable_metric_reporting=1, metrics_port=9024, ... > I1014 11:47:24.558478 328853 master_admin_service.cpp:301] Master Admin Metrics: role=leader, state=serving, service_ready=true, ... > I1014 11:47:27.557325 328879 real_client.cpp:1935] Client HTTP server started on port 8291 > ``` Select **H200 → Low-Latency** in Deployment, then enable **HiCache → Mooncake** in the Playground. Keep NEXTN inherited from the base. Docker commands use host networking so the SGLang container can reach these localhost services. Change the master and metadata endpoints in the **Env** dialog for a remote store. The TCP recipe leaves `MOONCAKE_DEVICE` and `--device_names` empty. The generated command includes `extra_buffer`, direct page-first I/O, and `hicache_storage_pass_prefix_keys=true` for hybrid KDA prefix reuse. To verify L3 round-trip: send a long prompt (thousands of tokens), wait for the server to go idle, flush with `curl -X POST http://localhost:30000/flush_cache -H 'Content-Type: application/json' -d '{}'`, then repeat the same prompt. > **Verify L3 prefetch (serve log)** > > ```text Output theme={null} > [2026-10-14 11:59:25 TP0 EP0] HiCache prefetch success req=2619007c50024156a9872f10ec14606a completed=5952 matched=0 loaded=5952 occupied=0 > [2026-10-14 11:59:25 TP1 EP1] HiCache prefetch success req=2619007c50024156a9872f10ec14606a completed=5952 matched=0 loaded=5952 occupied=0 > [2026-10-14 11:59:25 TP2 EP2] HiCache prefetch success req=2619007c50024156a9872f10ec14606a completed=5952 matched=0 loaded=5952 occupied=0 > [2026-10-14 11:59:25 TP7 EP7] HiCache prefetch success req=2619007c50024156a9872f10ec14606a completed=5952 matched=0 loaded=5952 occupied=0 > [2026-10-14 11:59:25 TP6 EP6] HiCache prefetch success req=2619007c50024156a9872f10ec14606a completed=5952 matched=0 loaded=5952 occupied=0 > [2026-10-14 11:59:25 TP5 EP5] HiCache prefetch success req=2619007c50024156a9872f10ec14606a completed=5952 matched=0 loaded=5952 occupied=0 > [2026-10-14 11:59:25 TP4 EP4] HiCache prefetch success req=2619007c50024156a9872f10ec14606a completed=5952 matched=0 loaded=5952 occupied=0 > [2026-10-14 11:59:25 TP3 EP3] HiCache prefetch success req=2619007c50024156a9872f10ec14606a completed=5952 matched=0 loaded=5952 occupied=0 > ``` > [!NOTE] > > `POST /flush_cache` is refused with 400 while any request is still in flight — the L3 write-through finishes after the response returns. Wait a few seconds of idle before flushing. For storage sizing and backend details, see [HiCache best practices](/docs/advanced_features/hicache_best_practices). # Ring-2.5-1T Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/Ring-2.5-1T ## 1. Model Introduction [Ring-2.5-1T](https://huggingface.co/inclusionAI/Ring-2.5-1T) is the world's first open-source trillion-parameter reasoning model based on hybrid linear attention architecture, developed by InclusionAI. Building on Ring-1T, Ring-2.5-1T demonstrates substantial improvements in generation efficiency, reasoning depth, and long-horizon task execution capabilities. **Key Features:** * **Trillion-Scale Model**: \~1T total parameters with 63B activation parameters using a hybrid linear attention architecture (1:7 MLA + Lightning Linear Attention) * **Generation Efficiency**: Reduces memory access overhead by over 10x and increases generation throughput by more than 3x for sequences exceeding 32K tokens * **Deep Reasoning**: Achieves gold medal level for both IMO 2025 and CMO 2025, with dense rewards for rigorous reasoning process feedback * **Long-horizon Task Execution**: Enhanced autonomous execution capability through large-scale fully-async agentic RL training * **Tool Calling**: Supports function calling with XML-style tool call format * **Context Length**: 128K -> 256K (YaRN) **Available Models:** * **FP8 (8-bit quantized)**: [inclusionAI/Ring-2.5-1T](https://huggingface.co/inclusionAI/Ring-2.5-1T) **License:** MIT ## 2. SGLang Installation Ring-2.5-1T runs on the standard SGLang Docker image: ```bash Command theme={null} # NVIDIA (H200 / B200 / GB200 / GB300) docker pull lmsysorg/sglang:latest # For MI300X/325X docker pull lmsysorg/sglang:v0.5.9-rocm700-mi30x # For MI355X docker pull lmsysorg/sglang:v0.5.9-rocm700-mi35x ``` For other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/install). ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform. Run this Command:

### 3.2 Configuration Tips

* The `--trust-remote-code` flag is required for this model due to custom modeling code.
* The model uses FP8 quantization (compressed-tensors format).

## 4. Model Invocation

Deploy Ring-2.5-1T with the following command (on H200, all features enabled):

```shell Command theme={null}
sglang serve \
  --model-path inclusionAI/Ring-2.5-1T \
  --tp 8 \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000
```

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

To enable reasoning output separation, add `--reasoning-parser deepseek-r1` when launching the server. The thinking process is returned via `reasoning_content` in the streaming response.

```shell Command theme={null}
sglang serve \
  --model-path inclusionAI/Ring-2.5-1T \
  --tp 8 \
  --trust-remote-code \
  --reasoning-parser deepseek-r1 \
  --host 0.0.0.0 \
  --port 30000
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="inclusionAI/Ring-2.5-1T",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    max_tokens=2048,
    stream=True
)

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            print(delta.reasoning_content, end="", flush=True)

        if delta.content:
            print(delta.content, end="", flush=True)

print()
```

Output Example ```text Output theme={null} We are asked: "Solve this problem step by step: What is 15% of 240?" This is a straightforward percentage calculation. We need to show step-by-step solution. We can compute 15% of 240 as (15/100)*240 = 0.15 * 240 = 36. But we need to present step by step. Also ensure it's clear. We could also break down: 10% of 240 = 24, then 5% = 12, so 15% = 36. But any method is fine. We'll produce a solution with explanation: "To find 15% of 240, multiply 240 by 0.15 (or 15/100)." We'll show: 15% = 15/100 = 0.15 Then 0.15 × 240 = 36. Alternatively: (15/100) × 240 = (15 × 240) / 100 = 3600/100 = 36. Finally, answer: 36. We can also illustrate stepwise: "First, convert the percentage to a decimal: 15% = 0.15. Then multiply by the number: 0.15 × 240 = 36." We'll present as a final answer: \boxed{36}. However, we need to provide step-by-step solution as per instructions. We'll write a full explanation. We can also use the fraction method: 15% of 240 = (15/100)*240 = (15*240)/100 = 3600/100 = 36. Alr. I think that's it. **Step 1:** Write 15% as a fraction or decimal. \[ 15\% = \frac{15}{100} = 0.15\] **Step 2:** Multiply the number (240) by this fraction/decimal. \[ 240 \times 0.15 = 36\] Alternatively, using the fraction: \[ \frac{15}{100} \times 240 = \frac{15 \times 240}{100} = \frac{3600}{100} = 36\] **Conclusion:** 15% of 240 is 36. \[ \boxed{36} \] ```
#### 4.2.2 Tool Calling To enable tool calling, add `--tool-call-parser qwen` when launching the server. ```shell Command theme={null} sglang serve \ --model-path inclusionAI/Ring-2.5-1T \ --tp 8 \ --trust-remote-code \ --tool-call-parser qwen \ --host 0.0.0.0 \ --port 30000 ``` ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" } }, "required": ["location"] } } } ] response = client.chat.completions.create( model="inclusionAI/Ring-2.5-1T", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools ) print(response.choices[0].message.tool_calls) ``` **Output Example:** ```text Output theme={null} [ChatCompletionMessageFunctionToolCall(id='call_770360e31d194ed79d32cd8c', function=Function(arguments='{"location": "Beijing"}', name='get_weather'), type='function', index=0)] ``` ## 5. Benchmark ### GSM8K * Deployment Command ```bash Command theme={null} sglang serve \ --model-path inclusionAI/Ring-2.5-1T \ --tp-size 8 \ --trust-remote-code ``` * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 \ --num-threads 64 \ --temperature 1.2 \ --top-p 0.8 \ --max-tokens 32768 \ --chat-template-kwarg enable_thinking=true ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. * Test Result ```text Output theme={null} Accuracy: 0.955 Invalid: 0.010 Latency: 615.833 s Output throughput: 412.360 token/s ``` # Ring-2.6-1T Source: https://docs.sglang.io/cookbook/autoregressive/InclusionAI/Ring-2.6-1T ## 1. Model Introduction [Ring-2.6-1T](https://huggingface.co/inclusionAI/Ring-2.6-1T) is InclusionAI's trillion-parameter flagship reasoning model for real-world complex task execution. It targets agent workflows, engineering development, scientific research analysis, enterprise automation, and other long-horizon settings where the model must plan, use tools, recover from intermediate errors, and keep context across multiple steps. **Key Features:** * **Trillion-Scale Reasoning Model**: `BailingMoeV2_5ForCausalLM` with a `bailing_hybrid` architecture, 80 hidden layers, 256 routed experts, 8 selected experts per token, and FP8 compressed-tensors weights. * **Agent Execution**: Designed for multi-step task decomposition, tool collaboration, context continuation, and long-horizon execution. The model card reports 87.60 on PinchBench, 63.82 on ClawEval, and 95.32 on Tau2-Bench Telecom for the `high` setting. * **Reasoning Effort**: The model card describes `high` and `xhigh` reasoning-effort modes. In SGLang's OpenAI-compatible chat API, use top-level `reasoning_effort: "high"` for production agent workflows. To request the model-card `xhigh` prompt path, pass it through `chat_template_kwargs.reasoning_effort`. * **Hybrid Attention**: Uses the Bailing hybrid stack with MLA plus Lightning linear attention kernels in SGLang. * **Context Length**: Native 128K in the released config. Configure YaRN separately if you need a 256K deployment. **Available Models:** * **FP8 (E4M3 compressed-tensors)**: [inclusionAI/Ring-2.6-1T](https://huggingface.co/inclusionAI/Ring-2.6-1T) **License:** MIT ## 2. SGLang Installation Ring-2.6-1T requires recent SGLang builds with Bailing hybrid model support. Start with the latest SGLang Docker image when validating this cookbook: ```bash Command theme={null} docker pull lmsysorg/sglang:latest ``` For other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/install). ## 3. Model Deployment Use the selector below to generate a single-node command for the tested hardware targets. Run this Command:

### Configuration Tips

* `--trust-remote-code` is required for the model's custom Bailing hybrid implementation.
* Use `--tp-size 4` on a single 4-GPU GB300 node.
* Use `--tp-size 8` on a single 8-GPU B200 node.
* Use `--tp-size 8` on a single 8-GPU H200 node.
* Use `--mem-fraction-static 0.95` on GB300 x4. The model uses about 238.5GB/GPU after loading, so lower values can fail during KV-pool initialization.
* Use `--mem-fraction-static 0.8` on B200 x8.
* Use `--mem-fraction-static 0.95` on H200 x8.
* `--model-loader-extra-config '{"enable_multithread_load":"true","num_threads":64}'` is recommended because the model has 175 large safetensors shards.
* Keep `--tool-call-parser glm` enabled by default for OpenAI-compatible tool calls. Ring's template emits XML `/` tool calls, which the `qwen` parser does not convert into `message.tool_calls`.
* Keep `--reasoning-parser deepseek-r1` enabled by default so `...` content is split into `message.reasoning_content`.

## 4. Model Invocation

### 4.1 Basic Usage

For example, launch the server on a single 4-GPU GB300 node:

```bash Command theme={null}
export PORT=30000

sglang serve \
  --model-path inclusionAI/Ring-2.6-1T \
  --tp-size 4 \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port ${PORT} \
  --mem-fraction-static 0.95 \
  --model-loader-extra-config '{"enable_multithread_load":"true","num_threads":64}' \
  --tool-call-parser glm \
  --reasoning-parser deepseek-r1
```

Send a basic chat request:

```bash Command theme={null}
curl -s http://localhost:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [{"role": "user", "content": "What is the capital of France?"}],
    "max_tokens": 128
  }'
```

### 4.2 Reasoning Effort

Ring-2.6-1T exposes two reasoning-effort levels in the model card: `high` and `xhigh`. In SGLang's OpenAI-compatible chat API, start with top-level `reasoning_effort: "high"` for agent and production workflows:

```bash Command theme={null}
curl -s http://localhost:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [{"role": "user", "content": "Solve: if 3x + 7 = 52, what is x?"}],
    "reasoning_effort": "high",
    "max_tokens": 512
}'
```

For the model-card `xhigh` path, pass the template value explicitly:

```bash Command theme={null}
curl -s http://localhost:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [{"role": "user", "content": "Solve: if 3x + 7 = 52, what is x?"}],
    "chat_template_kwargs": {"reasoning_effort": "xhigh"},
    "max_tokens": 512
  }'
```

With the default deployment command, thinking text is separated into `message.reasoning_content` when the model emits `...` blocks.

### 4.3 Tool Calling Example

```bash Command theme={null}
curl -s http://localhost:${PORT}/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto",
    "messages": [{"role": "user", "content": "What is the weather in Beijing?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get the current weather for a location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "The city name"}
          },
          "required": ["location"]
        }
      }
    }],
    "tool_choice": "auto",
    "max_tokens": 512
  }'
```

For more API examples, see the [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request).

## 5. Benchmark

### 5.1 Speed Benchmark

* Hardware: NVIDIA B200 GPU (8x), NVIDIA H200 GPU (8x), and NVIDIA GB300 GPU (4x)
* Model: `inclusionAI/Ring-2.6-1T`
* Docker image: `lmsysorg/sglang:latest`
* SGLang version tested: `0.5.11`
* Tensor Parallelism: 8 on B200 x8 and H200 x8, 4 on GB300 x4

Use the deployment command from [Section 3](#3-model-deployment), then confirm that the server is healthy before running benchmarks:

```bash Command theme={null}
curl -s http://localhost:${PORT}/health
curl -s http://localhost:${PORT}/v1/models
```

#### 5.1.1 Latency-Sensitive Benchmark

* Test Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port ${PORT} \
  --model inclusionAI/Ring-2.6-1T \
  --dataset-name random \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* Test Results (B200 x8):

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  207.18
Total input tokens:                      6101
Total generated tokens:                  4220
Request throughput (req/s):              0.05
Input token throughput (tok/s):          29.45
Output token throughput (tok/s):         20.37
Total token throughput (tok/s):          49.82
Mean E2E Latency (ms):                   20715.16
Mean TTFT (ms):                          187.86
Mean TPOT (ms):                          44.65
Mean ITL (ms):                           48.76
==================================================
```

* Test Results (GB300 x4):

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  62.21
Total input tokens:                      6101
Total generated tokens:                  4220
Request throughput (req/s):              0.16
Input token throughput (tok/s):          98.07
Output token throughput (tok/s):         67.83
Total token throughput (tok/s):          165.91
Mean E2E Latency (ms):                   6218.57
Mean TTFT (ms):                          233.04
Mean TPOT (ms):                          14.21
Mean ITL (ms):                           14.22
==================================================
```

* Test Results (H200 x8):

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  57.10
Total input tokens:                      6101
Total generated tokens:                  4220
Request throughput (req/s):              0.18
Input token throughput (tok/s):          106.85
Output token throughput (tok/s):         73.91
Total token throughput (tok/s):          180.76
Mean E2E Latency (ms):                   5707.72
Mean TTFT (ms):                          163.35
Mean TPOT (ms):                          13.17
Mean ITL (ms):                           13.17
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Test Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port ${PORT} \
  --model inclusionAI/Ring-2.6-1T \
  --dataset-name random \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 100 \
  --max-concurrency 100 \
  --request-rate inf
```

* Test Results (B200 x8):

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     100
Benchmark duration (s):                  46.30
Total input tokens:                      50561
Total generated tokens:                  52444
Request throughput (req/s):              2.16
Input token throughput (tok/s):          1092.10
Output token throughput (tok/s):         1132.77
Total token throughput (tok/s):          2224.86
Mean E2E Latency (ms):                   27581.74
Mean TTFT (ms):                          1710.53
Mean TPOT (ms):                          51.27
Mean ITL (ms):                           49.43
==================================================
```

* Test Results (GB300 x4):

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     100
Benchmark duration (s):                  55.80
Total input tokens:                      50561
Total generated tokens:                  52444
Request throughput (req/s):              1.79
Input token throughput (tok/s):          906.10
Output token throughput (tok/s):         939.84
Total token throughput (tok/s):          1845.94
Mean E2E Latency (ms):                   33736.85
Mean TTFT (ms):                          2156.40
Mean TPOT (ms):                          63.09
Mean ITL (ms):                           60.33
==================================================
```

* Test Results (H200 x8):

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     100
Benchmark duration (s):                  44.51
Total input tokens:                      50561
Total generated tokens:                  52444
Request throughput (req/s):              2.25
Input token throughput (tok/s):          1135.88
Output token throughput (tok/s):         1178.18
Total token throughput (tok/s):          2314.06
Mean E2E Latency (ms):                   27177.14
Mean TTFT (ms):                          2173.08
Mean TPOT (ms):                          51.11
Mean ITL (ms):                           47.77
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* Benchmark Command:

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:${PORT}/v1 \
  --model auto \
  --num-examples 200 \
  --num-threads 64 \
  --max-tokens 2048 \
  --reasoning-effort high
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* Test Results (B200 x8):

```text Output theme={null}
Total latency: 100.378 s
Score: 0.990
Output throughput: 627.401 token/s
```

* Test Results (GB300 x4):

```text Output theme={null}
Total latency: 98.386 s
Score: 0.990
Output throughput: 621.469 token/s
```

* Test Results (H200 x8):

```text Output theme={null}
Total latency: 76.849 s
Score: 0.990
Output throughput: 793.125 token/s
```


# Intern-S1
Source: https://docs.sglang.io/cookbook/autoregressive/InternLM/Intern-S1



## 1. Model Introduction

Intern-S1 includes the large **Intern-S1** MoE model and the smaller **Intern-S1-mini** dense model. The command generator below covers BF16 and FP8 serving on NVIDIA H100/H200/B200/B300 platforms.

## 2. SGLang Installation

Refer to the [official SGLang installation guide](../../../docs/get-started/install), or install from source:

```bash Command theme={null}
uv pip install --prerelease=allow 'git+https://github.com/sgl-project/sglang.git#subdirectory=python'
```

## 3. Model Deployment

### 3.1 Basic Configuration

Run this Command:


### 3.2 Configuration Tips

* FP8 checkpoints use the matching BF16 checkpoint as tokenizer path.
* B300 deployments use `--attention-backend flashinfer`.
* Enable `--reasoning-parser interns1` and `--tool-call-parser interns1` when your workload needs structured reasoning or tool-call parsing.


# Intern-S2-Mobius
Source: https://docs.sglang.io/cookbook/autoregressive/InternLM/Intern-S2-Mobius

Deploy the BF16 and FP8 Intern-S2-Mobius checkpoints with SGLang on NVIDIA H200 and B200.

## Deployment

> **Install SGLang**
>
> For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel.
>
> **Python (pip / uv)**
>
> ```bash Command theme={null}
> pip install --upgrade pip
> pip install uv
> uv pip install --prerelease=allow sglang
> ```
>
> Then run the **Python** output of the command panel below in that environment.
>
> **Docker**
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev
> ```
>
> Intern-S2-Mobius was upstreamed in PR [#33691](https://github.com/sgl-project/sglang/pull/33691) (merged 2026-08-08) — it lives on `lmsysorg/sglang:dev` (nightly) until the next release cut. For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces.

Pick your hardware + recipe to generate the launch command. The two serving strategies cover the main operating points:

* **Low-Latency** — MTP (NEXTN) speculative decoding on. Fastest reply for a single user.
* **High-Throughput** — spec off, more tokens per second when many users share the server.

> [!NOTE]
>
> Speed and accuracy numbers apply to the BF16 checkpoint. They were measured with `--random-range-ratio 1.0`, `--flush-cache`, on 2×H200 TP=2 against `main @ e0828ee3` + PR [#33691](https://github.com/sgl-project/sglang/pull/33691) head (since merged 2026-08-08 — `lmsysorg/sglang:dev` is the live equivalent). GSM8K is the full 1319-example test split; GPQA is Diamond 198 problems × 8 repeats (pass\@1 avg-of-8). Both ran with no server-side sampling override, so the checkpoint's `generation_config.json` defaults applied (temperature 1.0, top\_p 0.95, top\_k 20). The FP8 H200 recipes have launch, text, vision, and stop-reason verification but no benchmark numbers yet. All B200 recipes are inferred and unverified.

## Playground

The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing.

## 1. Model Introduction

**Intern-S2-Mobius** is InternLM's 35B scientific multimodal foundation model built on the **Mobius-v0** architecture (continually pre-trained from Qwen3.5-35B, then SFT and RL post-trained). Instead of binding knowledge storage and reasoning computation layer by layer as conventional Transformers do, Mobius organizes knowledge into a **globally shared Memory** that multiple **Reasoners** iteratively query against, yielding two native capabilities:

* **Backward Residual Connection** — shallow and deep reasoning stages can reach knowledge across the model rather than relying only on forward layer-wise flow.
* **Dynamic Latent Reasoning** — recurrent latent iteration refines hidden states before decoding, internalizing part of the deliberation process and shrinking visible chain-of-thought. The reported result is roughly a **4× end-to-end inference speedup** over the Qwen3.5-35B baseline while holding comparable scores on general reasoning benchmarks and improving on scientific tasks (Biology-Instructions, Mol-Instructions, MolecularIQ).

On the serving side the model is a hybrid: 30 of 40 transformer layers use **GDN (Gated Delta Net) linear attention** (`kimi-linear`-family), with a **full-attention** layer every 4th layer (`full_attention_interval: 4` → **10 full-attention** layers), and the bottom of the stack is MoE-routed (2,560 routed experts × 512 intermediate, 8 active per token); a separate **MoE-256 / top-8 MTP (NEXTN) layer** feeds speculative decoding. It takes images via a vision tower and recognizes the standard `<|vision_start|>…<|vision_end|>` + `<|image_pad|>` markers. Context length is **262,144** tokens.

Variant Architecture Context License
**[Intern-S2-Mobius](https://huggingface.co/internlm/Intern-S2-Mobius)** Mobius-v0 · GDN ×30 + full ×10 · MoE-2560 / top-8 · MTP · BF16 262,144 [Apache-2.0](https://huggingface.co/internlm/Intern-S2-Mobius/blob/main/LICENSE)
**[Intern-S2-Mobius-FP8](https://huggingface.co/internlm/Intern-S2-Mobius-FP8)** Mobius-v0 · GDN ×30 + full ×10 · MoE-2560 / top-8 · MTP · FP8 E4M3 262,144 [Apache-2.0](https://huggingface.co/internlm/Intern-S2-Mobius-FP8/blob/main/LICENSE)
**Recommended generation:** `temperature=0.8`, `top_p=1.0`, `top_k=50`, `min_p=0.0` — the values the [model card](https://huggingface.co/internlm/Intern-S2-Mobius) recommends. Both checkpoints ship `generation_config.json` with different values (`temperature=1.0`, `top_p=0.95`, `top_k=20`), and SGLang applies that file by default (`--sampling-defaults model`) — so send the recommended values explicitly per request if you want them. **Resources:** [HuggingFace (BF16)](https://huggingface.co/internlm/Intern-S2-Mobius) · [HuggingFace (FP8)](https://huggingface.co/internlm/Intern-S2-Mobius-FP8) · [GitHub (InternLM/Intern-S2-Mobius)](https://github.com/InternLM/Intern-S2-Mobius). ## 2. Configuration Tips * **Trust remote code is required.** Intern-S2-Mobius ships a custom `configuration_interns2_mobius.py` / `modeling_interns2_mobius.py` on its HF repo; every recipe adds `--trust-remote-code`. * **FP8 uses one H200.** The FP8 checkpoint stores E4M3 weights with 128×128 block scales and dynamic activation quantization. The verified H200 recipes use TP=1, `deep_gemm`, `--mem-fraction-static 0.6`, disabled prefill CUDA graphs, and decode graphs up to batch size 16. Higher memory fractions or the default graph range exhausted H200 memory during DeepGEMM warmup; the running MTP server used about 99 GB. * **Speculative decoding schedule.** The checkpoint ships one MTP layer. Enable MTP for the lowest latency (`--speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`). We measured accept-length \~3.9/4 draft tokens at 8K-in / 1K-out, roughly tripling single-stream decode speed (median TPOT 9.79 ms → 3.13 ms at conc=1, 14.26 ms → 6.84 ms at conc=16) and roughly doubling mid-concurrency total throughput (9358 → 18029 tokens/s at conc=16, 21395 → 26033 tokens/s at conc=64). The high-throughput recipe stays spec-off because once you can batch wide, its saturation point is higher (34786 tokens/s at conc=256 vs the spec recipe's peak at conc=64). * **Mamba pool sizing.** GDN layers live in a separate Mamba state pool; the `--mamba-full-memory-ratio` (defaults to 0.9) controls the split between the 10 full-attention layers' KV pool and the 30 GDN layers' conv+SSM state pool. Default split comfortably handles conc=64 on a 2×H200 node; if you need higher concurrency than `--max-running-requests` allows for your workload, raise `--mamba-full-memory-ratio` slightly (each +1% mamba ratio costs full-attn KV). * **Vision input.** Images are accepted via the standard `image_url` chat message type. Vision tokens are counted into the prompt (`prompt_tokens_details.image_tokens` shows the count), and the model honors `<|vision_start|>` / `<|vision_end|>` boundaries exactly. * **B200 sizing.** B200 (192 GB HBM) fits the BF16 weights + KV + Mamba pool on a **single GPU** with `--tp 1`. The FP8 B200 cells inherit the verified H200 TP=1 recipe but remain unverified; treat them as a starting point until a Blackwell measurement is available. ## 3. Advanced Usage > [!NOTE] > > The outputs below are verbatim captures from a live server (sampling per the checkpoint's `generation_config.json`, temperature 1.0). Re-running the same request yields a semantically equivalent but textually different trace — treat them as representative, not deterministic. ### 3.1 Reasoning InternS2-Mobius is a hybrid-reasoning model — thinking traces start with "Thinking Process:" before the final answer. Enable the **`qwen3` reasoning parser** (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to split thinking into `message.reasoning_content` and the answer into `message.content`. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="internlm/Intern-S2-Mobius", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: Thinking Process: > > 1. **Identify the core question:** The user is asking for 15% of 240. > 2. **Determine the calculation method:** To find a percentage of a > number, multiply the number by the percentage expressed as a decimal > or fraction. > * Percentage: 15% > * Decimal: 0.15 > * Fraction: 15/100 > 3. **Perform the calculation:** $240 \times 0.15$ > * Method 1: $240 \times 0.10 = 24$ (10%) and > $240 \times 0.05 = 12$ (5%). Then add them: $24 + 12 = 36$. > * Method 2: $240 \times 15 = 3600$. Divide by 100 -> 36. > 4. **Verify the result:** The calculation is correct. > 5. **Formulate the answer:** State the final number clearly.cw > > Answer: > > 15% of 240 is **36**. > > Here is the math: > $240 \times 0.15 = 36$ > ``` ### 3.2 Tool Calling Enable the **`qwen3_coder` tool-call parser** (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. Intern-S2-Mobius emits `………value……` — this is exactly the format `qwen3_coder` parses; without the parser the call is left as raw text in `content`. On this thinking-mode model the turn also fills `reasoning_content`, so print both fields. **Auto-resolution works out of the box.** Intern-S2-Mobius's chat template contains the ` **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > }, > "required": ["location"], > }, > }, > }] > resp = client.chat.completions.create( > model="internlm/Intern-S2-Mobius", > messages=[{"role": "user", "content": "What is the weather in Beijing?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user is asking for the weather in Beijing. I have access > to a get_weather function that can get the current weather for a > location. The function requires a "location" parameter which should be > the city name. In this case, the user specified "Beijing", so I should > use that as the location parameter. > > Tool calls: [ > { > "id": "call_545b5956b4c3457286261490", > "index": 0, > "type": "function", > "function": {"name": "get_weather", "arguments": "{\"location\": \"Beijing\"}"} > } > ] > > finish_reason: tool_calls > ``` ### 3.3 Vision Input Intern-S2-Mobius takes images via the OpenAI-compatible `image_url` content type. Vision input works with the same server the Deploy panel produces — no extra model-specific flags needed. > **Vision Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="internlm/Intern-S2-Mobius", > messages=[{ > "role": "user", > "content": [ > {"type": "image_url", > "image_url": {"url": "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg"}}, > {"type": "text", "text": "Describe this image in one sentence."}, > ], > }], > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user wants a one-sentence description of the image. > Key elements: Tiger, lying down, grass, looking at camera. > Drafting: A tiger is lying in the green grass looking directly at the > camera. > Refining for flow and detail: A majestic tiger with striking orange and > black stripes rests calmly on a bed of lush green grass, staring > intently directly at the viewer. > > Answer: > > A majestic tiger with striking orange and black stripes rests calmly on a > bed of lush green grass, staring intently directly at the viewer. > ``` # Intern-S2-Preview Source: https://docs.sglang.io/cookbook/autoregressive/InternLM/Intern-S2-Preview ## 1. Model Introduction **Intern-S2-Preview** is an efficient 35B scientific multimodal foundation model. Beyond conventional parameter and data scaling, Intern-S2-Preview explores task scaling: increasing the difficulty, diversity, and coverage of scientific tasks to further unlock model capabilities. **Resources:** * HuggingFace: [internLM/Intern-S2-Preview](https://huggingface.co/internLM/Intern-S2-Preview) ## 2. SGLang Installation SGLang offers multiple installation methods. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. Install SGLang from source or use an NVIDIA Docker image: ```bash Command theme={null} # Install from source uv pip install --prerelease=allow 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' # Or use Docker for NVIDIA GPUs docker pull lmsysorg/sglang:latest ``` For how to actually launch a docker image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). A minimal example (substitute the inner `sglang serve ...` with whatever the [command generator](#3-model-deployment) below produces): ```bash Command theme={null} docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=" \ --ipc=host \ lmsysorg/sglang:latest \ sglang serve ``` ## 3. Model Deployment ### 3.1 Basic Configuration **Interactive Command Generator**: Use the selector below to generate the deployment command for your hardware and parser configuration. Run this Command:

### 3.2 Configuration Tips

* Use `tp>=2` for the NVIDIA deployment commands.
* Use `--reasoning-parser qwen3` to separate reasoning content from final content in streaming responses.
* Use `--tool-call-parser qwen3_coder` when serving tool-calling workloads.
* Add `--mamba-radix-cache-strategy extra_buffer` with `--speculative-algo 'NEXTN'` to enable MTP.
* If weight loading is slow, add `--model-loader-extra-config='{"enable_multithread_load": "true", "num_threads": 64}'`.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, see:

* [Basic API Usage](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Vision Input

Intern-S2-Preview supports image inputs. Here is an example with an image:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="internLM/Intern-S2-Preview",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg"
                    },
                },
                {
                    "type": "text",
                    "text": "Describe this image in detail.",
                },
            ],
        }
    ],
    max_tokens=2048,
    stream=True,
)

thinking_started = False
has_thinking = False
has_answer = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        if hasattr(delta, "reasoning_content") and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        if delta.content:
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

#### 4.2.2 Reasoning Parser

Enable streaming to read reasoning content separately from the final answer:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="internLM/Intern-S2-Preview",
    messages=[
        {"role": "user", "content": "Solve this step by step: What is 15% of 240?"}
    ],
    max_tokens=2048,
    stream=True,
)

thinking_started = False
has_thinking = False
has_answer = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        if hasattr(delta, "reasoning_content") and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        if delta.content:
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

#### 4.2.3 Tool Calling

Serve with `--tool-call-parser qwen3_coder` enabled, then send OpenAI-compatible tool requests:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name",
                    }
                },
                "required": ["location"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="internLM/Intern-S2-Preview",
    messages=[{"role": "user", "content": "What is the weather in Beijing?"}],
    tools=tools,
    max_tokens=1024,
)

print(response.choices[0].message)
```


# InternVL3.5
Source: https://docs.sglang.io/cookbook/autoregressive/InternVL/InternVL3.5



## 📝 Community Contribution Welcome

This guide is currently under development. We welcome community contributions!

If you have experience deploying **InternVL3.5** with SGLang, please help us complete this documentation.

## 🚀 How to Contribute

```shell Command theme={null}
git clone https://github.com/YOUR_USERNAME/sglang-cookbook.git
cd sglang-cookbook
git checkout -b add-internvl3-5-guide
# Edit this file and submit a PR
```

## 📚 Reference

* [GLM-4.6V](../GLM/GLM-4.6V)

***

**Let's build this together!** 🌟


# Jina-reranker-m0
Source: https://docs.sglang.io/cookbook/autoregressive/Jina/Jina-reranker-m0



## 📝 Community Contribution Welcome

This guide is currently under development. We welcome community contributions!

If you have experience deploying **Jina-reranker-m0** with SGLang, please help us complete this documentation.

## 🚀 How to Contribute

```shell Command theme={null}
git clone https://github.com/YOUR_USERNAME/sglang-cookbook.git
cd sglang-cookbook
git checkout -b add-jina-reranker-m0-guide
# Edit this file and submit a PR
```

## 📚 Reference

* [DeepSeek-V3.2](../DeepSeek/DeepSeek-V3_2.md)

***

**Let's build this together!** 🌟


# Kev
Source: https://docs.sglang.io/cookbook/autoregressive/Kev/kev

Deploy the Kev decision models with SGLang. Kev returns calibrated probabilities for typed questions about a document, in sizes from 0.8B to 27B, each on one NVIDIA H200 in BF16.

## Deployment

Every Kev size runs on one GPU in BF16 with TP=1 and needs no extra flag. SGLang reads the checkpoint's `head.pt` and configures the server.

```bash Command theme={null}
sglang serve --model-path jaredpalmer/kev-27b --host 0.0.0.0 --port 30000
```

Replace the model path with any size in the table below. Each was validated on one H200.

| Model | Hugging Face ID | Checkpoint | Backbone | GPU memory for weights |
| - | - | - | - | - |
| Kev-27B | `jaredpalmer/kev-27b` | full weights | Qwen3.8-27B | 47.8 GB |
| Kev-9B | `jaredpalmer/kev-9b` | LoRA adapter | Qwen3.5-9B-Base | 14.9 GB |
| Kev-4B | `jaredpalmer/kev-4b` | LoRA adapter | Qwen3.5-4B-Base | 8.0 GB |
| Kev-0.8B | `jaredpalmer/kev-0.8b` | LoRA adapter | Qwen3.5-0.8B-Base | 1.5 GB |

For a LoRA adapter, SGLang loads the base revision that the adapter's `head.pt` pins and merges the adapter into its weights at startup, in FP32 with one rounding to BF16, as the reference code merges it. The base is downloaded on first use.

## 1. Model introduction

[Kev](https://huggingface.co/collections/jaredpalmer/kev) is a family of decision models published by Jared Palmer under the Apache-2.0 license, with [reference code](https://github.com/jaredpalmer/kev). Each model keeps a Qwen3.5 or Qwen3.8 backbone and replaces the LM head with a pointer head. Each question runs as its own prompt after the shared state. The head compares the final hidden state at each option's closing token with the one at the prompt's last token and returns one logit per option, with no text generation. A temperature stored in `head.pt` calibrates the probabilities.

Pass a text string, JSON object, or JSON array as the state. `/v1/systemone` returns one answer per question: a `choice` over allowed options, a `noul` probability of true, or a `score` over ordered levels. JSON states are flattened into labeled text as the reference code does.

## 2. Configuration tips

* **Route.** Send requests to `/v1/systemone`, or set your System One client's base URL to the server. This includes TypeSafe SDK clients. See the [API reference](/docs/supported-models/decision_models#system-one-compatible-api) for request and response fields. Kev refuses `/v1/decisions`, chat, generation, and `/encode` requests.
* **One prefill per question.** The model reads the state once for every question, as the reference does, so a request with many questions over a long state costs that many prefills. SGLang enables embedding mode and disables radix caching, chunked prefill, and CUDA graphs. Keep TP=1 and PP=1.
* **Answers.** `probabilities` are the softmax of the head's logits divided by the calibrated temperature. `confidence` uses the System One adapter formulas, as Kev's own server does. SGLang does not round the values to four decimals. Answers omit `x_label_mass` because the head scores only the allowed options.
* **Long states.** The reference server accepts states of up to 65,536 tokens. In SGLang each question's prompt must also fit one prefill, 16,384 tokens by default, so longer prompts are refused with an error that gives both lengths. Raising `--max-prefill-tokens` is not supported for this model yet, because the server does not reserve memory for longer unchunked prefills and can run out of memory under load.
* **Inputs.** Requests are text only, so `images` and `chat_template_kwargs` are refused. A `score` question takes up to 10 levels and a `choice` question up to 255 options.
* **Not supported.** Kev-27B v1, the `v1-lora` revision of `jaredpalmer/kev-27b`, is an adapter trained on a BF16 backbone that the reference applies unmerged, so SGLang refuses it and serves the current full weight release instead. Kev-0.5B is a prototype on a Qwen2.5 base and is refused too.

## 3. Advanced usage

### 3.1 TypeSafe SDK

```bash Command theme={null}
pip install typesafe-sdk
```

> **Text decision example (Python)**
>
> ```python Example theme={null}
> from typesafe_sdk import Choice, Noul, TypeSafeClient
>
> client = TypeSafeClient(api_key="local", base_url="http://localhost:30000", model="kev-latest")
> response = client.system_one(
>     state="I was charged twice for order 1182. Please refund one of the charges.",
>     questions={
>         "team": Choice(
>             instructions="Which team should handle this?",
>             criteria={"billing": "Charges and refunds", "shipping": "Deliveries", "returns": "Exchanges"},
>         ),
>         "urgent": Noul(instructions="Does this need a reply today?"),
>     },
> )
> print(response.choices["team"].choice, response.nouls["urgent"].noul)
> ```

> **Example output**
>
> Captured with Kev-27B on one H200. Probabilities can vary with the model size, hardware, and numerical backend.
>
> ```text Output theme={null}
> billing 0.7591662905989526
> ```


# LFM2.5
Source: https://docs.sglang.io/cookbook/autoregressive/LiquidAI/LFM2.5

Deploy Liquid AI's LFM2.5 with SGLang — hybrid gated short conv + GQA models from 350M to the 8B-A1B MoE, plus LFM2.5-VL vision, with reasoning and Pythonic tool calling.

## Deployment

> **Install SGLang**
>
> For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel.
>
> **Python (pip / uv)**
>
> ```bash Command theme={null}
> pip install --upgrade pip
> pip install uv
> uv pip install --prerelease=allow sglang
> ```
>
> > [!NOTE]
> >
> > LFM2.5 support — the dense / MoE / VL model classes and the `lfm2` tool-call parser — ships on SGLang `main`. If your installed release predates it, install from source or use the Docker dev image.
>
> Then run the **Python** output of the command panel below in that environment.
>
> **Docker**
>
> LFM2.5 support ships in the pinned SGLang dev image:
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev-cu13
> ```
>
> For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). A minimal example (substitute the inner `sglang serve ...` with whatever the command generator below produces):
>
> ```bash Command theme={null}
> docker run --gpus all \
>     --shm-size 32g \
>     -p 30000:30000 \
>     -v ~/.cache/huggingface:/root/.cache/huggingface \
>     --env "HF_TOKEN=" \
>     --ipc=host \
>     lmsysorg/sglang:dev-cu13 \
>     sglang serve 
> ```

Every LFM2.5 model runs on a **single GPU (TP=1)** — pick your hardware + model variant to generate the launch command. One recipe covers all operating points per variant; the commands differ only by the parsers a model needs and, on Blackwell, the attention backend. The `lfm2` tool-call parser and each reasoning model's `--reasoning-parser` are already part of the verified command.

**Panel controls** (top of the command box):

  • **Python / Docker** — bare `sglang serve …` for an existing SGLang env, or a `docker run … sglang serve …` wrap against the dev image from the [Install SGLang](#install) panel above.
  • **⧉ Copy** — copies the current command (with whichever framing is active) to your clipboard.
  • **\$ cURL** — a sample request against `localhost:30000` to confirm the server is up.
  • **⚙ Env** — edits the placeholders (`HOST_IP`, `PORT`, `HF_TOKEN`) the command and cURL share. Persists in localStorage across cookbooks.
  • **Verified / Not Verified** badge — green when the `(hw, variant, quant, strategy, nodes)` combo has been run end-to-end on real hardware; yellow when auto-derived from a neighbor and not yet re-checked.
## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations that have been signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. The base is read live from your Deploy selection — only your overrides change. For LFM2.5 the exposed knob is the **TP override** (every variant is verified at TP=1; TP=2 is available for experimentation on the larger checkpoints). The reasoning and tool-call parsers are not playground toggles here — they are variant-intrinsic and already baked into each verified command. Lines highlighted **green** are added by your overrides; lines with **red strikethrough** were in the verified base but stripped by an override. When no override differs from the base cell, the playground inherits the base's **Verified** badge; any actual change flips it to **Not Verified** until the new configuration is run end-to-end and submitted back. **Panel controls** reuse **Python / Docker** · **⧉ Copy** · **\$ cURL** · **⚙ Env** from the Deploy panel, plus one extra:
  • **Submit ↗** — opens a pre-filled GitHub issue so you can land your override combo as a new verified cookbook cell. Shown only while the badge says **Not Verified**; click it once you've actually run the command on your hardware and confirmed it works.
## 1. Model Introduction LFM2.5 is [Liquid AI](https://www.liquid.ai/)'s family of hybrid models for on-device deployment, released under the [LFM Open License v1.0](https://huggingface.co/LiquidAI/LFM2.5-8B-A1B/blob/main/LICENSE). It builds on the LFM2 architecture with extended pre-training — 10T → 28T tokens for the dense models, 12T → 38T for the 8B-A1B MoE — and large-scale reinforcement learning. The backbone interleaves **gated short convolution blocks** with a small minority of **grouped query attention (GQA) blocks**. Each convolution block applies input-dependent multiplicative gating around a depthwise short convolution, giving fast local mixing at low compute and memory cost. The GQA blocks handle global context and long-range retrieval. This minimal hybrid layout was selected by a hardware-in-the-loop architecture search under edge latency and memory budgets. On CPUs it delivers up to 2× faster prefill and decode than similarly sized models (see the [LFM2 Technical Report](https://arxiv.org/abs/2511.23404)). **Key Features:** * **Hybrid gated short conv + GQA layout**: the 1.2B / 350M dense models are 16 layers (10 conv + 6 GQA); the 8B-A1B MoE is 24 layers (18 conv + 6 GQA). With only 6 attention layers per model, the KV cache stays small even at long context. * **Block details**: depthwise convolutions with kernel size 3; GQA with 8 KV groups and head size 64, plus RoPE and QK-Norm; pre-norm RMSNorm and SwiGLU MLPs throughout. * **Sparse MoE (8B-A1B)**: 8.3B total / 1.5B active parameters. Every layer except the first two replaces its dense MLP with a 32-expert MoE block; each token is routed to the top-4 SwiGLU experts by a normalized sigmoid router with adaptive bias load balancing. * **New in 2.5 (8B-A1B)**: the blocks are unchanged from LFM2-8B-A1B, but the context window grows from 32K to 128K (a RoPE base-θ increase plus long-context midtraining) and the vocabulary doubles from 65,536 to 128,000 tokens for more efficient non-Latin tokenization. * **Pythonic tool calling**: function calls are emitted as a Python list between `<|tool_call_start|>` and `<|tool_call_end|>` tokens. The `lfm2` tool-call parser surfaces these as standard `message.tool_calls`. * **Reasoning variants**: the 8B-A1B and 1.2B-Thinking checkpoints are reasoning-only models that always emit an explicit `...` chain-of-thought before the answer. The MoE's 1.5B active parameters keep those reasoning tokens cheap. * **Multilingual**: every model except the JP checkpoints covers at least English, Arabic, Chinese, French, German, Japanese, Korean, and Spanish (some variants add more). The dedicated JP chat checkpoints focus on Japanese (Japanese + English only). * **Vision**: LFM2.5-VL-1.6B pairs the 1.2B language backbone with a SigLIP2 So400M NaFlex encoder for OCR, document understanding, and multilingual vision. LFM2.5-VL-450M pairs the 350M backbone with a SigLIP2 Base-86M encoder for captioning and object detection at edge sizes; bounding-box grounding and function calling are new in the 2.5 release. **Available Models:**
Model Parameters Context Role
**[LFM2.5-8B-A1B](https://huggingface.co/LiquidAI/LFM2.5-8B-A1B)** 8.3B total / 1.5B active (MoE) 128K Reasoning-tuned, agentic / tool use
**[LFM2.5-1.2B-Instruct](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct)** 1.17B (dense) 32K General instruct, RAG, data extraction
**[LFM2.5-1.2B-Thinking](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Thinking)** 1.17B (dense) 32K Reasoning (always-on chain-of-thought)
**[LFM2.5-350M](https://huggingface.co/LiquidAI/LFM2.5-350M)** 350M (dense) 32K Compact instruct, structured output
**[LFM2.5-230M](https://huggingface.co/LiquidAI/LFM2.5-230M)** 230M (dense) 32K Most compact; data extraction, structured output
**[LFM2.5-1.2B-JP-202606](https://huggingface.co/LiquidAI/LFM2.5-1.2B-JP-202606)** 1.17B (dense) 32K Japanese chat (latest)
[LFM2.5-1.2B-JP](https://huggingface.co/LiquidAI/LFM2.5-1.2B-JP) 1.17B (dense) 32K Japanese chat (original)
**[LFM2.5-VL-1.6B](https://huggingface.co/LiquidAI/LFM2.5-VL-1.6B)** 1.2B LM + SigLIP2 400M 32K Vision-language (OCR, docs, multi-image)
**[LFM2.5-VL-450M](https://huggingface.co/LiquidAI/LFM2.5-VL-450M)** 350M LM + SigLIP2 86M 32K Compact vision-language (captioning, object detection)
[LFM2.5-1.2B-Base](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Base) 1.17B (dense) 32K Pre-trained base (no post-training)
The Deploy panel above covers the eight serving variants; **LFM2.5-1.2B-JP** (original — launch without `--tool-call-parser`) and the **Base** repos (pre-trained only, no post-training — see [§3.5](#3-5-base-checkpoints)) launch the same way with the model path swapped. **Choosing a variant:** * **8B-A1B** — flagship for agentic and tool-calling workloads; the only 128K-context option. * **1.2B-Thinking** — reasoning-heavy tasks: math, tool use, programming. * **1.2B-Instruct** — the recommended pick for chat and creative writing. * **350M** — tool use, data extraction, and structured output; not recommended for math, code, or creative writing. * **230M** — the most compact checkpoint; same use as the 350M, not for math, code, or creative writing. **License:** [LFM Open License v1.0](https://huggingface.co/LiquidAI/LFM2.5-8B-A1B/blob/main/LICENSE). **Resources:** [LFM2.5 announcement](https://www.liquid.ai/blog/introducing-lfm2-5-the-next-generation-of-on-device-ai), [LFM2.5-8B-A1B blog](https://www.liquid.ai/blog/lfm2-5-8b-a1b), [LFM docs](https://docs.liquid.ai/lfm/getting-started/welcome), [LFM2 Technical Report (arXiv:2511.23404)](https://arxiv.org/abs/2511.23404). ## 2. Configuration Tips * **Reasoning parser**: LFM2.5 reasoning models wrap their chain-of-thought in `...` tags. The command generator passes `--reasoning-parser qwen3` for **8B-A1B** (it emits an explicit opening ``) and `--reasoning-parser qwen3-thinking` for **1.2B-Thinking** (always-on reasoning). This splits the thinking process into `reasoning_content`; without it the chain-of-thought stays inline in `content`. * **Tool calling**: `--tool-call-parser lfm2` surfaces LFM2.5's Pythonic `<|tool_call_start|>[...]<|tool_call_end|>` calls as standard `message.tool_calls`. The original **1.2B-JP** does not expose tool calling; **Base** has no post-training (see [§3.5](#3-5-base-checkpoints)). * **Attention backend on Blackwell (B200/sm100)**: SGLang defaults to the `trtllm_mha` backend on sm100, which is fastest for the dense text models. The **8B-A1B** uses a mamba-style state cache that runs on a page-size-1 backend, so the generator picks `--attention-backend flashinfer` for it. The **VL** language model also uses that state cache and offers two backends: `--attention-backend flashinfer` (keeps prefix/radix caching — what the generator emits), or `--attention-backend trtllm_mha --disable-radix-cache` to run the language model on Blackwell `trtllm_mha` attention (`--disable-radix-cache` lifts the page-size-1 requirement, at the cost of prefix caching). Pair either with `--mm-attention-backend fa4` for the vision tower. * **VL vision tower (`--mm-attention-backend`)**: on sm100 the `trtllm_mha` default is fastest for text but applies *causal* attention to image tokens. For the VL model, pass `--mm-attention-backend fa4` on B200/B300 (or `fa3` on H100/H200) to restore bidirectional image-token attention and full vision quality. * **VL multimodal feature transport**: the generator launches the VL models with `SGLANG_USE_CUDA_IPC_TRANSPORT=1 SGLANG_USE_IPC_POOL_HANDLE_CACHE=1`. The first moves the processor→scheduler image-feature handoff onto CUDA IPC instead of serializing tensors between processes; the second ships the pool handle so the scheduler opens it once and caches it, instead of opening a per-item handle on every request. On the image serving workload (1 image @ 720p, measured on VL-1.6B on H100 and B200) this pair is worth roughly 30–50% higher image throughput and 30–40% lower image TTFT vs running without them (measured on VL-1.6B, H100 and B200); decode speed (TPOT) is unaffected. * **VL-450M memory headroom (`--mem-fraction-static 0.8`)**: with the default memory fraction, the 450M's small weights make SGLang size its static KV/mamba pools to nearly the whole GPU, leaving no headroom for image-feature tensors — under sustained concurrent image load the scheduler can crash with a CUDA OOM in the radix-cache free path. The generator caps `--mem-fraction-static 0.8` for VL-450M; the pool is still far larger than this model ever needs. * **Mamba scheduling**: LFM2.5 runs on the default `no_buffer` mamba scheduler strategy — no `--mamba-radix-cache-strategy` flag is needed. The `extra_buffer` strategy (an overlap-scheduling throughput optimization available for some Gated-DeltaNet hybrids) does not apply to LFM2.5, whose convolution blocks use `mamba_chunk_size=1`. * **Hardware requirements**: all LFM2.5 models run on a single GPU (TP=1) on either Hopper or Blackwell. The 1.2B / 350M dense models fit in a few GB; the 8B-A1B MoE needs roughly 16 GB for bf16 weights plus KV cache. Multi-GPU tensor parallelism is not required for any variant. **Recommended sampling parameters** — pass these explicitly on every request. Some LFM2.5 checkpoints do not ship sampling defaults in `generation_config.json`, so the server will not apply them for you. `top_k`, `min_p`, and `repetition_penalty` are not standard OpenAI `chat.completions` fields — pass them through **`extra_body`** and SGLang forwards them to its sampler. Do not set `max_tokens` unless you intend to cap output, as it can truncate a response (or a reasoning model's chain-of-thought) mid-stream.
Model temperature extra\_body (sampler)
LFM2.5-8B-A1B0.2`{"top_k": 80, "repetition_penalty": 1.05}`
LFM2.5-1.2B-Instruct0.1`{"top_k": 50, "repetition_penalty": 1.05}`
LFM2.5-1.2B-Thinking0.05`{"top_k": 50, "repetition_penalty": 1.05}`
LFM2.5-350M0.1`{"top_k": 50, "repetition_penalty": 1.05}`
LFM2.5-230M0.1`{"top_k": 50, "repetition_penalty": 1.05}`
LFM2.5-1.2B-JP-2026060.1`{"top_k": 50, "repetition_penalty": 1.05}`
LFM2.5-1.2B-JP0.3`{"min_p": 0.15, "repetition_penalty": 1.05}`
LFM2.5-VL-1.6B (text)0.1`{"min_p": 0.15, "repetition_penalty": 1.05}`
LFM2.5-VL-450M (text)0.1`{"min_p": 0.15, "repetition_penalty": 1.05}`
LFM2.5-1.2B-Base0.3`{"min_p": 0.15, "repetition_penalty": 1.05}`
## 3. Advanced Usage ### 3.1 Basic Usage A single client with the recommended sampling presets applied per model (the examples in the following sections reuse this `chat` helper): ```python Example theme={null} from openai import OpenAI client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") # Non-OpenAI fields (top_k / min_p / repetition_penalty) ride in extra_body. SAMPLING = { "LiquidAI/LFM2.5-8B-A1B": dict(temperature=0.2, extra_body={"top_k": 80, "repetition_penalty": 1.05}), "LiquidAI/LFM2.5-1.2B-Instruct": dict(temperature=0.1, extra_body={"top_k": 50, "repetition_penalty": 1.05}), "LiquidAI/LFM2.5-1.2B-Thinking": dict(temperature=0.05, extra_body={"top_k": 50, "repetition_penalty": 1.05}), "LiquidAI/LFM2.5-350M": dict(temperature=0.1, extra_body={"top_k": 50, "repetition_penalty": 1.05}), "LiquidAI/LFM2.5-230M": dict(temperature=0.1, extra_body={"top_k": 50, "repetition_penalty": 1.05}), "LiquidAI/LFM2.5-1.2B-JP-202606": dict(temperature=0.1, extra_body={"top_k": 50, "repetition_penalty": 1.05}), "LiquidAI/LFM2.5-VL-1.6B": dict(temperature=0.1, extra_body={"min_p": 0.15, "repetition_penalty": 1.05}), "LiquidAI/LFM2.5-VL-450M": dict(temperature=0.1, extra_body={"min_p": 0.15, "repetition_penalty": 1.05}), } def chat(model, messages, **overrides): cfg = SAMPLING[model] body = cfg["extra_body"] | overrides.pop("extra_body", {}) return client.chat.completions.create( model=model, messages=messages, temperature=cfg["temperature"], extra_body=body, **overrides, ) resp = chat( "LiquidAI/LFM2.5-1.2B-Instruct", [{"role": "user", "content": "What is C. elegans? Answer in one sentence."}], ) print(resp.choices[0].message.content) ``` ### 3.2 Reasoning The 8B-A1B and 1.2B-Thinking checkpoints emit chain-of-thought as a built-in behavior. The Deploy panel launches them with the matching `--reasoning-parser`, which separates the thinking process into `reasoning_content`: ```python Example theme={null} resp = chat( "LiquidAI/LFM2.5-8B-A1B", [{"role": "user", "content": "If a train travels 60 km/h for 2.5 hours, how far does it go?"}], ) msg = resp.choices[0].message print("Reasoning:", msg.reasoning_content) print("Answer:", msg.content) ``` ### 3.3 Tool Calling LFM2.5 writes Pythonic tool calls. With `--tool-call-parser lfm2` (already part of the launch command) they are surfaced as standard `message.tool_calls`: ```python Example theme={null} resp = chat( "LiquidAI/LFM2.5-1.2B-Instruct", [{"role": "user", "content": "What's the weather in Paris?"}], tools=[{ "type": "function", "function": { "name": "get_weather", "description": "Get current weather for a location", "parameters": { "type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"], }, }, }], ) for call in resp.choices[0].message.tool_calls or []: print(call.function.name, call.function.arguments) ``` Tool calling is supported on 8B-A1B, 1.2B-Thinking, 1.2B-Instruct, 350M, 230M, 1.2B-JP-202606, VL-1.6B, and VL-450M. For the **VL** models it is text-turn-only — do not combine an image and tools in the same turn. ### 3.4 Vision Input The VL models (VL-1.6B and VL-450M) accept images via standard OpenAI multimodal content blocks. Base64 data URIs (`data:image/jpeg;base64,...`) work in place of a URL: ```python Example theme={null} resp = chat( "LiquidAI/LFM2.5-VL-1.6B", [{ "role": "user", "content": [ {"type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"}}, {"type": "text", "text": "What is in this image?"}, ], }], ) print(resp.choices[0].message.content) ``` ### 3.5 Base Checkpoints Each size ships a pre-trained Base repo — [LFM2.5-230M-Base](https://huggingface.co/LiquidAI/LFM2.5-230M-Base), [LFM2.5-1.2B-Base](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Base), [LFM2.5-350M-Base](https://huggingface.co/LiquidAI/LFM2.5-350M-Base), and [LFM2.5-8B-A1B-Base](https://huggingface.co/LiquidAI/LFM2.5-8B-A1B-Base) — intended for fine-tuning and continued pre-training. The repos ship a ChatML-style chat template, so `chat.completions` requests format normally. The checkpoints have no post-training, though — don't expect instruction following. For raw text continuation: ```python Example theme={null} comp = client.completions.create( model="LiquidAI/LFM2.5-1.2B-Base", prompt="The capital of France is", temperature=0.3, extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, ) print(comp.choices[0].text) ``` # LongCat-2.0 Source: https://docs.sglang.io/cookbook/autoregressive/Meituan/LongCat-2.0 Deploy LongCat-2.0-FP8 with SGLang - config-driven recipes for Meituan's 1.6T sparse MoE model on B300, B200, H200, and H20 GPUs. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). LongCat-2.0 support is on SGLang `main`; use a nightly wheel or rolling nightly Docker image until the next tagged release includes it. The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > > # Choose the nightly wheel index for your CUDA runtime. > SGLANG_WHL_INDEX=https://docs.sglang.ai/whl/cu130 # B300 / CUDA 13 > # SGLANG_WHL_INDEX=https://docs.sglang.ai/whl/cu129 # CUDA 12.9 > > uv pip install --prerelease=allow --extra-index-url "${SGLANG_WHL_INDEX}" "sglang[all]" > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > # Choose the rolling nightly image for your hardware. > SGLANG_DOCKER_IMAGE=lmsysorg/sglang:dev-cu13 # B300 / CUDA 13 > # SGLANG_DOCKER_IMAGE=lmsysorg/sglang:dev # Other supported hardware > > docker pull "${SGLANG_DOCKER_IMAGE}" > ``` > > For how to launch the image, see [Install -> Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your hardware + recipe to generate the launch command. LongCat-2.0 currently exposes one model-card-aligned serving strategy: * **Balanced** - the validated B300 recipe and the 2-node H200/B200/H20 topology use TP/EP parallelism with LongCat sparse attention prefill. > [!WARNING] > > All recipes here run the LongCat sparse-attention indexer top-k on the default `--dsa-topk-backend sgl-kernel`. Other top-k backend choices have not been fully validated on LongCat-2.0. > [!NOTE] > > The B300 single-node recipe was validated end-to-end with CUDA graph capture enabled. H200, B200, and H20 are shown as 2-node recipes because LongCat-2.0-FP8 needs 16 ranks for those GPU memory profiles. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction [LongCat-2.0-FP8](https://huggingface.co/meituan-longcat/LongCat-2.0-FP8) is the FP8 checkpoint of Meituan LongCat-2.0, a large sparse Mixture-of-Experts language model with 1.6T total parameters and about 48B activated parameters per token. It combines LongCat Sparse Attention (LSA), expert parallel MoE layers, and an n-gram/token-table embedding path for serving long-context workloads efficiently.
Model Architecture Serving precision
**[LongCat-2.0-FP8](https://huggingface.co/meituan-longcat/LongCat-2.0-FP8)** Sparse MoE · LongCat Sparse Attention · n-gram embedding FP8 weights, BF16 KV cache
**Resources:** [LongCat-2.0-FP8](https://huggingface.co/meituan-longcat/LongCat-2.0-FP8). ## 2. Configuration Tips * **Remote code.** Use `--trust-remote-code` for the Hugging Face checkpoint. * **Topology.** The 8x B300 recipe uses TP=8 and EP=8. H200, B200, and H20 use a 2-node 16 GPU layout with TP=16 and EP=16; the command panel injects the multi-node rank flags for you. * **LongCat sparse attention.** Keep `--dsa-prefill-backend fa3` with `--chunked-prefill-size 2048` for the model-card-aligned prefill path. * **Memory.** The recipe uses `--kv-cache-dtype bfloat16` and starts at `--mem-fraction-static 0.92`. Tune memory only after the generated command launches cleanly on your cluster. * **Weight loading.** `--model-loader-extra-config '{"enable_multithread_load":true,"num_threads":12}'` loads checkpoint shards in parallel and reduces startup time. * **FP8 backend selection.** Do not pass `--fp8-gemm-runner-backend` manually. SGLang selects the correct backend for the LongCat FP8 scale layout. * **Host, port, and ranks.** Use the command panel environment fields for `HOST_IP`, `PORT`, `NODE0_IP`, and `NODE_RANK` instead of hardcoding them in the recipe. ## 3. Advanced Usage ### 3.1 Test the deployment > **Chat completion example (cURL)** > > ```bash Command theme={null} > curl http://localhost:30000/v1/chat/completions \ > -H "Content-Type: application/json" \ > -d '{ > "model": "meituan-longcat/LongCat-2.0-FP8", > "messages": [ > {"role": "user", "content": "A shop has 17 apples and sells 8. Then it buys 6 more. How many apples are there? Answer with only the final number."} > ], > "max_tokens": 32, > "chat_template_kwargs": {"enable_thinking": false} > }' > ``` > **Expected output** > > ```text Output theme={null} > 15 > ``` > **OpenAI-compatible client (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI( > base_url="http://localhost:30000/v1", > api_key="EMPTY", > ) > > response = client.chat.completions.create( > model="meituan-longcat/LongCat-2.0-FP8", > messages=[ > { > "role": "user", > "content": "Solve: A shop has 17 apples and sells 8, then buys 6 more. Answer with only the final number.", > } > ], > max_tokens=32, > extra_body={"chat_template_kwargs": {"enable_thinking": False}}, > ) > > print(response.choices[0].message.content) > ``` > **Example output** > > ```text Output theme={null} > 15 > ``` ## 4. Validation The B300 recipe was validated with `meituan-longcat/LongCat-2.0-FP8` on 8x B300 using the command generated above.
Evaluation Examples Accuracy
GSM8K 200 98.0%
GSM8K 1314 95.8904109589041%
CUDA graph was enabled, and decode CUDA graph capture completed successfully during serving validation. # Llama-3.1 Source: https://docs.sglang.io/cookbook/autoregressive/Meta/Llama3.1 ## 1. Model Introduction Llama 3.1 is a collection of pretrained and instruction tuned generative models, released in July 2024 by Meta. These models are available in 8B, 70B and 405B sizes, with the 405B variant being the most capable fully-open source model at the time. These models bring open intelligence to all, with several new features and improvements: * **Stronger General Intelligence**: These models showcase significant improvements in coding, state-of-the-art tool use, and overall stronger reasoning capabilities. * **Extended Context Length**: Llama 3.1 extends the context length to 128K tokens to improve performance over long context tasks such as summarization and code reasoning. * **Tool Use**: Llama 3.1 is trained to interact with a search engine, python interpreter and mathematical engine, and also improves zero-shot tool use capabilities to interact with potentially unseen tools. * **Multilinguality**: Llama 3.1 supports 7 languages in addition to English: French, German, Hindi, Italian, Portuguese, Spanish, and Thai. For further details, please refer to the [Llama 3.1 blog](https://ai.meta.com/blog/meta-llama-3-1/) and the [Llama 3.1 model card](https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/MODEL_CARD.md).note ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms including NVIDIA GPUs, AMD GPUs, Intel Arc Pro B-Series GPUs(codename: BMG (Battlemage)), and Intel Xeon CPUs. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to generate a launch command for Llama 3.1 collection of models. Run this Command:

### 3.2 Configuration Tips

**Speculative Decoding (NVIDIA GPUs):**

* Using Speculative Decoding for latency-sensitive scenarios:
  * `--speculative-algorithm EAGLE3`: Speculative decoding algorithm
  * `--speculative-num-steps 3`: Number of speculative verification rounds
  * `--speculative-eagle-topk 1`: Top-k sampling for draft tokens
  * `--speculative-num-draft-tokens 4`: Number of draft tokens per step
  * `--speculative-draft-model-path`: The path of the draft model weights. This can be a local folder or a Hugging Face repo ID such as [`yuhuili/EAGLE3-LLaMA3.1-Instruct-8B`](https://huggingface.co/yuhuili/EAGLE3-LLaMA3.1-Instruct-8B).

**AMD GPU Deployment:**

* **Hardware-Aware TP**: MI355X (256GB memory) supports lower TP values compared to MI300X/MI325X (192GB)
* **Verified TP Configurations**:
  * MI300X/MI325X: 405B BF16 (TP=8), 405B FP8 (TP=4), 70B/8B (TP=1)
  * MI355X: 405B BF16 (TP=4), 405B FP8 (TP=2), 70B/8B (TP=1)
* **FP8 Model Variants**:
  * 405B: Use Meta's official `meta-llama/Llama-3.1-405B-Instruct-FP8`
  * 70B/8B: Use AMD's optimized `amd/Llama-3.1-{size}-Instruct-FP8-KV`
* **Tool Calling**: Enable with `--tool-call-parser llama3` for Instruct models

**Xeon CPU Deployment:**

* Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4. Model Invocation

### 4.1 Basic Usage

SGLang exposes an OpenAI-compatible endpoint. First, start the server

```shell Command theme={null}
sglang serve \
  --model-path  Meta-Llama/Llama-3.1-405B-Instruct \
  --tp 8
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY",
)

resp = client.chat.completions.create(
    model="Meta-Llama/Llama-3.1-405B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful coding assistant."},
        {"role": "user", "content": "Write a Python function that retries a request with exponential backoff."},
    ],
    temperature=0.2,
    max_tokens=512,
)

print(resp.choices[0].message.content)
```

**Output Example:**

````text Output theme={null}
**Exponential Backoff Retry Function in Python**
=====================================================

Below is a Python function that uses the `requests` library to retry a request with exponential backoff.

```python
import requests
import time
import random

def exponential_backoff_retry(url, method, retries=3, backoff_factor=1, max_delay=60):
    """
    Retry a request with exponential backoff.

    Args:
        url (str): The URL to make the request to.
        method (str): The HTTP method to use (e.g. 'GET', 'POST', etc.).
        retries (int): The number of retries to attempt. Defaults to 3.
        backoff_factor (int): The factor to multiply the delay by for each retry. Defaults to 1.
        max_delay (int): The maximum delay to wait between retries in seconds. Defaults to 60.

    Returns:
        The response object from the successful request.
    """

    delay = 1
    for attempt in range(retries + 1):
        try:
            response = requests.request(method, url)
            response.raise_for_status()  # Raise an exception for HTTP errors
            return response
        except requests.RequestException as e:
            if attempt < retries:
                # Calculate the delay for this retry
                delay = min(delay * backoff_factor, max_delay)
                # Add a random jitter to the delay to prevent thundering herd problem
                delay += random.uniform(0, delay * 0.1)
                # Wait for the calculated delay before retrying
                time.sleep(delay)
            else:
                # If all retries have failed, raise the exception
                raise e
...
````

### 4.2 Advanced Usage

#### 4.2.1 Tool Calling

Llama3 supports tool calling capabilities. First, start the server with tool call parser enabled:

```shell Command theme={null}
sglang serve \
  --model-path  Meta-Llama/Llama-3.1-405B-Instruct \
  --tool-call-parser llama3 \
  --tp 8
```

**Python Example**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(api_key="None", base_url=f"http://0.0.0.0:8000/v1")

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "The city to find the weather for, e.g. 'San Francisco'",
                    },
                    "unit": {
                        "type": "string",
                        "description": "The unit to fetch the temperature in",
                        "enum": ["celsius", "fahrenheit"],
                    },
                },
                "required": ["city", "unit"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="meta-llama/Llama-3.1-405B-Instruct",
    messages=[
        {
            "role": "user",
            "content": "What's the weather like in Boston today?",
        }
    ],
    temperature=0.7,
    stream=True,
    tools=tools,
)


arguments = []

tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"🔧 Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

Reference: [SGLang Tool Parser Documentation](../../../docs/advanced_features/tool_parser#openai-compatible-api)

**Output Example**

```text Output theme={null}
🔧 Tool Call: get_weather
   Arguments: {"city": "Boston", "unit": "fahrenheit"}
```

**Handling Tool Call Results**
After getting the tool call, you can execute the function:

```python Example theme={null}
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather like in Boston today?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Boston", "unit": "fahrenheit"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Boston", "fahrenheit")
    }
]

final_response = client.chat.completions.create(
    model="Meta-Llama/Llama-3.1-405B-Instruct",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The current weather in Boston is **22°C** and **sunny**. A perfect day to spend outside"
```

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA A100 GPU (8x)
* Model: Meta-Llama/Llama-3.1-70B
* Tensor Parallelism: 8
* sglang version: 0.5.6

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios.

#### 5.1.1 Standard Scenario Benchmark

* Model Deployment Command:

```shell Command theme={null}
sglang serve \
  --model-path Meta-Llama/Llama-3.1-70B \
  --tp 8
```

##### 5.1.1.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
sglang serve \
  --backend sglang \
  --model Meta-Llama/Llama-3.1-70B \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  79.81
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4208
Request throughput (req/s):              0.13
Input token throughput (tok/s):          76.44
Output token throughput (tok/s):         52.88
Peak output token throughput (tok/s):    54.00
Peak concurrent requests:                2
Total token throughput (tok/s):          129.32
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   7977.81
Median E2E Latency (ms):                 6373.48
---------------Time to First Token----------------
Mean TTFT (ms):                          131.61
Median TTFT (ms):                        131.77
P99 TTFT (ms):                           163.88
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          18.63
Median TPOT (ms):                        18.63
P99 TPOT (ms):                           18.65
---------------Inter-Token Latency----------------
Mean ITL (ms):                           18.64
Median ITL (ms):                         18.64
P95 ITL (ms):                            18.69
P99 ITL (ms):                            18.74
Max ITL (ms):                            21.95
==================================================
```

##### 5.1.1.2 Medium Concurrency

```shell Command theme={null}
sglang serve \
  --backend sglang \
  --model-path Meta-Llama/Llama-3.1-70B \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  79.47
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    38450
Request throughput (req/s):              1.01
Input token throughput (tok/s):          499.17
Output token throughput (tok/s):         513.48
Peak output token throughput (tok/s):    674.00
Peak concurrent requests:                20
Total token throughput (tok/s):          1012.65
Concurrency:                             13.47
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   13376.67
Median E2E Latency (ms):                 14130.48
---------------Time to First Token----------------
Mean TTFT (ms):                          264.84
Median TTFT (ms):                        147.02
P99 TTFT (ms):                           791.93
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          26.09
Median TPOT (ms):                        26.08
P99 TPOT (ms):                           34.65
---------------Inter-Token Latency----------------
Mean ITL (ms):                           25.76
Median ITL (ms):                         23.95
P95 ITL (ms):                            24.72
P99 ITL (ms):                            98.32
Max ITL (ms):                            478.92
==================================================
```

##### 5.1.1.3 High Concurrency

```shell Command theme={null}
sglang serve \
  --backend sglang \
  --model-path Meta-Llama/Llama-3.1-70B \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  131.64
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    243641
Request throughput (req/s):              3.80
Input token throughput (tok/s):          1897.87
Output token throughput (tok/s):         1919.38
Peak output token throughput (tok/s):    3100.00
Peak concurrent requests:                107
Total token throughput (tok/s):          3817.25
Concurrency:                             89.70
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   23616.71
Median E2E Latency (ms):                 22770.44
---------------Time to First Token----------------
Mean TTFT (ms):                          245.98
Median TTFT (ms):                        184.22
P99 TTFT (ms):                           1251.67
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          47.19
Median TPOT (ms):                        48.67
P99 TPOT (ms):                           56.37
---------------Inter-Token Latency----------------
Mean ITL (ms):                           46.34
Median ITL (ms):                         33.46
P95 ITL (ms):                            108.61
P99 ITL (ms):                            166.11
Max ITL (ms):                            1107.09
==================================================
```

#### 5.1.2 Summarization Scenario Benchmark

##### 5.1.2.1 Low Concurrency

```shell Command theme={null}
sglang serve \
  --backend sglang \
  --model-path Meta-Llama/Llama-3.1-70B\
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  83.25
Total input tokens:                      41941
Total input text tokens:                 41941
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4220
Request throughput (req/s):              0.12
Input token throughput (tok/s):          503.77
Output token throughput (tok/s):         50.69
Peak output token throughput (tok/s):    54.00
Peak concurrent requests:                2
Total token throughput (tok/s):          554.46
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   8322.45
Median E2E Latency (ms):                 6873.36
---------------Time to First Token----------------
Mean TTFT (ms):                          395.25
Median TTFT (ms):                        318.02
P99 TTFT (ms):                           850.80
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          18.80
Median TPOT (ms):                        18.81
P99 TPOT (ms):                           19.03
---------------Inter-Token Latency----------------
Mean ITL (ms):                           18.83
Median ITL (ms):                         18.81
P95 ITL (ms):                            19.06
P99 ITL (ms):                            19.08
Max ITL (ms):                            23.08
==================================================
```

##### 5.1.2.2 Medium Concurrency

```shell Command theme={null}
sglang serve \
  --backend sglang \
  --model-path Meta-Llama/Llama-3.1-70B \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  107.12
Total input tokens:                      300020
Total input text tokens:                 300020
Total input vision tokens:               0
Total generated tokens:                  41669
Total generated tokens (retokenized):    41603
Request throughput (req/s):              0.75
Input token throughput (tok/s):          2800.81
Output token throughput (tok/s):         389.00
Peak output token throughput (tok/s):    624.00
Peak concurrent requests:                19
Total token throughput (tok/s):          3189.81
Concurrency:                             14.18
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   18988.30
Median E2E Latency (ms):                 20290.66
---------------Time to First Token----------------
Mean TTFT (ms):                          603.42
Median TTFT (ms):                        531.82
P99 TTFT (ms):                           2607.95
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          36.94
Median TPOT (ms):                        36.73
P99 TPOT (ms):                           79.19
---------------Inter-Token Latency----------------
Mean ITL (ms):                           35.36
Median ITL (ms):                         25.72
P95 ITL (ms):                            27.07
P99 ITL (ms):                            439.74
Max ITL (ms):                            2529.51
==================================================
```

##### 5.1.2.3 High Concurrency

```shell Command theme={null}
sglang serve \
  --backend sglang \
  --model-path Meta-Llama/Llama-3.1-70B \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 320 \
  --max-concurrency 64
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  215.66
Total input tokens:                      1273893
Total input text tokens:                 1273893
Total input vision tokens:               0
Total generated tokens:                  170000
Total generated tokens (retokenized):    169035
Request throughput (req/s):              1.48
Input token throughput (tok/s):          5906.92
Output token throughput (tok/s):         788.27
Peak output token throughput (tok/s):    1920.00
Peak concurrent requests:                69
Total token throughput (tok/s):          6695.19
Concurrency:                             60.01
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   40443.85
Median E2E Latency (ms):                 39813.12
---------------Time to First Token----------------
Mean TTFT (ms):                          633.32
Median TTFT (ms):                        616.38
P99 TTFT (ms):                           1912.97
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          74.95
Median TPOT (ms):                        82.85
P99 TPOT (ms):                           118.46
---------------Inter-Token Latency----------------
Mean ITL (ms):                           75.08
Median ITL (ms):                         34.12
P95 ITL (ms):                            261.18
P99 ITL (ms):                            828.12
Max ITL (ms):                            1970.03
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* **Results**:

```text Output theme={null}
Accuracy: 0.830
Invalid: 0.000
Latency: 11.794 s
Output throughput: 1406.961 token/s
```


# Llama-3.3-70B
Source: https://docs.sglang.io/cookbook/autoregressive/Meta/Llama3.3-70B



## 1. Model Introduction

[Llama-3.3-70B-Instruct](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct) is Meta's latest 70 billion parameter instruction-tuned language model, featuring improved performance and efficiency over Llama 3.1. With a 128K token context window and enhanced capabilities across reasoning, coding, and multilingual tasks, Llama 3.3 delivers state-of-the-art results while maintaining accessibility for production deployment.

**Key Features:**

* **Enhanced Performance**: Improved instruction following, reasoning, and task completion over Llama 3.1
* **Tool Calling**: Native support for function calling and tool use scenarios
* **Multilingual Support**: Optimized for 8 languages (English, German, French, Italian, Portuguese, Hindi, Spanish, and Thai)
* **Extended Context**: 128K token context window for processing long documents and complex tasks
* **Efficient Deployment**: 70B parameters enable deployment on single GPU with AMD MI300X

**License:**
Llama 3.3 is licensed under the Llama 3.3 Community License. See [LICENSE](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct/blob/main/LICENSE) for details.

For more details, please refer to the [official Llama models repository](https://github.com/meta-llama/llama-models).

## 2. SGLang Installation

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for AMD GPUs (MI300X, MI325X, MI355X), Intel Arc Pro B-Series GPUs(codename: BMG (Battlemage)) and Intel Xeon CPUs.

### 3.1 Interactive Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your AMD GPU, Intel Arc Pro B-Series GPUs or Intel Xeon CPUs setup.

Run this Command:


### 3.2 Configuration Tips

**AMD GPU Deployment:**

* All AMD GPUs (MI300X, MI325X, MI355X) support TP=1 for both BF16 and FP8 variants
* **FP8 Model Variant**: Use AMD's optimized `amd/Llama-3.3-70B-Instruct-FP8-KV`
* **Tool Calling**: Enable with `--tool-call-parser llama3` for function calling support
* **Higher Throughput**: Optional TP=2 or TP=4 can be used for increased throughput

**Xeon CPU Deployment:**

Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Tool Calling

Llama 3.3 70B Instruct supports native tool calling. Enable the tool parser during deployment:

```shell Command theme={null}
python -m sglang.launch_server \
  --model-path meta-llama/Llama-3.3-70B-Instruct \
  --tool-call-parser llama3 \
  --tp 1 \
  --host 0.0.0.0 \
  --port 30000
```

**Python Example:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request
response = client.chat.completions.create(
    model="meta-llama/Llama-3.3-70B-Instruct",
    messages=[
        {"role": "user", "content": "What's the weather in Tokyo?"}
    ],
    tools=tools,
    temperature=0.7
)

# Check for tool calls
message = response.choices[0].message
if message.tool_calls:
    tool_call = message.tool_calls[0]
    print(f"Function: {tool_call.function.name}")
    print(f"Arguments: {tool_call.function.arguments}")
```

**Handling Tool Call Results:**

```python Example theme={null}
# After executing the function, send the result back
def get_weather(location, unit="celsius"):
    # Your weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Build conversation with tool result
messages = [
    {"role": "user", "content": "What's the weather in Tokyo?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Tokyo", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Tokyo", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="meta-llama/Llama-3.3-70B-Instruct",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The current weather in Tokyo is 22°C and sunny. A perfect day!"
```

#### 4.2.2 Long Context Processing

Leverage the 128K context window for processing long documents:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Example with long document
long_document = "..." * 10000  # Your long document here

response = client.chat.completions.create(
    model="meta-llama/Llama-3.3-70B-Instruct",
    messages=[
        {"role": "user", "content": f"Summarize this document:\n\n{long_document}"}
    ],
    temperature=0.7,
    max_tokens=1000
)

print(response.choices[0].message.content)
```

## 5. Benchmarking

Use the SGLang benchmarking suite to test model performance with different workload patterns:

### 5.1 Basic Benchmark Command

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --dataset-name random \
  --num-prompts 1000 \
  --random-input 1024 \
  --random-output 1024 \
  --max-concurrency 16
```

### 5.2 Adjusting Benchmark Parameters

**Input/Output Length**: Adjust `--random-input` and `--random-output` to test different workload patterns:

* Short conversations: `--random-input 1024 --random-output 1024`
* Long outputs: `--random-input 1024 --random-output 8192`
* Long inputs: `--random-input 8192 --random-output 1024`

**Concurrency Levels**: Adjust `--max-concurrency` to test different load scenarios:

* Low concurrency (latency-focused): `--max-concurrency 1 --num-prompts 100`
* Medium concurrency (balanced): `--max-concurrency 16 --num-prompts 1000`
* High concurrency (throughput-focused): `--max-concurrency 100 --num-prompts 2000`

***

## 📚 Additional Resources

* [Meta Llama Models Repository](https://github.com/meta-llama/llama-models)
* [Llama 3.3 Model Card](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct)
* [SGLang Documentation](/)
* [AMD ROCm Documentation](https://rocm.docs.amd.com/)


# Llama 4
Source: https://docs.sglang.io/cookbook/autoregressive/Meta/Llama4



## 1. Model Introduction

[Llama 4](https://github.com/meta-llama/llama-models/blob/main/models/llama4/MODEL_CARD.md) is Meta's latest generation of open-source LLM model with industry-leading performance.

SGLang has supported Llama 4 Scout (109B) and Llama 4 Maverick (400B) since [v0.4.5](https://github.com/sgl-project/sglang/releases/tag/v0.4.5).

Ongoing optimizations are tracked in the [Roadmap](https://github.com/sgl-project/sglang/issues/5118).

This generation delivers comprehensive upgrades across the board:

The highly capable Llama 4 Maverick with 17B active parameters out of \~400B total, with 128 experts.
The efficient Llama 4 Scout also has 17B active parameters out of \~109B total, using just 16 experts.
Both models leverage early fusion for native multimodality, enabling them to process text and image inputs. Maverick and Scout are both trained on up to 40 trillion tokens on data encompassing 200 languages (with specific fine-tuning support for 12 languages including Arabic, Spanish, German, and Hindi).

For more details, please refer to the official llama4 Repository:[https://www.llama.com/models/llama-4/](https://www.llama.com/models/llama-4/)

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

For SGLang CPU installation, please refer to the [CPU version installation guide](../../../docs/hardware-platforms/cpu_server#installation).

## 3. Model Deployment

This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and thinking capabilities.

Run this Command:


Run this Command:


### 3.2 Configuration Tips

* **OOM Mitigation:** Reduce `--context-length` to avoid GPU out-of-memory. Recommended: Scout up to 1M on 8×H100, up to 2.5M on 8×H200; Maverick doesn't need context-length set on 8×H200. With hybrid KV cache enabled, Scout can reach 5M on 8×H100 and 10M on 8×H200.
* **Attention Backend Auto-Selection:** SGLang automatically picks the optimal backend. Manual override with `--attention-backend`:
  * Blackwell (B200/GB200): `trtllm_mha`
  * Hopper (H100/H200): `fa3`
  * AMD GPUs: `aiter`
  * Intel XPU: `intel_xpu`
  * Other: `triton`
* **Chat Template:** Add `--chat-template llama-4` for chat completion tasks.
* **Multi-Modal:** Add `--enable-multimodal` to enable image input support.
* **Hybrid KV Cache:** Set `--swa-full-tokens-ratio` to control the ratio of SWA (local attention) KV tokens to full-attention KV tokens (default: 0.8, range: 0–1).
* **EAGLE Speculative Decoding:** Supported for Llama 4 Scout and Maverick via EAGLE3. Enable with the interactive command generator above.
* **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Launch the docker

```shell Command theme={null}
docker pull lmsysorg/sglang:v0.5.9-rocm720-mi30x
```

```shell Command theme={null}
docker run -d -it --ipc=host --network=host --privileged \
  --cap-add=CAP_SYS_ADMIN \
  --device=/dev/kfd --device=/dev/dri --device=/dev/mem \
  --group-add video --cap-add=SYS_PTRACE \
  --security-opt seccomp=unconfined \
  -v /:/work \
  -e SHELL=/bin/bash \
  --name Llama4 \
  lmsysorg/sglang:v0.5.9-rocm720-mi30x \
  /bin/bash
```

#### 4.2.2 Launch the server

### Llama-4-Scout

8-GPU deployment command:

```bash Command theme={null}
sglang serve \
  --model-path meta-llama/Llama-4-Scout-17B-16E-Instruct \
  --tp 8 \
  --context-length 1000000 \
  --trust-remote-code
```

### Llama-4-Maverick

8-GPU deployment command:

```bash Command theme={null}
sglang serve \
  --model-path meta-llama/Llama-4-Maverick-17B-128E-Instruct \
  --tp 8 \
  --trust-remote-code
```

#### 4.2.3 EAGLE Speculative Decoding

SGLang supports Llama 4 Maverick (400B) with [EAGLE speculative decoding](../../../docs/advanced_features/speculative_decoding). Enable with the EAGLE3 algorithm and the SGLang EAGLE3 draft model:

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path meta-llama/Llama-4-Maverick-17B-128E-Instruct \
  --speculative-algorithm EAGLE3 \
  --speculative-draft-model-path lmsys/sglang-EAGLE3-Llama-4-Maverick-17B-128E-Instruct-v1 \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --trust-remote-code \
  --tp 8
```

## 5. Benchmark

### 5.1 Speed Benchmark (Scout)

Test Environment:

Hardware: AMD MI300x GPU

Model: Llama-4-Scout

Tensor Parallelism: 8

sglang version: 0.5.9

* **Model Deployment**

```bash Command theme={null}
sglang serve \
  --model-path meta-llama/Llama-4-Scout-17B-16E-Instruct \
  --tp 8 \
  --context-length 1000000 \
  --trust-remote-code
```

### 5.1.1 Low Concurrency (Latency-Optimized)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  74.62
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4211
Request throughput (req/s):              0.14
Input token throughput (tok/s):          82.88
Output token throughput (tok/s):         57.42
Peak output token throughput (tok/s):    146.00
Peak concurrent requests:                2
Total token throughput (tok/s):          140.20
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   7459.48
Median E2E Latency (ms):                 4489.77
---------------Time to First Token----------------
Mean TTFT (ms):                          4246.98
Median TTFT (ms):                        68.57
P99 TTFT (ms):                           48091.05
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          7.49
Median TPOT (ms):                        7.40
P99 TPOT (ms):                           7.40
---------------Inter-Token Latency----------------
Mean ITL (ms):                           7.49
Median ITL (ms):                         7.49
P95 ITL (ms):                            7.47
P99 ITL (ms):                            7.52
Max ITL (ms):                            10.44
==================================================
```

### 5.1.2 Medium Concurrency (Balanced)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  45.41
Total input tokens:                      49668
Total input text tokens:                 49668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    40516
Request throughput (req/s):              2.26
Input token throughput (tok/s):          1120.46
Output token throughput (tok/s):         1152.47
Peak output token throughput (tok/s):    1520.00
Peak concurrent requests:                21
Total token throughput (tok/s):          2272.84
Concurrency:                             14.76
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   6089.22
Median E2E Latency (ms):                 6568.80
---------------Time to First Token----------------
Mean TTFT (ms):                          124.44
Median TTFT (ms):                        87.42
P99 TTFT (ms):                           268.72
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          11.88
Median TPOT (ms):                        12.00
P99 TPOT (ms):                           15.49
---------------Inter-Token Latency----------------
Mean ITL (ms):                           11.72
Median ITL (ms):                         10.54
P95 ITL (ms):                            11.22
P99 ITL (ms):                            67.88
Max ITL (ms):                            74.05
==================================================
```

### 5.1.3 High Concurrency (Throughput-Optimized)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model meta-llama/Llama-4-Scout-17B-16E-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  85.84
Total input tokens:                      249841
Total input text tokens:                 249841
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    250498
Request throughput (req/s):              5.84
Input token throughput (tok/s):          2910.84
Output token throughput (tok/s):         2944.82
Peak output token throughput (tok/s):    4100.00
Peak concurrent requests:                110
Total token throughput (tok/s):          5854.65
Concurrency:                             92.24
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   15844.00
Median E2E Latency (ms):                 15262.56
---------------Time to First Token----------------
Mean TTFT (ms):                          204.46
Median TTFT (ms):                        129.96
P99 TTFT (ms):                           528.54
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          41.56
Median TPOT (ms):                        42.90
P99 TPOT (ms):                           47.48
---------------Inter-Token Latency----------------
Mean ITL (ms):                           40.99
Median ITL (ms):                         24.46
P95 ITL (ms):                            84.46
P99 ITL (ms):                            87.64
Max ITL (ms):                            226.06
==================================================
```

### 5.2 Speed Benchmark (Maverick)

Test Environment:

Hardware: AMD MI300x GPU

Model: Llama-4-Maverick

Tensor Parallelism: 8

sglang version: 0.5.9

* **Model Deployment**

```bash Command theme={null}
sglang serve \
  --model-path meta-llama/Llama-4-Maverick-17B-128E-Instruct \
  --tp 8 \
  --context-length 1000000 \
  --trust-remote-code
```

### 5.2.1 Low Concurrency (Latency-Optimized)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model meta-llama/Llama-4-Maverick-17B-128E-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  68.08
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4202
Request throughput (req/s):              0.15
Input token throughput (tok/s):          89.62
Output token throughput (tok/s):         61.99
Peak output token throughput (tok/s):    168.00
Peak concurrent requests:                2
Total token throughput (tok/s):          151.61
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   6805.62
Median E2E Latency (ms):                 2733.91
---------------Time to First Token----------------
Mean TTFT (ms):                          4296.56
Median TTFT (ms):                        57.45
P99 TTFT (ms):                           38633.95
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          5.95
Median TPOT (ms):                        5.96
P99 TPOT (ms):                           5.97
---------------Inter-Token Latency----------------
Mean ITL (ms):                           5.96
Median ITL (ms):                         5.96
P95 ITL (ms):                            6.02
P99 ITL (ms):                            6.08
Max ITL (ms):                            7.02
==================================================
```

### 5.2.2 Medium Concurrency (Balanced)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model meta-llama/Llama-4-Maverick-17B-128E-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  30.72
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    40923
Request throughput (req/s):              2.60
Input token throughput (tok/s):          1291.39
Output token throughput (tok/s):         1328.41
Peak output token throughput (tok/s):    1760.00
Peak concurrent requests:                22
Total token throughput (tok/s):          2619.80
Concurrency:                             13.92
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5345.15
Median E2E Latency (ms):                 5679.73
---------------Time to First Token----------------
Mean TTFT (ms):                          259.30
Median TTFT (ms):                        72.60
P99 TTFT (ms):                           1063.45
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.53
Median TPOT (ms):                        10.22
P99 TPOT (ms):                           20.27
---------------Inter-Token Latency----------------
Mean ITL (ms):                           9.99
Median ITL (ms):                         9.10
P95 ITL (ms):                            9.87
P99 ITL (ms):                            55.62
Max ITL (ms):                            868.54
==================================================
```

### 5.2.3 High Concurrency (Throughput-Optimized)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model meta-llama/Llama-4-Maverick-17B-128E-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  90.95
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    251625
Request throughput (req/s):              5.50
Input token throughput (tok/s):          2746.77
Output token throughput (tok/s):         2777.90
Peak output token throughput (tok/s):    3700.00
Peak concurrent requests:                109
Total token throughput (tok/s):          5524.67
Concurrency:                             93.04
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   16924.17
Median E2E Latency (ms):                 16294.85
---------------Time to First Token----------------
Mean TTFT (ms):                          188.19
Median TTFT (ms):                        128.96
P99 TTFT (ms):                           534.81
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          33.63
Median TPOT (ms):                        35.37
P99 TPOT (ms):                           38.26
---------------Inter-Token Latency----------------
Mean ITL (ms):                           33.19
Median ITL (ms):                         27.66
P95 ITL (ms):                            76.91
P99 ITL (ms):                            78.82
Max ITL (ms):                            268.17
==================================================
```

### 5.3 Accuracy Benchmark

#### 5.3.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* Llama-4-Scout-17B-16E-Instruct

```text Output theme={null}
Accuracy: 0.945
Invalid: 0.000
Latency: 12.731 s
Output throughput: 1595.418 token/s
```

* Llama-4-Maverick-17B-128E-Instruct

```text Output theme={null}
Accuracy: 0.895
Invalid: 0.000
Latency: 9.739 s
Output throughput: 2405.505 token/s
```

#### 5.3.2 MMLU-Pro with sgl-eval

The table below records historical lm-eval measurements on 8×H100 alongside [Meta's official benchmark numbers](https://ai.meta.com/blog/llama-4-multimodal-intelligence/) (reproduction details: [PR #5092](https://github.com/sgl-project/sglang/pull/5092)). These scores were not produced by the sgl-eval commands below; rerun the evaluation for results using sgl-eval's prompts and grading.

Model Official SGLang
Llama-4-Scout-17B-16E-Instruct 74.3 75.2
Llama-4-Maverick-17B-128E-Instruct 80.5 80.7
Install the evaluation package before running either command: ```bash theme={null} pip install sgl-eval==0.1.0 ``` **Scout:** ```bash Command theme={null} # Start the server python -m sglang.launch_server \ --model-path meta-llama/Llama-4-Scout-17B-16E-Instruct \ --port 30000 \ --tp 8 \ --mem-fraction-static 0.8 \ --context-length 65536 # Run MMLU-Pro sgl-eval run mmlu_pro \ --base-url http://localhost:30000/v1 \ --model meta-llama/Llama-4-Scout-17B-16E-Instruct \ --max-tokens 2048 \ --num-threads 128 ``` **Maverick:** ```bash Command theme={null} # Start the server python -m sglang.launch_server \ --model-path meta-llama/Llama-4-Maverick-17B-128E-Instruct \ --port 30000 \ --tp 8 \ --mem-fraction-static 0.8 \ --context-length 65536 # Run MMLU-Pro sgl-eval run mmlu_pro \ --base-url http://localhost:30000/v1 \ --model meta-llama/Llama-4-Maverick-17B-128E-Instruct \ --max-tokens 2048 \ --num-threads 128 ``` # Muse Glimmer Source: https://docs.sglang.io/cookbook/autoregressive/Meta/MuseGlimmer A multimodal reasoning model served from a BF16, NVFP4 + MXFP8, vendor GGUF, or MLX checkpoint. ## Deployment > **Install SGLang** > > See the [official SGLang installation guide](../../../docs/get-started/install) for all installation methods and hardware platforms. The steps below match the **Python** and **Docker** options in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > # Muse Glimmer support is not in a release yet -- build the PR branch: > # https://github.com/sgl-project/sglang/pull/34262 > git clone -b muse-glimmer https://github.com/sgl-project/sglang.git > cd sglang > uv pip install --prerelease=allow -e "python[all]" > ``` > > Run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-muse-glimmer > ``` > > See [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker) to start the image. Replace the inner `sglang serve ...` command with the command from the panel below. Select a checkpoint format. Select whether to use speculative decoding: * **Standard**: Use normal autoregressive decoding. * **DFlash**: Use speculative decoding with the DFlash draft model. The draft serves as published, with no conversion step. See [§2](#2-configuration-tips). ## Playground Use the Playground to test SGLang features that are not in the verified matrix. The Deploy panel above shows only combinations that the SGLang team has verified. The Playground lets you add more options to the command from the Deploy panel. ## 1. Model Introduction Muse Glimmer is a multimodal reasoning model. You can serve Muse Glimmer in four formats: * A BF16 checkpoint (`MuseGlimmerForConditionalGeneration`). * A set of vendor GGUF files. * A ready-to-serve NVFP4 + MXFP8 checkpoint. * Three MLX repacks for Apple Silicon.
Form Source Notes
**BF16** `meta-models/Muse-Glimmer-30B` Supports image input.
**GGUF Q4\_K\_M** `meta-models/Muse-Glimmer-30B-GGUF` Text only. This path is not optimized. SGLang shows a warning at startup.
**NVFP4** `RadixArk/Muse-Glimmer-NVFP4` Text only. Ready to serve, no conversion needed.
**MLX Q4** `RadixArk/Muse-Glimmer-q4-MLX` Text only. Apple Silicon (MLX backend). Same serve recipe as gs128, no measured round yet. See §3.4.
**MLX Q4\_K\_M (gs128)** `RadixArk/Muse-Glimmer-q4km-gs128-MLX` Text only. Apple Silicon (MLX backend). Carries the vendor GGUF's exact quantization codes in MLX format. The measured MLX artifact. See §3.4.
**MLX Q4\_K (dynamic)** `RadixArk/Muse-Glimmer-q4k-dynamic-MLX` Text only. Apple Silicon (MLX backend). Same serve recipe as gs128, no measured round yet. See §3.4.
**Resources:** [Muse-Glimmer-30B (BF16)](https://huggingface.co/meta-models/Muse-Glimmer-30B) · [Muse-Glimmer-30B-assistant (DFlash draft)](https://huggingface.co/meta-models/Muse-Glimmer-30B-assistant) · [Muse-Glimmer-30B-GGUF](https://huggingface.co/meta-models/Muse-Glimmer-30B-GGUF) · [Muse-Glimmer-NVFP4](https://huggingface.co/RadixArk/Muse-Glimmer-NVFP4) · MLX · [q4](https://huggingface.co/RadixArk/Muse-Glimmer-q4-MLX) · [q4km-gs128](https://huggingface.co/RadixArk/Muse-Glimmer-q4km-gs128-MLX) · [q4k-dynamic](https://huggingface.co/RadixArk/Muse-Glimmer-q4k-dynamic-MLX). ## 2. Configuration Tips **The GGUF format is text only.** SGLang has no `mmproj` path. You cannot use the vision GGUF files. Use the BF16 checkpoint for multimodal input. **The NVFP4 checkpoint.** `RadixArk/Muse-Glimmer-NVFP4` is a ready-to-serve NVFP4 + MXFP8 checkpoint. No conversion needed — point `--model-path` straight at it. **The DFlash draft.** `meta-models/Muse-Glimmer-30B-assistant` is the vendor's native draft export and serves directly. No conversion needed. **DFlash with a GGUF target model** needs `--speculative-draft-load-format auto`. Without this flag, the draft model uses the `gguf` load format from the target model. The loader then rejects the draft directory. **Apple Silicon uses an MLX checkpoint, not the GGUF files.** The MLX backend has no GGUF path. Serve one of the three `RadixArk/Muse-Glimmer-*-MLX` artifacts with `SGLANG_USE_MLX=1` (see the Apple Silicon cells in the command panel). All three take the same flags; `q4km-gs128` is the one with a measured round. Keep `--disable-radix-cache` — the windowed KV storage for the sliding-window layers requires it — and set `SGLANG_MLX_CACHE_LIMIT_GB=8` so the MLX buffer cache does not grow the footprint under concurrent load. Speculative decoding is not available on the MLX backend. ## 3. Advanced Usage ### 3.1 Reasoning Muse Glimmer enables the `muse` reasoning parser by default. This parser separates the reasoning text from the final answer. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="meta-models/Muse-Glimmer-30B", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` ### 3.2 Tool Calling Muse Glimmer enables the `muse` tool-call parser by default. This parser sends structured tool calls in `message.tool_calls`. ### 3.3 Multimodal The BF16 checkpoint supports image input. It defaults to text only. To switch, select **Modality** in the command panel above. **Text only** adds `--language-model-only`. This flag turns off the vision tower. SGLang does not build or load the vision weights. This frees memory for the KV cache. SGLang rejects image requests in this mode. Select **Image + text** to turn on image input. NVFP4, GGUF, and the MLX artifacts are text only. The Modality option does not appear for GGUF or MLX; NVFP4 only offers **Text only**. ### 3.4 Apple Silicon (MLX) The MLX backend serves three Muse Glimmer artifacts on Apple Silicon Macs (48 GB unified memory or more). All three are text only — the MLX backend has no vision path — and all three take the same flags, so pick one in the command panel: * `RadixArk/Muse-Glimmer-q4-MLX` — no measured round yet. * `RadixArk/Muse-Glimmer-q4km-gs128-MLX` — a lossless repack of the vendor's Q4\_K\_M (gs128) GGUF: every weight keeps the GGUF's exact quantization code, with the group scales re-expressed in MLX affine bf16 (≤2⁻⁸ relative rounding). The numbers below are for this artifact. * `RadixArk/Muse-Glimmer-q4k-dynamic-MLX` — no measured round yet. Choose along the speed-versus-accuracy axis: footprint and expected accuracy both grow `q4` → `q4km-gs128` → `q4k-dynamic`, and decode speed moves the other way. Decode on Apple Silicon is memory-bandwidth-bound, so a smaller artifact reads fewer weight bytes per token — more tokens per second, and more unified memory left over for the KV cache. Take `q4` for the fastest responses on the smallest machine, `q4k-dynamic` to stay closest to BF16, and `q4km-gs128` for the middle ground — it is also the only one of the three with a measured round, below. This table shows accuracy for the gs128 checkpoint, with the vendor llama.cpp fork serving the source GGUF on the same machine as the reference. GSM8K: 200 questions, no-thinking chat template, temperature 0, max 2048 new tokens. CIMemories: 1 profile, full combo, single trial, DeepSeek-R1-0528 judge.
Benchmark SGLang MLX llama.cpp (same GGUF)
GSM8K (200q, no-thinking, greedy) 0.970 0.970
CIMemories — violation rate (lower is better) 0.00% 8.27%
CIMemories — coverage (higher is better) 76.0% 68.4%
CIMemories is a single-trial benchmark with a nondeterministic judge; treat the SGLang-vs-llama.cpp gap on that row as run noise, not a runtime effect. GSM8K parity is exact. Decode throughput for gs128 on an M5 Pro (64 GB), 1k-in/1k-out greedy: 15.3 tok/s at batch 1, rising to 52.6 tok/s aggregate at batch 8 — ahead of llama.cpp on the same GGUF codes at every batch size above 1. # Muse Spark Open Source: https://docs.sglang.io/cookbook/autoregressive/Meta/MuseSparkOpen Deploy Muse Spark Open with SGLang — launch recipes, feature compatibility, and tuning notes for GB300, B300, B200, H200, MI355X, Intel Xeon ## Deployment > **Install SGLang** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-muse-spark-open # NVIDIA B300 / GB300 / B200 / H200 > docker pull lmsysorg/sglang-rocm:muse-spark-open # AMD MI355X > docker pull lmsysorg/sglang:dev-muse-spark-xeon # Intel Xeon CPU > ``` > > The deployment panel can render a complete `docker run` command for the selected hardware and options. See [Install SGLang with Docker](/docs/get-started/install#method-3-using-docker) for host setup. The CUDA tag does not run on MI355X; use the ROCm image there; Use Xeon image for Xeon CPU and for more SGLang CPU installation approaches, see the [CPU version installation guide](/docs/hardware-platforms/cpu_server#installation). Choose your **Hardware Platform**, **Strategy**, and **Quantization** below. The default is **B300 / Low Latency / NVFP4**. **Low Latency** keeps the existing deployment settings; **High Throughput** removes all speculative decoding parameters. Use the Playground to tune parallelism, caching, speculative decoding, multimodal transport, and prefill/decode disaggregation. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## Agentic Long-Context Deployment Agentic workloads, such as coding agents and other multi-turn, tool-using assistants, send long prompts whose prefixes grow and repeat from turn to turn. Serving them well depends on reusing the KV cache across turns, offloading it beyond GPU memory, and keeping each session on the workers that already hold its prefix. This section gives complete launch commands for such deployments, each benchmarked in [SemiAnalysis InferenceX](https://inferencex.semianalysis.com/) and linked to the run that measured it. Pick a hardware platform, checkpoint, deployment shape, concurrency, KV cache offloading mechanism and router to get every process of the deployment as a raw command, one tab per process in launch order. * **Router.** Each configuration was submitted behind one front door: Dynamo (`dynamo.frontend` with `dynamo.sglang` workers) or SGLang (`sglang.launch_server`, behind `sglang_router` when there are several workers or DP-attention ranks). * **KV offload.** Choose among these KV cache offloading mechanisms: none (GPU KV only), HiCache (host DRAM), or a Mooncake store attached through the external linker. The Mooncake option needs an image whose SGLang build includes `--enable-unified-cache-external-linker`. * **Container image.** Run the commands inside the image listed for each configuration; flag names follow that image. ### GB300 deployments measured with Artificial Analysis AgentPerf Five aggregated Dynamo + SGLang deployments on GB300, measured with the [Artificial Analysis AgentPerf](https://github.com/ArtificialAnalysis/agentperf-client) coding-agent workload. Together they span the trade-off from the lowest per-user latency (concurrency 1) to the highest throughput per GPU (concurrency 160), ordered from low latency to high throughput. Each one starts from the Artificial Analysis SGLang submission for this model and changes only flags, environment variables and parallelism. * **Container image.** `lmsysorg/sglang:dev-muse-spark-open@sha256:8cfc5a72cb296771f5f8a4a4688cb6d05685610a830cbb616fa4ab0eb7bb2b0a` with the Dynamo wheels added: `pip install --no-deps ai-dynamo==1.6.0.dev20261019 ai-dynamo-runtime==1.6.0.dev20261019`. * **Router.** One Dynamo frontend with the KV-aware router. Session affinity keeps requests that carry the same `X-Dynamo-Session-ID` header on one worker; the AgentPerf client sends one ID per agent session. * **Checkpoints.** `meta-models/Muse-Spark-Open-816B-A42B-NVFP4` with the DFlash2 draft `RadixArk/Muse-Spark-Open-DFlash2` (8 draft tokens, FP8 KV cache). * **HiCache.** `--hicache-size` is the host tier in GB per rank; scale it to your host memory. * **Two-node deployments.** The TP8·EP8 worker spans two GB300 trays (4 GPUs each) over multi-node NVLink: run the worker command on both nodes, with `NODE_RANK` 0 on the first. > **Agg TP8·EP8 (2 nodes), lowest latency · 8 GPUs · concurrency 1** > > **Env Vars** > > ```bash theme={null} > export ETCD_IP= > export AGG_HEAD_IP= > export NODE_RANK=<0 on the first node, 1 on the second> > ``` > > **etcd** > > ```bash theme={null} > etcd \ > --data-dir /tmp/etcd \ > --listen-client-urls http://0.0.0.0:2379 \ > --advertise-client-urls http://$ETCD_IP:2379 > ``` > > **Dynamo frontend** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export DYN_ROUTER_QUEUE_THRESHOLD=None > export DYN_ROUTER_TEMPERATURE=0 > export DYN_TOKENIZER=fastokens > export DYN_TOKENIZER_CACHE=1 > export DYN_TOKENIZER_CACHE_BYTES=8000000000 > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > > python3 -m dynamo.frontend \ > --http-port 8000 \ > --router-mode kv \ > --router-session-affinity-ttl-secs 14400 \ > --active-decode-blocks-threshold None \ > --active-prefill-tokens-threshold None \ > --active-prefill-tokens-threshold-frac None > ``` > > **SGLang worker (run on each of the 2 nodes)** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > export NCCL_CUMEM_ENABLE=1 > export NCCL_MNNVL_ENABLE=1 > export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True > export SGLANG_TIMEOUT_KEEP_ALIVE=900 > > python3 -m dynamo.sglang \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --served-model-name meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --host 0.0.0.0 \ > --port 30000 \ > --dist-init-addr $AGG_HEAD_IP:20000 \ > --nnodes 2 \ > --node-rank $NODE_RANK \ > --kv-events-config '{"publisher":"zmq","topic":"kv-events","endpoint":"tcp://*:5557"}' \ > --request-plane tcp \ > --dyn-reasoning-parser muse \ > --dyn-tool-call-parser muse \ > --expert-parallel-size 8 \ > --kv-cache-dtype fp8_e4m3 \ > --max-running-requests 32 \ > --mem-fraction-static 0.85 \ > --mm-feature-transport cpu \ > --moe-runner-backend flashinfer_trtllm \ > --quantization modelopt_fp4 \ > --reasoning-parser muse \ > --speculative-algorithm DFLASH \ > --speculative-draft-attention-backend fa4 \ > --speculative-draft-model-path RadixArk/Muse-Spark-Open-DFlash2 \ > --speculative-num-draft-tokens 8 \ > --swa-full-tokens-ratio 0.1 \ > --tensor-parallel-size 8 \ > --trust-remote-code \ > --watchdog-timeout 3600 > ``` > **Agg TP8·EP8 (2 nodes), low latency · 8 GPUs · concurrency 4** > > **Env Vars** > > ```bash theme={null} > export ETCD_IP= > export AGG_HEAD_IP= > export NODE_RANK=<0 on the first node, 1 on the second> > ``` > > **etcd** > > ```bash theme={null} > etcd \ > --data-dir /tmp/etcd \ > --listen-client-urls http://0.0.0.0:2379 \ > --advertise-client-urls http://$ETCD_IP:2379 > ``` > > **Dynamo frontend** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export DYN_ROUTER_QUEUE_THRESHOLD=None > export DYN_ROUTER_TEMPERATURE=0 > export DYN_TOKENIZER=fastokens > export DYN_TOKENIZER_CACHE=1 > export DYN_TOKENIZER_CACHE_BYTES=8000000000 > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > > python3 -m dynamo.frontend \ > --http-port 8000 \ > --router-mode kv \ > --router-session-affinity-ttl-secs 14400 \ > --active-decode-blocks-threshold None \ > --active-prefill-tokens-threshold None \ > --active-prefill-tokens-threshold-frac None > ``` > > **SGLang worker (run on each of the 2 nodes)** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > export NCCL_CUMEM_ENABLE=1 > export NCCL_MNNVL_ENABLE=1 > export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True > export SGLANG_TIMEOUT_KEEP_ALIVE=900 > > python3 -m dynamo.sglang \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --served-model-name meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --host 0.0.0.0 \ > --port 30000 \ > --dist-init-addr $AGG_HEAD_IP:20000 \ > --nnodes 2 \ > --node-rank $NODE_RANK \ > --kv-events-config '{"publisher":"zmq","topic":"kv-events","endpoint":"tcp://*:5557"}' \ > --request-plane tcp \ > --dyn-reasoning-parser muse \ > --dyn-tool-call-parser muse \ > --expert-parallel-size 8 \ > --kv-cache-dtype fp8_e4m3 \ > --max-running-requests 32 \ > --mem-fraction-static 0.85 \ > --mm-feature-transport cpu \ > --moe-runner-backend flashinfer_trtllm \ > --quantization modelopt_fp4 \ > --reasoning-parser muse \ > --speculative-algorithm DFLASH \ > --speculative-draft-attention-backend fa4 \ > --speculative-draft-model-path RadixArk/Muse-Spark-Open-DFlash2 \ > --speculative-num-draft-tokens 8 \ > --swa-full-tokens-ratio 0.1 \ > --tensor-parallel-size 8 \ > --trust-remote-code \ > --watchdog-timeout 3600 > ``` > **Agg TP4·EP4, balanced · 4 GPUs · concurrency 16** > > **Env Vars** > > ```bash theme={null} > export ETCD_IP= > export AGG_HEAD_IP= > ``` > > **etcd** > > ```bash theme={null} > etcd \ > --data-dir /tmp/etcd \ > --listen-client-urls http://0.0.0.0:2379 \ > --advertise-client-urls http://$ETCD_IP:2379 > ``` > > **Dynamo frontend** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export DYN_ROUTER_QUEUE_THRESHOLD=None > export DYN_ROUTER_TEMPERATURE=0 > export DYN_TOKENIZER=fastokens > export DYN_TOKENIZER_CACHE=1 > export DYN_TOKENIZER_CACHE_BYTES=8000000000 > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > > python3 -m dynamo.frontend \ > --http-port 8000 \ > --router-mode kv \ > --router-session-affinity-ttl-secs 14400 \ > --active-decode-blocks-threshold None \ > --active-prefill-tokens-threshold None \ > --active-prefill-tokens-threshold-frac None > ``` > > **SGLang worker** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > export NCCL_CUMEM_ENABLE=1 > export SGLANG_TIMEOUT_KEEP_ALIVE=900 > > python3 -m dynamo.sglang \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --served-model-name meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --host 0.0.0.0 \ > --port 30000 \ > --kv-events-config '{"publisher":"zmq","topic":"kv-events","endpoint":"tcp://*:5557"}' \ > --request-plane tcp \ > --dyn-reasoning-parser muse \ > --dyn-tool-call-parser muse \ > --enable-layernorm-sp \ > --enable-megamoe-for-layernorm-sp \ > --expert-parallel-size 4 \ > --kv-cache-dtype fp8_e4m3 \ > --max-running-requests 32 \ > --mem-fraction-static 0.85 \ > --mm-feature-transport cpu \ > --moe-runner-backend flashinfer_trtllm \ > --prefill-decode-interval 64 \ > --quantization modelopt_fp4 \ > --reasoning-parser muse \ > --speculative-algorithm DFLASH \ > --speculative-draft-attention-backend fa4 \ > --speculative-draft-model-path RadixArk/Muse-Spark-Open-DFlash2 \ > --speculative-num-draft-tokens 8 \ > --swa-full-tokens-ratio 0.1 \ > --tensor-parallel-size 4 \ > --trust-remote-code \ > --watchdog-timeout 3600 > ``` > **Agg TP4·EP4, high throughput · 4 GPUs · concurrency 64** > > **Env Vars** > > ```bash theme={null} > export ETCD_IP= > export AGG_HEAD_IP= > ``` > > **etcd** > > ```bash theme={null} > etcd \ > --data-dir /tmp/etcd \ > --listen-client-urls http://0.0.0.0:2379 \ > --advertise-client-urls http://$ETCD_IP:2379 > ``` > > **Dynamo frontend** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export DYN_ROUTER_QUEUE_THRESHOLD=None > export DYN_ROUTER_TEMPERATURE=0 > export DYN_TOKENIZER=fastokens > export DYN_TOKENIZER_CACHE=1 > export DYN_TOKENIZER_CACHE_BYTES=8000000000 > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > > python3 -m dynamo.frontend \ > --http-port 8000 \ > --router-mode kv \ > --router-session-affinity-ttl-secs 14400 \ > --active-decode-blocks-threshold None \ > --active-prefill-tokens-threshold None \ > --active-prefill-tokens-threshold-frac None > ``` > > **SGLang worker** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > export NCCL_CUMEM_ENABLE=1 > export SGLANG_OPT_UNIFIED_CACHE_FREE_OUT_OF_WINDOW_SLOTS=1 > export SGLANG_TIMEOUT_KEEP_ALIVE=900 > > python3 -m dynamo.sglang \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --served-model-name meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --host 0.0.0.0 \ > --port 30000 \ > --kv-events-config '{"publisher":"zmq","topic":"kv-events","endpoint":"tcp://*:5557"}' \ > --request-plane tcp \ > --cuda-graph-max-bs-decode 64 \ > --dyn-reasoning-parser muse \ > --dyn-tool-call-parser muse \ > --enable-layernorm-sp \ > --enable-megamoe-for-layernorm-sp \ > --expert-parallel-size 4 \ > --kv-cache-dtype fp8_e4m3 \ > --max-running-requests 64 \ > --mem-fraction-static 0.85 \ > --mm-feature-transport cpu \ > --moe-runner-backend flashinfer_trtllm \ > --prefill-decode-interval 24 \ > --quantization modelopt_fp4 \ > --reasoning-parser muse \ > --speculative-algorithm DFLASH \ > --speculative-draft-attention-backend fa4 \ > --speculative-draft-model-path RadixArk/Muse-Spark-Open-DFlash2 \ > --speculative-num-draft-tokens 8 \ > --swa-full-tokens-ratio 0.15 \ > --tensor-parallel-size 4 \ > --trust-remote-code \ > --watchdog-timeout 3600 > ``` > **Agg TP4·EP4 + HiCache, max throughput · 4 GPUs · concurrency 160** > > **Env Vars** > > ```bash theme={null} > export ETCD_IP= > export AGG_HEAD_IP= > ``` > > **etcd** > > ```bash theme={null} > etcd \ > --data-dir /tmp/etcd \ > --listen-client-urls http://0.0.0.0:2379 \ > --advertise-client-urls http://$ETCD_IP:2379 > ``` > > **Dynamo frontend** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export DYN_ROUTER_QUEUE_THRESHOLD=None > export DYN_ROUTER_TEMPERATURE=0 > export DYN_TOKENIZER=fastokens > export DYN_TOKENIZER_CACHE=1 > export DYN_TOKENIZER_CACHE_BYTES=8000000000 > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > > python3 -m dynamo.frontend \ > --http-port 8000 \ > --router-mode kv \ > --router-session-affinity-ttl-secs 14400 \ > --active-decode-blocks-threshold None \ > --active-prefill-tokens-threshold None \ > --active-prefill-tokens-threshold-frac None > ``` > > **SGLang worker** > > ```bash theme={null} > export DYN_REQUEST_PLANE=tcp > export ETCD_ENDPOINTS=http://$ETCD_IP:2379 > export NCCL_CUMEM_ENABLE=1 > export SGLANG_OPT_UNIFIED_CACHE_FREE_OUT_OF_WINDOW_SLOTS=1 > export SGLANG_TIMEOUT_KEEP_ALIVE=900 > > python3 -m dynamo.sglang \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --served-model-name meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --host 0.0.0.0 \ > --port 30000 \ > --kv-events-config '{"publisher":"zmq","topic":"kv-events","endpoint":"tcp://*:5557"}' \ > --request-plane tcp \ > --cuda-graph-max-bs-decode 176 \ > --dyn-reasoning-parser muse \ > --dyn-tool-call-parser muse \ > --enable-hierarchical-cache \ > --enable-layernorm-sp \ > --enable-megamoe-for-layernorm-sp \ > --expert-parallel-size 4 \ > --hicache-size 120 \ > --kv-cache-dtype fp8_e4m3 \ > --max-running-requests 176 \ > --mem-fraction-static 0.9 \ > --mm-feature-transport cpu \ > --moe-runner-backend flashinfer_trtllm \ > --prefill-decode-interval 6 \ > --quantization modelopt_fp4 \ > --reasoning-parser muse \ > --speculative-algorithm DFLASH \ > --speculative-draft-attention-backend fa4 \ > --speculative-draft-model-path RadixArk/Muse-Spark-Open-DFlash2 \ > --speculative-num-draft-tokens 8 \ > --swa-full-tokens-ratio 0.15 \ > --tensor-parallel-size 4 \ > --trust-remote-code \ > --watchdog-timeout 3600 > ``` ### MI355X deployment measured with SemiAnalysis InferenceX TP8·EP8 with DFlash V2 on 8× MI355X, measured in [SemiAnalysis InferenceX](https://inferencex.semianalysis.com/) at concurrency 1–64. * **Container image.** `lmsysorg/sglang-rocm:muse-spark-open-1020`. * **HiCache.** At concurrency 16 and above, add the HiCache flags below. `--hicache-size` is the host tier in GB per rank, so 253 GB needs about 2 TB of host memory across the eight ranks. ```bash Command theme={null} SGLANG_USE_AITER=1 \ SGLANG_USE_AITER_UNIFIED_ATTN=1 \ MUSE_MOE_BACKEND=flydsl \ python -m sglang.launch_server \ --model-path amd/Muse-Spark-Open-816B-A42B-Quark-MXFP4 \ --tp-size 8 \ --ep-size 8 \ --attention-backend aiter \ --page-size 16 \ --kv-cache-dtype fp8_e4m3 \ --mem-fraction-static 0.85 \ --max-running-requests 128 \ --swa-full-tokens-ratio 0.2 \ --prefill-decode-interval 20 \ --scheduler-recv-interval 20 \ --tokenizer-worker-num 4 \ --speculative-algorithm DFLASH \ --speculative-draft-model-path RadixArk/Muse-Spark-Open-DFlash2 \ --speculative-draft-attention-backend triton \ --speculative-num-draft-tokens 8 \ --speculative-draft-window-size 2048 \ --reasoning-parser muse \ --tool-call-parser muse \ --watchdog-timeout 1800 \ --host 0.0.0.0 \ --port 30000 ``` ```bash HiCache (concurrency 16 and above) theme={null} --enable-hierarchical-cache \ --hicache-size 253 \ --hicache-write-policy write_through \ --hicache-io-backend kernel \ --hicache-mem-layout page_first ``` ## 1. Model introduction This cookbook provides deployment recipes for the Muse Spark Open 816B-A42B checkpoints: * **NVFP4:** `meta-models/Muse-Spark-Open-816B-A42B-NVFP4` (NVIDIA default). * **MXFP4:** `amd/Muse-Spark-Open-816B-A42B-Quark-MXFP4` (MI355X default; Quark-quantized). * **NVFP4 on MI355X (direct load):** the same `meta-models/Muse-Spark-Open-816B-A42B-NVFP4` checkpoint runs on MI355X with `--quantization quark_mxfp4`; the weights are requantized to MXFP4 while loading, so no separate export is needed. Select **MI355X / NVFP4** in the panel for this command. * **INT4** `intel-ai/Muse-Spark-Open-816B-A42B-INT4` (Xeon default; AutoRound-quantized). * **BF16:** `meta-models/Muse-Spark-Open-816B-A42B`. ## 2. Configuration tips ### H200 configuration NVFP4 runs on one 8x H200 node with Marlin W4A16 experts (`--moe-runner-backend marlin`), since Hopper has no TRT-LLM FP4 MoE. The BF16 checkpoint does not fit on one node, so it runs TP16/EP16 across two nodes; replace `` and `` for each node. Prefill sequence parallel and MegaMoE need SM100 kernels and are unavailable on H200. ### Xeon CPU service configuration * Xeon serves the **INT4** checkpoint (quantized by Intel AutoRound, HF id: `intel-ai/Muse-Spark-Open-816B-A42B-INT4`) on the SGLang CPU engine. A typical Xeon 6 P-core platform (e.g., Xeon 6980P) is recommended. * Set `--page-size 1` for the `intel_amx` attention backend (the CPU default attention backend). * We recommend setting the TP size equal to the NUMA count. See the **Notes** under [Launch of the Serving Engine](/docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) in the SGLang CPU server document for how to configure the arguments, especially TP and NUMA binding. ## 3. Advanced Usage ### 3.1 Reasoning On the server, enable `--reasoning-parser muse` in your `sglang serve` command. The [Deployment](#deployment) recipes above already include this flag; in the [Playground](#playground), keep **Reasoning Parser** enabled under **Parsers**. The parser separates the model's reasoning into `message.reasoning_content` and its final answer into `message.content`. On the client, set `reasoning_effort` for each chat completion request. Muse Spark Open supports **four levels: `low`, `medium`, `high`, and `xhigh`**. If you omit the parameter, the checkpoint's chat template defaults to **`xhigh`**. Use `low` or `medium` for faster, shorter responses, and `high` or `xhigh` for complex problem solving, coding, and agentic tasks. Other values, including `minimal`, are not supported. See the [model card](https://huggingface.co/meta-models/Muse-Spark-Open-816B-A42B-NVFP4) for the supported settings. The example below connects to the server on port `30000` and discovers its model ID, so it works with whichever checkpoint you selected in Deployment. Change `base_url` if the server runs on another host or port. The current checkpoint's chat template does not require `chat_template_kwargs={"thinking": True}`; set the reasoning level with `reasoning_effort`. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI( > base_url="http://127.0.0.1:30000/v1", > api_key="EMPTY", > timeout=600.0, > ) > model = client.models.list().data[0].id > response = client.chat.completions.create( > model=model, > messages=[ > {"role": "system", "content": "You are a helpful assistant."}, > {"role": "user", "content": "Briefly explain: what is SGLang?"}, > ], > max_tokens=16384, > reasoning_effort="xhigh", # low | medium | high | xhigh (default) > ) > choice = response.choices[0] > print("Reasoning:", getattr(choice.message, "reasoning_content", None)) > print("Content:", choice.message.content) > print("Finish reason:", choice.finish_reason) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: We need to briefly explain what is SGLang. Likely want concise explanation. SGLang is structured generation language? It's a framework for programming LLMs. Developed by LMSYS? Actually SGLang is a serving framework. > > Need to explain: SGLang is a fast serving framework/DSL for LLMs? Let's recall. > > SGLang is a structured generation language, a domain-specific language for LLM programs. Created by LMSYS Org. Allows efficient LLM programming with structured prompting, caching, constrained decoding etc. Provides high-performance serving via RadixAttention, paged attention, etc. Used for chaining calls, multi-turn, function calling, reasoning. > > We should give brief explanation. > > Possibly user wants simple. Provide definition, key features, use cases. > > Make it brief but informative. > > Maybe need to distinguish from other? Should be neutral. > > Potentially also SGLang = Serving framework? > > SGLang is open-source system for efficient LLM serving and programming. > > Key features: > - Front-end language (Python DSL) for controlling generation > - Backend runtime: RadixAttention for KV cache reuse, continuous batching, tensor parallelism, quantization, speculative decoding. > - Supports OpenAI-compatible API. > > Briefly explain. > > Keep concise. > > Add example maybe? > > User: "Briefly explain: what is SGLang?" > > Provide maybe 3-4 bullet points. > > Possibly mention origin: developed by LMSYS and UC Berkeley etc. > > Ensure not too long. Brief. > > Maybe add: SGL for Structured Generation Language. > > Make answer accessible. > > Probably mention advantages: faster, controllable. > > We should not hallucinate too much. Provide accurate info. > > SGLang GitHub: sgl-project/sglang. > > SGLang latest: SGLang is inference engine? > > Let's verify facts: SGLang was introduced in paper "SGLang: Efficient Execution of Structured Language Model Programs" arXiv 2312.07104, Dec 2023, authors Lianmin Zheng etc. > > It provides primitives: gen(), select(), etc. > > Runtime optimizations: RadixAttention, compressed FSM for constrained decoding, API speculative execution. > > Provides high throughput, low latency. > > Supports many models: Llama, Mistral, Qwen etc. Supports on NVIDIA GPUs, AMD. > > Should answer. > > User likely wants short. Provide 1 paragraph + bullets. > > Make tone helpful. > > Add use cases: agents, reasoning, data extraction. > > Probably not over. > > Potential need to add date knowledge cutoff 2026? > > Add nothing disallowed. > > Make final answer succinct. > > Maybe add link? Not needed. > > Use simple language. > > We should not mention reasoning strength. > > Proceed to final. > > Content: SGLang — **Structured Generation Language** — is an open-source system for programming and serving Large Language Models (LLMs). > > Created by LMSYS / UC Berkeley, it has 2 parts: > > **1. Frontend - a Python DSL:** Lets you write LLM programs with logic, not just string prompts. Primitives like `gen()`, `select()`, `fork()` for chaining calls, controlling reasoning, forcing JSON/tool-calling structure, multi-agent workflows, etc. > > **2. Backend - a high-performance inference engine:** Optimized runtime for fast, cheap serving with features like: > * **RadixAttention:** automatic KV-cache reuse for prefixes, few-shot examples, multi-turn chat > * Continuous batching, Tensor Parallelism, quantization, speculative decoding > * Fast constrained/structured decoding > > In short: It's an alternative to vLLM / TensorRT-LLM. You get both a cleaner way to *program* LLMs and a very fast engine to *run* them, with an OpenAI-compatible API. > > Finish reason: stop > ``` ### 3.2 Tool calling On the server, enable `--tool-call-parser muse` alongside `--reasoning-parser muse` in your `sglang serve` command. The [Deployment](#deployment) recipes above already include both flags; in the [Playground](#playground), keep **Tool Call Parser** and **Reasoning Parser** enabled under **Parsers**. SGLang converts Muse Spark Open's native tool-call format into OpenAI-compatible `message.tool_calls`, while keeping reasoning in `message.reasoning_content`. On the client, pass function definitions in `tools`, with each function's arguments described by a JSON Schema. The checkpoint's [chat template](https://huggingface.co/meta-models/Muse-Spark-Open-816B-A42B-NVFP4/blob/main/chat_template.jinja) formats these definitions for the model. With `tool_choice="auto"`, the model decides whether to call a tool. The example below requests a weather lookup and prints each returned function name and its JSON arguments. > **Tool Calling Example (Python)** > > ```python Example theme={null} > import json > > from openai import OpenAI > > client = OpenAI( > base_url="http://127.0.0.1:30000/v1", > api_key="EMPTY", > timeout=600.0, > ) > model = client.models.list().data[0].id > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city.", > "parameters": { > "type": "object", > "properties": { > "location": { > "type": "string", > "description": "City name, for example Beijing.", > }, > "unit": { > "type": "string", > "enum": ["celsius", "fahrenheit"], > }, > }, > "required": ["location", "unit"], > "additionalProperties": False, > }, > }, > } > ] > > response = client.chat.completions.create( > model=model, > messages=[ > {"role": "user", "content": "Use get_weather to check the current weather in Beijing in Celsius."}, > ], > tools=tools, > tool_choice="auto", > reasoning_effort="xhigh", > max_tokens=16384, > ) > choice = response.choices[0] > message = choice.message > print("Reasoning:", getattr(message, "reasoning_content", None)) > print("Content:", message.content) > for tool_call in message.tool_calls or []: > print("Tool call ID:", tool_call.id) > print("Function:", tool_call.function.name) > print("Arguments:", json.loads(tool_call.function.arguments)) > print("Finish reason:", choice.finish_reason) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: User wants get_weather to check current weather in Beijing in Celsius. > > We have function get_weather with parameters: location (string), unit (string enum celsius/fahrenheit) > > We need to call it. > > We must call the function with location=Beijing, unit=celsius > > Add reasoning. > > We should not add extra text beyond function call? In this format, we need to provide function call. Probably we need to output function call directly. > > We are Meta AI. Follow guidelines. > > We need to invoke get_weather. > > Be careful to JSON correct. > > Probably need thinking tags? But in this environment, we have tool access. We should call get_weather. > > We should do that now. > > Possibly reasoning strength 512, need thorough reasoning? No, we just need to call tool. > > Ensure we use correct recipient format: get_weather > > We need to produce "..." block. > > We need to provide location: "Beijing", unit: "celsius" > > Make call. > > Content: Beijing in Celsius — checking the weather for you immediately. > Tool call ID: call_43c0efae809d46988855bb79 > Function: get_weather > Arguments: {'location': 'Beijing', 'unit': 'celsius'} > Finish reason: tool_calls > ``` This example inspects the requested tool calls; it does not fetch weather data. Your application executes the corresponding function. To continue the conversation, append the assistant message containing `tool_calls`, then a `role="tool"` message for each result with the matching `tool_call_id`, and send the updated messages with the same tool definitions. ### 3.3 Encode Prefill Decode Disaggregation Encoder–Prefill–Decode (EPD) disaggregation separates media encoding, prompt processing, and token generation, so encoding-heavy image/video requests can be scheduled separately from language inference. The encoder sends features through `zmq_to_tokenizer`; prefill transfers KV state to decode through Mooncake, with a router exposing one client endpoint. The examples below use one 8× B300 NVLink host: encoder TP2 shares GPUs 0–1 with prefill TP4/EP4 on GPUs 0–3; decode TP4/EP4 uses GPUs 4–7. Run each command in a separate shell using the NVIDIA image from [Deployment](#deployment), with a shared host network. Start encoder, prefill, decode, then router, waiting for each to become ready. Prefill (`30001`), decode (`30002`), and router (`8000`) match the Playground ports; the encoder uses `30010`. > [!NOTE] > > These are simplified examples derived from [PR #265](https://github.com/radixark/sglang-muse-spark/pull/265). The source run checked transport with simulated outputs; this ordinary-serving configuration still needs runtime and accuracy validation. Leave GPU memory headroom for the encoder sharing the prefill GPUs. > **Encoder server (B300, GPUs 0–1)** > > ```bash Command theme={null} > CUDA_VISIBLE_DEVICES=0,1 sglang serve \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --quantization modelopt_fp4 \ > --tp-size 2 \ > --encoder-only \ > --encoder-transfer-backend zmq_to_tokenizer \ > --host 0.0.0.0 \ > --port 30010 > ``` > **Prefill server (B300, GPUs 0–3)** > > ```bash Command theme={null} > export MC_INTRANODE_NVLINK=true > export MC_TCP_ENABLE_CONNECTION_POOL=true > export SGLANG_MOONCAKE_CUSTOM_MEM_POOL=INTRA_NODE_NVLINK > > CUDA_VISIBLE_DEVICES=0,1,2,3 sglang serve \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --quantization modelopt_fp4 \ > --moe-runner-backend flashinfer_trtllm \ > --tp-size 4 --ep-size 4 \ > --mem-fraction-static 0.8 \ > --language-only \ > --encoder-urls http://127.0.0.1:30010 \ > --encoder-transfer-backend zmq_to_tokenizer \ > --encoder-bootstrap-port 8997 \ > --disaggregation-mode prefill \ > --disaggregation-transfer-backend mooncake \ > --disaggregation-bootstrap-port 8998 \ > --reasoning-parser muse --tool-call-parser muse \ > --host 0.0.0.0 \ > --port 30001 > ``` > **Decode server (B300, GPUs 4–7)** > > ```bash Command theme={null} > export MC_INTRANODE_NVLINK=true > export MC_TCP_ENABLE_CONNECTION_POOL=true > export SGLANG_MOONCAKE_CUSTOM_MEM_POOL=INTRA_NODE_NVLINK > > CUDA_VISIBLE_DEVICES=4,5,6,7 sglang serve \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --quantization modelopt_fp4 \ > --moe-runner-backend flashinfer_trtllm \ > --tp-size 4 --ep-size 4 \ > --mem-fraction-static 0.75 \ > --language-only \ > --encoder-urls http://127.0.0.1:30010 \ > --encoder-transfer-backend zmq_to_tokenizer \ > --encoder-bootstrap-port 8999 \ > --disaggregation-mode decode \ > --disaggregation-transfer-backend mooncake \ > --disaggregation-bootstrap-port 8998 \ > --reasoning-parser muse --tool-call-parser muse \ > --host 0.0.0.0 \ > --port 30002 > ``` > **Router** > > ```bash Command theme={null} > sglang-router launch \ > --pd-disaggregation \ > --prefill http://127.0.0.1:30001 8998 \ > --decode http://127.0.0.1:30002 \ > --host 0.0.0.0 --port 8000 > ``` The language workers use distinct encoder-bootstrap ports (`8997` / `8999`) on this shared host; the router's `8998` matches the prefill KV bootstrap port. Send client requests to `http://localhost:8000/v1`. See the [EPD guide](/docs/advanced_features/epd_disaggregation) for the architecture and additional deployment options. ### 3.4 Sequence Parallel for Prefill Sequence parallelism (SP) splits activations along the token dimension across TP ranks. Each rank processes its own token shard for normalization, pooling, and unpooling, reducing duplicated computation and activation storage during long-prompt prefill. NVFP4 MegaMoE connects these shards to expert parallelism through integrated all-to-all dispatch and combine: tokens reach their selected experts, and weighted expert outputs return to the original token ranks. For a Blackwell NVFP4 configuration (B300, B200, or GB300), use the [Playground](#playground) to enable **Prefill Sequence Parallel** and **Prefill MegaMoE** together. This adds `--enable-layernorm-sp --enable-megamoe-for-layernorm-sp` to the launch command. Keep **Attention TP** and **MoE EP** equal; MegaMoE requires SP to remain on. These prefill options are unavailable on H200 and are omitted for a PD decode worker. ### 3.5 Speculative Decoding with DFlash v2 and Block Verification DFlash V2 uses the target model's hidden states to propose a block of future tokens in one draft-model forward pass; Muse Spark Open then verifies the block in a single pass, advancing by multiple tokens when proposals are accepted. V2 mixes information across neighboring draft positions and selects candidates with their dependencies in mind. Optional [block verification](https://arxiv.org/abs/2403.10444) evaluates draft prefixes jointly instead of token by token, potentially accepting longer prefixes while preserving the target sampling distribution. In the [Playground](#playground), select **DFlash V2** under **Speculative Decoding** to add `--speculative-algorithm DFLASH` and `--speculative-draft-model-path RadixArk/Muse-Spark-Open-DFlash2`. Then adjust: * **Draft attention backend:** `fa4` for NVIDIA or `triton` for MI355X, inherited from Deployment and set with `--speculative-draft-attention-backend`. * **Num draft tokens:** 1–8, default **8**, set with `--speculative-num-draft-tokens`. * **Block Verification:** turn it on to add `--speculative-use-block-verification`; it is off by default. The Deployment **Low Latency** strategy enables DFlash V2 on supported GPUs; **High Throughput** leaves speculative decoding off. The Playground inherits that choice and lets you override it. ### 3.6 MegaKernel with Helion (Experimental) We support persistent Helion megakernels for DFlash V2 target verification. They fuse attention, projection and normalization boundaries, routing, MoE, and the layer tail, with a separate fused LM head, reducing kernel launches and communication overhead. TP4/EP1 shards each expert across four GPUs, avoiding the expert-load imbalance of EP4 at batch size 1. With **BS=1 + DFlash V2**, the reported decode performance is roughly **10% faster** than the TP4/EP4 baseline without megakernels on 4×GB300; gains depend on the workload. Use this experimental recipe **only on a PD-disaggregated decode worker**, with four **GB300 (SM 10.3)** GPUs, NVFP4 weights, FP8 E4M3 KV cache, and `helion==1.5.0`. Keep prefill on the regular path: EP1 prefill is slower than the TP4/EP4 baseline. This specialized TP4/EP1 command is separate from the Playground's equal-TP/EP configuration. > **Helion decode worker (4×GB300)** > > Install the dependency in the serving environment, then launch the decode worker: > > ```bash Command theme={null} > python -m pip install helion==1.5.0 > > export NCCL_NVLS_ENABLE=1 > export NCCL_MNNVL_ENABLE=1 > export NCCL_CUMEM_ENABLE=1 > export SGLANG_MOONCAKE_CUSTOM_MEM_POOL=NVLINK > export MC_FORCE_MNNVL=1 > > SGLANG_FORCE_FUSED_OP_BACKEND=helion \ > SGLANG_ENABLE_MUSE_SPARK_FINALIZE_AR=1 \ > SGLANG_FLASHINFER_NVFP4_PER_TOKEN_ACTIVATION=1 \ > python -m sglang.launch_server \ > --model-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --tokenizer-path meta-models/Muse-Spark-Open-816B-A42B-NVFP4 \ > --served-model-name external \ > --json-model-override-args '{"eos_token_id":[200001,200008]}' \ > --tp-size 4 \ > --ep-size 1 \ > --context-length 131072 \ > --max-running-requests 1 \ > --quantization modelopt_fp4 \ > --moe-runner-backend flashinfer_trtllm \ > --attention-backend trtllm_mha \ > --kv-cache-dtype fp8_e4m3 \ > --page-size 128 \ > --disable-flashinfer-autotune \ > --disable-prefill-cuda-graph \ > --cuda-graph-max-bs-decode 1 \ > --reasoning-parser muse \ > --tool-call-parser muse \ > --speculative-algorithm DFLASH \ > --speculative-draft-model-path RadixArk/Muse-Spark-Open-DFlash2 \ > --speculative-draft-attention-backend fa4 \ > --speculative-num-draft-tokens 8 \ > --disaggregation-mode decode \ > --disaggregation-transfer-backend mooncake \ > --disaggregation-bootstrap-port 8998 \ > --mem-fraction-static 0.80 \ > --host 0.0.0.0 \ > --port 30002 > ``` Pair this worker with a compatible prefill worker using the same target checkpoint, TP4, `--kv-cache-dtype fp8_e4m3`, `--page-size 128`, and `--served-model-name external`, with bootstrap port `8998`. Use the [Playground](#playground) PD router command with the decode URL pointing to this worker on port `30002`; send client requests to the router on port `8000`. # MiniMax-M2 Source: https://docs.sglang.io/cookbook/autoregressive/MiniMax/MiniMax-M2 ## 1. Model Introduction [MiniMax-M2](https://huggingface.co/MiniMaxAI/MiniMax-M2) is a compact, fast, and cost-effective MoE model (230 billion total parameters with 10 billion active parameters) built for elite performance in coding and agentic tasks, all while maintaining powerful general intelligence. This generation delivers comprehensive upgrades across the board: * **Superior Intelligence**: MiniMax-M2 demonstrates highly competitive general intelligence across mathematics, science, instruction following, coding, and agentic tool use in [Artificial Analysis](https://artificialanalysis.ai/). Its composite score ranks #1 among open-source models globally. * **Advanced Coding**: Engineered for end-to-end developer workflows, MiniMax-M2 excels at multi-file edits, coding-run-fix loops, and test-validated repairs. Strong performance on Terminal-Bench and (Multi-)SWE-Bench–style tasks demonstrates practical effectiveness in terminals, IDEs, and CI across languages. * **Agent Performance**: MiniMax-M2 plans and executes complex, long-horizon toolchains across shell, browser, retrieval, and code runners. In BrowseComp-style evaluations, it consistently locates hard-to-surface sources, maintains evidence traceable, and gracefully recovers from flaky steps. * **Efficient Design**: With 10 billion activated parameters (230 billion in total), MiniMax-M2 delivers lower latency, lower cost, and higher throughput for interactive agents and batched sampling—perfectly aligned with the shift toward highly deployable models that still shine on coding and agentic tasks. For more details, please refer to the [official Minimax GitHub Repository](https://github.com/MiniMax-AI). ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. The AMD environment is currently available in SGLang via Docker image install. ### 2.1 AMD Docker #### 2.1.1 Launch docker ```shell Command theme={null} docker pull lmsysorg/sglang:v0.5.9-rocm720-mi30x ``` ```shell Command theme={null} docker run -d -it --ipc=host --network=host --privileged \ --cap-add=CAP_SYS_ADMIN \ --device=/dev/kfd --device=/dev/dri --device=/dev/mem \ --group-add video --cap-add=SYS_PTRACE \ --security-opt seccomp=unconfined \ -v /:/work \ -e SHELL=/bin/bash \ --name Minimax \ lmsysorg/sglang:v0.5.9-rocm720-mi30x \ /bin/bash ``` #### 2.1.2 Make modifications inside the docker ```shell Command theme={null} mv /sgl-workspace/sglang/python/sglang/srt/models/transformers.py \ /sgl-workspace/sglang/python/sglang/srt/models/hf_transformers_model.py ``` #### 2.1.3 Fix torch compile Comment out the following line: @torch.compile(dynamic=True, backend=get\_compiler\_backend()) in /sgl-workspace/sglang/python/sglang/srt/models/minimax\_m2.py ```shell Command theme={null} #@torch.compile(dynamic=True, backend=get_compiler_backend()) ``` ## 3. Model Deployment This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and thinking capabilities. Run this Command:

#### 3.1.1 NVIDIA GPU Deployment

The interactive command generator above covers AMD deployments. For NVIDIA GPUs (H100/H200/B200), use these explicit commands:

**4-GPU deployment (up to 400K context):**

```bash Command theme={null}
python -m sglang.launch_server \
    --model-path MiniMaxAI/MiniMax-M2 \
    --tp-size 4 \
    --tool-call-parser minimax-m2 \
    --reasoning-parser minimax-append-think \
    --host 0.0.0.0 \
    --trust-remote-code \
    --port 30000 \
    --mem-fraction-static 0.85
```

**8-GPU deployment (up to 3M context):**

```bash Command theme={null}
python -m sglang.launch_server \
    --model-path MiniMaxAI/MiniMax-M2 \
    --tp-size 8 \
    --ep-size 8 \
    --tool-call-parser minimax-m2 \
    --reasoning-parser minimax-append-think \
    --host 0.0.0.0 \
    --trust-remote-code \
    --port 30000 \
    --mem-fraction-static 0.85
```

### 3.2 System Requirements

Recommended configurations — actual requirements depend on workload:

GPUs Context Length Support
4× 96 GB GPUs Up to 400K tokens
8× 144 GB GPUs Up to 3M tokens
### 3.3 Testing Deployment After the server starts, verify with: ```shell Command theme={null} curl http://localhost:30000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "model": "MiniMaxAI/MiniMax-M2", "messages": [ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]}, {"role": "user", "content": [{"type": "text", "text": "Who won the world series in 2020?"}]} ] }' ``` ## 4. Model Invocation ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) ### 4.2 Advanced Usage #### 4.2.1 Reasoning Parser Server Command: ```shell Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2 \ --tp-size 4 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 ``` Test Code: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Enable streaming to see the thinking process in real-time response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], temperature=0.6, max_tokens=2048, stream=True ) # Process the stream has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: # Close thinking section and add content header if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` Output Example: ```text Output theme={null} First, the user asks: "What is 15% of 240?" This is a straightforward percentage calculation. I need to solve it step by step as per the instruction. The problem is: What is 15% of 240? To find a percentage of a number, I multiply the number by the percentage divided by 100. So, 15% is 15/100, which simplifies to 0.15. Therefore, 15% of 240 is 240 times 0.15. Let me calculate that: 240 × 0.15. I can break it down: 240 × 0.15 = 240 × (15/100) = (240 × 15) / 100. Now, 240 × 15. 200 × 15 = 3000, and 40 × 15 = 600, so total 3000 + 600 = 3600. Then, divide by 100: 3600 / 100 = 36. So, 15% of 240 is 36. I should confirm this with another method. For example, 10% of 240 is 24, and 5% is half of that, which is 12. Then 15% is 10% + 5% = 24 + 12 = 36. Same answer. Or, using fractions: 15% = 3/20, so 240 × 3/20 = (240 / 20) × 3 = 12 × 3 = 36. All methods confirm it's 36. The user said "solve this problem step by step," so I should present the steps clearly. Step 1: Understand that "15% of 240" means 15 per hundred of 240. Step 2: Convert percentage to decimal: 15% = 15/100 = 0.15. Step 3: Multiply the number by the decimal: 240 × 0.15. Step 4: Calculate the multiplication: 240 × 0.15 = 36. Step 5: Therefore, 15% of 240 is 36. I should also mention that percentage means per hundred, so it's straightforward. Finally, I need to box the answer as per the instruction. So, the final answer is 36. To find 15% of 240, follow these steps: 1. **Understand the percentage**: "15%" means 15 per hundred, or 15/100. 2. **Convert to a decimal**: 15/100 = 0.15. 3. **Multiply by the number**: 240 × 0.15. 4. **Calculate the result**: - 240 × 0.15 = 36. Alternatively, you can break it down: - 10% of 240 is 24 (since 240 ÷ 10 = 24). - 5% of 240 is half of 10%, which is 12. - Therefore, 15% is 10% + 5% = 24 + 12 = 36. Both methods confirm the result. **Answer**: 36 ``` ### 4.2.2 Tool Calling Server Command: ```shell Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2 \ --tp-size 4 \ --tool-call-parser minimax-m2 \ --trust-remote-code \ --mem-fraction-static 0.85 ``` Test Code: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Make request with streaming to see thinking process response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, temperature=0.7, stream=True ) # Process streaming response thinking_started = False has_thinking = False tool_calls_accumulator = {} for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Accumulate tool calls if hasattr(delta, 'tool_calls') and delta.tool_calls: # Close thinking section if needed if has_thinking and thinking_started: print("\n=============== Content =================\n", flush=True) thinking_started = False for tool_call in delta.tool_calls: index = tool_call.index if index not in tool_calls_accumulator: tool_calls_accumulator[index] = { 'name': None, 'arguments': '' } if tool_call.function: if tool_call.function.name: tool_calls_accumulator[index]['name'] = tool_call.function.name if tool_call.function.arguments: tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments # Print content if delta.content: print(delta.content, end="", flush=True) # Print accumulated tool calls for index, tool_call in sorted(tool_calls_accumulator.items()): print(f"🔧 Tool Call: {tool_call['name']}") print(f" Arguments: {tool_call['arguments']}") print() ``` Output Example: ```text Output theme={null} Alright, the user is asking about the weather in Beijing. This is a straightforward request that I can help with using the get_weather tool that's available to me. Let me think about what I need to do here. The user wants to know the current weather conditions in Beijing, which is the capital city of China. To provide this information, I need to use the get_weather tool that's been provided to me. Looking at the tool's parameters, I can see it requires: 1. location - which is required and should be a string representing the city name 2. unit - which is optional and can be either "celsius" or "fahrenheit" For the location parameter, I'll use "Beijing" since that's what the user asked about. For the unit parameter, the user didn't specify their preference between celsius and fahrenheit. Since Beijing is in China, which primarily uses celsius, and celsius is the more standard unit internationally, I'll default to celsius. If the user wants the temperature in fahrenheit instead, they can ask in a follow-up message and I can provide that information. So I need to make a tool call to get_weather with the following parameters: - location: "Beijing" - unit: "celsius" This should return the current weather information for Beijing, which I can then share with the user. I'll format my response using the required XML tags for tool calls as specified in my instructions. 🔧 Tool Call: get_weather Arguments: {"location": "Beijing", "unit": "celsius"} ``` ## 5. Benchmark ### 5.1 Speed Benchmark **Test Environment**: * Hardware: AMD MI300X GPU(4x) * Model: MiniMax-M2 * Tensor Parallelism: 4 * sglang version: 0.5.7 **Model Deployment**: ```bash Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2 \ --tp-size 4 \ --trust-remote-code \ --mem-fraction-static 0.85 ``` ### 5.1.1 Low Concurrency (Latency-Optimized) * Benchmark Command: ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 138.91 Total input tokens: 6101 Total input text tokens: 6101 Total input vision tokens: 0 Total generated tokens: 4220 Total generated tokens (retokenized): 4220 Request throughput (req/s): 0.07 Input token throughput (tok/s): 43.92 Output token throughput (tok/s): 30.38 Peak output token throughput (tok/s): 46.00 Peak concurrent requests: 2 Total token throughput (tok/s): 74.30 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 13887.62 Median E2E Latency (ms): 10377.26 ---------------Time to First Token---------------- Mean TTFT (ms): 4528.94 Median TTFT (ms): 385.23 P99 TTFT (ms): 38338.51 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 22.21 Median TPOT (ms): 22.24 P99 TPOT (ms): 22.25 ---------------Inter-Token Latency---------------- Mean ITL (ms): 22.23 Median ITL (ms): 22.24 P95 ITL (ms): 22.35 P99 ITL (ms): 22.41 Max ITL (ms): 23.64 ================================================== ``` ### 5.1.2 Medium Concurrency (Balanced) * Benchmark Command: ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 81.07 Total input tokens: 39668 Total input text tokens: 39668 Total input vision tokens: 0 Total generated tokens: 40805 Total generated tokens (retokenized): 40803 Request throughput (req/s): 0.99 Input token throughput (tok/s): 489.29 Output token throughput (tok/s): 503.32 Peak output token throughput (tok/s): 704.00 Peak concurrent requests: 19 Total token throughput (tok/s): 992.61 Concurrency: 13.74 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 13925.95 Median E2E Latency (ms): 14348.75 ---------------Time to First Token---------------- Mean TTFT (ms): 532.32 Median TTFT (ms): 147.69 P99 TTFT (ms): 1978.48 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 27.49 Median TPOT (ms): 26.56 P99 TPOT (ms): 46.52 ---------------Inter-Token Latency---------------- Mean ITL (ms): 26.31 Median ITL (ms): 23.47 P95 ITL (ms): 24.37 P99 ITL (ms): 125.10 Max ITL (ms): 1192.51 ================================================== ``` ### 5.1.3 High Concurrency (Throughput-Optimized) * Benchmark Command: ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 153.71 Total input tokens: 249831 Total input text tokens: 249831 Total input vision tokens: 0 Total generated tokens: 252662 Total generated tokens (retokenized): 250982 Request throughput (req/s): 3.25 Input token throughput (tok/s): 1625.33 Output token throughput (tok/s): 1643.75 Peak output token throughput (tok/s): 2597.00 Peak concurrent requests: 107 Total token throughput (tok/s): 3269.09 Concurrency: 91.14 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 28017.24 Median E2E Latency (ms): 26865.28 ---------------Time to First Token---------------- Mean TTFT (ms): 387.41 Median TTFT (ms): 183.90 P99 TTFT (ms): 1192.44 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 55.23 Median TPOT (ms): 57.84 P99 TPOT (ms): 70.23 ---------------Inter-Token Latency---------------- Mean ITL (ms): 54.79 Median ITL (ms): 39.01 P95 ITL (ms): 143.10 P99 ITL (ms): 150.46 Max ITL (ms): 986.14 ================================================== ``` ### 5.2 Accuracy Benchmark #### 5.2.1 GSM8K Benchmark * **Server Command**: ```shell Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2 \ --tp-size 4 \ --trust-remote-code \ --mem-fraction-static 0.85 ``` * **Benchmark Command**: ```shell Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. * **Result**: * MiniMax-M2 ```text Output theme={null} Accuracy: 0.950 Invalid: 0.000 Latency: 15.120 s Output throughput: 1306.711 token/s ``` # MiniMax-M2.5 Source: https://docs.sglang.io/cookbook/autoregressive/MiniMax/MiniMax-M2.5 Deploy MiniMax-M2.5 with SGLang on NVIDIA, AMD, or Ascend A2, with an Ascend A3 reference configuration. ## 1. Model Introduction [MiniMax-M2.5](https://huggingface.co/MiniMaxAI/MiniMax-M2.5) is a powerful language model developed by MiniMax, built for real-world productivity with state-of-the-art performance across coding, reasoning, agentic tasks, and tool use. As the latest iteration in the MiniMax model series, MiniMax-M2.5 achieves comprehensive enhancements across multiple domains. Details are as follows: * **Superior coding performance**: Achieves 79.7 on Droid and 76.1 on OpenCode, surpassing Opus 4.6 (78.9 and 75.9 respectively). Strong results on SWE-bench Verified, SWE-bench Multilingual, SWE-bench-pro, and Multi-SWE-bench. * **Advanced reasoning**: Demonstrates strong performance on AIME25 and other reasoning benchmarks, with robust tool use during inference. * **More capable agents**: Excels in agentic tasks including web browsing (BrowseComp, Wide Search), information retrieval (RISE), and complex tool use scenarios (Terminal Bench 2, MEWC, Finance Modeling). * **Real-world productivity**: Designed for production-grade workloads with strong performance on practical coding, data analysis, and multi-step reasoning tasks. For more details, please refer to the [official MiniMax-M2.5 announcement](https://www.minimax.io/news/minimax-m25). ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](/docs/get-started/install) for installation instructions. **For AMD MI300X/MI325X/MI355X GPUs:** ```bash Command theme={null} # Docker (AMD MI300X/MI325X) docker pull lmsysorg/sglang:v0.5.9-rocm720-mi30x # Docker (AMD MI355X) docker pull lmsysorg/sglang:v0.5.9-rocm720-mi35x ``` ### Ascend A2 prerequisites (smoke tested) Select **Ascend A2** for the tested **8 × Ascend 910B4, 32 GiB HBM per device** configuration. It loads the W8A8 main model with TP=8 and serves one request at a time, without a draft model. The final run passed six simple chat checks and six synthetic generation probes, including 3500 input tokens plus 128 output tokens; see [the validation record](#5-4-ascend-a2-smoke-validation) for the runtime versions and test limits. 1. Prepare a compatible Ascend NPU runtime using the [NPU installation guide](/docs/hardware-platforms/ascend-npus/getting-started/installation). The tested runtime was SGLang `0.5.14.dev172+gf308abc05`, TorchNPU 2.10.0, and sgl-kernel-npu 2026.5.1. Follow-up inspection recorded CANN 9.0.0 and driver 25.5.2. An image digest was not captured; the A3 image below was not validated for this A2 run. 2. Run `npu-smi info` inside the container and confirm all eight 910B4 devices are visible and healthy. Reserve space for the approximately 230.82 GB main weights, download cache, and runtime. 3. Download the complete main model repository, including tokenizer and configuration files: ```bash Command theme={null} python -m pip install modelscope modelscope download --model Eco-Tech/MiniMax-M2.5-w8a8-QuaRot \ --local_dir /models/MiniMax-M2.5-w8a8-QuaRot ``` Enter absolute paths inside your container in the selector. Both directories default to the complete model directory. If you keep tokenizer files separately, use files from the same model revision and set **Tokenizer Directory** accordingly. The original experiment used separate metadata and weights directories, as recorded in section 5.4. ### Ascend A3 prerequisites (unvalidated reference) The A3 selector provides **one Ascend A3 node with 8 cards / 16 NPU dies**, running prefill and decode together (PD co-located). It uses W8A8 weights and EAGLE3 speculative decoding. Each A3 card contains two dies; a cloud allocation labelled "1 NPU" is not a full node. The [minimum recommended W8A8 configuration](/docs/hardware-platforms/ascend-npus/model-deployment/tutorials/minimax_m2_5#model-weights) is 4 cards / 8 dies with 64 GB per die, while this preset requires all 16 dies. > [!NOTE] > > This recipe is based on the upstream Ascend best practice. Hardware validation of the generated A3 cookbook command is pending; the reference accuracy and performance values below are not measurements of this recipe. The tested A2 selector is a separate low-concurrency configuration and does not validate the A3 preset. 1. Set up the Ascend runtime using the [MiniMax-M2.5 installation instructions](/docs/hardware-platforms/ascend-npus/model-deployment/tutorials/minimax_m2_5#installation). The reference environment uses CANN 9.0.0 and `quay.io/ascend/sglang:cann9.0.0-a3-v0.5.16`. Map `/dev/davinci0` through `/dev/davinci15` and mount your model directory into the container, for example `-v /path/to/models:/models`. 2. Check device health and allocation with `npu-smi info` inside the container. Confirm that all 16 dies are visible. For source builds, follow [installation with NPU support](/docs/hardware-platforms/ascend-npus/getting-started/installation), keep the CANN, TorchNPU, and kernel versions compatible, and record the SGLang commit you install. 3. Reserve space for the **230.82 GB** main weights, the draft model, download cache, and at least **30 GB** for the container image. Download both models below, or reuse complete copies from shared storage. | Role | Model | Directory inside the container | | - | - | - | | W8A8 main model | [Eco-Tech/MiniMax-M2.5-w8a8-QuaRot](https://www.modelscope.cn/models/Eco-Tech/MiniMax-M2.5-w8a8-QuaRot) | `/models/MiniMax-M2.5-w8a8-QuaRot` | | EAGLE3 draft model | [sgl-npu/MiniMax-M2.5-eagel-model-0318](https://www.modelscope.cn/models/sgl-npu/MiniMax-M2.5-eagel-model-0318) | `/models/MiniMax-M2.5-eagel-model-0318` | The draft repository identifier contains `eagel`; use that exact spelling. Keep its `custom_eagle3` Python package alongside the draft weights. The generated command adds this directory to `PYTHONPATH` and sets `SGLANG_EXTERNAL_MODEL_PACKAGE=custom_eagle3`. You can download the weights with the [ModelScope CLI](https://github.com/modelscope/modelscope/blob/master/docs/source/command.md#download): ```bash Command theme={null} python3 -m pip install modelscope modelscope download --model Eco-Tech/MiniMax-M2.5-w8a8-QuaRot \ --local_dir /models/MiniMax-M2.5-w8a8-QuaRot modelscope download --model sgl-npu/MiniMax-M2.5-eagel-model-0318 \ --local_dir /models/MiniMax-M2.5-eagel-model-0318 ``` Before launching, run `ip -brief address` and select an interface available inside the container for both HCCL and Gloo. The selector defaults to `lo` for this single-node setup. For comparable performance, use the host settings from the [selected 8-card reference](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/minimax_m2_5#minimax-m2-5-w8a8-8p-in3k5-out1k5-50ms). These affect the whole host; apply them on the dedicated benchmark server before running the generated command: ```bash Command theme={null} echo performance | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor sysctl -w vm.swappiness=0 sysctl -w kernel.numa_balancing=0 sysctl -w kernel.sched_migration_cost_ns=50000 ``` ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Select your hardware to generate the deployment command. For **Ascend A2**, complete the A2 prerequisites, expand **Deployment paths**, and enter the model and tokenizer directories; the command reproduces the tested single-request settings on port 31216. For **Ascend A3**, complete its separate prerequisites, expand **Deployment paths and network**, enter both model directories as absolute paths inside the container, and set the HCCL / Gloo interface. The unvalidated A3 preset uses 3,500 input and 1,500 output tokens as its reference workload. Run this Command:

### 3.2 Configuration Tips

**GPU parameters:** The following recommendations apply to the NVIDIA and AMD recipes. The Ascend presets use the separate settings described below.

Parameter Description Recommended Value
`--tool-call-parser` Tool call parser for function calling support `minimax-m2`
`--reasoning-parser` Reasoning parser for thinking mode `minimax-append-think`
`--trust-remote-code` Required for MiniMax model loading Always enabled
`--mem-fraction-static` Static memory fraction for KV cache `0.85`
`--tp` Tensor parallelism size `2` (2-GPU) or `4` (4-GPU) or `8` (8-GPU)
`--ep` Expert parallelism size `8` (NVIDIA 8-GPU) or EP=TP (AMD)
`--kv-cache-dtype` KV cache data type (AMD only) `fp8_e4m3`
`--attention-backend` Attention backend (AMD only) `triton`
**Hardware Requirements: NVIDIA** * **4-GPU deployment**: Requires 4× high-memory GPUs (e.g., H200, B200, A100, H100) with TP=4 * **8-GPU deployment**: Requires 8× GPUs (e.g., H200, B200, A100, H100) with TP=8 and EP=8 **Hardware Requirements: AMD** * **2-GPU deployment**: Requires 2× high-memory GPUs (e.g., MI300X, MI325X, MI355X) with TP=2, EP=2 * **4-GPU deployment**: Requires 4× GPUs (e.g., MI300X, MI325X, MI355X) with TP=4, EP=4 * **8-GPU deployment**: Requires 8× GPUs (e.g., MI300X, MI325X, MI355X) with TP=8, EP=8 ### 3.3 Ascend A3 configuration (unvalidated reference) The generated A3 command follows the [8-card throughput reference](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/minimax_m2_5#minimax-m2-5-w8a8-8p-in3k5-out1k5-50ms). Keep the environment variables and server arguments together when reproducing that workload. | Setting | A3 preset | Purpose | | - | - | - | | Device and parallelism | `--device npu --tp-size 16 --dp-size 16 --enable-dp-attention` | Use 16 dies on one node with DP attention. | | Quantization and communication | `--quantization modelslim --moe-a2a-backend ascend_fuseep --fuseep-mode 2` | Run the Ascend W8A8 weights with FuseEP. | | Speculative decoding | EAGLE3, 3 steps, top-k 1, 4 draft tokens, unquantized draft | Load the custom draft model from the supplied directory. | | Static memory and concurrency | `--mem-fraction-static 0.75 --max-running-requests 320` | Use the memory and request limits of the reference workload. | | Prefill | Chunk size 196608, maximum prefill tokens 8192, prefill delayer enabled | Match the reference scheduling configuration. | | NPU graph batches | `--cuda-graph-bs-decode 1 2 4 8 12 16 20` | Set capture sizes; the argument retains `cuda` in its name on NPU. | | API | `127.0.0.1:6688` | Send requests from the same host or container network. | The A3 preset fixes the reasoning parser to `minimax-append-think` and the tool parser to `minimax-m2`. The shared form displays a fixed 8-card count and enabled parsers; these controls are read-only for this preset. To use fewer A3 cards or a different workload, follow the corresponding [Ascend best practice](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/minimax_m2_5) with its complete configuration. ### 3.4 Ascend A2 configuration (smoke tested) The A2 selector fixes TP=8, ModelSlim quantization, BF16, `--context-length 4096`, and `--max-running-requests 1`. It uses prefill chunks of 128, maximum prefill tokens of 4096, static memory fraction 0.96, and `--max-total-tokens 4096`, and disables graph capture and radix cache. No EAGLE3 draft model is required. The `minimax` reasoning parser separated reasoning from answer content in the tested runtime. The `minimax-m2` tool-call parser is configured, but tool calling was not tested. The shared form displays a fixed 8-card count and enabled parsers; these controls are read-only for this preset. The final run allocated a **4096-token KV pool on all eight ranks** and completed a synthetic 3500-input/128-output request. This validates that request size on this allocation, not every workload up to the configured limit. See section 5.4 for the earlier capacity failure and the final measurements. GPQA accuracy, standardized throughput, and sustained stability remain unmeasured for this single-request preset; [section 5.5](#5-5-ascend-a2-performance-benchmark) reports synthetic performance measurements using a separate server configuration with concurrency up to 8. ## 4. Model Invocation For the **Ascend A3** preset, use [the A3 service checks](#4-3-verify-the-ascend-a3-service), which target port 6688 and read the deployed model identifier from `/v1/models`. The GPU examples below use their own model identifier and endpoints. For **Ascend A2**, use `http://127.0.0.1:31216/v1` from the same host or container network. After startup completes, this short request uses the settings from the smoke test: ```python Example theme={null} from openai import OpenAI client = OpenAI(base_url="http://127.0.0.1:31216/v1", api_key="EMPTY") model = client.models.list().data[0].id response = client.chat.completions.create( model=model, messages=[{"role": "user", "content": "What is the capital of France? Answer with the city name only."}], temperature=0, max_tokens=512, ) print(response.choices[0].message.content) ``` ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](/docs/basic_usage/send_request) **Testing Deployment:** After startup, you can test the SGLang OpenAI-compatible API with the following command: ```bash Command theme={null} curl http://localhost:8000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "model": "MiniMaxAI/MiniMax-M2.5", "messages": [ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]}, {"role": "user", "content": [{"type": "text", "text": "Who won the world series in 2020?"}]} ] }' ``` **Simple Completion Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2.5", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ], max_tokens=1024 ) print(response.choices[0].message.content) ``` **Example Output**: ```text Output theme={null} The user asks: "Who won the world series in 2020?" That is a straightforward factual question. The answer: the Los Angeles Dodgers. They won the 2020 World Series, beating the Tampa Bay Rays. The user is presumably expecting that answer. We must follow the policies. The question is safe: no disallowed content. It's just a factual question. Provide answer. We must ensure compliance: Use no disallowed content. Should we provide context? Just answer straightforwardly. The user simply asks "Who won the world series in 2020?" We'll answer: The Los Angeles Dodgers. No additional relevant info needed, but could elaborate briefly: They beat the Tampa Bay Rays in six games, the series was played in a bubble at Globe Life Field in Arlington, Texas due to COVID-19. No need for any extra. That's it. The Los Angeles Dodgers won the 2020 World Series, defeating the Tampa Bay Rays in six games. ``` ### 4.2 Advanced Usage #### 4.2.1 Reasoning Parser MiniMax-M2.5 supports Thinking mode. Enable the reasoning parser during deployment to separate the thinking and the content sections: ```shell Command theme={null} python -m sglang.launch_server \ --model-path MiniMaxAI/MiniMax-M2.5 \ --tp 4 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 ``` **Streaming with Thinking Process** With `minimax-append-think`, the thinking content is wrapped in `...` tags within the `content` field. You can parse these tags on the client side to separate the thinking and content sections: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) # Enable streaming to see the thinking process in real-time response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2.5", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], temperature=0.7, max_tokens=2048, stream=True ) # Process the stream, separating ... from content in_think = False think_printed_header = False content_printed_header = False buffer = "" for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if delta.content: buffer += delta.content while buffer: if in_think: # Look for closing tag end_idx = buffer.find("") if end_idx != -1: print(buffer[:end_idx], end="", flush=True) buffer = buffer[end_idx + len(""):] in_think = False else: # Still in thinking, print what we have print(buffer, end="", flush=True) buffer = "" else: # Look for opening tag start_idx = buffer.find("") if start_idx != -1: # Print any content before before = buffer[:start_idx] if before: if not content_printed_header: print("=============== Content =================", flush=True) content_printed_header = True print(before, end="", flush=True) buffer = buffer[start_idx + len(""):] in_think = True if not think_printed_header: print("=============== Thinking =================", flush=True) think_printed_header = True else: # No tag, print as content if not content_printed_header and think_printed_header: print("\n=============== Content =================", flush=True) content_printed_header = True print(buffer, end="", flush=True) buffer = "" print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user asks: "Solve this problem step by step: What is 15% of 240?" This is straightforward: 15% = 0.15; 0.15*240 = 36. So answer: 36. Provide step-by-step: convert percent to decimal, multiply. We need to obey policies. There's no policy violation. Just answer. Provide step by step. Should respond with solution. We can also mention alternative method: 15% = 15/100 = 3/20. Multiply 240 * 3/20 = (240/20)*3 = 12*3 = 36. Thus answer 36. We can add step-by-step. That's it. =============== Content ================= **Step‑by‑step solution** 1. **Convert the percent to a decimal** \[ 15\% = \frac{15}{100}=0.15 \] 2. **Multiply the decimal by the number** \[ 0.15 \times 240 = 36 \] (You can also think of it as \(15\% = \frac{3}{20}\) and then \(240 \times \frac{3}{20}=12 \times 3 = 36\).) \[ \boxed{36} \] ``` **Note:** The `minimax-append-think` reasoning parser embeds the thinking process in `...` tags within the `content` field. The code above parses these tags in real-time to display thinking and content separately. #### 4.2.2 Tool Calling MiniMax-M2.5 supports tool calling capabilities. Enable the tool call parser: ```shell Command theme={null} python -m sglang.launch_server \ --model-path MiniMaxAI/MiniMax-M2.5 \ --tp 4 \ --tool-call-parser minimax-m2 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 ``` **Python Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Non-streaming request response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2.5", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, temperature=0.7 ) message = response.choices[0].message # Check for tool calls if message.tool_calls: for tool_call in message.tool_calls: print(f"Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") else: print(message.content) ``` **Output Example**: ```text Output theme={null} Tool Call: get_weather Arguments: {"location": "Beijing"} ``` **Note:** * Tool calls are returned in `message.tool_calls` with the function name and arguments * You can then execute the function and send the result back to continue the conversation **Handling Tool Call Results:** ```python Example theme={null} # After getting the tool call, execute the function def get_weather(location, unit="celsius"): # Your actual weather API call here return f"The weather in {location} is 22°{unit[0].upper()} and sunny." # Send tool result back to the model messages = [ {"role": "user", "content": "What's the weather in Beijing?"}, { "role": "assistant", "content": None, "tool_calls": [{ "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": '{"location": "Beijing", "unit": "celsius"}' } }] }, { "role": "tool", "tool_call_id": "call_123", "content": get_weather("Beijing", "celsius") } ] final_response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2.5", messages=messages, temperature=0.7 ) print(final_response.choices[0].message.content) # Output: "The weather in Beijing is currently 22°C and sunny." ``` ### 4.3 Verify the Ascend A3 service Wait for the server to finish loading the weights and capturing graphs. Keep the generated command running, then open another terminal in the same container. The A3 preset listens on port **6688**. ```bash Command theme={null} curl --fail --silent --show-error --max-time 30 http://127.0.0.1:6688/health curl --fail --silent --show-error --max-time 30 http://127.0.0.1:6688/v1/models python3 - <<'PY' import json from urllib.request import Request, urlopen base = "http://127.0.0.1:6688" with urlopen(f"{base}/v1/models", timeout=30) as response: model = json.load(response)["data"][0]["id"] payload = { "model": model, "messages": [{"role": "user", "content": "What is the capital of France?"}], "temperature": 0, "max_tokens": 2048, } request = Request( f"{base}/v1/chat/completions", data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}, ) with urlopen(request, timeout=300) as response: result = json.load(response) print(json.dumps(result, indent=2, ensure_ascii=False)) choice = result["choices"][0] assert (choice["message"].get("content") or "").strip(), "No final answer returned" assert choice["finish_reason"] != "length", "Increase the token budget and retry" PY ``` Check that the final answer identifies Paris. Repeat requests and check the server logs for runtime errors. After any concurrent test, check `/health` again. A successful HTTP response alone does not establish model accuracy; use the evaluation below for that. ## 5. Benchmark For **Ascend A3**, use [the A3 throughput and accuracy benchmarks](#5-3-ascend-a3-benchmarks) with the command generated in section 3. For **Ascend A2**, [section 5.4](#5-4-ascend-a2-smoke-validation) records simple chat checks and serial synthetic generation probes. [Section 5.5](#5-5-ascend-a2-performance-benchmark) reports the official benchmark tool's results on a separate configuration with concurrency up to 8 and a synthetic workload. [Section 5.6](#5-6-ascend-a2-reference-length-performance) measures 3500-input/1500-output requests, and [section 5.7](#5-7-ascend-a2-fixed-50-question-gsm8k-regression) records a fixed 50-question GSM8K deployment regression. No GPQA accuracy result is reported here. The benchmark sections below use **industry-standard configurations** for comparable benchmark results; the A2 smoke record has a separate, limited scope. ### 5.1 Speed Benchmark **Test Environment**: * Hardware: NVIDIA B200 GPU (8x) * Model: MiniMax-M2.5 * Tensor Parallelism: 8 * Expert Parallelism: 8 * sglang version: 0.5.8 #### 5.1.1 Standard Scenario Benchmark * Model Deployment Command: ```shell Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2.5 \ --tp 8 \ --ep 8 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 \ --tool-call-parser minimax-m2 ``` ##### 5.1.1.1 Low Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 42.99 Total input tokens: 6091 Total input text tokens: 6091 Total generated tokens: 4220 Total generated tokens (retokenized): 3804 Request throughput (req/s): 0.23 Input token throughput (tok/s): 141.70 Output token throughput (tok/s): 98.17 Peak output token throughput (tok/s): 102.00 Peak concurrent requests: 2 Total token throughput (tok/s): 239.87 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 4295.92 Median E2E Latency (ms): 3419.28 P90 E2E Latency (ms): 7832.04 P99 E2E Latency (ms): 9601.40 ---------------Time to First Token---------------- Mean TTFT (ms): 130.57 Median TTFT (ms): 116.10 P99 TTFT (ms): 190.90 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 9.89 Median TPOT (ms): 9.89 P99 TPOT (ms): 9.91 ---------------Inter-Token Latency---------------- Mean ITL (ms): 9.89 Median ITL (ms): 9.89 P95 ITL (ms): 10.15 P99 ITL (ms): 10.32 Max ITL (ms): 14.46 ================================================== ``` ##### 5.1.1.2 Medium Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 48.43 Total input tokens: 39588 Total input text tokens: 39588 Total generated tokens: 40805 Total generated tokens (retokenized): 37142 Request throughput (req/s): 1.65 Input token throughput (tok/s): 817.37 Output token throughput (tok/s): 842.49 Peak output token throughput (tok/s): 1184.00 Peak concurrent requests: 21 Total token throughput (tok/s): 1659.86 Concurrency: 13.67 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 8274.32 Median E2E Latency (ms): 8692.90 P90 E2E Latency (ms): 13690.70 P99 E2E Latency (ms): 16104.18 ---------------Time to First Token---------------- Mean TTFT (ms): 305.44 Median TTFT (ms): 106.75 P99 TTFT (ms): 1053.26 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 16.20 Median TPOT (ms): 16.06 P99 TPOT (ms): 26.75 ---------------Inter-Token Latency---------------- Mean ITL (ms): 15.65 Median ITL (ms): 13.63 P95 ITL (ms): 14.90 P99 ITL (ms): 87.99 Max ITL (ms): 483.53 ================================================== ``` ##### 5.1.1.3 High Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 92.31 Total input tokens: 249331 Total input text tokens: 249331 Total generated tokens: 252662 Total generated tokens (retokenized): 218975 Request throughput (req/s): 5.42 Input token throughput (tok/s): 2700.94 Output token throughput (tok/s): 2737.02 Peak output token throughput (tok/s): 4479.00 Peak concurrent requests: 109 Total token throughput (tok/s): 5437.97 Concurrency: 91.19 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 16835.82 Median E2E Latency (ms): 16042.08 P90 E2E Latency (ms): 31027.63 P99 E2E Latency (ms): 34787.91 ---------------Time to First Token---------------- Mean TTFT (ms): 391.06 Median TTFT (ms): 133.12 P99 TTFT (ms): 1712.92 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 33.04 Median TPOT (ms): 34.29 P99 TPOT (ms): 41.98 ---------------Inter-Token Latency---------------- Mean ITL (ms): 32.61 Median ITL (ms): 21.67 P95 ITL (ms): 87.76 P99 ITL (ms): 118.81 Max ITL (ms): 1145.62 ================================================== ``` #### 5.1.2 Summarization Scenario Benchmark * Model Deployment Command: ```shell Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2.5 \ --tp 8 \ --ep 8 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 \ --tool-call-parser minimax-m2 ``` ##### 5.1.2.1 Low Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 43.49 Total input tokens: 41941 Total input text tokens: 41941 Total generated tokens: 4220 Total generated tokens (retokenized): 4220 Request throughput (req/s): 0.23 Input token throughput (tok/s): 964.42 Output token throughput (tok/s): 97.04 Peak output token throughput (tok/s): 102.00 Peak concurrent requests: 2 Total token throughput (tok/s): 1061.46 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 4346.83 Median E2E Latency (ms): 3508.84 P90 E2E Latency (ms): 7972.23 P99 E2E Latency (ms): 9659.71 ---------------Time to First Token---------------- Mean TTFT (ms): 131.50 Median TTFT (ms): 126.76 P99 TTFT (ms): 182.52 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 10.00 Median TPOT (ms): 10.01 P99 TPOT (ms): 10.12 ---------------Inter-Token Latency---------------- Mean ITL (ms): 10.01 Median ITL (ms): 10.02 P95 ITL (ms): 10.29 P99 ITL (ms): 10.44 Max ITL (ms): 14.11 ================================================== ``` ##### 5.1.2.2 Medium Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 50.12 Total input tokens: 300020 Total input text tokens: 300020 Total generated tokens: 41669 Total generated tokens (retokenized): 41662 Request throughput (req/s): 1.60 Input token throughput (tok/s): 5986.00 Output token throughput (tok/s): 831.38 Peak output token throughput (tok/s): 1152.00 Peak concurrent requests: 20 Total token throughput (tok/s): 6817.38 Concurrency: 13.93 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 8727.66 Median E2E Latency (ms): 9170.52 P90 E2E Latency (ms): 14220.00 P99 E2E Latency (ms): 16896.54 ---------------Time to First Token---------------- Mean TTFT (ms): 282.56 Median TTFT (ms): 149.37 P99 TTFT (ms): 1278.62 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 16.60 Median TPOT (ms): 16.61 P99 TPOT (ms): 25.17 ---------------Inter-Token Latency---------------- Mean ITL (ms): 16.24 Median ITL (ms): 13.89 P95 ITL (ms): 15.96 P99 ITL (ms): 105.79 Max ITL (ms): 1065.02 ================================================== ``` ##### 5.1.2.3 High Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 320 \ --max-concurrency 64 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 93.92 Total input tokens: 1273893 Total input text tokens: 1273893 Total generated tokens: 170000 Total generated tokens (retokenized): 169999 Request throughput (req/s): 3.41 Input token throughput (tok/s): 13563.30 Output token throughput (tok/s): 1810.01 Peak output token throughput (tok/s): 2881.00 Peak concurrent requests: 71 Total token throughput (tok/s): 15373.31 Concurrency: 58.87 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 17277.69 Median E2E Latency (ms): 16827.33 P90 E2E Latency (ms): 29045.40 P99 E2E Latency (ms): 33496.77 ---------------Time to First Token---------------- Mean TTFT (ms): 692.26 Median TTFT (ms): 188.46 P99 TTFT (ms): 4932.70 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 32.19 Median TPOT (ms): 32.69 P99 TPOT (ms): 50.46 ---------------Inter-Token Latency---------------- Mean ITL (ms): 31.28 Median ITL (ms): 21.59 P95 ITL (ms): 101.35 P99 ITL (ms): 136.74 Max ITL (ms): 4649.23 ================================================== ``` #### 5.1.3 H100 Benchmark **Test Environment**: * Hardware: NVIDIA H100 80GB HBM3 GPU (8x) * Model: MiniMax-M2.5 * Tensor Parallelism: 8 * Expert Parallelism: 8 * sglang version: 0.5.9 * Model Deployment Command: ```shell Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2.5 \ --tp 8 \ --ep 8 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 \ --tool-call-parser minimax-m2 ``` ##### 5.1.3.1 Low Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 35.44 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 4220 Request throughput (req/s): 0.28 Input token throughput (tok/s): 172.16 Output token throughput (tok/s): 119.08 Peak output token throughput (tok/s): 127.00 Peak concurrent requests: 2 Total token throughput (tok/s): 291.24 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 3542.38 Median E2E Latency (ms): 2791.92 P90 E2E Latency (ms): 6317.77 P99 E2E Latency (ms): 7780.15 ---------------Time to First Token---------------- Mean TTFT (ms): 145.20 Median TTFT (ms): 80.38 P99 TTFT (ms): 633.08 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 8.05 Median TPOT (ms): 8.08 P99 TPOT (ms): 8.09 ---------------Inter-Token Latency---------------- Mean ITL (ms): 8.07 Median ITL (ms): 8.08 P95 ITL (ms): 8.12 P99 ITL (ms): 8.16 Max ITL (ms): 10.10 ================================================== ``` ##### 5.1.3.2 Medium Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 43.68 Total input tokens: 39668 Total input text tokens: 39668 Total generated tokens: 40805 Total generated tokens (retokenized): 40805 Request throughput (req/s): 1.83 Input token throughput (tok/s): 908.19 Output token throughput (tok/s): 934.22 Peak output token throughput (tok/s): 1184.00 Peak concurrent requests: 20 Total token throughput (tok/s): 1842.42 Concurrency: 13.83 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 7551.91 Median E2E Latency (ms): 8094.28 P90 E2E Latency (ms): 12606.99 P99 E2E Latency (ms): 14977.84 ---------------Time to First Token---------------- Mean TTFT (ms): 116.86 Median TTFT (ms): 82.33 P99 TTFT (ms): 240.59 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 14.81 Median TPOT (ms): 14.98 P99 TPOT (ms): 17.98 ---------------Inter-Token Latency---------------- Mean ITL (ms): 14.61 Median ITL (ms): 13.50 P95 ITL (ms): 14.15 P99 ITL (ms): 66.52 Max ITL (ms): 107.39 ================================================== ``` ##### 5.1.3.3 High Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.5 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 80.63 Total input tokens: 249831 Total input text tokens: 249831 Total generated tokens: 252662 Total generated tokens (retokenized): 252331 Request throughput (req/s): 6.20 Input token throughput (tok/s): 3098.45 Output token throughput (tok/s): 3133.56 Peak output token throughput (tok/s): 4800.00 Peak concurrent requests: 113 Total token throughput (tok/s): 6232.01 Concurrency: 90.56 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 14604.59 Median E2E Latency (ms): 14044.04 P90 E2E Latency (ms): 26456.53 P99 E2E Latency (ms): 30136.68 ---------------Time to First Token---------------- Mean TTFT (ms): 149.32 Median TTFT (ms): 95.16 P99 TTFT (ms): 374.62 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 28.92 Median TPOT (ms): 30.09 P99 TPOT (ms): 34.31 ---------------Inter-Token Latency---------------- Mean ITL (ms): 28.66 Median ITL (ms): 21.52 P95 ITL (ms): 66.90 P99 ITL (ms): 96.76 Max ITL (ms): 376.34 ================================================== ``` ### 5.2 Accuracy Benchmark #### 5.2.1 GSM8K Benchmark * Benchmark Command: ```shell Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 \ --num-threads 64 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. * Test Results: ```text Output theme={null} Accuracy: 0.950 Invalid: 0.000 Latency: 18.033 s Output throughput: 1130.161 token/s ``` #### 5.2.2 MMLU Benchmark * Benchmark Command: ```shell Command theme={null} sgl-eval run mmlu \ --base-url http://127.0.0.1:30000/v1 \ --num-threads 64 --max-tokens 2048 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. * Test Results: ```text Output theme={null} subject: abstract_algebra, #q:100, acc: 0.620 subject: anatomy, #q:135, acc: 0.830 subject: astronomy, #q:152, acc: 0.928 subject: business_ethics, #q:100, acc: 0.810 subject: clinical_knowledge, #q:265, acc: 0.891 subject: college_biology, #q:144, acc: 0.951 subject: college_chemistry, #q:100, acc: 0.670 subject: college_computer_science, #q:100, acc: 0.820 subject: college_mathematics, #q:100, acc: 0.660 subject: college_medicine, #q:173, acc: 0.832 subject: college_physics, #q:102, acc: 0.814 subject: computer_security, #q:100, acc: 0.880 subject: conceptual_physics, #q:235, acc: 0.915 subject: econometrics, #q:114, acc: 0.719 subject: electrical_engineering, #q:145, acc: 0.834 subject: elementary_mathematics, #q:378, acc: 0.902 subject: formal_logic, #q:126, acc: 0.698 subject: global_facts, #q:100, acc: 0.710 subject: high_school_biology, #q:310, acc: 0.926 subject: high_school_chemistry, #q:203, acc: 0.793 subject: high_school_computer_science, #q:100, acc: 0.910 subject: high_school_european_history, #q:165, acc: 0.879 subject: high_school_geography, #q:198, acc: 0.955 subject: high_school_government_and_politics, #q:193, acc: 0.964 subject: high_school_macroeconomics, #q:390, acc: 0.908 subject: high_school_mathematics, #q:270, acc: 0.600 subject: high_school_microeconomics, #q:238, acc: 0.954 subject: high_school_physics, #q:151, acc: 0.781 subject: high_school_psychology, #q:545, acc: 0.956 subject: high_school_statistics, #q:216, acc: 0.847 subject: high_school_us_history, #q:204, acc: 0.922 subject: high_school_world_history, #q:237, acc: 0.916 subject: human_aging, #q:223, acc: 0.839 subject: human_sexuality, #q:131, acc: 0.893 subject: international_law, #q:121, acc: 0.934 subject: jurisprudence, #q:108, acc: 0.861 subject: logical_fallacies, #q:163, acc: 0.890 subject: machine_learning, #q:112, acc: 0.750 subject: management, #q:103, acc: 0.883 subject: marketing, #q:234, acc: 0.944 subject: medical_genetics, #q:100, acc: 0.920 subject: miscellaneous, #q:783, acc: 0.936 subject: moral_disputes, #q:346, acc: 0.829 subject: moral_scenarios, #q:895, acc: 0.632 subject: nutrition, #q:306, acc: 0.863 subject: philosophy, #q:311, acc: 0.833 subject: prehistory, #q:324, acc: 0.907 subject: professional_accounting, #q:282, acc: 0.720 subject: professional_law, #q:1534, acc: 0.640 subject: professional_medicine, #q:272, acc: 0.923 subject: professional_psychology, #q:612, acc: 0.871 subject: public_relations, #q:110, acc: 0.773 subject: security_studies, #q:245, acc: 0.845 subject: sociology, #q:201, acc: 0.930 subject: us_foreign_policy, #q:100, acc: 0.940 subject: virology, #q:166, acc: 0.614 subject: world_religions, #q:171, acc: 0.895 Total latency: 81.468 Average accuracy: 0.825 ``` ### 5.3 Ascend A3 benchmarks Use the A3 command generated in section 3 for both accuracy and performance evaluation. Record the SGLang commit, container image digest, CANN / TorchNPU / kernel versions, model revisions, visible dies, and host tuning with your logs. When testing `main`, record the installed source commit separately from the base container tag. #### 5.3.1 Throughput workload The [Ascend reference](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/minimax_m2_5#minimax-m2-5-w8a8-8p-in3k5-out1k5-50ms) lists **50 ms TPOT** for 8 A3 cards, W8A8, PD co-located, and 3.5k input / 1.5k output tokens. This is a reference value, not a measurement from a different allocation or software build. The reference table does not specify the TPOT percentile. After warm-up, run the reference workload from the same container: ```bash Command theme={null} set -o pipefail python3 -m sglang.bench_serving \ --dataset-name random \ --backend sglang \ --host 127.0.0.1 \ --port 6688 \ --max-concurrency 320 \ --num-prompts 1280 \ --random-input-len 3500 \ --random-output-len 1500 \ --random-range-ratio 1 \ --seed 1 2>&1 | tee minimax-a3-throughput.log ``` Keep the request success and failure counts, actual token counts, output and total token throughput, TTFT, TPOT, and end-to-end latency. Report mean, median, and P99 separately. Repeat the measurement with separate logs and check server health afterwards. Changes to concurrency, quantization, speculative decoding, or token lengths define a different benchmark configuration. #### 5.3.2 GPQA Diamond accuracy Install EvalScope in a separate environment following [Ascend accuracy evaluation](/docs/hardware-platforms/ascend-npus/evaluation/accuracy_evaluation). Keep the SGLang server running with the generated A3 command. The following request configuration follows the [upstream 8-card GPQA test](https://github.com/sgl-project/sglang/blob/c389dd086340878934bf96bc209534f1fbb8440c/test/registered/npu/accuracy/minimax_m2_5/test_npu_minimax_m2_5_w8a8_8p_in3k5_out1k5_50ms_gpqa.py): ```python evaluate_minimax_a3.py theme={null} import json from urllib.request import urlopen from evalscope import TaskConfig, run_task with urlopen("http://127.0.0.1:6688/v1/models", timeout=30) as response: model = json.load(response)["data"][0]["id"] run_task(task_cfg=TaskConfig( model=model, api_url="http://127.0.0.1:6688/v1/chat/completions", eval_type="openai_api", datasets=["gpqa_diamond"], eval_batch_size=64, generation_config={"max_tokens": 65536, "temperature": 1.0}, timeout=60000, stream=True, work_dir="./minimax-a3-gpqa", )) ``` Run the full **198-question** dataset and retain the EvalScope version, dataset revision, generation settings, reports, and all attempt scores. The upstream test declares an accuracy baseline of **0.852**; its [comparison utility](https://github.com/sgl-project/sglang/blob/c389dd086340878934bf96bc209534f1fbb8440c/python/sglang/test/ascend/e2e/test_npu_accuracy_utils.py) allows a fluctuation of 5 questions, giving a threshold of `0.852 - 5/198`, approximately **0.8267**, with up to 3 attempts. These are upstream validation criteria, not measured accuracy for this cookbook command. ### 5.4 Ascend A2 smoke validation On September 22, 2026, the W8A8 main model completed loading, warm-up, and three short chat requests on **8 Ascend 910B4 devices with 32 GiB HBM each**. Eight-rank HCCL all-reduce and BF16 matrix operations also passed. The final September 23 run increased the static memory fraction to 0.96 and set `--max-total-tokens 4096`; these are the settings now exposed by the **Ascend A2** selector. These experiments used no EAGLE3 draft model and are separate from the A3 reference configuration. The runtime was SGLang `0.5.14.dev172+gf308abc05` (commit `f308abc05212c2f5f455de22a525e14afa63ee4f`), Python 3.11.15, Torch 2.10.0+cpu, TorchNPU 2.10.0, Transformers 5.8.1, and sgl-kernel-npu 2026.5.1. A follow-up inspection of the same environment on September 23 recorded CANN 9.0.0 and driver 25.5.2. The supplied environment had modified `python/pyproject.toml` and a deleted `python/pyproject_npu.toml`; this was not a clean source-build validation. An image digest and immutable model revision were not captured, so this record is not a fully pinned environment specification. After downloading the W8A8 main model listed above, the final tested service settings were: ```bash Command theme={null} export HCCL_BUFFSIZE=128 export OMP_NUM_THREADS=1 export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True python -m sglang.launch_server \ --model-path /workspace/issue1215/model \ --tokenizer-path /workspace/issue1215/metadata \ --device npu --tp-size 8 --quantization modelslim --dtype bfloat16 \ --reasoning-parser minimax --tool-call-parser minimax-m2 \ --host 127.0.0.1 --port 31216 \ --context-length 4096 --max-running-requests 1 \ --chunked-prefill-size 128 --max-prefill-tokens 4096 \ --mem-fraction-static 0.96 --max-total-tokens 4096 \ --disable-cuda-graph --disable-radix-cache ``` The paths above are the experiment paths: `model` contains the complete main weights, while `metadata` contains the tokenizer and configuration files from the same model repository, downloaded separately while weights were transferring. Replace both paths with your local directories. The selector defaults both paths to one complete repository directory; this path convenience differs from the original experiment's separate metadata directory. Keep tokenizer and weights from the same revision. The original September 22 requests used `/v1/chat/completions`, `temperature=0`, and `max_tokens=512`: | Prompt | Answer content | Finish reason | | - | - | - | | What is the capital of France? Answer with the city name only. | `Paris` | `stop` | | 请用中文回答:2加2等于多少? | `2加2等于4。` | `stop` | | Return only a JSON object with one key named result whose value is 7 \* 8. | `{"result":56}` (parsed JSON) | `stop` | The `minimax` reasoning parser separated reasoning from answer content in this runtime. The three answers contained no thinking tags, and the final health check returned HTTP 200. The tool-call parser was configured but tool calling was not tested. **Earlier baseline:** a September 23 serial follow-up retained `--mem-fraction-static 0.95` without an explicit total-token setting. After two warm-up requests, five of six simple answer checks passed; the JSON check exhausted its 128-token output budget and was inconclusive. Reasoning consumes that budget as well as final-answer tokens. Startup allocated 896 KV tokens; requests with 1024 and 2048 input tokens were rejected with `BadRequestError`, reporting a maximum input length of 890. The client stopped after those two failures, before attempting 3500 input tokens, and the subsequent health check returned HTTP 200. These limits describe the earlier baseline, not the final configuration above. **Final September 23 run:** with memory fraction 0.96 and `--max-total-tokens 4096`, startup reported 4096 allocated KV tokens on each of the eight ranks. After two warm-up requests, all six chat checks passed with `temperature=0`, `max_tokens=512`, and finish reason `stop`: | Check | Answer content | Completion tokens | End-to-end time (s) | First observed output (s) | | - | - | - | - | - | | Capital of France | `Paris` | 87 | 21.172 | 0.474 | | 2 + 2 | `4` | 53 | 12.598 | 0.466 | | JSON object for 7 × 8 | `{"result":56}` | 185 | 43.747 | 0.477 | | 中国首都 | `北京` | 138 | 31.891 | 0.456 | | Copy a word | `orchard` | 73 | 16.724 | 0.459 | | Sort 3, 1, 2 as a JSON array | `[1,2,3]` | 142 | 33.590 | 0.465 | Six native `/generate` probes used exact input-token IDs from `/v1/tokenize`, requested 128 output tokens, and set `ignore_eos=true`. All completed with exactly 128 output tokens and the expected length limit. The inputs were synthetic repeated text: these are individual operational measurements, not a quality evaluation or standardized throughput benchmark. | Input tokens | Output tokens | End-to-end time (s) | First observed output (s) | | - | - | - | - | | 64 | 128 | 29.970 | 0.494 | | 128 | 128 | 29.313 | 0.478 | | 256 | 128 | 30.193 | 0.700 | | 1024 | 128 | 32.165 | 2.103 | | 2048 | 128 | 34.451 | 4.218 | | 3500 | 128 | 39.803 | 10.055 | Timing includes HTTP/SSE processing and ends at the stream's `DONE` event. First output means the first nonempty content or reasoning for chat, or the first text or positive output-token count for native generation; it is not the time to the final answer or a kernel timing. Completion counts include reasoning and special tokens as reported by the server. Parser buffering and chunks containing multiple tokens can affect observed timing. No cache flush was performed. Each input length was measured once at concurrency 1, so these results do not establish a latency percentile or saturation throughput. The final probe run completed and its post-run health check returned HTTP 200. Confirm startup KV allocation and actual request limits on your allocation; the successful 3500-input/128-output probe does not establish the full 4096-token boundary for every workload. These checks establish simple chat functionality and the listed synthetic request sizes. They do not establish GPQA accuracy, long-context answer quality, sustained stability, tool calling, or performance under the A3 reference workload. This observed 8×32 GiB low-concurrency run does not replace the upstream recommended hardware configuration. ### 5.5 Ascend A2 performance benchmark On September 23, 2026, the official `python -m sglang.bench_serving` tool completed **10 runs and 76 measured requests** on the same 8 × 910B4 allocation and runtime recorded in section 5.4. All requests succeeded, with the planned input lengths and exactly 128 output tokens each. Warm-up requests are excluded from the 76 measured requests. This benchmark used a separate server configuration: `--mem-fraction-static 0.97`, `--max-total-tokens 16384`, `--context-length 8192`, and `--max-running-requests 8`. The interactive selector retains the single-request configuration from section 5.4. The benchmark launch command was: ```bash Command theme={null} export HCCL_BUFFSIZE=128 export OMP_NUM_THREADS=1 export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True python -m sglang.launch_server \ --model-path /workspace/issue1215/model \ --tokenizer-path /workspace/issue1215/metadata \ --device npu --tp-size 8 --quantization modelslim --dtype bfloat16 \ --reasoning-parser minimax --tool-call-parser minimax-m2 \ --host 127.0.0.1 --port 31216 \ --context-length 8192 --max-running-requests 8 \ --chunked-prefill-size 128 --max-prefill-tokens 4096 \ --mem-fraction-static 0.97 --max-total-tokens 16384 \ --disable-cuda-graph --disable-radix-cache ``` #### 5.5.1 Workload and measured results The source data contained **16 locally authored synthetic English prompts in ShareGPT-compatible JSON format**; it was not the ShareGPT dataset. The tool used `--dataset-name random`, `--random-range-ratio 1`, and `--tokenize-prompt` to produce exact input lengths of 128 or 1024 tokens. Each run used `--request-rate inf`, temperature 0, one warm-up request, and `--flush-cache`. The serial control used seed 17; each repeated group used seeds **17, 29, and 43**, once each. The repeated groups below report the arithmetic **mean and minimum–maximum across three runs**. TTFT, TPOT, and E2E use each run's mean latency before computing this summary. The serial control has one run and therefore no repeat range. Output throughput is aggregate output tokens per second from the benchmark, not per-request decoding speed. All latency values are in milliseconds. **128 input / 128 output tokens, concurrency 1** — one run of 4 requests; 4/4 succeeded. | Metric | Value | | - | - | | Output throughput (tok/s) | 4.266 | | Mean TTFT (ms) | 486.589 | | Mean TPOT (ms) | 232.385 | | Mean E2E (ms) | 29999.459 | **128 input / 128 output tokens, concurrency 4** — three runs of 8 requests; 24/24 succeeded. | Metric | Mean | Min–max | | - | - | - | | Output throughput (tok/s) | 16.731 | 16.618–16.810 | | Mean TTFT (ms) | 807.497 | 801.011–814.685 | | Mean TPOT (ms) | 234.492 | 233.452–236.043 | | Mean E2E (ms) | 30588.025 | 30449.379–30792.190 | **128 input / 128 output tokens, concurrency 8** — three runs of 8 requests; 24/24 succeeded. | Metric | Mean | Min–max | | - | - | - | | Output throughput (tok/s) | 32.457 | 32.373–32.532 | | Mean TTFT (ms) | 1312.882 | 1276.591–1359.876 | | Mean TPOT (ms) | 237.912 | 237.480–238.622 | | Mean E2E (ms) | 31527.731 | 31456.127–31607.222 | **1024 input / 128 output tokens, concurrency 8** — three runs of 8 requests; 24/24 succeeded. | Metric | Mean | Min–max | | - | - | - | | Output throughput (tok/s) | 13.694 | 13.291–13.942 | | Mean TTFT (ms) | 12582.293 | 12329.436–13062.333 | | Mean TPOT (ms) | 272.578 | 268.251–280.396 | | Mean E2E (ms) | 47199.685 | 46422.970–48672.617 | Every run had a 100% request success rate; this measures successful request completion, not answer accuracy. Per-run percentiles remain in the detailed benchmark output and are not averaged into pooled percentiles. These short tests do not establish sustained stability or long-context answer quality. Their workload, runtime, and hardware differ from the A3 reference, so the table does not provide an A2-versus-A3 comparison. #### 5.5.2 Reproduce the benchmark Start the server above and wait for `/health` to return HTTP 200. Replace the two model paths below with your container paths, using the same tokenizer revision as the weights. Save the following as `benchmark_minimax_a2.py` and run it from the tested SGLang environment. It creates the synthetic data used here and runs the fixed suite, retaining each command, log, and detailed JSONL result. It refuses to overwrite an existing result and stops if a run fails validation. ```python benchmark_minimax_a2.py theme={null} import json from pathlib import Path import subprocess import sys model = "/workspace/issue1215/model" tokenizer = "/workspace/issue1215/metadata" out = Path("minimax-a2-perf") out.mkdir(exist_ok=True) topics = [ "gardening", "astronomy", "cooking", "geometry", "music", "weather", "transport", "ecology", "history", "software", "literature", "chemistry", "geography", "photography", "materials", "language", ] data = [{"id": f"synthetic-{i}", "conversations": [ {"from": "human", "value": ( f"Explain the basic principles of {topic}. Give a clear example and discuss its practical limitations. " ) * 8}, {"from": "gpt", "value": "This is a synthetic performance workload, not a quality evaluation."}, ]} for i, topic in enumerate(topics)] dataset = out / "synthetic-prompts.json" dataset.write_text(json.dumps(data), encoding="utf-8") cases = ([(128, 1, 4, 17)] + [(128, c, 8, s) for c in (4, 8) for s in (17, 29, 43)] + [(1024, 8, 8, s) for s in (17, 29, 43)]) for length, concurrency, count, seed in cases: name = f"in{length}-out128-c{concurrency}-n{count}-seed{seed}" result = out / f"{name}.jsonl" if result.exists(): raise RuntimeError(f"Refusing to overwrite {result}") command = [ sys.executable, "-m", "sglang.bench_serving", "--backend", "sglang", "--base-url", "http://127.0.0.1:31216", "--model", model, "--tokenizer", tokenizer, "--dataset-name", "random", "--dataset-path", str(dataset), "--random-input-len", str(length), "--random-output-len", "128", "--random-range-ratio", "1", "--tokenize-prompt", "--num-prompts", str(count), "--max-concurrency", str(concurrency), "--request-rate", "inf", "--temperature", "0", "--seed", str(seed), "--warmup-requests", "1", "--flush-cache", "--output-details", "--disable-tqdm", "--output-file", str(result), ] (out / f"{name}.command.json").write_text(json.dumps(command, indent=2), encoding="utf-8") with (out / f"{name}.log").open("w", encoding="utf-8") as log: subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True) rows = [json.loads(line) for line in result.read_text().splitlines() if line.strip()] if len(rows) != 1: raise RuntimeError(f"Expected exactly one result in {result}") row = rows[0] if not (row["completed"] == count and row["input_lens"] == [length] * count and row["output_lens"] == [128] * count and len(row["errors"]) == count and not any(row["errors"])): raise RuntimeError(f"Incomplete or mismatched run: inspect {result}") print(name, row["output_throughput"], flush=True) ``` Retain failed runs and missing-run records when reporting a reproduction; do not summarize only successful seeds. Keep each run's mean and percentile metrics separate. The synthetic data and performance measurements provide no GPQA or other model-quality score. ### 5.6 Ascend A2 reference-length performance On September 24, 2026, the same A2 hardware and runtime completed three official `sglang.bench_serving` runs with **3500 input tokens and 1500 output tokens**, using seeds **1, 17, and 29**. Each run measured two requests at client concurrency 2. All **6/6 measured requests** completed with the exact planned token lengths and no request errors: 21000 input tokens and 9000 output tokens in total. Each run's one-request, 32-output-token warm-up is excluded from these counts. The server used the section 5.5 launch command with `--context-length 9216` instead of 8192. Its other settings remained TP8, ModelSlim, BF16, memory fraction 0.97, KV limit 16384, maximum running requests 8, prefill chunk 128, maximum prefill tokens 4096, and graph capture and radix cache disabled. **Client concurrency 2 did not change the server's maximum of 8.** No draft model was used; the interactive selector's conservative default is unchanged. The workload reused the 16 synthetic prompts from section 5.5. It matches only the A3 reference's token lengths, not its ShareGPT workload, concurrency 320, hardware, or EAGLE3 configuration. It does not validate A3 throughput or the reference's 50 ms TPOT target. | Metric | Mean | Min–max | | - | - | - | | Output throughput (tok/s) | 8.004 | 7.896–8.065 | | Total throughput (tok/s) | 26.680 | 26.319–26.882 | | Mean TTFT (ms) | 10317.118 | 10267.749–10365.114 | | Mean TPOT (ms) | 243.163 | 241.222–246.570 | | Mean E2E (s) | 374.818 | 371.957–379.927 | These are arithmetic means and minimum–maximum values across the three run-level means or rates, not request extrema. Per-run percentiles are retained separately and are not averaged. Six measured requests provide a bounded performance observation, not a sustained-load or stability result. To reproduce, generate `minimax-a2-perf/synthetic-prompts.json` using the data-creation portion of section 5.5.2, launch the server with context 9216, and run the following from that working directory. Use the same model/tokenizer paths as the server, and retain each JSONL and log, including failures: ```bash Command theme={null} set -euo pipefail mkdir -p minimax-a2-reference-perf for SEED in 1 17 29; do RESULT="minimax-a2-reference-perf/in3500-out1500-c2-n2-seed${SEED}.jsonl" test ! -e "$RESULT" python -m sglang.bench_serving \ --backend sglang --base-url http://127.0.0.1:31216 \ --model /workspace/issue1215/model \ --tokenizer /workspace/issue1215/metadata \ --dataset-name random --dataset-path minimax-a2-perf/synthetic-prompts.json \ --random-input-len 3500 --random-output-len 1500 --random-range-ratio 1 \ --tokenize-prompt --num-prompts 2 --max-concurrency 2 \ --request-rate inf --temperature 0 --seed "$SEED" \ --warmup-requests 1 --flush-cache --output-details --disable-tqdm \ --output-file "$RESULT" 2>&1 | tee "${RESULT%.jsonl}.log" done ``` Check every result for `completed=2`, input lengths `[3500,3500]`, output lengths `[1500,1500]`, and two empty error entries before aggregating it. Verify server health after each run. A successful process exit alone is insufficient to establish those conditions. ### 5.7 Ascend A2 fixed 50-question GSM8K regression On September 24, 2026, a **preselected 50-question deployment regression completed with 49/50 correct (98%)**, zero capped outputs, zero transport/protocol errors, and no missing or duplicate questions. This is a bounded GSM8K test subset, not full GSM8K accuracy, an EvalScope result, GPQA accuracy, or evidence of A3 parity. The run used the same A2 hardware, W8A8 weights, and runtime as above. The server used context 9216, maximum running requests **2**, memory fraction 0.97, and KV limit 16384; all other launch settings matched section 5.6. The client submitted **one request at a time** to `/v1/chat/completions`, with `temperature=1.0`, `max_tokens=6144`, and generation seed `42 + original test row index`. The reasoning parser remained `minimax`; scoring used only final answer content. The protocol was frozen before an independent three-question pilot: 1. Use the MIT-licensed [official GSM8K data at revision 3101c7d5072418e28b9008a6636bde82a006892c](https://github.com/openai/grade-school-math/tree/3101c7d5072418e28b9008a6636bde82a006892c/grade_school_math/data). Take training rows 0–4 as five worked demonstrations. 2. Shuffle all 1319 test-row indices with Python `random.Random(20260924).shuffle`. Reserve the first three indices for the independent pilot and use the next 50, in order, for this regression. Do not include pilot answers in the result or select, replace, reorder, or drop questions based on observed answers. 3. Build a single user message by joining the five `Question: ...\nAnswer: ...` demonstrations with two newlines, then append the test question as `Question: ...\nAnswer:`. Preserve the training answers, including their worked solutions. Apply the deployed MiniMax chat template through the chat endpoint. 4. Before any generation, tokenize all 50 messages with the server and verify that each prompt plus the 6144-token output allowance fits context 9216. Submit each frozen question exactly once, with a per-request wall limit of 1800 seconds. Stop new submissions on a transport/protocol error; do not retry or resume a failed run. 5. Parse only final content using the pinned runtime's last-number rule: remove commas, find matches of `-?\d+\.?\d*`, and parse the last match numerically. Compare it with the gold answer parsed the same way. A missing number, wrong answer, length cap, or transport/protocol error scores zero. Keep the denominator fixed at 50; report an incomplete run as incomplete rather than a full score. The selection can be reconstructed without model access: ```python Example theme={null} import random indices = list(range(1319)) random.Random(20260924).shuffle(indices) pilot_ids = indices[:3] # Excluded from regression scoring. regression_ids = indices[3:53] assert len(set(regression_ids)) == 50 assert not set(pilot_ids).intersection(regression_ids) ``` | Check | Observed result | | - | - | | Unique completed questions | 50/50 | | Correct final answers | 49/50 (98%) | | Wrong final answers | 1 | | Length-capped responses | 0 | | Transport/protocol errors | 0 | | Completion-token range | 292–2507 | All 50 prompts passed preflight. The client elapsed time, including preflight, was 9444.598 seconds; it is not a per-request latency benchmark. The downloaded run's 172 manifest entries passed hash verification, and rescoring the preserved final answers with the declared parser reproduced 49/50. Preserve the frozen IDs, prompt hashes, parameters, every response, and raw SSE when reproducing the regression. This result tests the declared subset and parsing protocol; it does not establish full-dataset accuracy, long-context quality, sustained stability, or the unvalidated A3 recipe's acceptance criteria. # MiniMax-M2.7 Source: https://docs.sglang.io/cookbook/autoregressive/MiniMax/MiniMax-M2.7 ## 1. Model Introduction [MiniMax-M2.7](https://huggingface.co/MiniMaxAI/MiniMax-M2.7) is MiniMax's first model deeply participating in its own evolution. Built for real-world productivity, M2.7 excels at building complex agent harnesses and completing highly elaborate productivity tasks, leveraging Agent Teams, complex Skills, and dynamic tool search. Key highlights: * **Model Self-Evolution**: During development, M2.7 updates its own memory, builds complex skills for RL experiments, and improves its own learning process. An internal version autonomously optimized a programming scaffold over 100+ rounds, achieving a **30% performance improvement**. On MLE Bench Lite, M2.7 achieved a **66.6% medal rate**. * **Professional Software Engineering**: Delivers outstanding real-world programming capabilities. On SWE-Pro, M2.7 achieved **56.22%**, with strong results on SWE Multilingual (76.5) and Multi SWE Bench (52.7). On Terminal Bench 2 (57.0%) and NL2Repo (39.8%), M2.7 demonstrates deep understanding of complex engineering systems. * **Professional Work**: Achieved an ELO score of **1495** on GDPval-AA (highest among open-source models). On Toolathon, M2.7 reached **46.3%** accuracy (global top tier). * **Native Agent Teams**: Supports multi-agent collaboration with stable role identity and autonomous decision-making. For more details, see the [official MiniMax-M2.7 blog post](https://www.minimax.io/news/minimax-m27-en). **License**: [Modified-MIT (MiniMax Model License)](https://github.com/MiniMax-AI/MiniMax-M2.7/blob/main/LICENSE) ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. For SGLang CPU installation, please refer to the [CPU version installation guide](../../../docs/hardware-platforms/cpu_server#installation). **Docker Images by Hardware Platform:**
Hardware Platform Docker Image
NVIDIA A100 / H100 / H200 / B200 `lmsysorg/sglang:v0.5.10.post1`
NVIDIA B300 / GB300 `lmsysorg/sglang:v0.5.10.post1-cu130`
AMD MI300X / MI325X `lmsysorg/sglang:v0.5.10.post1-rocm720-mi30x`
AMD MI355X `lmsysorg/sglang:v0.5.10.post1-rocm720-mi35x`
## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, deployment strategy, and feature capabilities. Run this Command:

### 3.2 Configuration Tips

**Key Parameters:**

Parameter Description Recommended Value
`--tool-call-parser` Tool call parser for function calling support `minimax-m2`
`--reasoning-parser` Reasoning parser for thinking mode `minimax-append-think`
`--trust-remote-code` Required for MiniMax model loading Always enabled
`--mem-fraction-static` Static memory fraction for KV cache `0.85`
`--tp` Tensor parallelism size `2` / `4` / `8` depending on hardware
`--ep` Expert parallelism size `8` (NVIDIA 8-GPU) or EP=TP (AMD)
`--kv-cache-dtype` KV cache data type (AMD only) `fp8_e4m3`
`--attention-backend` Attention backend (AMD only) `triton`
**Hardware Requirements: NVIDIA** * **4-GPU deployment**: Requires 4× high-memory GPUs (e.g., H200, B200, A100, H100) with TP=4 * **8-GPU deployment**: Requires 8× GPUs (e.g., H200, B200, A100, H100) with TP=8 and EP=8 **Hardware Requirements: NVIDIA GB300** * **2-GPU deployment**: GB300 (275GB per die) can host the model with TP=2 * **4-GPU deployment**: Maximum single-node TP for GB300, recommended for higher throughput **Hardware Requirements: AMD** * **2-GPU deployment**: Requires 2× high-memory GPUs (e.g., MI300X, MI325X, MI355X) with TP=2, EP=2 * **4-GPU deployment**: Requires 4× GPUs (e.g., MI300X, MI325X, MI355X) with TP=4, EP=4 * **8-GPU deployment**: Requires 8× GPUs (e.g., MI300X, MI325X, MI355X) with TP=8, EP=8 **Hardware Requirements: Intel Xeon CPU** * It is recommended to run the model service on a Granite Rapids (GNR) AP 2-Socket server. * For configuring CPU service, please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings. ## 4. Model Invocation ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) **Deployment Command:** ```bash Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2.7 \ --tp 4 \ --tool-call-parser minimax-m2 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 ``` **Testing Deployment:** After startup, you can test the SGLang OpenAI-compatible API with the following command: ```bash Command theme={null} curl http://localhost:30000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "model": "MiniMaxAI/MiniMax-M2.7", "messages": [ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]}, {"role": "user", "content": [{"type": "text", "text": "Who won the world series in 2020?"}]} ] }' ``` **Simple Completion Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2.7", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ], max_tokens=1024 ) print(response.choices[0].message.content) ``` **Example Output**: ```text Output theme={null} The user asks: "Who won the World Series in 2020?" That's a simple factual question. The answer: the Los Angeles Dodgers won the 2020 MLB World Series, defeating the Tampa Bay Rays. So answer accordingly. We must be mindful of policy: it's a factual question about sports. It's allowed. Provide answer with brief context. We should answer concisely. Hence final answer: The Los Angeles Dodgers won the 2020 World Series, defeating the Tampa Bay Rays in six games (best-of-seven series). Possibly mention it was played at a neutral site due to COVID-19, at Globe Life Field in Arlington, Texas. We must avoid disallowed content, no issue. Thus final. The **Los Angeles Dodgers** won the 2020 World Series. They defeated the **Tampa Bay Rays** in six games (4‑2) in a best‑of‑seven series that was played at Globe Life Field in Arlington, Texas, under the MLB bubble‑like arrangements for the COVID‑19 pandemic. ``` ### 4.2 Advanced Usage #### 4.2.1 Reasoning Parser MiniMax-M2.7 supports Thinking mode. Enable the reasoning parser during deployment to separate the thinking and the content sections: ```bash Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2.7 \ --tp 4 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 ``` **Streaming with Thinking Process** With `minimax-append-think`, the thinking content is wrapped in `...` tags within the `content` field. You can parse these tags on the client side to separate the thinking and content sections: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Enable streaming to see the thinking process in real-time response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2.7", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], max_tokens=2048, stream=True ) # Process the stream, separating ... from content in_think = False think_printed_header = False content_printed_header = False buffer = "" for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if delta.content: buffer += delta.content while buffer: if in_think: # Look for closing tag end_idx = buffer.find("") if end_idx != -1: print(buffer[:end_idx], end="", flush=True) buffer = buffer[end_idx + len(""):] in_think = False else: # Still in thinking, print what we have print(buffer, end="", flush=True) buffer = "" else: # Look for opening tag start_idx = buffer.find("") if start_idx != -1: # Print any content before before = buffer[:start_idx] if before: if not content_printed_header: print("=============== Content =================", flush=True) content_printed_header = True print(before, end="", flush=True) buffer = buffer[start_idx + len(""):] in_think = True if not think_printed_header: print("=============== Thinking =================", flush=True) think_printed_header = True else: # No tag, print as content if not content_printed_header and think_printed_header: print("\n=============== Content =================", flush=True) content_printed_header = True print(buffer, end="", flush=True) buffer = "" print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user asks: "Solve this problem step by step: What is 15% of 240?" Straightforward. Provide solution: 15% = 15/100 = 0.15. Multiply 240 * 0.15 = 36. Show steps. So answer: 36. Provide explanation. But also ensure we follow any policy? No issues. Just straightforward. I'll provide a step-by-step solution. Also could show fraction: 15% = 15/100 = 3/20, multiply 240 * 3/20 = (240/20)*3 = 12*3 = 36. Yes. Provide final answer. Also show verification: 10% of 240 is 24, 5% is 12, total 36. All good. =============== Content ================= **Step‑by‑step solution** 1. **Convert the percent to a decimal (or a fraction).** 15% = 15/100 = 0.15 = 3/20 2. **Multiply the original number (240) by this decimal/fraction.** Using the decimal: 240 × 0.15 = 36 Or using the fraction: 240 × 3/20 = (240/20) × 3 = 12 × 3 = 36 3. **Result:** 15% of 240 = **36** *Check:* - 10% of 240 = 24 - 5% of 240 = 12 - Adding them: 24 + 12 = 36, which matches the calculation. ``` **Note:** The `minimax-append-think` reasoning parser embeds the thinking process in `...` tags within the `content` field. The code above parses these tags in real-time to display thinking and content separately. #### 4.2.2 Tool Calling MiniMax-M2.7 supports tool calling capabilities. Enable the tool call parser: ```bash Command theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M2.7 \ --tp 4 \ --tool-call-parser minimax-m2 \ --reasoning-parser minimax-append-think \ --trust-remote-code \ --mem-fraction-static 0.85 ``` **Python Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Non-streaming request response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2.7", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools ) message = response.choices[0].message # Check for tool calls if message.tool_calls: for tool_call in message.tool_calls: print(f"Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") else: print(message.content) ``` **Output Example**: ```text Output theme={null} Tool Call: get_weather Arguments: {"location": "Beijing"} ``` **Handling Tool Call Results:** ```python Example theme={null} # After getting the tool call, execute the function def get_weather(location, unit="celsius"): # Your actual weather API call here return f"The weather in {location} is 22°{unit[0].upper()} and sunny." # Send tool result back to the model messages = [ {"role": "user", "content": "What's the weather in Beijing?"}, { "role": "assistant", "content": None, "tool_calls": [{ "id": "call_123", "type": "function", "function": { "name": "get_weather", "arguments": '{"location": "Beijing", "unit": "celsius"}' } }] }, { "role": "tool", "tool_call_id": "call_123", "content": get_weather("Beijing", "celsius") } ] final_response = client.chat.completions.create( model="MiniMaxAI/MiniMax-M2.7", messages=messages ) print(final_response.choices[0].message.content) ``` **Output Example:** ```text Output theme={null} The weather in Beijing is currently 22°C and sunny. ``` ## 5. Benchmark This section uses **industry-standard configurations** for comparable benchmark results. **Test Environment**: * Hardware: 2× NVIDIA GB300 (275GB per die) * Docker Image: `lmsysorg/sglang:v0.5.10.post1-cu130` * Model: MiniMax-M2.7 (FP8) * Tensor Parallelism: 2 * SGLang version: 0.5.10.post1 ### 5.1 Accuracy Benchmark **Evaluation Tool**: [sgl-eval](https://github.com/sgl-project/sgl-eval) **Evaluation Settings**: temperature=0.6, top\_p=0.95, 8 repeats, max\_tokens=120,000 (GPQA and AIME; MMLU-Pro is greedy and single-pass, see below) #### 5.1.1 GPQA Diamond * Dataset: [GPQA Diamond](https://huggingface.co/datasets/Idavidrein/gpqa) (198 questions) * Prompt: `eval/aai/mcq-4choices` (4-choice multiple choice, matching [Artificial Analysis methodology](https://artificialanalysis.ai/methodology/intelligence-benchmarking)) -- sgl-eval's default for this benchmark * Evaluation command: ```bash Command theme={null} pip install sgl-eval sgl-eval run gpqa \ --base-url http://localhost:30000/v1 \ --model MiniMaxAI/MiniMax-M2.7 \ --n-repeats 8 \ --max-tokens 120000 \ --temperature 0.6 \ --top-p 0.95 ``` * Test Results:
Evaluation Mode Accuracy No Answer
pass\@1 (avg-of-8) 84.91% 3.54%
**majority\@8** **88.89%** 0.00%
pass\@8 96.46% 0.00%
#### 5.1.2 AIME 2025 * Dataset: AIME 2025 (30 problems) * Prompt: `generic/math` (boxed answer format) -- sgl-eval's default for this benchmark * Evaluation command: ```bash Command theme={null} sgl-eval run aime25 \ --base-url http://localhost:30000/v1 \ --model MiniMaxAI/MiniMax-M2.7 \ --n-repeats 8 \ --max-tokens 120000 \ --temperature 0.6 \ --top-p 0.95 ``` * Test Results:
Evaluation Mode Accuracy No Answer
pass\@1 (avg-of-8) 92.50% ± 5.56% 2.92%
**majority\@8** **97.08%** 0.00%
pass\@8 100.00% 0.00%
#### 5.1.3 MMLU-Pro * Dataset: [MMLU-Pro](https://huggingface.co/datasets/TIGER-Lab/MMLU-Pro) (12,032 questions, 10-choice) * Prompt: `eval/aai/mcq-10choices` (10-choice multiple choice) -- sgl-eval's default for this benchmark * Evaluation command: ```bash Command theme={null} sgl-eval run mmlu_pro \ --base-url http://localhost:30000/v1 \ --model MiniMaxAI/MiniMax-M2.7 \ --max-tokens 32768 \ --temperature 0.0 ``` * Test Results:
Evaluation Mode Accuracy No Answer
pass\@1 (greedy) 69.41% 18.75%
> **Note**: The high no-answer rate is due to the 32K token limit being insufficient for M2.7's extended thinking on some questions. A rerun with 120K tokens is expected to improve accuracy significantly. #### 5.1.4 GSM8K Benchmark * Benchmark Method: 8-shot Chain-of-Thought, evaluated via OpenAI-compatible API * Test Results: ```text Output theme={null} GSM8K Results (8-shot CoT) Model: MiniMaxAI/MiniMax-M2.7 Total: 1319 Correct: 1218 Accuracy: 92.34% ``` ### 5.2 Speed Benchmark #### 5.2.1 Low Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.7 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 34.33 Total input tokens: 6101 Total generated tokens: 4220 Request throughput (req/s): 0.29 Input token throughput (tok/s): 177.71 Output token throughput (tok/s): 122.92 Total token throughput (tok/s): 300.63 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 3431.21 Median E2E Latency (ms): 2742.57 ---------------Time to First Token---------------- Mean TTFT (ms): 50.28 Median TTFT (ms): 53.85 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 8.02 Median TPOT (ms): 8.01 ---------------Inter-Token Latency---------------- Mean ITL (ms): 8.03 Median ITL (ms): 8.02 ================================================== ``` #### 5.2.2 High Concurrency * Benchmark Command: ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model MiniMaxAI/MiniMax-M2.7 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 ``` * Test Results: ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 100.20 Total input tokens: 249831 Total generated tokens: 252662 Request throughput (req/s): 4.99 Input token throughput (tok/s): 2493.41 Output token throughput (tok/s): 2521.66 Total token throughput (tok/s): 5015.07 Concurrency: 90.19 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 18072.69 Median E2E Latency (ms): 17761.84 ---------------Time to First Token---------------- Mean TTFT (ms): 247.94 Median TTFT (ms): 92.05 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 35.75 Median TPOT (ms): 36.67 ---------------Inter-Token Latency---------------- Mean ITL (ms): 35.34 Median ITL (ms): 30.55 ================================================== ``` # MiniMax-M3 Source: https://docs.sglang.io/cookbook/autoregressive/MiniMax/MiniMax-M3 Deploy MiniMax-M3 with SGLang — a ~428B-param (23B activated) multimodal Mixture-of-Experts reasoning model with MiniMax Sparse Attention and 1M context, MXFP8 on NVIDIA Blackwell & AMD Instinct, bf16 on Hopper. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install -U uv > uv venv --python 3.12 && source .venv/bin/activate > > # MiniMax-M3 ships in SGLang PR #27944, not yet in a tagged release — install from > # the PR head. The serving runtime is in the base dependencies, so no extra is needed: > git clone https://github.com/sgl-project/sglang.git > cd sglang > git fetch origin pull/27944/head && git checkout FETCH_HEAD > uv pip install --prerelease=allow -e python > ``` > > Then run the **Python** output of the command panel below in that environment. The **Docker** tab is simpler — its image bundles the CUDA-13 runtime and the #27944 code. Once [PR #27944](https://github.com/sgl-project/sglang/pull/27944) is merged and released, `uv pip install --prerelease=allow sglang` will pull M3 support directly. > > **Docker** > > ```bash Command theme={null} > # Pull the M3 image the command panel selects for your platform, e.g.: > docker pull lmsysorg/sglang:dev-cu13-minimax-m3 > ``` > > The command panel below fills in the right tag per platform: `dev-cu13-minimax-m3` (CUDA 13 — B300, GB200, GB300), `dev-cu12-minimax-m3` (CUDA 12 — Hopper H200; final build, the CUDA 12 lane is retired), or `dev-minimax-m3` (default). On AMD Instinct it uses the matching ROCm image (MI300X/MI325X → `aigmkt/minimax-m3-sglang-rocm700-mi30x`, MI350X/MI355X → `aigmkt/minimax-m3-sglang-rocm720-mi35x`). For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker), substituting the inner `sglang serve ...` with what the command generator produces. > > > [!NOTE] > > > > These M3 dev images now **bundle MiniMax's MSA sparse-attention kernel** (`fmha_sm100`), so Blackwell users get the recommended fast path automatically — no manual install needed (see **§2.1**). On a custom image without it, the same recipe still serves on the built-in Triton sparse path. Pick your hardware + recipe to generate the launch command. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction [MiniMax-M3](https://huggingface.co/MiniMaxAI/MiniMax-M3-MXFP8) is MiniMax's native-multimodal Mixture-of-Experts reasoning model: **\~428B total parameters with \~23B activated per token** (128 experts, 4 active per token), 60 layers, and a **1M-token context** over text, image, and video. Its defining feature is **MiniMax Sparse Attention (MSA)** — a block-sparse "lightning indexer" attention that keeps long-context cost low (MiniMax reports \~9× prefill / \~15× decode speedup over M2 at 1M context). This page serves the **MXFP8** variant (`MiniMaxAI/MiniMax-M3-MXFP8`, \~440 GB) on NVIDIA Blackwell and AMD Instinct; on NVIDIA Hopper (H200), use the full-precision **bfloat16** build [`MiniMaxAI/MiniMax-M3`](https://huggingface.co/MiniMaxAI/MiniMax-M3) (§2.4). Released under the **MiniMax Community License**. Key characteristics as served by SGLang: * **Multimodal (vision + text)**: accepts interleaved text and images through the OpenAI-compatible chat API (loaded as `MiniMaxM3SparseForConditionalGeneration`). Image input via URL and base64 is validated; video input has not been tested here. * **Reasoning model**: emits its chain of thought wrapped in `...`. Always launch with **`--reasoning-parser auto`** — it auto-detects the right parser from the chat template, and SGLang then strips the tags and returns the trace separately in `message.reasoning_content`. * **Native tool calling**: a custom namespace-token XML format, parsed into standard OpenAI `tool_calls`. Always launch with **`--tool-call-parser auto`** — it auto-detects the right parser from the chat template. Single, parallel, and nested (object / array) arguments are supported. * **Sparse attention**: most layers use M3's "lightning indexer" block-sparse attention (top-k 128-token blocks), which keeps decode cost roughly flat in context length. On Blackwell, MiniMax's open-source [MSA kernel](https://github.com/MiniMax-AI/MSA) accelerates this path further (§2.1). * **MXFP8 quantization across vendors**: the MXFP8 MoE weights run natively on NVIDIA Blackwell (B200 / B300 / GB200 / GB300) and on AMD Instinct MI350X/MI355X (gfx950 / CDNA4), both of which have hardware MX-scaled matmul. On AMD MI300X/MI325X (gfx942 / CDNA3) — no hardware MX — SGLang converts the weights to block-fp8 `[128,128]` at load and serves them on the tuned ROCm kernels (§2.3). The vision tower stays unquantized. **Recommended generation**: the model's `generation_config.json` sets `temperature` 1.0 / `top_p` 0.95, which SGLang applies automatically (the default `--sampling-defaults model`). The model card additionally suggests `top_k` 40, but that value is **not** in `generation_config.json`, so SGLang does not apply it by default. `top_k` is a per-request sampling parameter (not a launch flag) — set it per call if you want it, e.g. `extra_body={"top_k": 40}` with the OpenAI client. **Resources:** [HuggingFace](https://huggingface.co/MiniMaxAI/MiniMax-M3-MXFP8) · [MSA kernel](https://github.com/MiniMax-AI/MSA) ## 2. Configuration Tips ### 2.1 MSA sparse-attention fast path (recommended for Blackwell users) [MiniMax MSA](https://github.com/MiniMax-AI/MSA) (`fmha_sm100`, MIT-licensed) is the recommended Blackwell kernel for M3's main sparse-attention step — faster and more memory-efficient than the built-in Triton fallback. **It ships pre-installed in the M3 dev image** (`lmsysorg/sglang:dev-minimax-m3`, also published under the `dev-cu13-minimax-m3` tag), so the Blackwell recipe above engages it automatically with no extra setup — `import fmha_sm100` works out of the box and the kernels JIT-compile on first use. It is otherwise purely additive: on a custom image, install it (below) and the recipe engages it automatically; without it the same recipe still serves on the built-in Triton path. The swap is numerically equivalent (cosine ≥ 0.99999 vs Triton), decode stays CUDA-graph-capturable, prefill TTFT drops \~9–12% at 8K–64K context, and the MSA path survives memory configurations where the Triton path OOMs. **Requirements** (from the [MSA README](https://github.com/MiniMax-AI/MSA#requirements)): * **GPU**: NVIDIA SM100 family — sm\_100 (B200 / GB200) and sm\_103 (B300 / GB300). * **Toolchain**: CUDA Toolkit with `nvcc` ≥ 12.x on `PATH` (or `CUDA_HOME` set) — the kernels are JIT-compiled at first import. * **Python**: ≥ 3.11; **OS**: Linux — works on both **x86\_64 and aarch64 (Grace, e.g. GB200 / GB300)**; the aarch64 build needs no source edits. > **Install MSA (only on a custom image) & verify the gate (Python)** > > The M3 Blackwell dev images above already bundle MSA, so you can skip straight to the gate check. The `git clone` / `pip install` steps are only needed on a custom image that doesn't have `fmha_sm100`. > > ```bash Command theme={null} > # Only on a custom image: --recursive pulls the CUTLASS submodule required for JIT compilation > git clone --recursive https://github.com/MiniMax-AI/MSA.git msa > cd msa && pip install . > # Verify the SGLang gate (True -> MSA engaged on this device; False -> Triton fallback): > python -c "from sglang.srt.layers.attention.minimax_sparse_ops.msa import msa_available; print(msa_available())" > ``` > [!NOTE] > > The first import JIT-compiles the kernels, which can take 30 s to a few minutes on a cold `nvcc` cache — this is normal, not a hang. Subsequent server starts hit the JIT cache. > [!WARNING] > > **Warm the JIT cache before a multi-GPU launch.** On a *cold* cache, several tensor-parallel ranks racing to JIT-compile MSA's plan kernel can leave one rank loading a half-linked module (`AttributeError: Module has no function 'plan'` at CUDA-graph capture). Run the gate-check `python -c "..."` (or any single-process `fmha_sm100_plan` call) once before launching the server — that compiles the kernel single-process, and every rank then hits the warm cache. The gate requires `--attention-backend fa4` (MSA's sparse blocks are 128 tokens, so the page size must be 128). SGLang auto-forces `page_size` to 128 for the `fa4` backend — including the combined `--attention-backend fa4` the M3 recipe uses (#28976) — so `--page-size 128` is omitted from the Blackwell cells below. Force the Triton path at any time with the env var `SGLANG_DISABLE_MSA=1`. MSA is a Blackwell (SM100) kernel and does not apply to the AMD ROCm paths. > [!NOTE] > > For multimodal (image) serving, keep the same text recipe above — `--attention-backend fa4` (MSA) is unchanged — and add `--mm-attention-backend flashinfer_cudnn` for the vision tower. The text and vision-tower attention backends are independent knobs; MSA only touches the language-model sparse attention, not image handling. ### 2.2 Memory and workload tuning The NVIDIA Blackwell recipes are validated single-node: **B200 at `--tp 8`** and **B300 / GB300 at `--tp 4`** (4-GPU is also the GB200 / GB300 single-node ceiling). GB200 (sm\_100, aarch64) is inferred-supported — both of its axes are validated above (B200 is sm\_100; GB300 is sm\_103 aarch64) — but not directly benchmarked. The AMD recipes use **8-GPU (`--tp 8`)**. * **Memory**: `--mem-fraction-static` reserves GPU memory for weights + KV pool; the rest is prefill **activation headroom**. The value scales with *free* memory per GPU (card capacity minus per-GPU weight), so it tracks the card more than the TP degree: **`0.65` on B200** (180 GB — less headroom once weights are resident) and **`0.75` on the larger-memory B300 / GB300** (`0.80` on AMD). Lower TP packs more weight per GPU, so a tighter config needs a *lower* value — B200 needs `0.65` even at `--tp 4`. Raising it past the validated value is fine only for low-concurrency single-stream serving; it OOMs under high concurrency or long context. * **Long context (32K+)**: keep `--mem-fraction-static` at the platform default and raise `--chunked-prefill-size` to `16384`. Decode TPOT stays roughly flat in context length thanks to sparse attention; 1K–128K prompts are validated. * **HiSparse for decode capacity**: on NVIDIA CUDA, HiSparse keeps the three dense layers on GPU, moves the 57 sparse-layer K/V caches to pinned host memory, and feeds selected block IDs directly to the swap-in kernel. For the released four-KV-head model, use `--tp 4` or greater, `--disable-radix-cache`, and `device_buffer_size >= 2048`. Enable it with `--enable-hisparse --hisparse-config='{"device_buffer_size":4096,"host_to_device_ratio":2}'` on the Triton launch command. * **Scaling TP**: B200 is documented at `--tp 8`; B300 / GB200 / GB300 at `--tp 4` (the single-node cross-family common denominator). On an 8-GPU B300 host you can also raise to `--tp 8` for more throughput / KV headroom. * **Expert parallelism**: to trade latency for throughput add `--ep` (see [Expert Parallelism Deployment](../../../docs/advanced_features/expert_parallelism)). On AMD, set `--ep` equal to `--tp`. Shared-experts fusion is automatically disabled when EP > 1; on AMD standard EP the server also disables `--enable-aiter-allreduce-fusion` automatically to preserve accuracy. * `--trust-remote-code` is required to load the MiniMax config / processor classes. ### 2.3 AMD Instinct (ROCm) MiniMax-M3 runs on AMD Instinct GPUs through two code paths, by architecture — both selected automatically; you still pass `--quantization mxfp8` either way: * **MI350X / MI355X (gfx950, CDNA4)** has hardware MX-scaled matmul, so the **MXFP8 weights are served natively**. SGLang auto-detects the checkpoint, selects the Triton MiniMax-M3 MoE path with the packaged tuned MXFP8 configs, and enables AITER fused all-reduce for single-node tensor parallelism. The launch command is the NVIDIA recipe minus the Blackwell-only backend flags. * **MI300X / MI325X (gfx942, CDNA3)** has **no** hardware MX matmul. SGLang transparently **converts the MXFP8 weights to block-fp8 `[128,128]` at load time**, then serves them with the tuned ROCm block-fp8 kernels (`--attention-backend aiter`, `--moe-runner-backend triton`; the `aiter` runner also works and scores marginally higher). On a cold start the first generation can JIT-compile AITER configs and exceed the default warmup/HTTP timeout, so the recipe adds `--watchdog-timeout 3600 --skip-server-warmup`. The block-fp8 step adds only a small relative error over MXFP8's native `1×32` scaling — negligible on GSM8K (see the benchmark card). Select an MI300X/MI325X or MI350X/MI355X tile in the command panel above to get the exact launch command for each path. > [!NOTE] > > The AMD recipes are validated end-to-end on **text** workloads — chat, reasoning separation, and tool calling. The vision tower was not exercised on ROCm; for image input on AMD, omit the Blackwell `--mm-attention-backend flashinfer_cudnn` flag and let the encoder use the ROCm default backend, and treat vision as unvalidated on that path. ### 2.4 Serving on Hopper (H200) with the bf16 build The MXFP8 kernels are Blackwell-only, so Hopper (H200) serves the full-precision bfloat16 build [`MiniMaxAI/MiniMax-M3`](https://huggingface.co/MiniMaxAI/MiniMax-M3). Select **H200 + BF16** in the Deploy panel above for the exact command — it runs at `--tp 8` (the bf16 weights need a full 8-GPU node). SGLang picks the right backends for Hopper automatically, so the recipe stays minimal: * **MoE runner**: Triton, auto-selected for bf16 weights. * **Attention**: FlashAttention-3 with page size 1. MSA (§2.1) is a Blackwell kernel, so M3's sparse step runs on the built-in Triton path here. * **CUDA graph**: on, with full decode-graph capture. **High-concurrency throughput (optional).** On Hopper the sparse prefill runs on the Triton path as a separate eager forward, which briefly stalls the in-flight decode batch under heavy concurrent load. Adding `--enable-mixed-chunk --chunked-prefill-size 2048` merges the running decodes into the prefill step instead of preempting them, which recovers roughly **+10% output throughput** and **\~10% lower median TPOT** at high concurrency on 8×H200, with no change in accuracy. Leave it off for latency-sensitive low-concurrency serving. Validated on 8×H200 — reasoning and tool-call auto-detection plus long-context generation. For prefill/decode disaggregation on Hopper, see §3.4. ## 3. Advanced Usage ### 3.1 Reasoning Launch with `--reasoning-parser auto` (or toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)). The `` trace then lands in `message.reasoning_content`, separate from the final answer in `message.content` — no client-side tag stripping needed. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3-MXFP8", > messages=[{"role": "user", "content": "What is 15% of 240? Explain briefly."}], > max_tokens=2048, > ) > > message = response.choices[0].message > print("=============== Reasoning ===============") > print(message.reasoning_content) > print("=============== Answer ==================") > print(message.content) > ``` > **Example Output** > > ```text Output theme={null} > =============== Reasoning =============== > 15% of 240. 15% = 0.15. 240 * 0.15 = 36. Quick check: 10% is 24, 5% is 12, 24 + 12 = 36. > =============== Answer ================== > 15% of 240 is **36**. > (10% of 240 = 24, and 5% of 240 = 12; 24 + 12 = 36.) > ``` When streaming, the trace arrives on `delta.reasoning_content` and the answer on `delta.content`, so the two sections can be rendered separately in real time: > **Streaming Reasoning (Python)** > > ```python Example theme={null} > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3-MXFP8", > messages=[{"role": "user", "content": "Solve step by step: what is 15% of 240?"}], > max_tokens=2048, > stream=True, > ) > > for chunk in response: > if not chunk.choices: > continue > delta = chunk.choices[0].delta > if getattr(delta, "reasoning_content", None): > print(delta.reasoning_content, end="", flush=True) # thinking stream > if delta.content: > print(delta.content, end="", flush=True) # answer stream > print() > ``` > > **Output Example:** > > ```text Output theme={null} > [delta.reasoning_content — thinking stream] > Let me solve this step by step. > > 15% of 240 > = 0.15 × 240 > = 36 > > Let me verify: 10% of 240 = 24, 5% of 240 = 12, so 15% = 24 + 12 = 36. ✓ > > [delta.content — answer stream] > # Solving 15% of 240 > ## Step 1: Convert the percentage to a decimal > 15% = 15/100 = 0.15 > ## Step 2: Multiply by 240 > 0.15 × 240 = 36 > ## Answer > **15% of 240 = 36** > ``` ### 3.2 Tool Calling Launch with `--tool-call-parser auto` (or toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) — it auto-detects M3's tool-call parser from the chat template. M3 emits tool calls in a custom namespace-token XML format: ```text Raw model output theme={null} ]<]minimax[>[ ]<]minimax[>[]<]minimax[>[Beijing]<]minimax[>[]<]minimax[>[ ]<]minimax[>[ ``` The parser converts that into the standard OpenAI `tool_calls` structure: > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["location"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3-MXFP8", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > > message = response.choices[0].message > if message.tool_calls: > for call in message.tool_calls: > print(f"Tool: {call.function.name}") > print(f"Args: {call.function.arguments}") > ``` > **Example Output** > > ```text Output theme={null} > Tool: get_weather > Args: {"location": "Beijing"} > ``` Beyond a single flat call, the parser also supports: * **Parallel calls** — multiple `` blocks inside the single `` wrapper, surfaced as multiple `message.tool_calls` entries. * **Nested object arguments** — an `object`-typed parameter is emitted as nested XML tags and reconstructed into a JSON object. * **Array arguments** — an `array`-typed parameter uses repeated `` children and is reconstructed into a JSON list. For example, a tool with object and array parameters round-trips cleanly: ```text Output theme={null} create_event {"title": "Design sync", "attendees": ["alice", "bob"], "location": {"room": "R2", "floor": 3}} ``` To return a tool result, append the assistant's `tool_calls` turn plus a matching `tool` message and ask the model to continue — the follow-up answer may place text in `reasoning_content` as well as `content`, so print both. ### 3.3 Multimodal (Vision) Input Images go through the standard OpenAI `image_url` content type. The vision tower is always loaded; for image serving add `--mm-attention-backend flashinfer_cudnn` (the vision-tower backend) to the Blackwell deployment recipe — the text `--attention-backend` is unchanged (§2.1 note). On AMD, omit `--mm-attention-backend` and let the encoder use the ROCm default (vision is unvalidated on ROCm — §2.3). > **Vision Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3-MXFP8", > messages=[ > { > "role": "user", > "content": [ > { > "type": "image_url", > "image_url": { > "url": "https://raw.githubusercontent.com/sgl-project/sglang/main/examples/assets/example_image.png" > }, > }, > {"type": "text", "text": "Describe this image in detail."}, > ], > } > ], > max_tokens=1024, > ) > print(response.choices[0].message.content) > ``` > > **Output Example:** > > ```text Output theme={null} > This image captures a striking and unusual urban scene on what appears to be a busy New York City street. > > **Main Subject:** > A man stands on the rear bumper of a yellow taxi cab (an SUV-style cab, likely a Ford Escape hybrid), operating a full-sized ironing board set up across the back of the vehicle. He is wearing a bright yellow long-sleeved shirt and dark pants, and is actively ironing a blue garment, holding an iron in his right hand. > > **Vehicles:** > - The yellow SUV taxi on the right is stationary, its rear hatch serving as the ironing platform. > - A second yellow taxi (a sedan) drives past on the left, captured with motion blur. > > **Setting:** > Tall city buildings with classic urban architecture, an American flag, and white lane markings — a bustling downtown area, possibly Midtown Manhattan. > ``` Notes: * If the server cannot fetch external URLs, embed the image as a base64 `data:image/png;base64,...` URI — SGLang decodes it server-side. * Multiple images per message are supported; add more `image_url` entries to the `content` list. * Reasoning and tool calling work the same way for multimodal requests — a vision prompt can still produce a `` trace and/or tool calls. ### 3.4 Prefill-Decode (PD) Disaggregation [PD disaggregation](../../../docs/advanced_features/pd_disaggregation) runs prefill and decode on **separate** SGLang servers linked by an RDMA KV-transfer fabric (mooncake or NIXL), fronted by the PD router. M3 needs one thing beyond a dense model: alongside the main KV cache, every sparse "lightning-indexer" layer keeps a **K-only index buffer**, and that buffer must reach the decode server too — otherwise sparse attention reads stale state. SGLang transfers it alongside the main KV — reusing the same page mapping — so M3 disaggregates correctly with no extra flags. **Supported topology** (the released MiniMax-M3, whose sparse layers are all K-only): * **Equal tensor parallelism** — the prefill and decode servers run the same `--tp`. * **Single pipeline stage** — PP = 1 (the default). * **mooncake or NIXL** transfer backend over RDMA / InfiniBand. Launch the prefill server, then the decode server — the same recipe with `--disaggregation-mode decode` and no bootstrap port. Pick your hardware: **Blackwell · MXFP8** On Blackwell the MXFP8 recipe — fa4, page size 128, deep\_gemm MoE, and the MSA fast path (§2.1) — is auto-selected, so each role adds only the `--disaggregation-*` flags. This is the validated **2 × 4×B200** setup (TP4 prefill on node A, TP4 decode on node B); point `--disaggregation-ib-device` at your RDMA NIC(s). ```bash Prefill server (node A) theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M3-MXFP8 \ --trust-remote-code \ --reasoning-parser auto \ --tool-call-parser auto \ --tp 4 \ --disaggregation-mode prefill \ --disaggregation-transfer-backend nixl \ --disaggregation-ib-device mlx5_0 \ --host 0.0.0.0 --port 30000 \ --disaggregation-bootstrap-port 8998 ``` ```bash Decode server (node B) theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M3-MXFP8 \ --trust-remote-code \ --reasoning-parser auto \ --tool-call-parser auto \ --tp 4 \ --disaggregation-mode decode \ --disaggregation-transfer-backend nixl \ --disaggregation-ib-device mlx5_0 \ --host 0.0.0.0 --port 30001 ``` **Hopper · bf16** On Hopper (H200) M3 runs the bf16 build (§2.4) with Triton MoE and the built-in Triton sparse path, pinned to `--page-size 128` so both roles share the page layout the sparse-index transfer relies on. This is the validated **2 × 8×H200** setup (TP8 each). ```bash Prefill server (node A) theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M3 \ --trust-remote-code \ --reasoning-parser auto \ --tool-call-parser auto \ --tp 8 \ --attention-backend triton \ --moe-runner-backend triton \ --page-size 128 \ --disaggregation-mode prefill \ --disaggregation-transfer-backend mooncake \ --disaggregation-ib-device mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7 \ --host 0.0.0.0 --port 30000 \ --disaggregation-bootstrap-port 8998 ``` ```bash Decode server (node B) theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-M3 \ --trust-remote-code \ --reasoning-parser auto \ --tool-call-parser auto \ --tp 8 \ --attention-backend triton \ --moe-runner-backend triton \ --page-size 128 \ --disaggregation-mode decode \ --disaggregation-transfer-backend mooncake \ --disaggregation-ib-device mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7 \ --host 0.0.0.0 --port 30001 ``` Then start the PD router, pointing it at the prefill bootstrap (URL plus its `--disaggregation-bootstrap-port`) and the decode endpoint: ```bash PD router theme={null} python3 -m sglang_router.launch_router \ --pd-disaggregation \ --prefill http://:30000 8998 \ --decode http://:30001 \ --policy round_robin \ --host 0.0.0.0 --port 8000 ``` Clients hit the router exactly like a single server — it splits each request across the two stages transparently: > **PD Client Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://:8000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3-MXFP8", > messages=[{"role": "user", "content": "What is 2 + 2?"}], > max_tokens=64, > ) > print(response.choices[0].message.content) > ``` > > **Output Example:** > > ```text Output theme={null} > 2 + 2 = 4 > ``` **Validation.** PD disaggregation preserves output quality — the K-only sparse index transfers arrive intact and disaggregated output matches non-disaggregated serving. GSM8K is scored with the single sgl-eval harness used by the benchmark card above (full 1319-question split, chat with `--thinking`); see that card for per-platform single-node accuracy. * **2 × 4×B200** (TP4+TP4, MXFP8, NIXL over InfiniBand) — output matches single-node serving. The 2-node PD serving benchmark (512-token input, 256-token output, 16 concurrent — a different workload from the card's single-node `random` isl=2048 / osl=256 / conc=64 row, so the throughput figures are not directly comparable) measured mean TTFT 1.1 s and TPOT 16.6 ms (≈ 60 tok/s per stream, ≈ 2.3k tok/s aggregate). * **2 × 8×H200** (TP8+TP8, bf16, mooncake) — output matches single-node serving. # MiniMax-M3.1 Source: https://docs.sglang.io/cookbook/autoregressive/MiniMax/MiniMax-M3.1 Deploy MiniMax-M3.1-Flash with SGLang — the static-NVFP4 build of MiniMax's sparse-attention Mixture-of-Experts reasoning model, with its bundled DSpark draft or RadixArk's DFlash2 draft for speculative decoding, on NVIDIA and AMD. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > MiniMax-M3.1 support has not yet been merged into SGLang `main`. Install from the support PR below. The PR number is **TBD**; replace `TBD` with the actual PR number before running these commands. > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > > PR_NUMBER= > git clone https://github.com/sgl-project/sglang.git > cd sglang > git fetch origin "pull/${PR_NUMBER}/head" > git checkout FETCH_HEAD > uv pip install --prerelease=allow -e python > cd .. > ``` > > On NVIDIA Blackwell (B300 / GB300 / B200), also install the MSA sparse-attention kernels at the tested commit. SGLang imports them at startup, and the server fails without them. Hopper and AMD do not use them. Some of these kernels are compiled at runtime and need a **CUDA toolkit (`nvcc`) >= 13.4** on the machine. The CUDA version of the PyTorch wheel (`cu130`) does not count. See [Blackwell prerequisites](#blackwell-prerequisites). > > ```bash Command theme={null} > git clone https://github.com/MiniMax-AI/MSA.git > cd MSA > git checkout c8e1013a16a708d2a7656805d5fc26f2b87715d1 > uv pip install --no-deps -e . > cd .. > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-minimax-m31-flash > # AMD MI350X / MI355X (ROCm 7.2): > docker pull lmsysorg/sglang:dev-minimax-m31-flash-mi35x > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your hardware + recipe to generate the launch command. The serving strategies cover the common operating points: * **Low-Latency** — fastest responses with a few users at once. On B300 it serves one request at a time through the MSA-V1 MonoKernel; on AMD it is a TP4 recipe for up to about 32 concurrent requests. * **Balanced** — good speed with several users at once. Use for typical multi-user serving. * **High-Throughput** — most tokens per second across many users. Best for batch jobs and many concurrent agent sessions. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction **Resources:** [HuggingFace](https://huggingface.co/MiniMaxAI/MiniMax-M3.1-Flash), [DFlash2 draft](https://huggingface.co/RadixArk/Minimax-M3.1-Flash-Dflash2). ## 2. Configuration Tips ### NVIDIA Blackwell (B300 / GB300 / B200) * **`FMHA_SM100_ALLOW_JIT=1`** lets the MSA sparse-attention kernels compile on first launch. They are cached under `~/.cache/minfer/msa_v1` (override with `MSA_V1_AOT_CACHE`) and reused afterwards. Without the variable and without a cached build, the server fails at startup with `JIT compilation is disabled and AOT kernel ... was not found`. Only the variable's presence is checked, so `=0` does not turn JIT off. An image that ships a prebuilt cache can drop it. * **CUDA toolkit >= 13.4.** The decode path dequantizes the NVFP4 KV cache with the `qmul4` kernel, which needs `nvcc` 13.4 or newer. The toolkit is taken from `CUDA_HOME`, then `CUDACXX`, then the `nvcc` on `PATH` or `/usr/local/cuda`. An older toolkit does not fail: the server silently falls back to a slower path with an extra FP8 scratch buffer. Check that the startup log prints `nvfp4_to_fp8 backend=qmul4`, and point `CUDA_HOME` at a 13.4 toolkit (for example `/usr/local/cuda-13.4`) if it does not. * **The first launch is slow** while these kernels and the FlashInfer kernels compile. Later launches on the same machine reuse the caches. * **DSpark draft.** The checkpoint ships the DSpark draft in its own `dspark/` subfolder. With `--speculative-algorithm DSPARK` and no `--speculative-draft-model-path`, the server finds that subfolder and loads the draft from it, for a Hub repo id as well as a local directory, so the recipes need no draft flag. Pass `--speculative-draft-model-path` only to use a different draft. * **DFlash2 draft.** Pick **DFlash2** under **Speculative Decoding** in the command panel to use RadixArk's trained draft instead. It is a separate checkpoint, so the command passes `--speculative-algorithm DFLASH --speculative-draft-model-path RadixArk/Minimax-M3.1-Flash-Dflash2`. It also adds `--speculative-use-block-verification`, which accepts sampled draft proposals by their joint probability instead of token by token. For a greedy draft the two are the same, and the server logs that the flag has no effect. DFlash2 runs on Blackwell only, without DP attention (so not with the B300 / B200 High-Throughput recipes, which use `--attn-dp-size 2`), and only in colocated serving. ### MonoKernel (Low-Latency) The B300 **Low-Latency** recipe serves batch-size-1 decode through the MSA-V1 MonoKernel plugin with `--monokernel-backend msa`. The plugin supports Blackwell sm\_100 and sm\_103 (B200 / GB200 and B300 / GB300) at `--tp 4` only; it has been measured on B300. Each MoE layer of the DSpark verify step runs as two persistent kernels, MegaAttention then the token-parallel MoE, each fused with its TP4 all-reduce. The DSpark draft step runs as one cooperative kernel per rank. On 4x B300 with the acceptance length fixed at 5, decode reaches 1028 tokens/s at 1K context, 919 at 256K and 723 at 1M, against 479, 465 and 408 on the standard path. * **Batch size 1 only.** Prefill, plain decode and batches of more than one request run on the standard path, so throughput under concurrency is lower than the Balanced recipe. The recipe caps `--max-running-requests` at 8. * **Required flags.** The plugin needs `--page-size 128`, a DSpark chain of 8 draft tokens (`--speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 8 --speculative-dspark-block-size 7`), and `--disable-attn-tp-gather`; without the last one SGLang pads the 7-row draft block and the server refuses to start. At startup the server lists every unsupported setting it finds, and the log confirms the plugin with `--monokernel-backend msa: minimax_m3_msa_v1 on sm_103, widths [8]`. * **`ALLOW_JIT=1`** lets the MonoKernel kernels compile on first launch; set `CACHE_DIR` to keep the compiled kernels across restarts. * **`SGLANG_FORCE_COARSE_WAR_BARRIER=1`** runs MegaAttention in canonical cluster placement, about 3–4% faster end to end. Canonical placement faults if another kernel holds SMs when MegaAttention launches, so the server must have the GPUs to itself. Without the variable, the server keeps cluster placement on, which is safe and slightly slower. The log prints `cluster placement off (canonical)` or `cluster placement on`. * **Memory.** The plugin keeps its own copy of the routed experts (54.1 GiB per rank), so at `--mem-fraction-static 0.8` the KV pool holds about 6.5M tokens instead of 10.4M. * DFlash2 is not available with this recipe. ### Memory and workload tuning * **`--mem-fraction-static 0.8`** is the validated value at `--tp 4` on B300, and also on B200. The pool it reserves holds the NVFP4 main KV cache, the sparse-attention index cache and the bf16 DSpark draft KV cache. B200 has 192 GB per GPU against B300's 288 GB. Its high-throughput recipe (`--tp 8 --attn-dp-size 2`) therefore uses `--mem-fraction-static 0.75` and `--cuda-graph-max-bs-prefill 16384`. With B300's settings, 8x B200 runs out of GPU memory capturing the 32k-token prefill CUDA graphs, and then while preprocessing images on GPU 0. * **`--tokenizer-worker-num 8`.** With 100K-token prompts a single tokenizer process becomes the bottleneck: tokenization blocks the server's event loop and TTFT climbs under load even when the GPUs have headroom. Eight workers remove that ceiling, so every recipe above sets it. * **Hierarchical KV cache for multi-turn traffic.** `--enable-hierarchical-cache --hicache-size ` keeps evicted prefixes in host memory so a returning session reloads its prefix instead of recomputing it. Adding `--hicache-storage-backend mooncake` puts a Mooncake storage tier (L3) under it, which a set of replicas can share; pick **Mooncake** under **Storage** in the HiCache card of the [Playground](#playground). The Mooncake tier is validated on GB300 and B300, with DSpark and with DFlash speculative decoding. Other storage backends have not been validated. For the Mooncake master and environment setup, see [Deployment with Mooncake](../../../docs/advanced_features/hicache_best_practices#deployment-with-mooncake). When several replicas serve one endpoint, put the router in front with `--policy cache_aware` so a session's later turns reach the replica that holds its prefix. * **`--max-running-requests` and `--cuda-graph-max-bs-decode`** are both 128 in the recipes. Keep them equal so every decode batch the scheduler can form replays a captured CUDA graph. ### AMD MI350X / MI355X * Requires ROCm 7.2 (Triton 3.7); earlier ROCm images are not supported. * **NVFP4 on MI355X:** the same `MiniMaxAI/MiniMax-M3.1-Flash` checkpoint as on NVIDIA; the routed experts are requantized to MXFP4 while loading. * **MXFP4 on MI350X / MI355X:** `amd/MiniMax-M3.1-Flash-Quark-MXFP4` (Quark-quantized), same command as NVFP4 Low-Latency on both; select **MI350X / MXFP4** or **MI355X / MXFP4** in the panel. Only the Low-Latency recipe has been run with this checkpoint. * **One server per four GPUs.** M3.1 NVFP4 on ROCm runs at `--tp 4` or less, and the server refuses a larger TP. On an 8-GPU node, start two servers with `HIP_VISIBLE_DEVICES=0,1,2,3` and `HIP_VISIBLE_DEVICES=4,5,6,7` on different ports, and put the router in front with `--policy cache_aware`. * **Pick the recipe by concurrency.** Low-Latency is for up to about 32 concurrent requests. High-Throughput is for 48 or more concurrent long multi-turn sessions, such as coding agents, and adds two things to Low-Latency: * **Hierarchical KV cache** (`--enable-hierarchical-cache`). At the default ratio of 2, the host pools (main KV, index K and draft KV) take about 350 GB per rank, so one TP4 server needs about 1.4 TB of host memory. On a host with less free memory, the server lowers the ratio until the pools fit in 80% of it. When two servers share a host, lower `--hicache-host-memory-fraction` on each. * **FP8 DSpark draft KV cache** (`--speculative-draft-kv-cache-dtype fp8_e4m3`). The same memory holds 9% more tokens. The draft cache only affects which draft tokens get accepted; the target model still verifies every token. * **`--prefill-decode-interval 16`** runs 16 decode steps after each prefill batch before the next prefill. With 64 concurrent sessions and HiCache on MI350X, it lowered P90 inter-token latency by about 10% at the cost of about 3% throughput. * The High-Throughput recipe was measured on MI350X. MI355X runs the same command but has not been measured with it. ## 3. Advanced Usage ### 3.1 Reasoning Enable the `minimax-m3` reasoning parser (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to separate thinking from the final answer. The `` trace then lands in `message.reasoning_content`, separate from the final answer in `message.content`. The reasoning traces in the example outputs below are abridged; `…` marks omitted text. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3.1-Flash", > messages=[{"role": "user", "content": "What is 15% of 240? Explain briefly."}], > max_tokens=4096, > ) > > message = response.choices[0].message > print("=============== Reasoning ===============") > print(message.reasoning_content) > print("=============== Answer ==================") > print(message.content) > ``` > **Example Output** > > ```text Output theme={null} > =============== Reasoning =============== > … Calculate 15%=0.15*240 = 36. Brief explanation likely 10%=24, 5%=12 total 36 or 0.15×240. … > =============== Answer ================== > 15% of 240 is **36**. > > Calculation: \(0.15 \times 240 = 36\). > ``` When streaming, the trace arrives on `delta.reasoning_content` and the answer on `delta.content`, so the two can be rendered separately as they arrive: > **Streaming Reasoning (Python)** > > ```python Example theme={null} > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3.1-Flash", > messages=[{"role": "user", "content": "Solve step by step: what is 15% of 240?"}], > max_tokens=4096, > stream=True, > ) > > for chunk in response: > if not chunk.choices: > continue > delta = chunk.choices[0].delta > if getattr(delta, "reasoning_content", None): > print(delta.reasoning_content, end="", flush=True) # thinking stream > if delta.content: > print(delta.content, end="", flush=True) # answer stream > print() > ``` > **Example Output** > > ```text Output theme={null} > [delta.reasoning_content — thinking stream] > … Can give 15%=15/100=.15, .15×240=(15×240)/100=3600/100=36. … > > [delta.content — answer stream] > 1. Convert the percentage to a decimal: \(15\% = 0.15\). > 2. Multiply by 240: \(0.15 \times 240 = 36\). > > **Answer: 36** > ``` ### 3.2 Thinking Mode and Reasoning Effort M3.1 takes two request-level controls. Pass them as top-level fields of the Chat Completions body, through `extra_body` with the OpenAI client: * **`thinking`** — `{"type": "enabled" | "disabled" | "adaptive"}`. `enabled` always thinks before answering, `disabled` answers directly, and `adaptive` lets the model decide per turn. Omitting it means `adaptive`. Any other `type` is rejected with HTTP 400. * **`reasoning_effort`** — `"low"`, `"medium"`, `"high"`, `"xhigh"` or `"max"`. The value is passed to the chat template, which tells the model how much to reason. `"none"` and `"minimal"` turn thinking off, the same as `thinking={"type": "disabled"}`. The effort is ignored when thinking is disabled. > **Thinking Mode and Effort Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > question = [{"role": "user", "content": "How many prime numbers are there below 50?"}] > > for label, extra in [ > ("thinking disabled", {"thinking": {"type": "disabled"}}), > ("adaptive, effort low", {"thinking": {"type": "adaptive"}, "reasoning_effort": "low"}), > ("enabled, effort max", {"thinking": {"type": "enabled"}, "reasoning_effort": "max"}), > ]: > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3.1-Flash", > messages=question, > max_tokens=8192, > extra_body=extra, > ) > message = response.choices[0].message > reasoning_chars = len(message.reasoning_content or "") > print(f"[{label}] reasoning chars: {reasoning_chars}") > print(f" answer: {message.content.strip()}") > ``` > **Example Output** > > ```text Output theme={null} > [thinking disabled] reasoning chars: 0 > answer: There are **15** prime numbers below 50: > > 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, and 47. > [adaptive, effort low] reasoning chars: 8 > answer: There are **15** prime numbers below 50: > > 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47. > [enabled, effort max] reasoning chars: 268 > answer: There are **15 prime numbers** below 50: > > 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, and 47. > ``` ### 3.3 Tool Calling Enable the `minimax-m3` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["location"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3.1-Flash", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > > message = response.choices[0].message > if message.tool_calls: > for call in message.tool_calls: > print(f"Tool: {call.function.name}") > print(f"Args: {call.function.arguments}") > ``` > **Example Output** > > ```text Output theme={null} > Tool: get_weather > Args: {"location": "Beijing", "unit": "celsius"} > ``` To return a tool result, append the assistant turn with its `tool_calls` and one `tool` message per call (matching `tool_call_id`), then ask the model to continue. ### 3.4 Multimodal (Vision) Input Images go through the standard OpenAI `image_url` content type. > **Vision Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="MiniMaxAI/MiniMax-M3.1-Flash", > messages=[ > { > "role": "user", > "content": [ > { > "type": "image_url", > "image_url": { > "url": "https://raw.githubusercontent.com/sgl-project/sglang/main/examples/assets/example_image.png" > }, > }, > {"type": "text", "text": "Describe this image in two sentences."}, > ], > } > ], > max_tokens=4096, > ) > print(response.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > A man in a yellow shirt stands on the rear bumper of a yellow taxi, pressing clothes on an ironing board extending from its open hatch. Another yellow taxi speeds past on the city street lined with tall buildings. > ``` ### 3.5 Prefill-Decode (PD) Disaggregation [PD disaggregation](../../../docs/advanced_features/pd_disaggregation) runs prefill and decode on **separate** SGLang servers, linked by an RDMA KV-transfer fabric and fronted by the PD router. Each M3.1 layer stores three things the decode server needs: the packed NVFP4 main KV cache with its block scales, an NVFP4 K-only sparse-index cache, and, with DSpark, the draft model's KV cache. SGLang sends all three from prefill to decode over the same page mapping, so PD needs no M3.1-specific flags. **Supported topology** * **Same attention parallelism on both roles.** Prefill and decode must use the same `--tp` and `--attn-dp-size`. The sparse-index transfer cannot reshard across different attention TP sizes. * **Single pipeline stage.** PP must be 1, which DSpark also requires. * **Speculative decoding.** Run DSpark on both roles. DFlash2 is only supported in colocated serving. * **Transfer backend.** Mooncake over RDMA. * **KV caching.** Run HiCache on the prefill server. The decode server keeps its default chunk cache. `--disaggregation-decode-enable-radix-cache` lets decode reuse prefixes it already holds. It is experimental and off by default. * **HiCache on the decode server needs the decode radix cache.** A decode server turns its radix cache off unless `--disaggregation-decode-enable-radix-cache` is set, and `--enable-hierarchical-cache` with the radix cache off fails at startup (`enable-hierarchical-cache and disable-radix-cache are mutually exclusive`). Pass both flags on decode. The decode radix cache works with DSpark or without speculative decoding. With DP attention, route each session to the same DP rank so it finds its prefix. The playground adds the flag when you pick the decode role with HiCache on. **Recommended layout: DP8 / TP1 / EP8 on each role.** Each role takes one 8×B300 node: * Attention is data-parallel over eight ranks, each with attention TP 1 (`--tp 8 --attn-dp-size 8`). * The experts are split eight ways through MegaMoE (`--ep 8`). * The other flags follow the B300 High-Throughput recipe. On B300, picking **Prefill role** or **Decode role** in the [Playground](#playground) PD card applies this layout to either recipe. Start the prefill server on node A, the decode server on node B, and then the router. Mooncake picks the RDMA NICs automatically; add `--disaggregation-ib-device` to pin specific ones. ```bash Prefill server (node A) theme={null} FMHA_SM100_ALLOW_JIT=1 \ SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK=32768 \ sglang serve \ --model-path MiniMaxAI/MiniMax-M3.1-Flash \ --trust-remote-code \ --reasoning-parser minimax-m3 \ --tool-call-parser minimax-m3 \ --tp 8 \ --attn-dp-size 8 \ --enable-dp-lm-head \ --ep 8 \ --speculative-algorithm DSPARK \ --cuda-graph-backend-prefill breakable \ --chunked-prefill-size 65536 \ --max-running-requests 256 \ --cuda-graph-max-bs-decode 128 \ --mem-fraction-static 0.8 \ --tokenizer-worker-num 8 \ --enable-hierarchical-cache \ --hicache-size 192 \ --disaggregation-mode prefill \ --disaggregation-transfer-backend mooncake \ --disaggregation-bootstrap-port 8998 \ --host 0.0.0.0 --port 30000 ``` ```bash Decode server (node B) theme={null} FMHA_SM100_ALLOW_JIT=1 \ SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK=32768 \ sglang serve \ --model-path MiniMaxAI/MiniMax-M3.1-Flash \ --trust-remote-code \ --reasoning-parser minimax-m3 \ --tool-call-parser minimax-m3 \ --tp 8 \ --attn-dp-size 8 \ --enable-dp-lm-head \ --ep 8 \ --speculative-algorithm DSPARK \ --cuda-graph-backend-prefill breakable \ --chunked-prefill-size 65536 \ --max-running-requests 256 \ --cuda-graph-max-bs-decode 128 \ --mem-fraction-static 0.8 \ --tokenizer-worker-num 8 \ --disaggregation-mode decode \ --disaggregation-transfer-backend mooncake \ --host 0.0.0.0 --port 30100 ``` ```bash Router theme={null} python3 -m sglang_router.launch_router \ --pd-disaggregation \ --prefill http://:30000 8998 \ --decode http://:30100 \ --policy round_robin \ --host 0.0.0.0 --port 8000 ``` The `8998` after the prefill URL is the prefill bootstrap port. It must match the prefill server's `--disaggregation-bootstrap-port`. * **HiCache host memory.** `--hicache-size` is per rank, so at DP8 the prefill node reserves 8 × 192 GB of host memory for the host pools. Lower it on nodes with less memory. * **MegaMoE token budget.** `SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK` must cover each rank's share of a prefill chunk (65536 / 8 here) and its largest decode or verify batch. * **Media options through the router.** The PD router forwards only the standard OpenAI request fields. Per-request media options such as `max_long_side_pixel` and video `fps` do not reach the servers; this was observed with sglang-router 0.3.2. > [!NOTE] > > Correctness was validated on 1P1D with TP4 on each role (8×B300, Mooncake, DSpark on both roles, HiCache on prefill). GSM8K matched colocated serving, and `--disaggregation-enable-kv-checksum` reported no mismatch. The DP8 / TP1 / EP8 layout has not been benchmarked yet. # Devstral 2 (Mistral) Source: https://docs.sglang.io/cookbook/autoregressive/Mistral/Devstral-2 ## 1. Model Introduction **Devstral 2** is an agentic LLM family for software engineering tasks. It is designed for agentic workflows such as tool use, codebase exploration, and multi-file edits, and achieves strong performance on **SWE-bench**. The **Devstral 2 Instruct** checkpoints are instruction-tuned **FP8** models, making them a good fit for chat, tool-using agents, and instruction-following SWE workloads. **Key Features:** * **Agentic coding**: Optimized for tool-driven coding and software engineering agents * **Improved performance**: A step up compared to earlier Devstral models * **Better generalization**: More robust across diverse prompts and coding environments * **Long context**: Up to a **256K** context window **Use Cases:** AI code assistants, agentic coding, and software engineering tasks that require deep codebase understanding and tool integration. For enterprises requiring specialized capabilities (increased context, domain-specific knowledge, etc.), please reach out to Mistral. **Models:** * **Collection**: [mistralai/devstral-2 (Hugging Face)](https://huggingface.co/collections/mistralai/devstral-2) * **FP8 Instruct**: * **[mistralai/Devstral-2-123B-Instruct-2512](https://huggingface.co/mistralai/Devstral-2-123B-Instruct-2512)** * **[mistralai/Devstral-Small-2-24B-Instruct-2512](https://huggingface.co/mistralai/Devstral-Small-2-24B-Instruct-2512)** *** ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. > [!WARNING] > > Devstral 2 requires a recent `transformers`. Please verify `transformers >= 5.0.0.rc`: > > ```shell Command theme={null} > python -c "import transformers; print(transformers.__version__)" > ``` > > If your version is lower, upgrade: > > ```shell Command theme={null} > pip install -U --pre "transformers>=5.0.0rc0" > ``` *** ## 3. Model Deployment ### 3.1 Basic configuration **Interactive Command Generator**: Use the configuration selector below to generate a launch command for Devstral Small 2 (24B) or Devstral 2 (123B). > [!NOTE] > > The TP size is set to the minimum required for the selected model size. Run this Command:

### 3.2 Configuration tips

* **Context length vs memory**: Devstral 2 advertises a long context window; if you are memory-constrained, start by lowering `--context-length` (for example `32768`) and increase once things are stable.
* **FP8 checkpoints**: Both Devstral Small 2 and Devstral 2 are published as **FP8** weights. If you hit kernel / dtype issues, try a newer SGLang build and recent CUDA drivers.

***

## 4. Model Invocation

### 4.1 Basic Usage (OpenAI-Compatible API)

SGLang exposes an OpenAI-compatible endpoint. Example:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

resp = client.chat.completions.create(
    model="mistralai/Devstral-Small-2-24B-Instruct-2512",
    messages=[
        {"role": "system", "content": "You are a helpful coding assistant."},
        {"role": "user", "content": "Write a Python function that retries a request with exponential backoff."},
    ],
    temperature=0.2,
    max_tokens=512,
)

print(resp.choices[0].message.content)
```

**Output Example:**

````text Output theme={null}
  Here's a Python function that implements exponential backoff for retrying a request. This function uses the `requests` library to make HTTP requests and includes error handling for common HTTP and connection errors.

  ```python
  import time
  import requests
  from requests.exceptions import RequestException

  def retry_with_exponential_backoff(
      url,
      max_retries=3,
      initial_delay=1,
      backoff_factor=2,
      method="GET",
      **kwargs
  ):
      """
      Retry a request with exponential backoff.

      Parameters:
      - url: The URL to request.
      - max_retries: Maximum number of retry attempts (default: 3).
      - initial_delay: Initial delay in seconds (default: 1).
      - backoff_factor: Multiplier for the delay between retries (default: 2).
      - method: HTTP method to use (default: "GET").
      - **kwargs: Additional arguments to pass to the request function (e.g., headers, data, etc.).

      Returns:
      - Response object if the request succeeds.
      - Raises an exception if all retries fail.
      """
      retry_count = 0
      delay = initial_delay

      while retry_count < max_retries:
          try:
              response = requests.request(method, url, **kwargs)
              # Check if the response status code indicates success
              if response.status_code < 400:
                  return response
              else:
                  raise RequestException(f"HTTP {response.status_code}: {response.text}")

          except RequestException as e:
              if retry_count == max_retries - 1:
                  raise Exception(f"All retries failed. Last error: {e}")

              print(f"Attempt {retry_count + 1} failed. Retrying in {delay} seconds...")
              time.sleep(delay)
...
````

### 4.2 Tool calling (optional)

Devstral 2 supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model mistralai/Devstral-2-123B-Instruct-2512 \
  --tp 2 \
  --tool-call-parser mistral
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="mistralai/Devstral-2-123B-Instruct-2512",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"🔧 Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Output Example:**

```text Output theme={null}
🔧 Tool Call: get_weather
   Arguments: {"location": "Beijing"}
```

## AMD GPU Support

## 1. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 1.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 1.2 Advanced Usage

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path mistralai/Devstral-2-123B-Instruct-2512 \
  --tp 8 \
  --trust-remote-code \
  --port 8888
```

## 2.Benchmark

### 5.1 Benchmark Commands

**Scenario 1: Chat (1K/1K) - Most Important**

* **Model Deployment**

```bash Command theme={null}
python3 -m sglang.launch_server \
  --model-path mistralai/Devstral-2-123B-Instruct-2512 \
  --tp 8 \
  --trust-remote-code \
  --port 8888
```

* Low Concurrency (Latency-Optimized)

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Devstral-2-123B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf \
  --port 8888
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  94.30
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4206
Request throughput (req/s):              0.11
Input token throughput (tok/s):          64.70
Output token throughput (tok/s):         44.75
Peak output token throughput (tok/s):    82.00
Peak concurrent requests:                2
Total token throughput (tok/s):          109.44
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   9427.59
Median E2E Latency (ms):                 5637.23
---------------Time to First Token----------------
Mean TTFT (ms):                          4253.85
Median TTFT (ms):                        116.95
P99 TTFT (ms):                           37764.48
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          12.28
Median TPOT (ms):                        12.29
P99 TPOT (ms):                           12.30
---------------Inter-Token Latency----------------
Mean ITL (ms):                           12.29
Median ITL (ms):                         12.29
P95 ITL (ms):                            12.38
P99 ITL (ms):                            12.42
Max ITL (ms):                            12.90
==================================================
```

* Medium Concurrency (Balanced)

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Devstral-2-123B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf \
  --port 8888
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  52.11
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    40761
Request throughput (req/s):              1.54
Input token throughput (tok/s):          761.31
Output token throughput (tok/s):         783.13
Peak output token throughput (tok/s):    1120.00
Peak concurrent requests:                20
Total token throughput (tok/s):          1544.44
Concurrency:                             13.60
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   8856.19
Median E2E Latency (ms):                 9314.71
---------------Time to First Token----------------
Mean TTFT (ms):                          398.80
Median TTFT (ms):                        127.81
P99 TTFT (ms):                           1500.32
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          17.32
Median TPOT (ms):                        16.90
P99 TPOT (ms):                           32.78
---------------Inter-Token Latency----------------
Mean ITL (ms):                           16.61
Median ITL (ms):                         14.26
P95 ITL (ms):                            15.07
P99 ITL (ms):                            114.46
Max ITL (ms):                            1224.45
==================================================
```

* High Concurrency (Throughput-Optimized)

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Devstral-2-123B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf \
  --port 8888
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  116.08
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    252523
Request throughput (req/s):              4.31
Input token throughput (tok/s):          2152.21
Output token throughput (tok/s):         2176.60
Peak output token throughput (tok/s):    3600.00
Peak concurrent requests:                107
Total token throughput (tok/s):          4328.81
Concurrency:                             92.42
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   21456.71
Median E2E Latency (ms):                 20126.82
---------------Time to First Token----------------
Mean TTFT (ms):                          291.60
Median TTFT (ms):                        199.24
P99 TTFT (ms):                           866.02
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          42.42
Median TPOT (ms):                        45.18
P99 TPOT (ms):                           53.32
---------------Inter-Token Latency----------------
Mean ITL (ms):                           41.97
Median ITL (ms):                         27.59
P95 ITL (ms):                            130.43
P99 ITL (ms):                            137.87
Max ITL (ms):                            616.73
==================================================
```

#### 5.2 Understanding the Results

**Key Metrics:**

* **Request Throughput (req/s)**: Number of requests processed per second
* **Output Token Throughput (tok/s)**: Total tokens generated per second
* **Mean TTFT (ms)**: Time to First Token - measures responsiveness
* **Mean TPOT (ms)**: Time Per Output Token - measures generation speed
* **Mean ITL (ms)**: Inter-Token Latency - measures streaming consistency

**Why These Configurations Matter:**

* **1K/1K (Chat)**: Represents the most common conversational AI workload. This is the highest priority scenario for most deployments.
* **1K/8K (Reasoning)**: Tests long-form generation capabilities crucial for complex reasoning, code generation, and detailed explanations.
* **8K/1K (Summarization)**: Evaluates performance with large context inputs, essential for RAG systems, document Q\&A, and summarization tasks.
* **Variable Concurrency**: Captures the Pareto frontier - the optimal trade-off between throughput and latency at different load levels. Low concurrency shows best-case latency, high concurrency shows maximum throughput.

**Interpreting Results:**

* Compare your results against baseline numbers for your hardware
* Higher throughput at same latency = better performance
* Lower TTFT = more responsive user experience
* Lower TPOT = faster generation speed

### 5.3 Accuracy Benchmark

Document model accuracy on standard benchmarks:

#### 5.3.1 GSM8K Benchmark

* Benchmark Command

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:8888/v1 \
  --num-examples 1319 \
  --num-threads 1316
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Test Results:**

```text Output theme={null}
Accuracy: 0.922
Invalid: 0.000
Latency: 35.800 s
Output throughput: 4507.697 token/s
```


# Ministral-3
Source: https://docs.sglang.io/cookbook/autoregressive/Mistral/Ministral-3



## 1. Model Introduction

The largest model in the Ministral 3 family, Ministral 3 14B offers frontier capabilities and performance comparable to its larger Mistral Small 3.2 24B counterpart. A powerful and efficient language model with vision capabilities.

The Ministral 3 14B Instruct model offers the following capabilities:

Vision: Enables the model to analyze images and provide insights based on visual content, in addition to text.
Multilingual: Supports dozens of languages, including English, French, Spanish, German, Italian, Portuguese, Dutch, Chinese, Japanese, Korean, Arabic.
System Prompt: Maintains strong adherence and support for system prompts.
Agentic: Offers best-in-class agentic capabilities with native function calling and JSON outputting.
Edge-Optimized: Delivers best-in-class performance at a small scale, deployable anywhere.
Apache 2.0 License: Open-source license allowing usage and modification for both commercial and non-commercial purposes.
Large Context Window: Supports a 256k context window.

For further details, please refer to the [official documentation](https://github.com/mistralai)

## 2. SGLang Installation

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and thinking capabilities.

Run this Command:


### 3.2 Configuration Tips

**Context length vs memory**: Ministral-3 advertises a long context window; if you are memory-constrained, start by lowering --context-length (for example 32768) and increase once things are stable.

**Pre-installation steps**: Adding the following steps after launching the docker

```shell Command theme={null}
pip install mistral-common --upgrade
pip install transformers==5.0.0.rc0
```

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Launch the docker

```shell Command theme={null}
docker pull lmsysorg/sglang:v0.5.9-rocm720-mi30x
```

```shell Command theme={null}
docker run -d -it --ipc=host --network=host --privileged \
  --cap-add=CAP_SYS_ADMIN \
  --device=/dev/kfd --device=/dev/dri --device=/dev/mem \
  --group-add video --cap-add=SYS_PTRACE \
  --security-opt seccomp=unconfined \
  -v /:/work \
  -e SHELL=/bin/bash \
  --name Ministral \
 lmsysorg/sglang:v0.5.9-rocm720-mi30x \
  /bin/bash
```

#### 4.2.2 Launch the server

```shell Command theme={null}
sglang serve \
  --model-path mistralai/Ministral-3-14B-Instruct-2512 \
  --tp 1 \
  --trust-remote-code
```

## 5. Benchmark

This section uses **industry-standard configurations** for comparable benchmark results.

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: MI300X GPU (8x)

* Model: mistralai/Ministral-3-14B-Instruct-2512

* Tensor Parallelism: 1

* SGLang Version: 0.5.7

* Model Deployment Command:

```bash Command theme={null}
sglang serve \
  --model-path mistralai/Ministral-3-14B-Instruct-2512 \
  --tp 1 \
  --trust-remote-code
```

##### Low Concurrency

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Ministral-3-14B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  65.08
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4218
Request throughput (req/s):              0.15
Input token throughput (tok/s):          93.75
Output token throughput (tok/s):         64.84
Peak output token throughput (tok/s):    151.00
Peak concurrent requests:                2
Total token throughput (tok/s):          158.59
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   6505.51
Median E2E Latency (ms):                 3037.37
---------------Time to First Token----------------
Mean TTFT (ms):                          3709.33
Median TTFT (ms):                        53.72
P99 TTFT (ms):                           33320.77
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          6.63
Median TPOT (ms):                        6.64
P99 TPOT (ms):                           6.66
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.64
Median ITL (ms):                         6.65
P95 ITL (ms):                            6.75
P99 ITL (ms):                            6.82
Max ITL (ms):                            8.45
==================================================
```

##### Medium Concurrency

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Ministral-3-14B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  31.20
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    40783
Request throughput (req/s):              2.56
Input token throughput (tok/s):          1271.38
Output token throughput (tok/s):         1307.82
Peak output token throughput (tok/s):    1760.00
Peak concurrent requests:                22
Total token throughput (tok/s):          2579.20
Concurrency:                             13.72
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5351.07
Median E2E Latency (ms):                 5626.45
---------------Time to First Token----------------
Mean TTFT (ms):                          280.87
Median TTFT (ms):                        68.16
P99 TTFT (ms):                           1194.79
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.47
Median TPOT (ms):                        10.10
P99 TPOT (ms):                           20.00
---------------Inter-Token Latency----------------
Mean ITL (ms):                           9.96
Median ITL (ms):                         9.10
P95 ITL (ms):                            9.87
P99 ITL (ms):                            51.39
Max ITL (ms):                            888.63
==================================================
```

##### High Concurrency

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model mistralai/Ministral-3-14B-Instruct-2512 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  88.75
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    252547
Request throughput (req/s):              5.63
Input token throughput (tok/s):          2815.01
Output token throughput (tok/s):         2846.91
Peak output token throughput (tok/s):    4271.00
Peak concurrent requests:                110
Total token throughput (tok/s):          5661.93
Concurrency:                             93.04
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   16514.45
Median E2E Latency (ms):                 15834.45
---------------Time to First Token----------------
Mean TTFT (ms):                          148.57
Median TTFT (ms):                        99.15
P99 TTFT (ms):                           455.86
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          32.93
Median TPOT (ms):                        34.73
P99 TPOT (ms):                           38.05
---------------Inter-Token Latency----------------
Mean ITL (ms):                           32.45
Median ITL (ms):                         27.30
P95 ITL (ms):                            71.73
P99 ITL (ms):                            73.45
Max ITL (ms):                            328.10
==================================================
```

### 5.2 Accuracy Benchmark

Document model accuracy on standard benchmarks:

#### 5.2.1 GSM8K Benchmark

* Benchmark Command

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 1319 \
  --num-threads 1316
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Test Results:**

```text Output theme={null}
Accuracy: 0.959
Invalid: 0.000
Latency: 29.185 s
Output throughput: 4854.672 token/s
```


# Mistral Medium 3.5
Source: https://docs.sglang.io/cookbook/autoregressive/Mistral/Mistral-Medium-3.5



## 1. Model Introduction

**Mistral Medium 3.5** is Mistral AI's first flagship **merged model** — a single dense 128B checkpoint that handles instruction following, reasoning, and coding in one set of weights. It replaces Mistral Medium 3.1 and Magistral in Le Chat, and replaces Devstral 2 in the Vibe coding agent. Reasoning effort is configurable per request, so the same model can answer a quick chat reply or work through a deep agentic run. The vision encoder was trained from scratch to handle variable image sizes and aspect ratios.

**Key Features:**

* **Dense 128B parameters** — no MoE, no MLA, plain GQA (96 heads, 8 KV heads, head\_dim=128)
* **256K context window** — YARN RoPE scaling on top of the original 4K base
* **Hybrid Reasoning**: Toggle between instant reply and deep reasoning per request via `reasoning_effort` (`"none"` or `"high"`)
* **Vision**: Accepts text + image input; from-scratch encoder that handles variable image sizes/aspect ratios
* **Function Calling**: Native tool calling and JSON output
* **FP8 Native**: Released with FP8 e4m3 static-tensor quantization built in
* **Multilingual**: 24 supported languages including English, French, German, Spanish, Portuguese, Italian, Japanese, Korean, Russian, Chinese, Arabic, Persian, Indonesian, Malay, Nepali, Polish, Romanian, Serbian, Swedish, Turkish, Ukrainian, Vietnamese, Hindi, and Bengali
* **License**: Modified MIT (open for commercial and non-commercial use except for companies with large revenue)

**Architecture:**

* Mistral 3 backbone with YARN RoPE for 256K context
* Dense (no MoE), 128B parameters
* Standard GQA attention (not MLA)
* Pixtral-style vision encoder (48 layers, patch\_size=14, spatial\_merge=2, image\_size=1540) trained from scratch
* Multimodal input: text + image

**Models:**

* **[mistralai/Mistral-Medium-3.5-128B](https://huggingface.co/mistralai/Mistral-Medium-3.5-128B)** (FP8)

The HuggingFace repo ships both the mistral native layout (`params.json` + `consolidated-*.safetensors`) and the HF layout (`config.json` + `model-*.safetensors`). SGLang auto-detects the format — the HF layout is preferred when both are present.

***

## 2. SGLang Installation

Refer to the [official SGLang installation guide](../../../docs/get-started/install).

**Docker Image:** `lmsysorg/sglang:latest` covers all the GPUs in this cookbook (H100 / H200 / B200 / B300).

***

## 3. Model Deployment

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to generate a launch command for Mistral Medium 3.5.

Run this Command:


### 3.2 Configuration Tips

* **Tensor Parallelism**: Mistral Medium 3.5 FP8 (\~130 GB) requires `--tp 4` on Hopper (H100/H200) and `--tp 2` on Blackwell (B200/B300).
* **Reasoning effort**: Reasoning depth is configurable per request via `reasoning_effort` (`"none"`, `"high"`). No restart required — toggle per call.
* **Recommended temperature**: `0.7` when `reasoning_effort="high"`. Anywhere from `0.0` to `0.7` when `reasoning_effort="none"`, depending on the task — lower for to-the-point answers, higher for creative output.
* **Context length vs memory**: The model has a 256K context window. If you are memory-constrained, lower `--context-length` (e.g. `32768`) and increase once things are stable.
* **Tool calling**: Enable `--tool-call-parser mistral` to activate native function calling support.
* **Reasoning parser**: Enable `--reasoning-parser mistral` to separate `reasoning_content` from the main response content.
* **System prompt**: The model ships with a recommended system prompt in `chat_template.jinja` and `SYSTEM_PROMPT.txt`. If you do not pass a system message yourself, the chat template injects Mistral's default (model identity, current date, tool-use guidelines). For full fidelity with Mistral's reference setup, load `SYSTEM_PROMPT.txt` from the HF repo and substitute `{name}`, `{today}`, `{yesterday}` (see Section 4.6).

### 3.3 Speculative Decoding (EAGLE)

Mistral ships an EAGLE draft head, [`mistralai/Mistral-Medium-3.5-128B-EAGLE`](https://huggingface.co/mistralai/Mistral-Medium-3.5-128B-EAGLE), that lets you run speculative decoding on top of the dense 128B target. The draft is a 2-layer GQA body sharing the target's vocab/head, FP8-quantized like the target (\~4 GB), and is meant for low-concurrency latency-bound serving.

```bash Command theme={null}
python -m sglang.launch_server \
  --model-path mistralai/Mistral-Medium-3.5-128B \
  --tp 4 \
  --dtype bfloat16 \
  --tool-call-parser mistral \
  --reasoning-parser mistral \
  --speculative-algorithm EAGLE \
  --speculative-draft-model-path mistralai/Mistral-Medium-3.5-128B-EAGLE \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --port 30000
```

* **`--dtype bfloat16` is required.** The draft `params.json` does not carry a `dtype` field, so `--dtype auto` falls back to fp32 and downcasts to fp16, which conflicts with the bf16 target when the embed/head are shared. Setting bf16 explicitly keeps both sides aligned (this is a no-op for the target — it already loads as bf16).
* The draft uses the same vocab and lm\_head as the target. Memory overhead on top of the base model is \~4 GB per TP shard.
* `(num-steps, eagle-topk, num-draft-tokens) = (3, 1, 4)` is the recommended starting point. Tune for your workload — wider trees (higher `eagle-topk` / `num-draft-tokens`) help high-acceptance (templated) outputs, narrower trees keep latency tight on more diverse text.
* EAGLE shines at low concurrency. At high concurrency, throughput is dominated by the target's batched forward pass and the draft's contribution shrinks; consider running without EAGLE for batch-serving workloads.

***

## 4. Model Invocation

### 4.1 Thinking Mode

Mistral Medium 3.5 is a hybrid reasoning model. By default it does not produce a reasoning trace — pass `reasoning_effort="high"` to switch on the deep-reasoning path. Mistral recommends `temperature=0.7` for reasoning mode.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="mistralai/Mistral-Medium-3.5-128B",
    messages=[
        {"role": "user", "content": "Solve step by step: what is 17 × 23 + 144 / 12?"},
    ],
    temperature=0.7,
    extra_body={"reasoning_effort": "high"},
)

print("Reasoning:", response.choices[0].message.reasoning_content)
print("Answer:", response.choices[0].message.content)
```

**Output:**

```text Output theme={null}
Reasoning: I need to follow the order of operations (PEMDAS/BODMAS): multiplication and
division before addition, evaluated left to right.

17 × 23: I'll break it as 17 × (20 + 3) = 340 + 51 = 391.
144 / 12 = 12.
Finally, 391 + 12 = 403.

Answer: **17 × 23 + 144 / 12 = 403**

Step by step:
1. 17 × 23 = 391
2. 144 / 12 = 12
3. 391 + 12 = 403
```

### 4.2 Instruct Mode (Reasoning Off)

To skip the reasoning trace and get a fast direct response, set `reasoning_effort="none"`. For instruct mode, Mistral recommends temperature in the `0.0`–`0.7` range depending on how creative the task is:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="mistralai/Mistral-Medium-3.5-128B",
    messages=[
        {"role": "user", "content": "What is the capital of France?"},
    ],
    temperature=0.1,
    extra_body={"reasoning_effort": "none"},
)

print(response.choices[0].message.content)
```

**Output:**

```text Output theme={null}
The capital of France is **Paris**. It is one of the most famous and visited cities in
the world, known for its rich history, art, culture, and landmarks like the Eiffel Tower,
Louvre Museum, and Notre-Dame Cathedral.
```

### 4.3 Streaming with Reasoning

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

stream = client.chat.completions.create(
    model="mistralai/Mistral-Medium-3.5-128B",
    messages=[
        {"role": "user", "content": "Explain the difference between async and threading in Python."},
    ],
    temperature=0.7,
    extra_body={"reasoning_effort": "high"},
    stream=True,
)

print("=== Reasoning ===")
for chunk in stream:
    delta = chunk.choices[0].delta
    if hasattr(delta, "reasoning_content") and delta.reasoning_content:
        print(delta.reasoning_content, end="", flush=True)
    elif delta.content:
        print("\n=== Response ===")
        print(delta.content, end="", flush=True)
print()
```

### 4.4 Tool Calling

Mistral Medium 3.5 supports native function calling. Enable with `--tool-call-parser mistral`:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="mistralai/Mistral-Medium-3.5-128B",
    messages=[{"role": "user", "content": "What's the weather in Paris?"}],
    tools=tools,
    tool_choice="auto",
)

tool_calls = response.choices[0].message.tool_calls
for tc in tool_calls:
    print(f"Tool: {tc.function.name}")
    print(f"Args: {tc.function.arguments}")
```

**Output:**

```text Output theme={null}
Tool: get_weather
Args: {"location": "Paris"}
```

### 4.5 Vision (Image Input)

Mistral Medium 3.5 accepts image inputs alongside text. The vision encoder was retrained from scratch to handle variable image sizes and aspect ratios:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="mistralai/Mistral-Medium-3.5-128B",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Describe what you see in this image."},
                {
                    "type": "image_url",
                    "image_url": {"url": "https://raw.githubusercontent.com/sgl-project/sglang/main/assets/logo.png"},
                },
            ],
        }
    ],
    temperature=0.7,
    extra_body={"reasoning_effort": "none"},
)

print(response.choices[0].message.content)
```

**Output:**

```text Output theme={null}
The image features a stylized representation of the acronym "SGL." The letters
are large, bold, and orange with a brown outline, giving them a three-dimensional
effect. To the left of the letters, there is a graphic that resembles a neuron
or a node with connections, also in a similar orange and brown color scheme. The
node has a code symbol () inside a square, suggesting a connection to
programming or technology.
```

### 4.6 Loading the Reference System Prompt

Mistral ships a `SYSTEM_PROMPT.txt` alongside the weights. The reference setup loads it from the HF repo and substitutes `{name}`, `{today}`, and `{yesterday}` at runtime so the model knows its identity and the current date. SGLang's chat template will inject a default system prompt if you omit one, but for full parity with Mistral's reference, load it explicitly:

```python Example theme={null}
from datetime import datetime, timedelta
from huggingface_hub import hf_hub_download
from openai import OpenAI

MODEL = "mistralai/Mistral-Medium-3.5-128B"

def load_system_prompt(repo_id: str, filename: str = "SYSTEM_PROMPT.txt") -> str:
    path = hf_hub_download(repo_id=repo_id, filename=filename)
    today = datetime.today().strftime("%Y-%m-%d")
    yesterday = (datetime.today() - timedelta(days=1)).strftime("%Y-%m-%d")
    name = repo_id.split("/")[-1]
    with open(path) as f:
        return f.read().format(name=name, today=today, yesterday=yesterday)

client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

response = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "system", "content": load_system_prompt(MODEL)},
        {"role": "user", "content": "Write me a sentence where every word starts with the next letter in the alphabet — start with 'a' and end with 'z'."},
    ],
    temperature=0.1,
    extra_body={"reasoning_effort": "none"},
)

print(response.choices[0].message.content)
```

***

## 5. Benchmarks

Validation runs on 4× H200 with `--tp 4`, served via the `/v1/chat/completions` endpoint.

### 5.1 Accuracy Benchmarks

#### GSM8K

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Results:**

```text Output theme={null}
Accuracy: 0.945
Invalid: 0.000
Latency: 13.594 s
Output throughput: 1560.660 token/s
```

#### MMMU

```bash Command theme={null}
python3 benchmark/mmmu/bench_sglang.py --port 30000
```

**Results:**

```text Output theme={null}
Overall accuracy: 0.586
```

### 5.2 Speed Benchmarks

#### Latency (Low Concurrency)

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --dataset-name random \
  --num-prompts 10 \
  --max-concurrency 1 \
  --random-input-len 1024 \
  --random-output-len 512 \
  --port 30000
```

**Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Successful requests:                     10
Benchmark duration (s):                  38.86
Total input tokens:                      6101
Total generated tokens:                  2684
Output token throughput (tok/s):         69.07
Mean E2E Latency (ms):                   3883.80
Median TTFT (ms):                        95.90
Median TPOT (ms):                        14.19
==================================================
```

#### Throughput (High Concurrency)

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --dataset-name random \
  --num-prompts 1000 \
  --max-concurrency 100 \
  --random-input-len 1024 \
  --random-output-len 512 \
  --port 30000
```

**Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Successful requests:                     1000
Benchmark duration (s):                  117.28
Total input tokens:                      512842
Total generated tokens:                  262023
Output token throughput (tok/s):         2234.18
Total token throughput (tok/s):          6607.01
Mean E2E Latency (ms):                   11303.79
Median TTFT (ms):                        152.95
Median TPOT (ms):                        42.53
==================================================
```

### 5.3 EAGLE Speculative Decoding (Latency)

Same 4× H200 setup, EAGLE configuration from [Section 3.3](#3-3-speculative-decoding-eagle). Single-stream latency benchmark (`--max-concurrency 1`).

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --dataset-name random \
  --num-prompts 10 \
  --max-concurrency 1 \
  --random-input-len 1024 \
  --random-output-len 512 \
  --port 30000
```

**Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Successful requests:                     10
Benchmark duration (s):                  27.64
Total input tokens:                      6101
Total generated tokens:                  2684
Output token throughput (tok/s):         97.10
Mean E2E Latency (ms):                   2762.99
Median TTFT (ms):                        90.69
Median TPOT (ms):                        9.73
Accept length:                           1.72
==================================================
```

EAGLE delivers **\~1.41× output throughput and \~29% lower E2E latency** vs. the baseline in [Section 5.2](#5-2-speed-benchmarks) on the same workload. Acceptance length of 1.72 means each draft cycle averages roughly 1.7 accepted tokens.


# Mistral Small 4
Source: https://docs.sglang.io/cookbook/autoregressive/Mistral/Mistral-Small-4



## 1. Model Introduction

**Mistral Small 4** is a powerful hybrid model from Mistral AI that unifies the capabilities of three different model families — **Instruct**, **Reasoning** (formerly called Magistral), and **Agentic (formerly called Devstral)** — into a single, unified model.

With its multimodal capabilities, efficient MoE architecture, and flexible mode switching, Mistral Small 4 is a versatile general-purpose model for virtually any task. In a latency-optimized setup, it achieves a 40% reduction in end-to-end completion time; in a throughput-optimized setup, it delivers 3× more requests per second compared to Mistral Small 3.

**Key Features:**

* **Hybrid Reasoning**: Switch between instant reply mode and deep reasoning/thinking mode — reasoning effort is configurable per request
* **Vision**: Accepts both text and image inputs, providing insights based on visual content
* **Function Calling**: Native tool calling and JSON output support with best-in-class agentic capabilities
* **Multilingual**: Supports dozens of languages including English, French, Spanish, German, Chinese, Japanese, Korean, Arabic, and more
* **Context Window**: 256K context window
* **Efficient MoE**: 119B total parameters, 128 experts, 4 active per token (6.5B activated parameters)
* **Apache 2.0 License**: Open-source, usable and modifiable for commercial and non-commercial purposes
* Reasoning effort supported are only **"none" and "high"**

**Architecture:**

* Same general architecture as Mistral 3
* MoE: 128 experts, 4 active per token
* 119B total parameters, 6.5B activated per token
* Multimodal input: text + image

**Models:**

* **[mistralai/Mistral-Small-4-119B-2603](https://huggingface.co/mistralai/Mistral-Small-4-119B-2603)** (FP8)
* **[mistralai/Mistral-Small-4-119B-2603-NVFP4](https://huggingface.co/mistralai/Mistral-Small-4-119B-2603-NVFP4)**
* **[mistralai/Leanstral-2603](https://huggingface.co/mistralai/Leanstral-2603)** — same architecture, use the same launch commands as Mistral-Small-4-119B-2603
* **[mistralai/Mistral-Small-4-119B-2603-eagle](https://huggingface.co/mistralai/Mistral-Small-4-119B-2603-eagle)** — EAGLE speculative decoding weights for faster inference

***

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

> [!NOTE]
>
> Mistral Small 4 support landed in [sgl-project/sglang#20708](https://github.com/sgl-project/sglang/pull/20708) and has been merged into `main`. A model-specific Docker image is no longer required. Use the standard SGLang installation methods from the [official installation guide](../../../docs/get-started/install).

***

## 3. Model Deployment

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to generate a launch command for Mistral Small 4.

Run this Command:


### 3.2 Configuration Tips

* **Tensor Parallelism**: Mistral Small 4 FP8 (\~119 GB) requires tp=2 on Hopper (H100/H200), tp=1 on Blackwell (B200/B300). NVFP4 (\~60 GB, Blackwell only) runs with tp=1.
* **Reasoning effort**: Reasoning depth is configurable per request via `reasoning_effort` (`"none"`, `"high"`). No restart required — toggle per call.
* **Context length vs memory**: The model has a 256K context window. If you are memory-constrained, lower `--context-length` (e.g. `32768`) and increase once things are stable.
* **Tool calling**: Enable `--tool-call-parser mistral` to activate native function calling support.
* **Reasoning parser**: Enable `--reasoning-parser mistral` to separate `reasoning_content` from the main response content.
* **Speculative decoding (EAGLE)**: Enable with `--speculative-algorithm EAGLE --speculative-draft-model-path mistralai/Mistral-Small-4-119B-2603-eagle` using the [EAGLE weights](https://huggingface.co/mistralai/Mistral-Small-4-119B-2603-eagle) for lower latency.

***

## 4. Model Invocation

### 4.1 Thinking Mode

Mistral Small 4 is a hybrid reasoning model. By default, it does not produce a default reasoning response. Use `--reasoning_effort high` to toggle reasoning on.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="mistralai/Mistral-Small-4-119B-2603",
    messages=[
        {"role": "user", "content": "Solve step by step: what is 17 × 23 + 144 / 12?"},
    ],
    extra_body={"reasoning_effort": "high"},
)

print("Reasoning:", response.choices[0].message.reasoning_content)
print("Answer:", response.choices[0].message.content)
```

**Output:**

```text Output theme={null}
Reasoning: First, I'll break down the problem into two parts: the multiplication and
the division. According to the order of operations (PEMDAS/BODMAS), multiplication and
division are performed from left to right before addition.

17 × 23 = 17 × (20 + 3) = (17 × 20) + (17 × 3) = 340 + 51 = 391
144 / 12 = 12

Finally, add the results: 391 + 12 = 403

Answer: The solution to the problem is as follows:

1. First, perform the multiplication: 17 × 23.
   - 17 × 20 = 340
   - 17 × 3 = 51
   - 340 + 51 = 391

2. Then, perform the division: 144 / 12 = 12.

3. Finally, add the results:
   - 391 + 12 = 403

**Answer:** \boxed{403}
```

### 4.2 Instruct Mode (Reasoning Off)

To skip the reasoning trace and get a fast direct response, set `reasoning_effort` to `"none"`:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="mistralai/Mistral-Small-4-119B-2603",
    messages=[
        {"role": "user", "content": "Write a Python function to reverse a string."},
    ],
    extra_body={"reasoning_effort": "none"},
)

print(response.choices[0].message.content)
```

**Output:**

````text Output theme={null}
# Python Function to Reverse a String

Here are several ways to write a Python function to reverse a string:

## Method 1: Using String Slicing (Most Pythonic)
```python
def reverse_string(s):
    """Reverse a string using slicing."""
    return s[::-1]
```

## Method 2: Using a Loop
```python Example
def reverse_string(s):
    """Reverse a string using a loop."""
    reversed_str = ""
    for char in s:
        reversed_str = char + reversed_str
    return reversed_str
```

## Method 3: Using reversed() function
```python Example
def reverse_string(s):
    """Reverse a string using reversed() function."""
    return ''.join(reversed(s))
```

The first method using string slicing (`s[::-1]`) is generally the most efficient and
recommended approach in Python.

Example usage:
```python Example
original = "Hello, World!"
reversed_str = reverse_string(original)
print(reversed_str)  # Output: "!dlroW ,olleH"
```
````

### 4.3 Streaming with Reasoning

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

stream = client.chat.completions.create(
    model="mistralai/Mistral-Small-4-119B-2603",
    messages=[
        {"role": "user", "content": "Explain the difference between async and threading in Python."},
    ],
    extra_body={"reasoning_effort": "high"},
    stream=True,
)

print("=== Reasoning ===")
for chunk in stream:
    delta = chunk.choices[0].delta
    if hasattr(delta, "reasoning_content") and delta.reasoning_content:
        print(delta.reasoning_content, end="", flush=True)
    elif delta.content:
        print("\n=== Response ===")
        print(delta.content, end="", flush=True)
print()
```

**Output:**

```text Output theme={null}
=== Reasoning ===
Okay, the user is asking about the difference between async and threading in Python.
I need to break this down clearly, covering the key aspects of both, like their
purposes, performance characteristics, and use cases...
=== Response ===
In Python, **`async`/`asyncio`** and **`threading`** are two different concurrency
models, each suited for specific use cases. Here's a breakdown of their key differences:

### 1. Model of Concurrency
- **Threading**: Based on preemptive multitasking using OS threads.
- **Async** (`asyncio`): Based on cooperative multitasking. Tasks voluntarily yield...
```

### 4.4 Tool Calling

Mistral Small 4 supports native function calling. Enable with `--tool-call-parser mistral`:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]

response = client.chat.completions.create(
    model="mistralai/Mistral-Small-4-119B-2603",
    messages=[{"role": "user", "content": "What's the weather in Paris?"}],
    tools=tools,
    tool_choice="auto",
)

tool_calls = response.choices[0].message.tool_calls
for tc in tool_calls:
    print(f"Tool: {tc.function.name}")
    print(f"Args: {tc.function.arguments}")
```

**Output:**

```text Output theme={null}
Tool: get_weather
Args: {"location": "Paris"}
```

### 4.5 Vision (Image Input)

Mistral Small 4 accepts image inputs alongside text:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="mistralai/Mistral-Small-4-119B-2603",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "Describe what you see in this image."},
                {
                    "type": "image_url",
                    "image_url": {"url": "https://raw.githubusercontent.com/sgl-project/sglang/main/assets/logo.png"},
                },
            ],
        }
    ],
)

print(response.choices[0].message.content)
```

**Output:**

```text Output theme={null}
The image is a copyright symbol, represented by a stylized version of the lowercase
letter "c" inside a circle. The "c" is depicted in a white or light-colored font, and
the circle is orange. The design is simple yet striking, using oval and elliptical
shapes to create a distinct symbol which signifies copyright protection.
```

***

## 5. Benchmarks

### 5.1 Accuracy Benchmarks

#### GSM8K

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

**Results:**

```text Output theme={null}
TODO
```

#### MMLU

```bash Command theme={null}
sgl-eval run mmlu \
  --base-url http://127.0.0.1:30000/v1 \
  --num-threads 64 --max-tokens 2048
```

**Results:**

```text Output theme={null}
TODO
```

### 5.2 Speed Benchmarks

#### Latency (Low Concurrency)

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --num-prompts 10 \
  --max-concurrency 1 \
  --random-input-len 1024 \
  --random-output-len 512 \
  --port 30000
```

**Results:**

```text Output theme={null}
TODO
```

#### Throughput (High Concurrency)

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --num-prompts 1000 \
  --max-concurrency 100 \
  --random-input-len 1024 \
  --random-output-len 512 \
  --port 30000
```

**Results:**

```text Output theme={null}
TODO
```


# Kimi-K2
Source: https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-K2



## 1. Model Introduction

[Kimi-K2](https://moonshotai.github.io/Kimi-K2/) is a state-of-the-art MoE language model by Moonshot AI with 32B activated parameters and 1T total parameters.

**Model Variants:**

* **[Kimi-K2-Instruct](https://huggingface.co/moonshotai/Kimi-K2-Instruct)**: Post-trained model optimized for general-purpose chat and agentic tasks. Compatible with vLLM, SGLang, KTransformers, and TensorRT-LLM.
* **[Kimi-K2-Thinking](https://huggingface.co/moonshotai/Kimi-K2-Thinking)**: Advanced thinking model with step-by-step reasoning and tool calling. Native INT4 quantization with 256k context window. Ideal for complex reasoning and multi-step tool use.
* **ROCm Support**: Compatible with AMD MI300X GPUs via SGLang (verified).

For details, see [official documentation](https://github.com/MoonshotAI/Kimi-K2) and [technical report](https://www.arxiv.org/abs/2507.20534).

## 2. SGLang Installation

Refer to the [official SGLang installation guide](../../../docs/get-started/install).

## 3. Model Deployment

This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and capabilities.

Run this Command:


### 3.2 Configuration Tips

* **Memory**: Requires 8 GPUs with ≥140GB each (H200/B200). Use `--context-length 128000` to conserve memory.
* **Expert Parallelism (EP)**: Use `--ep` for better MoE throughput. See [EP docs](../../../docs/advanced_features/expert_parallelism).
* **Data Parallel (DP)**: Enable with `--attn-dp-size 4` for production throughput.
* **KV Cache**: Use `--kv-cache-dtype fp8_e4m3` to reduce memory by 50% (CUDA 11.8+).
* **Reasoning Parser**: Add `--reasoning-parser kimi_k2` for Kimi-K2-Thinking to separate thinking and content.
* **Tool Call Parser**: Add `--tool-call-parser kimi_k2` for structured tool calls.
* **AMD GPU**: Set `SGLANG_ROCM_FUSED_DECODE_MLA=0` before launching AMD GPU.

## 4. Model Invocation

### 4.1 Basic Usage

See [Basic API Usage](../../../docs/get-started/quickstart).

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

Enable reasoning parser for Kimi-K2-Thinking:

```shell Command theme={null}
python -m sglang.launch_server \
  --model moonshotai/Kimi-K2-Thinking \
  --reasoning-parser kimi_k2 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

**Example:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="moonshotai/Kimi-K2-Thinking",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.6,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
  The user asks: "What is 15% of 240?" This is a straightforward percentage calculation problem. I need to solve it step by step.

Step 1: Understand what "percent" means.
- "Percent" means "per hundred". So 15% means 15 per 100, or 15/100, or 0.15.

Step 2: Convert the percentage to a decimal.
- 15% = 15 / 100 = 0.15

Step 3: Multiply the decimal by the number.
- 0.15 * 240

Step 4: Perform the multiplication.
- 0.15 * 240 = (15/100) * 240
- = 15 * 240 / 100
- = 3600 / 100
- = 36

Alternatively, I can calculate it directly:
- 0.15 * 240
- 15 * 240 = 3600
- 3600 / 100 = 36

Or, break it down:
- 10% of 240 = 24
- 5% of 240 = half of 10% = 12
- 15% of 240 = 10% + 5% = 24 + 12 = 36

I should present the solution clearly with steps. The most standard method is converting to decimal and multiplying.

Let me structure the answer:
1. Convert the percentage to a decimal.
2. Multiply the decimal by the number.
3. Show the calculation.
4. State the final answer.

This is simple and easy to follow.
=============== Content =================
 Here is the step-by-step solution:

**Step 1: Convert the percentage to a decimal**
15% means 15 per 100, which is 15 ÷ 100 = **0.15**

**Step 2: Multiply the decimal by the number**
0.15 × 240

**Step 3: Calculate the result**
0.15 × 240 = **36**

**Answer:** 15% of 240 is **36**.
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.2 Tool Calling

Kimi-K2-Instruct and Kimi-K2-Thinking support tool calling capabilities. Enable the tool call parser during deployment:

**Deployment Command:**

```shell Command theme={null}
python -m sglang.launch_server \
  --model moonshotai/Kimi-K2-Instruct \
  --tool-call-parser kimi_k2 \
  --tp 8 \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 8000
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="moonshotai/Kimi-K2-Thinking",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"🔧 Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
  The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information. Beijing is a major city in China, so I should be able to get weather data for it. The location parameter is required, but the unit parameter is optional. Since the user didn't specify a temperature unit, I can just provide the location and let the function use its default. I'll check the weather in Beijing for you.
=============== Content =================

  🔧 Tool Call: get_weather
   Arguments: {"location":"Beijing"}
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="moonshotai/Kimi-K2-Thinking",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The weather in Beijing is currently 22°C and sunny."
```

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8x)
* Model: Kimi-K2-Instruct
* sglang version: 0.5.6.post1

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios.

#### 5.1.1 Latency-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python3 -m sglang.launch_server \
    --model-path moonshotai/Kimi-K2-Instruct \
    --tp 8 \
    --attn-dp-size 4 \
    --trust-remote-code \
    --host 0.0.0.0 \
    --port 8000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 8000 \
  --model moonshotai/Kimi-K2-Instruct\
  --num-prompts 10 \
  --max-concurrency 1
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  44.93
Total input tokens:                      1951
Total input text tokens:                 1951
Total input vision tokens:               0
Total generated tokens:                  2755
Total generated tokens (retokenized):    2748
Request throughput (req/s):              0.22
Input token throughput (tok/s):          43.42
Output token throughput (tok/s):         61.32
Peak output token throughput (tok/s):    64.00
Peak concurrent requests:                3
Total token throughput (tok/s):          104.74
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   4489.56
Median E2E Latency (ms):                 4994.53
---------------Time to First Token----------------
Mean TTFT (ms):                          141.22
Median TTFT (ms):                        158.28
P99 TTFT (ms):                           166.90
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          18.40
Median TPOT (ms):                        15.63
P99 TPOT (ms):                           39.88
---------------Inter-Token Latency----------------
Mean ITL (ms):                           15.78
Median ITL (ms):                         15.76
P95 ITL (ms):                            16.36
P99 ITL (ms):                            16.59
Max ITL (ms):                            19.94
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python3 -m sglang.launch_server \
    --model-path moonshotai/Kimi-K2-Instruct \
    --tp 8 \
    --attn-dp-size 4 \
    --ep 4 \
    --trust-remote-code \
    --host 0.0.0.0 \
    --port 8000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 8000 \
  --model moonshotai/Kimi-K2-Instruct\
  --num-prompts 1000 \
  --max-concurrency 100
```

* **Test Results**:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  174.11
Total input tokens:                      296642
Total input text tokens:                 296642
Total input vision tokens:               0
Total generated tokens:                  193831
Total generated tokens (retokenized):    168687
Request throughput (req/s):              5.74
Input token throughput (tok/s):          1703.73
Output token throughput (tok/s):         1113.25
Peak output token throughput (tok/s):    2383.00
Peak concurrent requests:                112
Total token throughput (tok/s):          2816.97
Concurrency:                             89.60
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   15601.09
Median E2E Latency (ms):                 10780.52
---------------Time to First Token----------------
Mean TTFT (ms):                          457.42
Median TTFT (ms):                        221.62
P99 TTFT (ms):                           2475.32
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          97.23
Median TPOT (ms):                        85.61
P99 TPOT (ms):                           435.95
---------------Inter-Token Latency----------------
Mean ITL (ms):                           78.61
Median ITL (ms):                         43.66
P95 ITL (ms):                            169.53
P99 ITL (ms):                            260.91
Max ITL (ms):                            1703.21
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* Server Command

```shell Command theme={null}
python3 -m sglang.launch_server \
    --model-path moonshotai/Kimi-K2-Instruct \
    --tp 8 \
    --dp 4 \
    --trust-remote-code  \
    --host 0.0.0.0 \
    --port 8000
```

* Benchmark Command

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:8000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* **Result**:

```text Output theme={null}
Accuracy: 0.960
Invalid: 0.000
Latency: 15.956 s
Output throughput: 1231.699 token/s
```


# Kimi-K2.5
Source: https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-K2.5



## 1. Model Introduction

[Kimi-K2.5](https://huggingface.co/moonshotai/Kimi-K2.5) is an open-source, native multimodal agentic model by Moonshot AI, built through continual pretraining on approximately 15 trillion mixed visual and text tokens atop Kimi-K2-Base. It seamlessly integrates vision and language understanding with advanced agentic capabilities, instant and thinking modes.

**Key Features:**

* **Native Multimodality**: Pre-trained on vision-language tokens, K2.5 excels in visual knowledge, cross-modal reasoning, and agentic tool use grounded in visual inputs.
* **Coding with Vision**: K2.5 generates code from visual specifications (UI designs, video workflows) and autonomously orchestrates tools for visual data processing.
* **Agent Swarm**: K2.5 transitions from single-agent scaling to a self-directed, coordinated swarm-like execution scheme. It decomposes complex tasks into parallel sub-tasks executed by dynamically instantiated, domain-specific agents.
* **Speculative Decoding**: EAGLE-based speculative decoding support for lower latency.

**Available Models**:

* INT4 (Initial Released): [moonshotai/Kimi-K2.5](https://huggingface.co/moonshotai/Kimi-K2.5)
* NVFP4 (4-bit quantized): [nvidia/Kimi-K2.5-NVFP4](https://huggingface.co/nvidia/Kimi-K2.5-NVFP4)

For details, see [official documentation](https://huggingface.co/moonshotai/Kimi-K2.5) and [deployment guidance](https://huggingface.co/moonshotai/Kimi-K2.5/blob/main/docs/deploy_guidance.md).

## 2. SGLang Installation

Refer to the [official SGLang installation guide](../../../docs/get-started/install).

## 3. Model Deployment

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, deployment strategy, and capabilities.

Run this Command:


### 3.2 Configuration Tips

* **Memory**: Requires GPUs with >=140GB each. Supported platforms: H200 (8x, TP=8), B300 (8x, TP=8), GB300 (4x, TP=4), MI300X/MI325X (4x, TP=4), MI350X/MI355X (4x, TP=4). Use `--context-length 128000` to conserve memory.
* **AMD GPU TP Constraint**: On AMD GPUs, TP must be \<= 4 (not 8). Kimi-K2.5 has 64 attention heads; the AITER MLA kernel requires `heads_per_gpu % 16 == 0`. With TP=4, each GPU gets 16 heads (valid). With TP=8, each GPU gets 8 heads (invalid).
* **AMD Docker Image**: Use `lmsysorg/sglang:v0.5.9-rocm700-mi35x` for MI350X/MI355X and `lmsysorg/sglang:v0.5.9-rocm700-mi30x` for MI300X/MI325X. The ROCm 7.2 images (`rocm720`) have an AITER compatibility issue.
* **DP Attention**: Enable with `--attn-dp-size ` for production throughput. A common choice is to set `--attn-dp-size` equal to `--tp`, but this is not required.
* **Reasoning Parser**: Add `--reasoning-parser kimi_k2` to separate thinking and content in model outputs.
* **Tool Call Parser**: Add `--tool-call-parser kimi_k2` for structured tool calls.

## 4. Model Invocation

### 4.1 Basic Usage

See [Basic API Usage](../../../docs/basic_usage/send_request).

### 4.2 Advanced Usage

#### 4.2.1 Multimodal (Vision + Text) Input

Kimi-K2.5 supports native multimodal input with images:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.5",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                    }
                },
                {
                    "type": "text",
                    "text": "What is in this image? Describe it in detail."
                }
            ]
        }
    ]
)

print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
This image shows a **receipt from Auntie Anne's** (a pretzel franchise restaurant).

## Key Details:

**Item Purchased:**
- **CINNAMON SUGAR** - 1 unit x 17,000 = **17,000**

**Payment Summary:**
- **SUB TOTAL:** 17,000
- **GRAND TOTAL:** 17,000
- **CASH IDR:** 20,000 (Indonesian Rupiah)
- **CHANGE DUE:** 3,000

## Context:
The receipt indicates a transaction in **Indonesian Rupiah (IDR)**. A customer purchased one Cinnamon Sugar pretzel for 17,000 IDR, paid with a 20,000 IDR note, and received 3,000 IDR in change.

The top of the receipt shows the Auntie Anne's logo (a heart-shaped pretzel with a halo), and some text appears blurred for privacy, likely obscuring the store location, date, and transaction number. The receipt is printed on white thermal paper.
```

#### 4.2.2 Reasoning Output

Kimi-K2.5 supports both thinking mode (default) and instant mode.

**Thinking Mode (default)** -- reasoning content is automatically separated:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.5",
    messages=[
        {"role": "user", "content": "Which one is bigger, 9.11 or 9.9? Think carefully."}
    ]
)

print("====== Reasoning Content (Thinking Mode) ======")
print(response.choices[0].message.reasoning_content)
print("====== Response (Thinking Mode) ======")
print(response.choices[0].message.content)
```

**Instant Mode (thinking off)** -- disable thinking for faster responses:

```python Example theme={null}
response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.5",
    messages=[
        {"role": "user", "content": "Which one is bigger, 9.11 or 9.9? Think carefully."}
    ],
    extra_body={"chat_template_kwargs": {"thinking": False}}
)

print("====== Response (Instant Mode) ======")
print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
====== Reasoning Content (Thinking Mode) ======
The user is asking which number is bigger: 9.11 or 9.9.

At first glance, someone might think 9.11 is bigger because 11 > 9, but that's incorrect because we're dealing with decimal numbers, not whole numbers.

Let me compare them properly:
- 9.9 = 9.90
- 9.11

When comparing decimals, we look at each place value from left to right:
- Units place: 9 = 9 (tie)
- Tenths place: 9 vs 1

Since 9 > 1, we have 9.9 > 9.11.

Alternatively, we can think of it as:
- 9.9 = 9 + 9/10 = 9 + 0.9 = 9.90
- 9.11 = 9 + 11/100 = 9 + 0.11

Since 0.90 > 0.11, then 9.9 > 9.11.

So the answer is clearly 9.9 is bigger.

The "think carefully" hint suggests the user is trying to catch the common error where people compare 11 and 9 as whole numbers rather than understanding decimal place value (tenths vs hundredths).

I should explain this clearly to avoid confusion.
====== Response (Thinking Mode) ======
**9.9 is bigger.**

Here's why this can be tricky: Many people instinctively compare 11 and 9 and think "11 is bigger than 9," but that's comparing the wrong place values.

When comparing decimals, align them by place value:
- 9.9 = 9.**90**
- 9.11 = 9.**11**

After the decimal point:
- The first digit (tenths place): **9** vs **1**
- Since 9 > 1, we stop there. **9.9 is larger.**

Think of it as money:
- $9.90 (nine dollars and ninety cents)
- $9.11 (nine dollars and eleven cents)

$9.90 is clearly more than $9.11.
====== Response (Instant Mode) ======
 Let me think through this carefully.

**9.9 is bigger than 9.11**

Here's why: When comparing decimals, we need to align them by their decimal places:

- 9.9 = 9.90
- 9.11 = 9.11

Now comparing:
- The whole number parts are equal (9 = 9)
- Comparing tenths: **9 > 1**

So 9.90 > 9.11

A common mistake is thinking 11 hundredths is larger than 9 tenths, but 9 tenths = 90 hundredths, which is clearly larger than 11 hundredths.
```

#### 4.2.3 Tool Calling

Kimi-K2.5 supports tool calling capabilities for agentic tasks:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.5",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    stream=True
)

# Process streaming response
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {'name': None, 'arguments': ''}
                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        if delta.content:
            print(delta.content, end="", flush=True)

for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"Tool Call: {tool_call['name']}")
    print(f"  Arguments: {tool_call['arguments']}")
```

**Output Example:**

```text Output theme={null}
Tool Call: get_weather
  Arguments: {"location": "Beijing"}
```

**Handling Tool Call Results:**

```python Example theme={null}
# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": "The weather in Beijing is 22°C and sunny."
    }
]

final_response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.5",
    messages=messages
)

print(final_response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
The weather in Beijing is **22°C and sunny**. ☀️

It's a nice day there with comfortable temperatures and clear skies!
```

#### 4.2.4 Multimodal + Tool Calling (Agentic Vision)

Combine vision understanding with tool calling for advanced agentic tasks:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "search_product",
            "description": "Search for a product by name or description",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The product name or description to search for"
                    }
                },
                "required": ["query"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.5",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                    }
                },
                {
                    "type": "text",
                    "text": "Can you identify this product and search for similar items?"
                }
            ]
        }
    ],
    tools=tools
)

msg = response.choices[0].message

# Print reasoning process
if msg.reasoning_content:
    print("=== Reasoning ===")
    print(msg.reasoning_content)

# Print response content
if msg.content:
    print("=== Content ===")
    print(msg.content)

# Print tool calls
if msg.tool_calls:
    print("=== Tool Calls ===")
    for tc in msg.tool_calls:
        print(f"  Function: {tc.function.name}")
        print(f"  Arguments: {tc.function.arguments}")
```

**Output Example:**

```text Output theme={null}
=== Reasoning ===
The user is asking me to identify a product from a receipt and search for similar items.
Looking at the receipt, I can see:

 1. The store is "Auntie Anne's" - which is a popular pretzel chain
 2. The product purchased is "CINNAMON SUGAR"
 3. Price is 17,000 (likely Indonesian Rupiah based on "CASH IDR")
 4. Quantity is 1

So the product is a Cinnamon Sugar pretzel from Auntie Anne's.
Now I need to search for this product or similar items using the search_product function.
=== Content ===
I can see from the receipt that the product is a **Cinnamon Sugar** item from **Auntie Anne's** (the famous pretzel chain). This appears to be a Cinnamon Sugar Pretzel purchased for 17,000 IDR (Indonesian Rupiah).

Let me search for this product and similar items:
=== Tool Calls ===
  Function: search_product
  Arguments: {"query": "Auntie Anne's Cinnamon Sugar Pretzel"}
```

#### 4.2.5 Speculative Decoding

**Nvidia**

Deploy Kimi-K2.5 with the following command (H200/B300, all features enabled):

```shell Command theme={null}
sglang serve \
  --model-path moonshotai/Kimi-K2.5 \
  --tp 8 \
  --reasoning-parser kimi_k2 \
  --tool-call-parser kimi_k2 \
  --speculative-algorithm=EAGLE3 \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --speculative-draft-model-path lightseekorg/kimi-k2.5-eagle3-mla \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000
```

Deploy Kimi-K2.5-NVFP4 with the following command (B300, all features enabled):

```shell Command theme={null}
sglang serve \
  --model-path nvidia/Kimi-K2.5-NVFP4 \
  --tp 8 \
  --reasoning-parser kimi_k2 \
  --tool-call-parser kimi_k2 \
  --kv-cache-dtype fp8_e4m3 \
  --speculative-algorithm=EAGLE3 \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --speculative-draft-model-path lightseekorg/kimi-k2.5-eagle3-mla \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000
```

For GB300, use `--tp 4`.

## 5. Benchmark

### 5.1 Accuracy Benchmark

#### 5.1.1 MMMU Benchmark

You can evaluate the model's accuracy using the MMMU benchmark, which tests multimodal understanding and reasoning across various subjects:

* **Benchmark Command:**

```shell Command theme={null}
python3 benchmark/mmmu/bench_sglang.py \
    --response-answer-regex "(?i)(?:answer|ans)[:\s]*(?:\*\*)?[\(\[]?([A-Za-z])[\)\]]?(?:\*\*)?" \
    --port 30000 \
    --concurrency 64
```

* **Result:**

```text Output theme={null}
Benchmark time: 2785.4322692090645
answers saved to: ./answer_sglang.json
Evaluating...
answers saved to: ./answer_sglang.json
{'Accounting': {'acc': 0.667, 'num': 30},
 'Agriculture': {'acc': 0.567, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.733, 'num': 30},
 'Art': {'acc': 0.833, 'num': 30},
 'Art_Theory': {'acc': 0.8, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.833, 'num': 30},
 'Biology': {'acc': 0.6, 'num': 30},
 'Chemistry': {'acc': 0.633, 'num': 30},
 'Clinical_Medicine': {'acc': 0.733, 'num': 30},
 'Computer_Science': {'acc': 0.667, 'num': 30},
 'Design': {'acc': 0.7, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.5, 'num': 30},
 'Economics': {'acc': 0.867, 'num': 30},
 'Electronics': {'acc': 0.3, 'num': 30},
 'Energy_and_Power': {'acc': 0.767, 'num': 30},
 'Finance': {'acc': 0.833, 'num': 30},
 'Geography': {'acc': 0.667, 'num': 30},
 'History': {'acc': 0.767, 'num': 30},
 'Literature': {'acc': 0.767, 'num': 30},
 'Manage': {'acc': 0.733, 'num': 30},
 'Marketing': {'acc': 0.833, 'num': 30},
 'Materials': {'acc': 0.567, 'num': 30},
 'Math': {'acc': 0.633, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.567, 'num': 30},
 'Music': {'acc': 0.5, 'num': 30},
 'Overall': {'acc': 0.698, 'num': 900},
 'Overall-Art and Design': {'acc': 0.708, 'num': 120},
 'Overall-Business': {'acc': 0.787, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.74, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.75, 'num': 120},
 'Overall-Science': {'acc': 0.66, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.595, 'num': 210},
 'Pharmacy': {'acc': 0.767, 'num': 30},
 'Physics': {'acc': 0.767, 'num': 30},
 'Psychology': {'acc': 0.667, 'num': 30},
 'Public_Health': {'acc': 0.867, 'num': 30},
 'Sociology': {'acc': 0.8, 'num': 30}}
eval out saved to ./val_sglang.json
Overall accuracy: 0.698
```

### 5.2 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA H200 GPU (8x)
* Model: Kimi-K2.5
* Tensor Parallelism: 8
* SGLang Version: 0.5.6.post2

We use SGLang's built-in benchmarking tool with the `random` dataset for standardized performance evaluation.

#### 5.2.1 Latency Benchmark

* **Model Deployment:**

```bash Command theme={null}
sglang serve \
  --model-path moonshotai/Kimi-K2.5 \
  --tp 8 \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000
```

* **Benchmark Command:**

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* **Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  39.77
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  4220
Total generated tokens (retokenized):    4221
Request throughput (req/s):              0.25
Input token throughput (tok/s):          153.40
Output token throughput (tok/s):         106.10
Peak output token throughput (tok/s):    156.00
Peak concurrent requests:                2
Total token throughput (tok/s):          259.50
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   3972.87
Median E2E Latency (ms):                 4044.55
P90 E2E Latency (ms):                    7046.30
P99 E2E Latency (ms):                    7441.13
---------------Time to First Token----------------
Mean TTFT (ms):                          176.89
Median TTFT (ms):                        154.24
P99 TTFT (ms):                           285.75
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          9.22
Median TPOT (ms):                        9.32
P99 TPOT (ms):                           12.72
---------------Inter-Token Latency----------------
Mean ITL (ms):                           9.02
Median ITL (ms):                         8.80
P95 ITL (ms):                            13.23
P99 ITL (ms):                            14.17
Max ITL (ms):                            29.38
==================================================
```

* Medium Concurrency (Balanced)

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  158.05
Total input tokens:                      39668
Total input text tokens:                 39668
Total generated tokens:                  40805
Total generated tokens (retokenized):    40775
Request throughput (req/s):              0.51
Input token throughput (tok/s):          250.99
Output token throughput (tok/s):         258.18
Peak output token throughput (tok/s):    1103.00
Peak concurrent requests:                19
Total token throughput (tok/s):          509.17
Concurrency:                             14.09
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   27837.05
Median E2E Latency (ms):                 23508.00
P90 E2E Latency (ms):                    57126.31
P99 E2E Latency (ms):                    66044.35
---------------Time to First Token----------------
Mean TTFT (ms):                          374.30
Median TTFT (ms):                        375.51
P99 TTFT (ms):                           695.58
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          53.25
Median TPOT (ms):                        57.93
P99 TPOT (ms):                           85.45
---------------Inter-Token Latency----------------
Mean ITL (ms):                           53.95
Median ITL (ms):                         53.97
P95 ITL (ms):                            84.74
P99 ITL (ms):                            244.84
Max ITL (ms):                            655.61
==================================================
```

* High Concurrency (Throughput-Optimized)

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf
```

* **Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  996.64
Total input tokens:                      249831
Total input text tokens:                 249831
Total generated tokens:                  252662
Total generated tokens (retokenized):    252588
Request throughput (req/s):              0.50
Input token throughput (tok/s):          250.67
Output token throughput (tok/s):         253.51
Peak output token throughput (tok/s):    1199.00
Peak concurrent requests:                104
Total token throughput (tok/s):          504.18
Concurrency:                             92.70
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   184773.75
Median E2E Latency (ms):                 174183.65
P90 E2E Latency (ms):                    343625.28
P99 E2E Latency (ms):                    404284.53
---------------Time to First Token----------------
Mean TTFT (ms):                          1289.59
Median TTFT (ms):                        1313.35
P99 TTFT (ms):                           2346.78
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          364.70
Median TPOT (ms):                        403.32
P99 TPOT (ms):                           452.34
---------------Inter-Token Latency----------------
Mean ITL (ms):                           363.82
Median ITL (ms):                         316.21
P95 ITL (ms):                            745.91
P99 ITL (ms):                            1345.88
Max ITL (ms):                            3118.59
==================================================
```

**Scenario 2: Reasoning (1K/8K)**

* Low Concurrency

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  680.26
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  44462
Total generated tokens (retokenized):    44455
Request throughput (req/s):              0.01
Input token throughput (tok/s):          8.97
Output token throughput (tok/s):         65.36
Peak output token throughput (tok/s):    151.00
Peak concurrent requests:                2
Total token throughput (tok/s):          74.33
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   68019.29
Median E2E Latency (ms):                 70568.85
P90 E2E Latency (ms):                    113237.40
P99 E2E Latency (ms):                    121682.34
---------------Time to First Token----------------
Mean TTFT (ms):                          206.17
Median TTFT (ms):                        177.28
P99 TTFT (ms):                           445.37
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          14.36
Median TPOT (ms):                        15.89
P99 TPOT (ms):                           16.43
---------------Inter-Token Latency----------------
Mean ITL (ms):                           15.26
Median ITL (ms):                         15.85
P95 ITL (ms):                            17.50
P99 ITL (ms):                            23.21
Max ITL (ms):                            45.22
==================================================
```

* Medium Concurrency

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  2475.98
Total input tokens:                      39668
Total input text tokens:                 39668
Total generated tokens:                  318306
Total generated tokens (retokenized):    318166
Request throughput (req/s):              0.03
Input token throughput (tok/s):          16.02
Output token throughput (tok/s):         128.56
Peak output token throughput (tok/s):    847.00
Peak concurrent requests:                18
Total token throughput (tok/s):          144.58
Concurrency:                             14.62
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   452592.46
Median E2E Latency (ms):                 486002.05
P90 E2E Latency (ms):                    833197.57
P99 E2E Latency (ms):                    957399.48
---------------Time to First Token----------------
Mean TTFT (ms):                          359.38
Median TTFT (ms):                        350.78
P99 TTFT (ms):                           500.36
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          111.18
Median TPOT (ms):                        122.76
P99 TPOT (ms):                           145.90
---------------Inter-Token Latency----------------
Mean ITL (ms):                           113.69
Median ITL (ms):                         122.81
P95 ITL (ms):                            147.87
P99 ITL (ms):                            151.03
Max ITL (ms):                            272.05
==================================================
```

* High Concurrency

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 320 \
  --max-concurrency 64 \
  --request-rate inf
```

```text Output theme={null}
Waiting for completion...
```

**Scenario 3: Summarization (8K/1K)**

* Low Concurrency

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  120.73
Total input tokens:                      41941
Total input text tokens:                 41941
Total generated tokens:                  4220
Total generated tokens (retokenized):    4220
Request throughput (req/s):              0.08
Input token throughput (tok/s):          347.41
Output token throughput (tok/s):         34.96
Peak output token throughput (tok/s):    73.00
Peak concurrent requests:                2
Total token throughput (tok/s):          382.36
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   12068.56
Median E2E Latency (ms):                 10211.36
P90 E2E Latency (ms):                    23203.32
P99 E2E Latency (ms):                    30677.66
---------------Time to First Token----------------
Mean TTFT (ms):                          1625.64
Median TTFT (ms):                        1526.63
P99 TTFT (ms):                           3743.51
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          24.95
Median TPOT (ms):                        23.95
P99 TPOT (ms):                           35.40
---------------Inter-Token Latency----------------
Mean ITL (ms):                           24.80
Median ITL (ms):                         21.73
P95 ITL (ms):                            59.56
P99 ITL (ms):                            61.10
Max ITL (ms):                            62.70
==================================================
```

* Medium Concurrency

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  389.96
Total input tokens:                      300020
Total input text tokens:                 300020
Total generated tokens:                  41669
Total generated tokens (retokenized):    41670
Request throughput (req/s):              0.21
Input token throughput (tok/s):          769.36
Output token throughput (tok/s):         106.86
Peak output token throughput (tok/s):    304.00
Peak concurrent requests:                19
Total token throughput (tok/s):          876.22
Concurrency:                             14.95
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   72870.97
Median E2E Latency (ms):                 70495.88
P90 E2E Latency (ms):                    121820.46
P99 E2E Latency (ms):                    148933.09
---------------Time to First Token----------------
Mean TTFT (ms):                          2460.45
Median TTFT (ms):                        1976.29
P99 TTFT (ms):                           7305.53
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          140.57
Median TPOT (ms):                        142.31
P99 TPOT (ms):                           273.40
---------------Inter-Token Latency----------------
Mean ITL (ms):                           135.44
Median ITL (ms):                         95.96
P95 ITL (ms):                            152.93
P99 ITL (ms):                            1488.37
Max ITL (ms):                            6540.24
==================================================
```

* High Concurrency

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 320 \
  --max-concurrency 64 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  1279.50
Total input tokens:                      1273893
Total input text tokens:                 1273893
Total generated tokens:                  170000
Total generated tokens (retokenized):    169981
Request throughput (req/s):              0.25
Input token throughput (tok/s):          995.62
Output token throughput (tok/s):         132.86
Peak output token throughput (tok/s):    703.00
Peak concurrent requests:                67
Total token throughput (tok/s):          1128.49
Concurrency:                             60.12
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   240385.63
Median E2E Latency (ms):                 236266.30
P90 E2E Latency (ms):                    429882.12
P99 E2E Latency (ms):                    515158.36
---------------Time to First Token----------------
Mean TTFT (ms):                          2710.44
Median TTFT (ms):                        2345.63
P99 TTFT (ms):                           7144.20
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          443.84
Median TPOT (ms):                        493.29
P99 TPOT (ms):                           606.19
---------------Inter-Token Latency----------------
Mean ITL (ms):                           448.23
Median ITL (ms):                         296.17
P95 ITL (ms):                            1869.15
P99 ITL (ms):                            2708.95
Max ITL (ms):                            7778.47
==================================================
```

#### 5.2.2 Speculative Decoding Benchmark

* **Model Deployment:**

```bash Command theme={null}
sglang serve \
  --model-path moonshotai/Kimi-K2.5 \
  --tp 8 \
  --reasoning-parser kimi_k2 \
  --tool-call-parser kimi_k2 \
  --speculative-algorithm=EAGLE3 \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --speculative-draft-model-path lightseekorg/kimi-k2.5-eagle3-mla \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000
```

* **Benchmark Command:**

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* **Results:**

```text Output theme={null}
Pending update...
```

* Medium Concurrency (Balanced)

```bash Command theme={null}
python -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

```text Output theme={null}
Pending update...
```

* High Concurrency (Throughput-Optimized)

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf
```

```text Output theme={null}
Pending update...
```

### 5.3 Speed Benchmark (AMD MI350X)

**Test Environment:**

* Hardware: AMD Instinct MI350X GPU (4x)
* Model: Kimi-K2.5 (BF16)
* Tensor Parallelism: 4
* SGLang Version: 0.5.9
* Docker Image: `lmsysorg/sglang:v0.5.9-rocm700-mi35x`
* ROCm: 7.0

We use SGLang's built-in benchmarking tool with the `random` dataset for standardized performance evaluation.

:::info AMD GPU TP Constraint
Kimi-K2.5 requires TP \<= 4 on AMD GPUs. The model has 64 attention heads, and the AITER MLA kernel requires `heads_per_gpu % 16 == 0`. With TP=4, each GPU gets 16 heads (valid). With TP=8, each GPU gets 8 heads (invalid).
:::

#### 5.3.1 Latency Benchmark

* **Model Deployment:**

```bash Command theme={null}
SGLANG_USE_AITER=1 SGLANG_ROCM_FUSED_DECODE_MLA=0 \
sglang serve \
  --model-path moonshotai/Kimi-K2.5 \
  --tp 4 \
  --mem-fraction-static 0.8 \
  --trust-remote-code \
  --reasoning-parser kimi_k2 \
  --host 0.0.0.0 \
  --port 30000
```

* **Benchmark Command:**

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* **Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  155.81
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  4220
Total generated tokens (retokenized):    4222
Request throughput (req/s):              0.06
Input token throughput (tok/s):          39.16
Output token throughput (tok/s):         27.09
Peak output token throughput (tok/s):    29.00
Peak concurrent requests:                2
Total token throughput (tok/s):          66.24
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   15576.22
Median E2E Latency (ms):                 12539.80
P90 E2E Latency (ms):                    28150.56
P99 E2E Latency (ms):                    34873.51
---------------Time to First Token----------------
Mean TTFT (ms):                          563.50
Median TTFT (ms):                        594.92
P99 TTFT (ms):                           830.31
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          35.61
Median TPOT (ms):                        35.66
P99 TPOT (ms):                           35.77
---------------Inter-Token Latency----------------
Mean ITL (ms):                           35.66
Median ITL (ms):                         35.69
P95 ITL (ms):                            35.96
P99 ITL (ms):                            36.13
Max ITL (ms):                            36.92
==================================================
```

* Medium Concurrency (Balanced)

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-K2.5 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  526.66
Total input tokens:                      39668
Total input text tokens:                 39668
Total generated tokens:                  40805
Total generated tokens (retokenized):    40798
Request throughput (req/s):              0.15
Input token throughput (tok/s):          75.32
Output token throughput (tok/s):         77.48
Peak output token throughput (tok/s):    96.00
Peak concurrent requests:                18
Total token throughput (tok/s):          152.80
Concurrency:                             14.59
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   96023.27
Median E2E Latency (ms):                 93940.20
P90 E2E Latency (ms):                    159449.54
P99 E2E Latency (ms):                    194706.61
---------------Time to First Token----------------
Mean TTFT (ms):                          989.08
Median TTFT (ms):                        886.42
P99 TTFT (ms):                           1543.60
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          191.04
Median TPOT (ms):                        195.20
P99 TPOT (ms):                           238.84
---------------Inter-Token Latency----------------
Mean ITL (ms):                           186.68
Median ITL (ms):                         183.82
P95 ITL (ms):                            189.90
P99 ITL (ms):                            673.64
Max ITL (ms):                            1633.20
==================================================
```


# Kimi-K2.6
Source: https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-K2.6



## 1. Model Introduction

[Kimi-K2.6](https://huggingface.co/moonshotai/Kimi-K2.6) is an open-source, native multimodal agentic model by Moonshot AI, delivering industry-leading coding, long-horizon execution, and agent swarm capabilities. It matches or surpasses GPT-5.4, Claude Opus 4.6, and Gemini 3.1 Pro across key benchmarks.

**Key Features:**

* **Long-Horizon Coding**: Excels at complex, end-to-end coding tasks with 13+ hours of continuous execution and 4,000+ lines of code modification, generalizing across languages (Rust, Go, Python) and tasks (frontend, devops, performance optimization).
* **Coding-Driven Design**: Transforms prompts and visual inputs into production-ready interfaces with motion-rich elements including WebGL shaders, GSAP + Framer Motion, and Three.js 3D.
* **Agent Swarms Elevated**: Scales to 300 parallel sub-agents executing 4,000 coordinated steps per run. One prompt, 100+ files.
* **Proactive Agents**: Powers OpenClaw, Hermes Agent, and other autonomous frameworks for 5-day continuous operation.
* **Native Multimodality**: Pre-trained on vision–language tokens with MoonViT (400M parameters) for visual understanding, cross-modal reasoning, and agentic tool use grounded in visual inputs.

**Benchmarks (Open-Source SOTA):**

Benchmark Score
HLE w/ tools 54.0
SWE-Bench Pro 58.6
SWE-bench Multilingual 76.7
BrowseComp 83.2
Toolathlon 50.0
AIME 2026 96.4
GPQA-Diamond 90.5
LiveCodeBench 89.6
**Recommended Generation Parameters:** * Thinking Mode: `temperature=1.0`, `top_p=0.95` * Instant Mode: `temperature=0.6`, `top_p=0.95` **Available Models:** * **INT4 (native checkpoint)**: [moonshotai/Kimi-K2.6](https://huggingface.co/moonshotai/Kimi-K2.6) * **NVFP4 (4-bit quantized, NVIDIA Blackwell)**: [nvidia/Kimi-K2.6-NVFP4](https://huggingface.co/nvidia/Kimi-K2.6-NVFP4) **License:** Modified MIT for the native checkpoint. The NVIDIA NVFP4 checkpoint is governed by the [NVIDIA Open Model License](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/). For details, see [official documentation](https://huggingface.co/moonshotai/Kimi-K2.6) and [tech blog](https://kimi.com/blog/kimi-k2-6). ## 2. SGLang Installation Refer to the [official SGLang installation guide](../../../docs/get-started/install). ## 3. Model Deployment ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, deployment strategy, and capabilities. Run this Command:

### 3.2 Configuration Tips

* **Memory**: Requires GPUs with ≥140GB each. The native INT4 checkpoint supports H200 (8×, TP=8), B300 (8×, TP=8), GB300 (4×, TP=4), MI300X/MI325X (4×, TP=4), and MI350X/MI355X (4×, TP=4). Use `--context-length 128000` to conserve memory.
* **NVFP4**: Use `nvidia/Kimi-K2.6-NVFP4` with `--quantization modelopt_fp4` on NVIDIA Blackwell. Use `tp=8` on B300 and `tp=4` on GB300.
* **AMD GPU TP Constraint**: On AMD GPUs, TP must be ≤ 4 (not 8). Kimi-K2.6 has 64 attention heads; the AITER MLA kernel requires `heads_per_gpu % 16 == 0`. With TP=4, each GPU gets 16 heads (valid). With TP=8, each GPU gets 8 heads (invalid).
* **AMD Docker Image**: Use `lmsysorg/sglang:v0.5.9-rocm700-mi35x` for MI350X/MI355X and `lmsysorg/sglang:v0.5.9-rocm700-mi30x` for MI300X/MI325X.
* **DP Attention**: Enable with `--attn-dp-size ` for production throughput. A common choice is to set `--attn-dp-size` equal to `--tp`, but this is not required.
* **Reasoning Parser**: Add `--reasoning-parser kimi_k2` to separate thinking and content in model outputs.
* **Tool Call Parser**: Add `--tool-call-parser kimi_k2` for structured tool calls.
* **AMD FP8 KV Cache**: On AMD platforms the generator adds `--kv-cache-dtype fp8_e4m3` by default and sets `--mem-fraction-static 0.8` to fit the INT4 weights plus KV cache. FP8 KV cache trades a small amount of accuracy for memory; omit the flag if you observe accuracy regressions on your workload.

## 4. Model Invocation

### 4.1 Basic Usage

See [Basic API Usage](../../../docs/basic_usage/send_request).

### 4.2 Advanced Usage

#### 4.2.1 Multimodal (Vision + Text) Input

Kimi-K2.6 supports native multimodal input with images:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.6",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                    }
                },
                {
                    "type": "text",
                    "text": "What is in this image? Describe it in detail."
                }
            ]
        }
    ]
)

print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
This image shows a **paper receipt from Auntie Anne's**, the pretzel chain restaurant. Here's a detailed breakdown:

## Header
- At the top left is the Auntie Anne's logo (a pretzel with a halo)
- The store name "**Auntie Anne's**" is printed prominently at the top
- Some text below the store name appears blurred/redacted (likely store location, address, or transaction details)

## Purchase Details
- **Item**: CINNAMON SUGAR
- **Quantity & Price**: 1 × 17,000
- **Item Total**: 17,000

## Financial Summary
- **SUB TOTAL**: 17,000
- **GRAND TOTAL**: 17,000
- **CASH IDR**: 20,000 (customer paid 20,000 Indonesian Rupiah)
- **CHANGE DUE**: 3,000

## Physical Description
- The receipt is printed on white thermal paper
- Some information in the middle section and toward the bottom is intentionally blurred/obscured
- The paper appears slightly curved/wrinkled and is placed on a dark brown surface (likely a table or counter)

The transaction is in **Indonesian Rupiah (IDR)**, indicating this purchase was made at an Auntie Anne's location in Indonesia. The customer bought one Cinnamon Sugar pretzel for 17,000 IDR and received 3,000 IDR in change after paying with 20,000 IDR cash.
```

#### 4.2.2 Reasoning Output

Kimi-K2.6 supports both thinking mode (default) and instant mode.

**Thinking Mode (default)** — reasoning content is automatically separated:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.6",
    messages=[
        {"role": "user", "content": "Which one is bigger, 9.11 or 9.9? Think carefully."}
    ]
)

print("====== Reasoning Content (Thinking Mode) ======")
print(response.choices[0].message.reasoning_content)
print("====== Response (Thinking Mode) ======")
print(response.choices[0].message.content)
```

**Instant Mode (thinking off)** — disable thinking for faster responses:

```python Example theme={null}
response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.6",
    messages=[
        {"role": "user", "content": "Which one is bigger, 9.11 or 9.9? Think carefully."}
    ],
    extra_body={"chat_template_kwargs": {"thinking": False}}
)

print("====== Response (Instant Mode) ======")
print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
====== Reasoning Content (Thinking Mode) ======
The user is asking which number is bigger: 9.11 or 9.9. This seems straightforward, but there's a viral internet debate about this due to decimal confusion.

Let me think carefully:
- 9.11 means 9 + 11/100 = 9.11
- 9.9 means 9 + 9/10 = 9.90

So 9.9 = 9.90, and 9.90 > 9.11 because 0.90 > 0.11.

The confusion often comes from people thinking of software versioning (where 9.11 comes after 9.9) or comparing the numbers after the decimal as whole numbers (11 vs 9, thinking 11 > 9).

So mathematically, 9.9 is clearly bigger. 9.9 - 9.11 = 0.79.

I should explain this clearly and address the common misconception.
====== Response (Thinking Mode) ======
Mathematically, **9.9 is bigger**.

Here's why:

**9.9 = 9.90**

When comparing decimals, you need to look at the same place values:
- 9.11 = 9 ones, 1 tenth, and 1 hundredth
- 9.9 = 9 ones, 9 tenths, and 0 hundredths (9.90)

Since **0.90 > 0.11**, it follows that **9.9 > 9.11**.

The difference is:
9.9 - 9.11 = 0.79

**Why people get confused:** Many mistakenly treat the decimals like whole numbers (thinking "11 is bigger than 9") or confuse this with software version numbering (where version 9.11 comes after version 9.9). But in standard mathematics, 9.9 is definitively larger.
====== Response (Instant Mode) ======
I need to compare 9.11 and 9.9.

Let me think carefully by aligning the decimal places:

- 9.11 = 9 and 11/100 = 9.11
- 9.9 = 9 and 9/10 = 9.90

Since 0.90 > 0.11

**9.9 is bigger.**

This is a common trick question because people sometimes mistakenly compare 11 and 9 as whole numbers after the decimal point, forgetting that 9.9 = 9.90, which is greater than 9.11.
```

#### 4.2.3 Tool Calling

Kimi-K2.6 supports tool calling capabilities for agentic tasks:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.6",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    stream=True
)

# Process streaming response
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {'name': None, 'arguments': ''}
                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        if delta.content:
            print(delta.content, end="", flush=True)

for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"Tool Call: {tool_call['name']}")
    print(f"  Arguments: {tool_call['arguments']}")
```

**Output Example:**

```text Output theme={null}
Tool Call: get_weather
  Arguments: {"location": "Beijing"}
```

**Handling Tool Call Results:**

```python Example theme={null}
# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": "The weather in Beijing is 22°C and sunny."
    }
]

final_response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.6",
    messages=messages
)

print(final_response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
The weather in Beijing is currently **22°C and sunny**. ☀️

It's a nice, warm day there—great for being outdoors!
```

#### 4.2.4 Multimodal + Tool Calling (Agentic Vision)

Combine vision understanding with tool calling for advanced agentic tasks:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "search_product",
            "description": "Search for a product by name or description",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The product name or description to search for"
                    }
                },
                "required": ["query"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.6",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                    }
                },
                {
                    "type": "text",
                    "text": "Can you identify this product and search for similar items?"
                }
            ]
        }
    ],
    tools=tools
)

msg = response.choices[0].message

# Print reasoning process
if msg.reasoning_content:
    print("=== Reasoning ===")
    print(msg.reasoning_content)

# Print response content
if msg.content:
    print("=== Content ===")
    print(msg.content)

# Print tool calls
if msg.tool_calls:
    print("=== Tool Calls ===")
    for tc in msg.tool_calls:
        print(f"  Function: {tc.function.name}")
        print(f"  Arguments: {tc.function.arguments}")
```

**Output Example:**

```text Output theme={null}
=== Reasoning ===
The user wants me to identify the product from the receipt and search for similar items. Looking at the receipt, it's from Auntie Anne's and the item purchased is "CINNAMON SUGAR" for 17,000 IDR. This is likely a Cinnamon Sugar Pretzel from Auntie Anne's, which is a popular pretzel chain.

I should search for this product using the search_product function. The query should be something like "Auntie Anne's Cinnamon Sugar Pretzel" or just "Cinnamon Sugar Pretzel" to find similar items.
=== Content ===
Based on the receipt, the product is a **Cinnamon Sugar Pretzel** from **Auntie Anne's** (a popular pretzel bakery chain). The receipt shows it was purchased for 17,000 Indonesian Rupiah (IDR).

Let me search for this product and similar items for you.
=== Tool Calls ===
  Function: search_product
  Arguments: {"query":"Auntie Anne's Cinnamon Sugar Pretzel"}
```

#### 4.2.5 Speculative Decoding

**NVIDIA**

Deploy Kimi-K2.6 with the following command (H200/B300, all features enabled):

```shell Command theme={null}
sglang serve \
  --model-path moonshotai/Kimi-K2.6 \
  --tp 8 \
  --reasoning-parser kimi_k2 \
  --tool-call-parser kimi_k2 \
  --speculative-algorithm EAGLE3 \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --speculative-draft-model-path lightseekorg/kimi-k2.6-eagle3.1-mla \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000
```

Deploy Kimi-K2.6-NVFP4 with the following command (B300, all features enabled):

```shell Command theme={null}
sglang serve \
  --model-path nvidia/Kimi-K2.6-NVFP4 \
  --tp 8 \
  --quantization modelopt_fp4 \
  --reasoning-parser kimi_k2 \
  --tool-call-parser kimi_k2 \
  --speculative-algorithm EAGLE3 \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --speculative-draft-model-path lightseekorg/kimi-k2.6-eagle3.1-mla \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000
```

For GB300, use `--tp 4`.

## 5. Benchmark

### 5.1 Accuracy Benchmark

**Test Environment:**

* Hardware: 8× NVIDIA H200
* Model: moonshotai/Kimi-K2.6 (INT4)
* Tensor Parallelism: 8
* SGLang version: 0.5.9
* Reasoning Parser: `kimi_k2`
* Tool Call Parser: `kimi_k2`

#### NVIDIA NVFP4 Accuracy Reference

NVIDIA reports the following accuracy results for `nvidia/Kimi-K2.6-NVFP4` compared with the native INT4 baseline, using `temperature=1.0`, `top_p=0.95`, and max tokens 128,000:

Precision GPQA Diamond SciCode τ²-Bench Telecom MMMU Pro AA-LCR IFBench
Baseline (INT4) 90.9 52.6 98.2 75.6 71.0 73.9
NVFP4 90.4 54.4 98.0 76.5 71.8 73.9
#### 5.1.1 K2-Vendor-Verifier (Tool Calling) * Dataset: [K2-Vendor-Verifier](https://github.com/MoonshotAI/K2-Vendor-Verifier) tool-calls dataset (2,000 requests) * Evaluation Tool: K2-Vendor-Verifier `tool_calls_eval.py` * Settings: temperature=1.0, max\_tokens=64,000, concurrency=256 **Evaluation Command:** ```shell Command theme={null} cd K2-Vendor-Verifier python tool_calls_eval.py tool-calls/samples.jsonl \ --model "moonshotai/Kimi-K2.6" \ --base-url "http://localhost:30000/v1" \ --api-key "placeholder" \ --concurrency 256 \ --temperature 1.0 \ --max-tokens 64000 \ --output kimi-k26-results.jsonl ``` **Results:**
Metric Value
Success Rate 99.95% (1999/2000)
Tool Call Triggered 970
Tool Call Valid 89.6% (869/970)
Tool Call Invalid (schema error) 10.4% (101/970)
#### 5.1.2 AIME 2025 * Dataset: [AIME 2025](https://huggingface.co/datasets/nvidia/aime25) (30 problems) * Evaluation Tool: [sgl-eval](https://github.com/sgl-project/sgl-eval) * Prompt: `eval/matharena/aime` (MathArena format with `\boxed{}` answers) * Settings: temperature=1.0, top\_p=0.95, max\_tokens=131,072, 32 repeats **Evaluation Command:** ```shell Command theme={null} pip install sgl-eval # The dataset ships with sgl-eval; --n-repeats runs all 32 samples per problem. sgl-eval run aime25 \ --base-url http://localhost:30000/v1 \ --model moonshotai/Kimi-K2.6 \ --n-repeats 32 \ --temperature 1.0 \ --top-p 0.95 \ --max-tokens 131072 \ --prompt matharena-aime \ --num-threads 512 ``` **Results:**
Evaluation Mode Accuracy
pass\@1 (avg-of-32) 98.9% (29.7/30)
**majority\@32** **100.0% (30/30)**
pass\@32 100.0%
> 22 out of 32 seeds achieved a perfect score of 30/30. The remaining 10 seeds each missed exactly 1 problem (29/30). #### 5.1.3 GPQA Diamond * Dataset: [GPQA Diamond](https://huggingface.co/datasets/Idavidrein/gpqa) (198 questions, 4-choice multiple choice) * Evaluation Tool: [Inspect AI](https://github.com/UKGovernmentBEIS/inspect_ai) with `inspect_evals/gpqa_diamond` * Settings: temperature=1.0, top\_p=0.95, max\_tokens=131,072, 4 epochs, cot=True **Evaluation Command:** ```shell Command theme={null} OPENAI_BASE_URL=http://localhost:30000/v1 OPENAI_API_KEY=placeholder \ inspect eval inspect_evals/gpqa_diamond \ --model openai/moonshotai/Kimi-K2.6 \ --max-tokens 131072 \ --temperature 1.0 \ --top-p 0.95 \ --max-connections 128 \ -T cot=True ``` **Results (partial — 553/792 samples across 4 epochs):**
Evaluation Mode Accuracy
pass\@1 (avg across epochs) **96.9%**
Epoch Accuracy
1 96.4% (160/166)
2 96.9% (156/161)
3 96.9% (155/160)
4 98.5% (65/66)
#### 5.1.4 OCRBench * Dataset: [OCRBench](https://huggingface.co/datasets/echo840/OCRBench) (1,000 questions with images) * Evaluation Tool: [Kimi-Vendor-Verifier](https://github.com/MoonshotAI/Kimi-Vendor-Verifier) (inspect-ai based) * Settings: max\_tokens=4,096, thinking mode enabled (opensource) **Evaluation Command:** ```shell Command theme={null} cd Kimi-Vendor-Verifier OPENAI_BASE_URL=http://localhost:30000/v1 OPENAI_API_KEY=placeholder \ python3 eval.py ocrbench \ --model openai/moonshotai/Kimi-K2.6 \ --max-tokens 4096 \ --think-mode opensource \ --thinking \ --max-connections 256 ``` **Results:**
Evaluation Mode Accuracy
pass\@1 **90.8%**
#### 5.1.5 MMMU Pro Vision * Dataset: [MMMU Pro](https://huggingface.co/datasets/MMMU/MMMU_Pro) standard 10-option subset (1,730 questions with images) * Evaluation Tool: [Kimi-Vendor-Verifier](https://github.com/MoonshotAI/Kimi-Vendor-Verifier) (inspect-ai based) * Settings: max\_tokens=32,768, thinking mode (default), max\_connections=256 > **Important**: Kimi-K2.6 is a reasoning model. Setting `max_tokens` too low (e.g., 4096) causes the thinking process to consume the entire token budget, leaving no tokens for the final answer. Use `max_tokens=32768` or higher. **Evaluation Command:** ```shell Command theme={null} cd Kimi-Vendor-Verifier OPENAI_BASE_URL=http://localhost:30000/v1 OPENAI_API_KEY=placeholder \ python3 eval.py mmmu \ --model openai/moonshotai/Kimi-K2.6 \ --max-tokens 32768 \ --think-mode none \ --max-connections 256 ``` **Results (1,481/1,730 samples completed):**
Evaluation Mode Accuracy
pass\@1 **82.2%**
### 5.2 Speed Benchmark **Test Environment:** * Hardware: NVIDIA H200 GPU (8x) * Model: Kimi-K2.6 * Tensor Parallelism: 8 * SGLang Version: 0.5.9 > [!NOTE] > > Kimi-K2.6 shares the same architecture as K2.5. Speed benchmarks are expected to be equivalent. The results below are measured with K2.5 and serve as a reference. We use SGLang's built-in benchmarking tool with the `random` dataset for standardized performance evaluation. #### 5.2.1 Latency Benchmark * **Model Deployment:** ```shell Command theme={null} sglang serve \ --model-path moonshotai/Kimi-K2.6 \ --tp 8 \ --trust-remote-code \ --host 0.0.0.0 \ --port 30000 ``` **Scenario 1: Chat (1K/1K)** * Low Concurrency ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 39.77 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 4221 Request throughput (req/s): 0.25 Input token throughput (tok/s): 153.40 Output token throughput (tok/s): 106.10 Peak output token throughput (tok/s): 156.00 Peak concurrent requests: 2 Total token throughput (tok/s): 259.50 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 3972.87 Median E2E Latency (ms): 4044.55 P90 E2E Latency (ms): 7046.30 P99 E2E Latency (ms): 7441.13 ---------------Time to First Token---------------- Mean TTFT (ms): 176.89 Median TTFT (ms): 154.24 P99 TTFT (ms): 285.75 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 9.22 Median TPOT (ms): 9.32 P99 TPOT (ms): 12.72 ---------------Inter-Token Latency---------------- Mean ITL (ms): 9.02 Median ITL (ms): 8.80 P95 ITL (ms): 13.23 P99 ITL (ms): 14.17 Max ITL (ms): 29.38 ================================================== ``` * Medium Concurrency (Balanced) ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 158.05 Total input tokens: 39668 Total input text tokens: 39668 Total generated tokens: 40805 Total generated tokens (retokenized): 40775 Request throughput (req/s): 0.51 Input token throughput (tok/s): 250.99 Output token throughput (tok/s): 258.18 Peak output token throughput (tok/s): 1103.00 Peak concurrent requests: 19 Total token throughput (tok/s): 509.17 Concurrency: 14.09 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 27837.05 Median E2E Latency (ms): 23508.00 P90 E2E Latency (ms): 57126.31 P99 E2E Latency (ms): 66044.35 ---------------Time to First Token---------------- Mean TTFT (ms): 374.30 Median TTFT (ms): 375.51 P99 TTFT (ms): 695.58 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 53.25 Median TPOT (ms): 57.93 P99 TPOT (ms): 85.45 ---------------Inter-Token Latency---------------- Mean ITL (ms): 53.95 Median ITL (ms): 53.97 P95 ITL (ms): 84.74 P99 ITL (ms): 244.84 Max ITL (ms): 655.61 ================================================== ``` * High Concurrency (Throughput-Optimized) ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 500 Benchmark duration (s): 996.64 Total input tokens: 249831 Total input text tokens: 249831 Total generated tokens: 252662 Total generated tokens (retokenized): 252588 Request throughput (req/s): 0.50 Input token throughput (tok/s): 250.67 Output token throughput (tok/s): 253.51 Peak output token throughput (tok/s): 1199.00 Peak concurrent requests: 104 Total token throughput (tok/s): 504.18 Concurrency: 92.70 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 184773.75 Median E2E Latency (ms): 174183.65 P90 E2E Latency (ms): 343625.28 P99 E2E Latency (ms): 404284.53 ---------------Time to First Token---------------- Mean TTFT (ms): 1289.59 Median TTFT (ms): 1313.35 P99 TTFT (ms): 2346.78 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 364.70 Median TPOT (ms): 403.32 P99 TPOT (ms): 452.34 ---------------Inter-Token Latency---------------- Mean ITL (ms): 363.82 Median ITL (ms): 316.21 P95 ITL (ms): 745.91 P99 ITL (ms): 1345.88 Max ITL (ms): 3118.59 ================================================== ``` **Scenario 2: Reasoning (1K/8K)** * Low Concurrency ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 680.26 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 44462 Total generated tokens (retokenized): 44455 Request throughput (req/s): 0.01 Input token throughput (tok/s): 8.97 Output token throughput (tok/s): 65.36 Peak output token throughput (tok/s): 151.00 Peak concurrent requests: 2 Total token throughput (tok/s): 74.33 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 68019.29 Median E2E Latency (ms): 70568.85 P90 E2E Latency (ms): 113237.40 P99 E2E Latency (ms): 121682.34 ---------------Time to First Token---------------- Mean TTFT (ms): 206.17 Median TTFT (ms): 177.28 P99 TTFT (ms): 445.37 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 14.36 Median TPOT (ms): 15.89 P99 TPOT (ms): 16.43 ---------------Inter-Token Latency---------------- Mean ITL (ms): 15.26 Median ITL (ms): 15.85 P95 ITL (ms): 17.50 P99 ITL (ms): 23.21 Max ITL (ms): 45.22 ================================================== ``` * Medium Concurrency ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 8000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 2475.98 Total input tokens: 39668 Total input text tokens: 39668 Total generated tokens: 318306 Total generated tokens (retokenized): 318166 Request throughput (req/s): 0.03 Input token throughput (tok/s): 16.02 Output token throughput (tok/s): 128.56 Peak output token throughput (tok/s): 847.00 Peak concurrent requests: 18 Total token throughput (tok/s): 144.58 Concurrency: 14.62 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 452592.46 Median E2E Latency (ms): 486002.05 P90 E2E Latency (ms): 833197.57 P99 E2E Latency (ms): 957399.48 ---------------Time to First Token---------------- Mean TTFT (ms): 359.38 Median TTFT (ms): 350.78 P99 TTFT (ms): 500.36 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 111.18 Median TPOT (ms): 122.76 P99 TPOT (ms): 145.90 ---------------Inter-Token Latency---------------- Mean ITL (ms): 113.69 Median ITL (ms): 122.81 P95 ITL (ms): 147.87 P99 ITL (ms): 151.03 Max ITL (ms): 272.05 ================================================== ``` **Scenario 3: Summarization (8K/1K)** * Low Concurrency ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 120.73 Total input tokens: 41941 Total input text tokens: 41941 Total generated tokens: 4220 Total generated tokens (retokenized): 4220 Request throughput (req/s): 0.08 Input token throughput (tok/s): 347.41 Output token throughput (tok/s): 34.96 Peak output token throughput (tok/s): 73.00 Peak concurrent requests: 2 Total token throughput (tok/s): 382.36 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 12068.56 Median E2E Latency (ms): 10211.36 P90 E2E Latency (ms): 23203.32 P99 E2E Latency (ms): 30677.66 ---------------Time to First Token---------------- Mean TTFT (ms): 1625.64 Median TTFT (ms): 1526.63 P99 TTFT (ms): 3743.51 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 24.95 Median TPOT (ms): 23.95 P99 TPOT (ms): 35.40 ---------------Inter-Token Latency---------------- Mean ITL (ms): 24.80 Median ITL (ms): 21.73 P95 ITL (ms): 59.56 P99 ITL (ms): 61.10 Max ITL (ms): 62.70 ================================================== ``` * Medium Concurrency ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 389.96 Total input tokens: 300020 Total input text tokens: 300020 Total generated tokens: 41669 Total generated tokens (retokenized): 41670 Request throughput (req/s): 0.21 Input token throughput (tok/s): 769.36 Output token throughput (tok/s): 106.86 Peak output token throughput (tok/s): 304.00 Peak concurrent requests: 19 Total token throughput (tok/s): 876.22 Concurrency: 14.95 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 72870.97 Median E2E Latency (ms): 70495.88 P90 E2E Latency (ms): 121820.46 P99 E2E Latency (ms): 148933.09 ---------------Time to First Token---------------- Mean TTFT (ms): 2460.45 Median TTFT (ms): 1976.29 P99 TTFT (ms): 7305.53 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 140.57 Median TPOT (ms): 142.31 P99 TPOT (ms): 273.40 ---------------Inter-Token Latency---------------- Mean ITL (ms): 135.44 Median ITL (ms): 95.96 P95 ITL (ms): 152.93 P99 ITL (ms): 1488.37 Max ITL (ms): 6540.24 ================================================== ``` * High Concurrency ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 8000 \ --random-output-len 1000 \ --num-prompts 320 \ --max-concurrency 64 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 64 Successful requests: 320 Benchmark duration (s): 1279.50 Total input tokens: 1273893 Total input text tokens: 1273893 Total generated tokens: 170000 Total generated tokens (retokenized): 169981 Request throughput (req/s): 0.25 Input token throughput (tok/s): 995.62 Output token throughput (tok/s): 132.86 Peak output token throughput (tok/s): 703.00 Peak concurrent requests: 67 Total token throughput (tok/s): 1128.49 Concurrency: 60.12 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 240385.63 Median E2E Latency (ms): 236266.30 P90 E2E Latency (ms): 429882.12 P99 E2E Latency (ms): 515158.36 ---------------Time to First Token---------------- Mean TTFT (ms): 2710.44 Median TTFT (ms): 2345.63 P99 TTFT (ms): 7144.20 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 443.84 Median TPOT (ms): 493.29 P99 TPOT (ms): 606.19 ---------------Inter-Token Latency---------------- Mean ITL (ms): 448.23 Median ITL (ms): 296.17 P95 ITL (ms): 1869.15 P99 ITL (ms): 2708.95 Max ITL (ms): 7778.47 ================================================== ``` ### 5.3 Speed Benchmark (AMD MI350X) **Test Environment:** * Hardware: AMD Instinct MI350X GPU (4x) * Model: Kimi-K2.6 (INT4) * Tensor Parallelism: 4 * SGLang Version: 0.5.9 * Docker Image: `lmsysorg/sglang:v0.5.9-rocm700-mi35x` * ROCm: 7.0 We use SGLang's built-in benchmarking tool with the `random` dataset for standardized performance evaluation. > [!NOTE] > > **AMD GPU TP Constraint**: Kimi-K2.6 requires TP ≤ 4 on AMD GPUs. The model has 64 attention heads, and the AITER MLA kernel requires `heads_per_gpu % 16 == 0`. With TP=4, each GPU gets 16 heads (valid). With TP=8, each GPU gets 8 heads (invalid). #### 5.3.1 Latency Benchmark * **Model Deployment:** ```shell Command theme={null} SGLANG_USE_AITER=1 SGLANG_ROCM_FUSED_DECODE_MLA=0 \ sglang serve \ --model-path moonshotai/Kimi-K2.6 \ --tp 4 \ --mem-fraction-static 0.8 \ --trust-remote-code \ --reasoning-parser kimi_k2 \ --tool-call-parser kimi_k2 \ --kv-cache-dtype fp8_e4m3 \ --host 0.0.0.0 \ --port 30000 ``` * **Benchmark Command:** ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` * **Results:** ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 155.81 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 4222 Request throughput (req/s): 0.06 Input token throughput (tok/s): 39.16 Output token throughput (tok/s): 27.09 Peak output token throughput (tok/s): 29.00 Peak concurrent requests: 2 Total token throughput (tok/s): 66.24 Concurrency: 1.00 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 15576.22 Median E2E Latency (ms): 12539.80 P90 E2E Latency (ms): 28150.56 P99 E2E Latency (ms): 34873.51 ---------------Time to First Token---------------- Mean TTFT (ms): 563.50 Median TTFT (ms): 594.92 P99 TTFT (ms): 830.31 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 35.61 Median TPOT (ms): 35.66 P99 TPOT (ms): 35.77 ---------------Inter-Token Latency---------------- Mean ITL (ms): 35.66 Median ITL (ms): 35.69 P95 ITL (ms): 35.96 P99 ITL (ms): 36.13 Max ITL (ms): 36.92 ================================================== ``` * Medium Concurrency (Balanced) ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model moonshotai/Kimi-K2.6 \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 80 \ --max-concurrency 16 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 16 Successful requests: 80 Benchmark duration (s): 526.66 Total input tokens: 39668 Total input text tokens: 39668 Total generated tokens: 40805 Total generated tokens (retokenized): 40798 Request throughput (req/s): 0.15 Input token throughput (tok/s): 75.32 Output token throughput (tok/s): 77.48 Peak output token throughput (tok/s): 96.00 Peak concurrent requests: 18 Total token throughput (tok/s): 152.80 Concurrency: 14.59 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 96023.27 Median E2E Latency (ms): 93940.20 P90 E2E Latency (ms): 159449.54 P99 E2E Latency (ms): 194706.61 ---------------Time to First Token---------------- Mean TTFT (ms): 989.08 Median TTFT (ms): 886.42 P99 TTFT (ms): 1543.60 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 191.04 Median TPOT (ms): 195.20 P99 TPOT (ms): 238.84 ---------------Inter-Token Latency---------------- Mean ITL (ms): 186.68 Median ITL (ms): 183.82 P95 ITL (ms): 189.90 P99 ITL (ms): 673.64 Max ITL (ms): 1633.20 ================================================== ``` # Kimi-K2.7-Code Source: https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-K2.7-Code Deploy Kimi-K2.7-Code with SGLang for coding-focused agentic workflows, thinking output, tool calling, and multimodal input. ## 1. Model Introduction [Kimi-K2.7-Code](https://huggingface.co/moonshotai/Kimi-K2.7-Code) is a coding-focused agentic model by Moonshot AI, built on top of Kimi-K2.6. It improves real-world long-horizon coding task completion while reducing thinking-token usage by approximately 30% compared with Kimi-K2.6. **Key Features:** * **Coding-Focused Agentic Model**: Optimized for end-to-end coding workflows and complex software engineering tasks. * **Token Efficiency**: Reduces thinking-token usage by approximately 30% versus Kimi-K2.6. * **K2.6-Compatible Deployment**: Shares the same architecture as Kimi-K2.5/Kimi-K2.6, so the SGLang deployment method can be reused with the new model ID. * **Native Multimodality**: Shares Kimi-K2.6's native multimodal architecture with a MoonViT vision encoder (400M parameters) and supports image and video (experimental) input. **Benchmarks:**
Benchmark Kimi-K2.6 Kimi-K2.7-Code
Kimi Code Bench v2 50.9 62.0
Program Bench 48.3 53.6
MLS Bench Lite 26.7 35.1
Kimi Claw 24/7 Bench 42.9 46.9
MCP Atlas 69.4 76.0
MCP Mark Verified 72.8 81.1
**Recommended Generation Parameters:** * Thinking Mode: `temperature=1.0`, `top_p=0.95` * Kimi-K2.7-Code forces thinking and preserve-thinking behavior; instant mode is not supported. **Available Models:** * **INT4 (native checkpoint)**: [moonshotai/Kimi-K2.7-Code](https://huggingface.co/moonshotai/Kimi-K2.7-Code) * **MXFP4**: [amd/Kimi-K2.7-Code-MXFP4](https://huggingface.co/amd/Kimi-K2.7-Code-MXFP4) — validated on AMD MI350X/MI355X. **License:** Modified MIT for the native checkpoint. For details, see the [official model card](https://huggingface.co/moonshotai/Kimi-K2.7-Code). ## 2. SGLang Installation Refer to the [official SGLang installation guide](/docs/get-started/install). ## 3. Model Deployment ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, deployment strategy, and capabilities. Run this Command:

### 3.2 Configuration Tips

* **Memory**: Requires GPUs with ≥140GB each. The native INT4 checkpoint supports H200 (8×, TP=8), B300 (8×, TP=8), GB300 (4×, TP=4), MI300X/MI325X (4×, TP=4), and MI350X/MI355X (4×, TP=4). Use `--context-length 128000` to conserve memory.
* **Context Length**: The model supports a 256K context length. Use a shorter `--context-length` when you need to reserve memory for larger batches.
* **Transformers Version**: The model card requires `transformers>=4.57.1,<5.0.0`.
* **AMD GPU TP Constraint**: On AMD GPUs, TP must be ≤ 4 (not 8). Kimi-K2.7-Code has 64 attention heads; the AITER MLA kernel requires `heads_per_gpu % 16 == 0`. With TP=4, each GPU gets 16 heads (valid). With TP=8, each GPU gets 8 heads (invalid).
* **AMD Docker Image**: Use `lmsysorg/sglang:v0.5.9-rocm700-mi35x` for MI350X/MI355X and `lmsysorg/sglang:v0.5.9-rocm700-mi30x` for MI300X/MI325X.
* **DP Attention**: Enable with `--attn-dp-size ` for production throughput. A common choice is to set `--attn-dp-size` equal to `--tp`, but this is not required.
* **Reasoning Parser**: Add `--reasoning-parser kimi_k2` to separate thinking and content in model outputs.
* **Tool Call Parser**: Add `--tool-call-parser kimi_k2` for structured tool calls.
* **AMD FP8 KV Cache**: On AMD platforms the generator adds `--kv-cache-dtype fp8_e4m3` by default and sets `--mem-fraction-static 0.8` to fit the INT4 weights plus KV cache. FP8 KV cache trades a small amount of accuracy for memory; omit the flag if you observe accuracy regressions on your workload.
* **MXFP4 Checkpoint**: The [MXFP4 checkpoint](https://huggingface.co/amd/Kimi-K2.7-Code-MXFP4) is validated on MI350X/MI355X (TP=4) with the `rocm/sgl-dev:v0.5.17-rocm720-mi35x-20260812` image (ROCm 7.2). Select `MXFP4` in the Quantization control to target `amd/Kimi-K2.7-Code-MXFP4`. The MXFP4 quantization is auto-detected from the checkpoint, so no `--quantization` flag is required; the generator emits the AITER/ROCm environment block plus `--attention-backend aiter`, `--mem-fraction-static 0.90`, FP8 KV cache, `--disable-radix-cache`, and `--enable-aiter-allreduce-fusion`. The reasoning and tool-call parsers are auto-detected, so they are not passed explicitly.

## 4. Model Invocation

### 4.1 Basic Usage

See [Basic API Usage](/docs/basic_usage/send_request).

### 4.2 Advanced Usage

#### 4.2.1 Multimodal (Vision + Text) Input

Kimi-K2.7-Code supports native multimodal input with images:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.7-Code",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                    }
                },
                {
                    "type": "text",
                    "text": "What is in this image? Describe it in detail."
                }
            ]
        }
    ]
)

print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
This image shows a **paper receipt from Auntie Anne's**, the pretzel chain restaurant. Here's a detailed breakdown:

## Header
- At the top left is the Auntie Anne's logo (a pretzel with a halo)
- The store name "**Auntie Anne's**" is printed prominently at the top
- Some text below the store name appears blurred/redacted (likely store location, address, or transaction details)

## Purchase Details
- **Item**: CINNAMON SUGAR
- **Quantity & Price**: 1 × 17,000
- **Item Total**: 17,000

## Financial Summary
- **SUB TOTAL**: 17,000
- **GRAND TOTAL**: 17,000
- **CASH IDR**: 20,000 (customer paid 20,000 Indonesian Rupiah)
- **CHANGE DUE**: 3,000

## Physical Description
- The receipt is printed on white thermal paper
- Some information in the middle section and toward the bottom is intentionally blurred/obscured
- The paper appears slightly curved/wrinkled and is placed on a dark brown surface (likely a table or counter)

The transaction is in **Indonesian Rupiah (IDR)**, indicating this purchase was made at an Auntie Anne's location in Indonesia. The customer bought one Cinnamon Sugar pretzel for 17,000 IDR and received 3,000 IDR in change after paying with 20,000 IDR cash.
```

#### 4.2.2 Reasoning Output

Kimi-K2.7-Code forces thinking mode and preserve-thinking behavior.

**Thinking Mode (default)** — reasoning content is automatically separated:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.7-Code",
    messages=[
        {"role": "user", "content": "Which one is bigger, 9.11 or 9.9? Think carefully."}
    ]
)

print("====== Reasoning Content (Thinking Mode) ======")
print(response.choices[0].message.reasoning_content)
print("====== Response (Thinking Mode) ======")
print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
====== Reasoning Content (Thinking Mode) ======
The user is asking which number is bigger: 9.11 or 9.9. This seems straightforward, but there's a viral internet debate about this due to decimal confusion.

Let me think carefully:
- 9.11 means 9 + 11/100 = 9.11
- 9.9 means 9 + 9/10 = 9.90

So 9.9 = 9.90, and 9.90 > 9.11 because 0.90 > 0.11.

The confusion often comes from people thinking of software versioning (where 9.11 comes after 9.9) or comparing the numbers after the decimal as whole numbers (11 vs 9, thinking 11 > 9).

So mathematically, 9.9 is clearly bigger. 9.9 - 9.11 = 0.79.

I should explain this clearly and address the common misconception.
====== Response (Thinking Mode) ======
Mathematically, **9.9 is bigger**.

Here's why:

**9.9 = 9.90**

When comparing decimals, you need to look at the same place values:
- 9.11 = 9 ones, 1 tenth, and 1 hundredth
- 9.9 = 9 ones, 9 tenths, and 0 hundredths (9.90)

Since **0.90 > 0.11**, it follows that **9.9 > 9.11**.

The difference is:
9.9 - 9.11 = 0.79

**Why people get confused:** Many mistakenly treat the decimals like whole numbers (thinking "11 is bigger than 9") or confuse this with software version numbering (where version 9.11 comes after version 9.9). But in standard mathematics, 9.9 is definitively larger.
```

#### 4.2.3 Preserve Thinking

Kimi-K2.7-Code keeps reasoning content across multi-turn interactions. This behavior is enabled by default and cannot be disabled.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

messages = [
    {
        "role": "user",
        "content": "Tell me three random numbers."
    },
    {
        "role": "assistant",
        "reasoning_content": "I'll start by listing five numbers: 473, 921, 235, 215, 222, and I'll tell you the first three.",
        "content": "473, 921, 235"
    },
    {
        "role": "user",
        "content": "What are the other two numbers you have in mind?"
    }
]

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.7-Code",
    messages=messages,
    stream=False,
    max_tokens=4096,
)

print(response.choices[0].message.content)
```

Some OpenAI-compatible deployments use `reasoning` instead of `reasoning_content` in assistant messages. Use the field your serving stack exposes.

#### 4.2.4 Tool Calling

Kimi-K2.7-Code supports tool calling capabilities for agentic tasks:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.7-Code",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    stream=True
)

# Process streaming response
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {'name': None, 'arguments': ''}
                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        if delta.content:
            print(delta.content, end="", flush=True)

for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"Tool Call: {tool_call['name']}")
    print(f"  Arguments: {tool_call['arguments']}")
```

**Output Example:**

```text Output theme={null}
Tool Call: get_weather
  Arguments: {"location": "Beijing"}
```

**Handling Tool Call Results:**

```python Example theme={null}
# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": "The weather in Beijing is 22°C and sunny."
    }
]

final_response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.7-Code",
    messages=messages
)

print(final_response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
The weather in Beijing is currently **22°C and sunny**. ☀️

It's a nice, warm day there—great for being outdoors!
```

#### 4.2.5 Multimodal + Tool Calling (Agentic Vision)

Combine vision understanding with tool calling for advanced agentic tasks:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "search_product",
            "description": "Search for a product by name or description",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The product name or description to search for"
                    }
                },
                "required": ["query"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="moonshotai/Kimi-K2.7-Code",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                    }
                },
                {
                    "type": "text",
                    "text": "Can you identify this product and search for similar items?"
                }
            ]
        }
    ],
    tools=tools
)

msg = response.choices[0].message

# Print reasoning process
if msg.reasoning_content:
    print("=== Reasoning ===")
    print(msg.reasoning_content)

# Print response content
if msg.content:
    print("=== Content ===")
    print(msg.content)

# Print tool calls
if msg.tool_calls:
    print("=== Tool Calls ===")
    for tc in msg.tool_calls:
        print(f"  Function: {tc.function.name}")
        print(f"  Arguments: {tc.function.arguments}")
```

**Output Example:**

```text Output theme={null}
=== Reasoning ===
The user wants me to identify the product from the receipt and search for similar items. Looking at the receipt, it's from Auntie Anne's and the item purchased is "CINNAMON SUGAR" for 17,000 IDR. This is likely a Cinnamon Sugar Pretzel from Auntie Anne's, which is a popular pretzel chain.

I should search for this product using the search_product function. The query should be something like "Auntie Anne's Cinnamon Sugar Pretzel" or just "Cinnamon Sugar Pretzel" to find similar items.
=== Content ===
Based on the receipt, the product is a **Cinnamon Sugar Pretzel** from **Auntie Anne's** (a popular pretzel bakery chain). The receipt shows it was purchased for 17,000 Indonesian Rupiah (IDR).

Let me search for this product and similar items for you.
=== Tool Calls ===
  Function: search_product
  Arguments: {"query":"Auntie Anne's Cinnamon Sugar Pretzel"}
```

#### 4.2.6 Deployment Command Example

Deploy Kimi-K2.7-Code with the following command (H200/B300, reasoning and tool parsing enabled):

```shell Command theme={null}
sglang serve \
  --model-path moonshotai/Kimi-K2.7-Code \
  --tp 8 \
  --reasoning-parser kimi_k2 \
  --tool-call-parser kimi_k2 \
  --trust-remote-code \
  --host 0.0.0.0 \
  --port 30000
```

For GB300, use `--tp 4`.

Deploy the MXFP4 checkpoint on AMD MI350X/MI355X (reasoning and tool-call parsers are auto-detected from the checkpoint):

```shell Command theme={null}
SGLANG_USE_AITER=1 \
HIP_FORCE_DEV_KERNARG=1 \
SGLANG_EXPERT_PARALLEL_SIZE=1 \
TORCH_BLAS_PREFER_HIPBLASLT=1 \
TENSILE_STREAMK_DYNAMIC_GRID=6 \
AITER_QUICK_REDUCE_QUANTIZATION=INT4 \
AITER_USE_FLYDSL_MOE_SORTING=1 \
AITER_AR_1STAGE_MAX_KB=512 \
AITER_MXFP4_INTERMEDIATE=1 \
ROCM_QUICK_REDUCE_QUANTIZATION=INT4 \
sglang serve \
  --model-path amd/Kimi-K2.7-Code-MXFP4 \
  --tp 4 \
  --trust-remote-code \
  --attention-backend aiter \
  --mem-fraction-static 0.90 \
  --kv-cache-dtype fp8_e4m3 \
  --disable-radix-cache \
  --enable-aiter-allreduce-fusion \
  --host 0.0.0.0 \
  --port 30000
```

## 5. Benchmark

### 5.1 Model Card Benchmarks

The following results are from the official Kimi-K2.7-Code model card. They were evaluated with thinking mode enabled through Kimi Code CLI at `temperature=1.0`, `top_p=0.95`, and a 262,144-token context length unless otherwise stated.

Category Benchmark Kimi-K2.6 Kimi-K2.7-Code
Coding Kimi Code Bench v2 50.9 62.0
Coding Program Bench 48.3 53.6
Coding MLS Bench Lite 26.7 35.1
Agentic Kimi Claw 24/7 Bench 42.9 46.9
Agentic MCP Atlas 69.4 76.0
Agentic MCP Mark Verified 72.8 81.1
### 5.2 MXFP4 Benchmark **Test Environment:** * Hardware: 4× AMD MI355X * Model: `amd/Kimi-K2.7-Code-MXFP4` (MXFP4) * Tensor Parallelism: 4 * Docker Image: `rocm/sgl-dev:v0.5.17-rocm720-mi35x-20260812` (ROCm 7.2) #### 5.2.1 Accuracy Benchmark Evaluate GSM8K on the deployed MXFP4 checkpoint across client parallelism levels (all 1319 test questions via sgl-eval): ```shell Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 1319 \ --num-threads '' ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above.
Parallel GSM8K Accuracy
100 0.951
300 0.953
600 0.942
1200 0.950
#### 5.2.2 Latency Benchmark We use SGLang's built-in `bench_serving` tool with the `random` dataset (input 8192, output 1024, range ratio 0.8). For each concurrency `C`, `--num-prompts` is set to `C × 5`. ```shell Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model amd/Kimi-K2.7-Code-MXFP4 \ --dataset-name random \ --random-input-len 8192 \ --random-output-len 1024 \ --random-range-ratio 0.8 \ --max-concurrency \ --num-prompts \ --host 0.0.0.0 \ --port 30000 ```
Concurrency Output Throughput (tok/s) Total Throughput (tok/s) Mean TTFT (ms) Median TTFT (ms) Mean TPOT (ms) Mean E2E Latency (ms)
4 416.22 3747.97 260.35 194.14 9.03 8720.79
8 670.88 6086.74 364.15 199.00 11.19 10687.52
16 963.47 8766.11 490.72 203.12 15.49 14680.68
32 1329.55 11857.47 775.37 215.45 22.61 21831.61
64 1740.46 15759.18 1343.98 300.81 34.41 33068.86
# Kimi-K3 Source: https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-K3 Deploy Moonshot AI's Kimi-K3 with SGLang — a 2.8T-parameter hybrid Mixture-of-Experts vision-language model (Kimi Delta Attention + MLA, 16/896 active experts) with NVIDIA, AMD, and NPU recipes. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest # NVIDIA (CUDA) > docker pull lmsysorg/sglang-rocm:v0.5.19-rocm720-mi35x-20260916 # AMD MI350X / MI355X (ROCm) > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. > > **NPU** > > ```bash Command theme={null} > docker pull quay.io/ascend/sglang:main-cann9.1.0-a3 # Ascend A3 Series > docker pull swr.cn-southwest-2.myhuaweicloud.com/base_image/dockerhub/lmsysorg/sglang:cann9.1.0-950-B070 # Ascend 950PR/DT Series > ``` > > For host and platform setup, see the > [NPU installation guide](../../../docs/hardware-platforms/ascend-npus/getting-started/installation) and the > [quick start guide](../../../docs/hardware-platforms/ascend-npus/getting-started/quick_start). > > **Weights (NPU):** [Kimi-K3](https://modelscope.cn/models/moonshotai/Kimi-K3) (950PR/DT Series, MXFP4) · > [Kimi-K3-W4A8](https://www.modelscope.cn/models/sgl-npu/Kimi-K3-W4A8) (A3 Series, W4A8, 1.49 TB) · > [Kimi-K3-DSpark](https://www.modelscope.cn/models/RadixArk/Kimi-K3-DSpark) (DSPARK draft, 4.5 GB) Pick your hardware, then the deployment shape and operating point. Node count follows the hardware recipe (B200 2×8, GB200 4×4, H100 4×8, B300 1×8, H200 2×8 — 4×8 on Unified High-Throughput, GB300 2×4, MI350X/MI355X 1×8, Ascend A3 Series 4×8 — 32 cards / 64 dies, Ascend 950PR/DT Series 4×8), so it is not a separate choice. If you serve the NVFP4 checkpoint (`nvidia/Kimi-K3-NVFP4`, the **Quantization** row in the panel below), use the `lmsysorg/sglang:dev-dev-kimi-k3-nvfp4` image. **PD Mode** — `Unified` serves prefill and decode together. `Prefill` / `Decode` split them into dedicated pools (see [PD disaggregation](#3-4-pd-disaggregation)); `Prefill` ships two strategies, both chunked at 16k. On the 8-GPU platforms (B300 1×8, GB300 2×4), `Default` is TP8 and `Long-Context` is `--pp-size 8 --tp-size 1`. On the 16-GPU platforms (B200 2×8, GB200 4×4), both are `--pp-size 16 --tp-size 1` and differ only in `--mem-fraction-static` (0.85 vs 0.90) — deep PP is the throughput shape there, not just the long-context one (see [Deep PP](#deep-pp-for-prefill)). **Ascend NPU PD** — the A3 Series splits over the Ascend memory fabric, with `Default` as the only prefill strategy: an asymmetric **2P4D** (TP16 × PP2 × DP2 prefill, NOSPEC; TP64 × DP4 decode). Pool layout and the fabric env: [On Ascend NPUs](#npu-pd). **Strategy** — the operating point within that shape: * **Low-Latency** — no DCP, so the MLA KV stays TP-replicated. For chat. B200 splits its two nodes into PP2 × TP8; every other platform is flat TP. * **Balanced** — the accuracy-preserving default: PP2 × DCPEP8 on B200 (the two pipeline stages and DCP8 split KV and KDA state), TP16/DCP16 on GB200, TP8/DCP8 on B300/GB300, TP8/DCP8 ROCm/AITER on MI35x. * **High-Throughput** — the large-scale lane: pick a **Cluster Size** and **Large-Scale Preset** in the Playground ([details](#large-scale-presets)). The cell itself is Balanced, except on H100 (plus `extra_buffer_lazy`) and H200 (widens to 4×8 TP32/EP32 at `--mem-fraction-static 0.90`). `Long-Context` appears only under the `Prefill` PD mode; for long-context unified serving on B200, start from High-Throughput and raise `--context-length`. **Spec Decode** — layers onto the strategy without changing it, on every platform except B200. DSPARK proposes 7 draft tokens per step (tune in the Playground) and requires `pp_size == 1` on the shipped recipes, so on B200 it also drops the pipeline and re-lays the same 16 GPUs flat: PP2 × TP8 → TP16, PP2 × DCPEP8 → DCPEP16. DFLASH uses the [Kimi-K3-DFlash](https://huggingface.co/modal-labs/Kimi-K3-DFlash) draft at block size 8; it doesn't support pipeline parallelism or DP attention yet, so it is unavailable on the pipelined B200 Unified recipes. It has only been validated on Blackwell, so the Hopper and AMD recipes don't offer it yet. The win is largest on short interactive traffic and fades as the prompt grows. > [!NOTE] > > `--mamba-full-memory-ratio` is the one sizing flag, computed live: set your average request length in the [Mamba ratio calculator](#mamba-ratio-calculator); everything else follows the panels, and the result is pinned into the command. (The Ascend NPU recipes don't use the calculator and set no ratio at all — the Ascend path sizes the KDA state pool itself: the A3 Series Unified cell pins `--max-mamba-cache-size` and its PD roles size the pool from `--max-running-requests` instead, while the A5 recipe caps the paged KV pool with `--max-total-tokens` and serves with the radix cache off.) > [!NOTE] > > B300 1×8 Unified speed numbers are measured on `v0.5.18 @ 71de97b2` with `--random-range-ratio 1.0`, > `--warmup-requests 64`, `--flush-cache`, at ISL 8192 / OSL 1024. DSPARK cells pin the acceptance > length via the serve env `SGLANG_SIMULATE_ACC_LEN=4.5` — they report what block size 7 delivers at > that acceptance, not a measured acceptance rate for this workload. Balanced DSPARK adds > `--max-running-requests 256`; without it speculation resets the cap to 48. The KDA state pool still > clamps admission below that (101 / 68 / 91 / 60 concurrent requests for MXFP4 NOSPEC / MXFP4 DSPARK / > NVFP4 NOSPEC / NVFP4 DSPARK), which is why no point past concurrency 64 is published for Balanced. ### AMD AITER with DCP8 The MI350X/MI355X unified Balanced recipe uses TP8/DCP8 with AITER prefill and decode attention. DCP shards the target MLA KV cache; RadixArk DSPARK's draft KV remains replicated. The pinned `v0.5.19-rocm720-mi35x-20260916` image records SGLang revision `e7f7447333`, which includes [AITER DCP support (#34432)](https://github.com/sgl-project/sglang/pull/34432) and the [DCP KV-free fix (#38941)](https://github.com/sgl-project/sglang/pull/38941). No source overlay is required for DCP. Keep `SGLANG_ROCM_K3_KDA_FUSED_BACKEND` unset with this image. The separate fused-KDA opt-in requires the [deferred-gate fix (#39066)](https://github.com/sgl-project/sglang/pull/39066), which is not included in this image. This updated recipe remains **Final Verification In Progress**; the recorded speed numbers use their original configurations and do not validate the new image or DCP8 recipe. ### Mamba ratio calculator > **How --mamba-full-memory-ratio is calculated** > > `--mamba-full-memory-ratio` is the ratio between the KDA state pool and the MLA KV pool. Every parameter below except `L` is read live from the Deploy panel and Playground selection; the balanced value is the per-request cost ratio: > > ```text theme={null} > ratio = (S + D) x state_bytes / (L x (mla_kv_bytes / DCP + draft_kv_bytes)) > ``` > > * `S` — KDA state slots per request: `extra_buffer=5`, `extra_buffer_lazy=4`, `no_buffer=3`, disabled radix cache `=1`. `SGLANG_OPT_MAMBA_SKIP_DECODE_LOCK` frees one slot on the extra-buffer strategies; with the overlap scheduler off (or `pp > 1`, which disables it) the track buffer costs one slot instead of two. > * `D` — verify intermediate states under speculative decoding: `0` when disabled, otherwise DSPARK block size + 1 (`8` at the default 7). ReplaySSM (`--enable-linear-replayssm-spec`) folds them into a per-slot ring, returning `D` to `0`. > * `state_bytes` — one state slot's bytes, from K3's fixed geometry, the attention-TP width, and the SSM dtype. > * `mla_kv_bytes` — one token's MLA latent KV bytes (KV-dtype dependent); DCP shards it across its ranks. The DSPARK draft model's KV (\~1.4 KB per token) is replicated on every rank, so it enters flat — negligible without DCP, the same order as the sharded MLA share under DCP8. > * `L` — average total request length in tokens: input + output. ## Advanced Features Playground The Playground is where you experiment with **SGLang features beyond the deployment matrix**. The Deploy panel above emits the recipes the SGLang team is converging on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction **Kimi-K3** is Moonshot AI's flagship hybrid MoE vision-language model: **2.8 trillion parameters**, **16 of 896 experts** active per token, roughly **2.5× the scaling efficiency of Kimi-K2**. The backbone interleaves **Kimi Delta Attention (KDA)** with MLA across 93 layers (plus Attention Residuals and Stable LatentMoE); serving supports image input and a **1M-token** window with prefix caching. Weights ship in **MXFP4**: the FlashInfer MXFP4 (trtllm-gen SiTU) runner serves them on Blackwell, Marlin (W4A16) elsewhere, MegaMoE for short-context batch throughput. K3 **always runs with thinking enabled**, with reasoning depth controlled by `reasoning_effort` (`low` / `high` / `max`; default `max`). > [!NOTE] > > Kimi-K3 is Moonshot AI's first open-source model in the trillion-plus class; **full model weights > are scheduled to release by July 27, 2026**. The recipes on this page were validated on the public > [`sgl-project/sglang` `kimi-k3` branch](https://github.com/sgl-project/sglang/tree/kimi-k3) — the HuggingFace > repository (`moonshotai/Kimi-K3`) and a public `lmsysorg/sglang` image with K3 support will be > available at launch. > > The B300 1×8 `Unified` Low-Latency and Balanced cells are **Verified** — a speed round on the final > weights is published below. Every other cell is still marked **Final Verification In Progress**: the > recipe runs, but its serving round on the final weights and current code is still open. Accuracy has > not been re-measured on any cell — re-measure before you rely on one. **Recommended generation:** `temperature=1.0`, `top_p=0.95`, `presence_penalty=0`, `frequency_penalty=0` (fixed by the model; informational — do not hardcode in sample code). **Resources:** [HuggingFace](https://huggingface.co/moonshotai/Kimi-K3) · [Kimi-K3 Quickstart](https://platform.kimi.ai/docs/guide/kimi-k3-quickstart). ## 2. Configuration Tips **Memory: two pools, one flag.** K3 splits static memory into a worst-case-reserved **KDA state pool** (it sets the concurrency ceiling) and a paged **MLA KV pool**, divided by `--mamba-full-memory-ratio`. The command panel pins that flag to the [calculator](#mamba-ratio-calculator)'s output — set your average request length there; every other calculator input follows the panels. (On the Ascend NPU recipes there is no calculator and no ratio flag: the Ascend path sizes the KDA state pool itself — the A3 Series pins `--max-mamba-cache-size`, and the A5 recipe caps the paged KV pool with `--max-total-tokens` and runs the radix cache off.) After boot, read back `max_total_num_tokens` (the KV side) and the admitted-request cap (the state side). Capacity levers, all in the Playground. Each trades precision or cache behavior for capacity — re-verify accuracy on your workload: | Lever | Effect | | - | - | | `--mamba-radix-cache-strategy extra_buffer_lazy` | 4 state slots per request instead of 5 | | `--mamba-ssm-dtype bfloat16` | \~halves state bytes; with spec on, KDA verification falls back from the fused kernel to Triton | | `--kv-cache-dtype fp8_e4m3` | halves KV bytes per token; under PD both roles must match at connect | | `--mem-fraction-static` 0.90–0.92 | cheapest first win when the boot log shows a large idle `avail mem` | | `SGLANG_OPT_MAMBA_SKIP_DECODE_LOCK=1` | frees one more slot per request (experimental, under validation) | Speculation: DSPARK holds block size + 1 (= 8) intermediate states per request — the calculator folds this in — and an unset `--max-running-requests` resets to 48 under spec (the command panel reminds you; set it explicitly to raise). **MoE runner.** Leave `--moe-runner-backend` unset on Blackwell: FlashInfer MXFP4 (W4A8, official trtllm-gen SiTU kernels) is selected; H100/H200 pin Marlin. The B200 Balanced and High-Throughput cells pin `flashinfer_mxfp4` explicitly because that is the shape they were brought up on. **Attention backend.** Leave all three attention knobs unset on Blackwell: K3 resolves prefill, decode, and — under DSPARK — verification as a set (`trtllm_mla` across the board; `cutedsl_mla` takes decode and verification under DCP). On the non-DCP recipes, setting any one of the three cancels the auto-resolution for the others. The B200 Balanced and High-Throughput cells pin `--decode-attention-backend cutedsl_mla`, which is what auto-resolution picks for those DCP recipes anyway — it is written out because it is the shape they were brought up on, not because it changes the resolution. H100/H200 pin `flashmla` for decode. **Context length.** `--context-length` bounds the longest accepted request plus some context-scaled buffers; it does not size the KV pool. For long context the lever that adds capacity is `fp8_e4m3` KV. **DSPARK.** Adds `--speculative-algorithm DSPARK` plus the draft checkpoint on top of the showing strategy. Leave `--speculative-draft-attention-backend` unset. The published B300 DSPARK numbers pin the acceptance length with `SGLANG_SIMULATE_ACC_LEN`, so no measured acceptance rate exists for a real workload yet — measure against the same recipe running NOSPEC before adopting. **Per-platform notes:** | Platform | Topology | Notes | | - | - | - | | B300 1×8 | TP8 (+DCP8) | accuracy-first defaults on Low-Latency and Balanced | | GB300 2×4 | TP8/DCP8 | MNNVL transport and cuMem auto-detected | | B200 2×8 | PP2 × TP8 on Low-Latency, PP2 × DCPEP8 on Balanced and High-Throughput. DSPARK re-lays the same 16 GPUs as TP16 / TP16+DCP16+EP16. PD prefill is TP1 × PP16 | Unified serves all three operating points; `Long-Context` is a `Prefill`-only strategy | | GB200 4×4 | TP16/DCP16 | MNNVL auto-detected | | H200 2×8 (4×8 on Unified High-Throughput) | TP16/EP16 + symm-mem, Marlin + FlashMLA; High-Throughput widens to TP32/EP32 over 4 nodes at mem-frac 0.90 with `extra_buffer_lazy` | same block on every node; export the cross-node NIC (`GLOO_SOCKET_IFNAME` / `NCCL_SOCKET_IFNAME`, `SGLANG_HOST_IP`); keep `NCCL_MNNVL_ENABLE=1 NCCL_CUMEM_ENABLE=1` | | H100 4×8 | TP32/EP32, Marlin + FlashMLA | SM90a build of the K3 image; pin NCCL/Gloo to the same NIC on all nodes; least post-weight headroom (80 GB) | | MI350X/MI355X 1×8 | TP8/DCP8 ROCm/AITER (Unified Balanced) | AITER A8W4 FlyDSL MoE, AITER prefill/decode attention with sharded target MLA KV, graph bs up to 256, fp8 kvcache; DSPARK supported. Activation-quant and fused-KDA-decode knobs: [AMD ROCm/AITER environment](#amd-env) | | Ascend A3 Series 4×8 (32 cards / 64 dies) | TP64/DP4 + DeepEP | `Unified` plus an asymmetric 2P4D PD split — 2-node prefill (TP16/PP2/DP2, NOSPEC, no CUDA graph) + 4-node decode (TP64/DP4, DSPARK); pin `GLOO`/`HCCL_SOCKET_IFNAME` on every node | | Ascend 950PR/DT Series 4×8 | TP32/dp1 + DeepEP | `Unified` only; DSPARK baked in; shared experts / dense MLP shard over attention-TP (`--shared-experts-tp-size 4`); radix cache off; pin `GLOO`/`HCCL_SOCKET_IFNAME` on every node | **Blackwell DCP notes** — the DCP cells are Balanced and High-Throughput on every Blackwell platform, in both the `Unified` and `Decode` roles: * DCP is the only axis that shards the TP-replicated MLA KV; Low-Latency skips it. * Leave `--dcp-comm-backend` unset (fabric-resolved: `fi_a2a` on GB200/GB300, `a2a` on B200/B300). * No `--enable-symm-mem` under DCP (force-disabled for decode-graph correctness). * Calculator ratios run well above 1 here (`r > 1` is legal): `bfloat16` state buys admission, `fp8` KV buys context. * Don't use EP with an a2a backend: a2a buffers reclaim the KV that DCP buys. Compose only to measure. a2a backend is set when `--moe-a2a-backend` is set. Outside the two verified B300 1×8 `Unified` cells, no cell has a serving round in this exact shape — treat those as starting points to verify. **AMD ROCm/AITER environment (MI350X / MI355X).** The MI35x cell emits `SGLANG_USE_AITER=1 SGLANG_AITER_K3_OPT=1 AITER_FLYDSL_FORCE=1 AITER_SITUV2_A8W4=1` — the first three turn on the AITER ROCm path, its K3-specific fused kernels, and the FlyDSL MoE kernels; the rest of this table is what you can change on top. Everything here is gfx950/ROCm-only and inert elsewhere. These knobs first ship in the `20260903` daily ROCm image pinned above — on an older image they are simply unread — and the two SiTU rows also need an AITER revision at or past [ROCm/aiter#4534](https://github.com/ROCm/aiter/pull/4534) (FlyDSL 0.3.0). | Env var | Default | Effect | | - | - | - | | `AITER_SITUV2_A8W4=1` | unset | SiTU v2 MoE with A8W4 activation quantization, on AITER's GU-interleaved preshuffled weight layout. The performance default the cell ships. | | `AITER_SITUV2_A4W4=1` | unset | A4W4 instead, on the generic separated shuffle layout. Numerically correct but slower than A8W4 (530.8 vs 537.3 tok/s median output on 8×MI35x). Setting **both** gives A8W4 precedence — SGLang follows AITER and keeps the GU-interleaved layout. | | `SGLANG_ROCM_K3_KDA_FUSED_BACKEND=aiter` | unset | Opt in to the fused ROCm KDA decode boundary: the `f_b` projection is deferred into the gfx950 FlyDSL kernel so decode fuses `f_b` + convolution + recurrent state update + gated RMSNorm. Any other value (or unset) keeps the unfused KDA path. | | `SGLANG_K3_FLYDSL_SOURCE` | `auto` | Which FlyDSL implementation backs the fused decode: `auto` prefers SGLang's vendored kernels and falls back to the AITER module, `sglang` / `aiter` pin one. Leave it alone unless you are bisecting the two. | The fused KDA backend is fail-closed at two levels: it arms during model init only when the flag is exactly `aiter` **and** the gfx950 FlyDSL kernels are importable, and each decode step re-validates shapes, dtypes, strides, state indices, and output buffers before dispatch — anything unexpected falls back to the stock KDA implementation rather than erroring. Batch size 2 automatically picks a separately validated kernel schedule; every other batch keeps the original build options. Measured on a 69-layer graph the fused boundary is 9.20 → 8.38 µs/layer (−8.9%), with GSM8K 1319 at 0.950. ## 3. Advanced Usage ### 3.1 Reasoning K3 always thinks; the `kimi_k3` reasoning parser (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) separates that thinking from the final answer — thinking lands in `message.reasoning_content`, the answer in `message.content`. Control the reasoning depth with `reasoning_effort` (`low` / `high` / `max`; default `max`). > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="moonshotai/Kimi-K3", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > reasoning_effort="high", # "low" | "high" | "max" (default max) > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Pending update... > ``` ### 3.2 Tool Calling Enable the `kimi_k3` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. Because K3 is a thinking model, the follow-up turn may put text in `reasoning_content` as well as `content` — print both. (Not yet supported on the Ascend NPU recipes — A3 and A5.) > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string"}}, > "required": ["city"], > }, > }, > }] > resp = client.chat.completions.create( > model="moonshotai/Kimi-K3", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Pending update... > ``` ### 3.3 HiCache (Hierarchical KV Caching) K3's hybrid HiCache tiers the paged MLA KV **and** the KDA/mamba state across L1 (GPU) / L2 (host) / L3 (Mooncake) — enable it from the **HiCache** card in the [Playground above](#playground) for long multi-turn workloads. * On the DCP recipes (Blackwell Balanced / High-Throughput, `Unified` and `Decode` roles), **L1+L2 keeps DCP**, with Spec Decode off or on DSPARK. On B200 the DSPARK pipeline collapse scales it too (PP2 × DCPEP8 → DCPEP16). * **L3 drops the DCP flags** on those recipes (storage keys are not dcp\_rank-aware yet; the command hints call it out, and per-request KV capacity shrinks). Only DCP goes: the MLA KV reverts to TP-replicated while the cell's other parallelism stays, so B300/GB300/GB200 land on plain TP and B200 Unified keeps its `--pp-size 2` / `--ep-size`. * Low-Latency and the Hopper recipes take all tiers unchanged. ### 3.4 PD Disaggregation PD splits prefill and decode into separate server groups; because K3 is hybrid, the transfer moves **both** the paged MLA KV and the KDA recurrent state. * **Transfer**: the CUDA cells emit **NiXL** (RDMA); Mooncake stays selectable in the Playground. The Ascend NPU cells emit `--disaggregation-transfer-backend ascend` — the KV/KDA transfer rides the Ascend memory fabric instead (see [below](#npu-pd)). * **Ports**: prefill `30000`, decode `30100` (derived ZMQ/dist ranges must not collide on a shared host). The positional `8998` after `--prefill` must match `--disaggregation-bootstrap-port`, or only the decode worker registers. * **Decode state pool**: radix cache disabled — one slot per request; `--mamba-radix-cache-strategy` is inert. Keep `--disaggregation-decode-extra-slots` pinned: unpinned it defaults to twice the batch below 32 requests and **zero** above. #### On Ascend NPUs (A3 Series) The A3 Series disaggregates over the **Ascend memory fabric** (`--disaggregation-transfer-backend ascend`) in an asymmetric **2P4D** pool layout: | Pool layout | A3 Series (2P4D) | | - | - | | Prefill pool | 2 nodes, TP16 × PP2 × DP2, NOSPEC, no CUDA graph | | Decode pool | 4 nodes, TP64 × DP4, DSPARK, decode graph at bs 16 | | Total | 6 nodes | * Every rank of **both** pools registers its transfer buffers against a store served from the **prefill head node** (`ASCEND_MF_STORE_URL`) — set the prefill head's IP on the decode nodes too, not just the prefill pool. * The A3 prefill role is **pipelined** (PP2) and runs NOSPEC — the Spec Decode overlay ships DSPARK on the flat recipes here; newer releases admit it behind a PD prefill ([sgl-project/sglang#40045](https://github.com/sgl-project/sglang/pull/40045)), but no measured A3 command uses it yet. * Each pool is its own `--dist-init-addr` group, so fill `NODE0_IP` per role command (the A3 split's prefill head and decode head are different hosts) — pointing both pools at one address merges the rendezvous, and the mismatched `--nnodes` stalls the launch. * The router can run on any host that reaches both pools. #### Deep PP for prefill Deep PP is `--tp-size 1` with one pipeline stage per GPU — `--pp-size 8` on B300/GB300, `--pp-size 16` on B200/GB200. Pipeline P2P overlaps the next microbatch's compute, unlike TP/EP collectives, and each stage owns whole layers (a clean slice of KV and state). `--tp-size 1` is also what buys context: above TP1 the MLA KV is replicated across the TP ranks, so TP2 × PP8 holds roughly half the tokens of TP1 × PP16 for the same memory. * Use one stage per GPU; a shallow split still pays the in-stage all-reduce and can lose to flat TP. * Pays only with several requests in flight. On the 8-GPU platforms that is why `Default` stays TP8; on the 16-GPU platforms deep PP wins at the Default operating point too, so both strategies use it — measured on GB200 at ISL 8192 / concurrency 32, PP16 × TP1 reached 4550 prefill tok/s/GPU vs 3596 (PP8 × TP2), 2407 (TEP16), and 1652 (TP16). Below concurrency \~8 the pipeline cannot fill and TEP16 leads instead (1947 vs 1227) — use `--tp-size 16 --ep-size 16` there. * DSPARK off on the pipelined recipes — on B200/GB200 that applies to `Default` as well. * Fan one prefill role out to several decode roles; budget for in-transfer KV on the decode side. > **Router** > > ```bash Command theme={null} > python3 -m sglang_router.launch_router \ > --pd-disaggregation \ > --prefill http://:30000 8998 \ > --decode http://:30100 \ > --host 0.0.0.0 --port 8000 \ > --disable-circuit-breaker \ > --health-check-interval-secs 999999 > ``` Clients then send requests to the router (`:8000`) instead of an individual role server. ### 3.5 VLM Serving Profiles The open-source K3 serving contract currently supports **image input only** — its processor rejects video and audio input. #### VLM feature transport Use **VLM Transport** in the command picker. `Auto` is a topology-aware starting point, not a claim that one configuration is fastest for every workload. | Picker selection | Processor-to-scheduler feature path | | - | - | | Auto · single-node Unified CUDA | CUDA IPC | | Auto · Unified GB200/GB300 | CUDA VMM when IMEX is available; CPU otherwise | | Auto · PD or other topologies | CPU | | CPU | CPU, with no GPU feature pool | CUDA IPC and CUDA VMM reserve up to `SGLANG_MM_FEATURE_CACHE_MB` (1 GiB by default) on the base GPU and fall back to CPU per tensor when full. This setting does not control EPD encoder output or PD KV/KDA transfer. K3 already defaults to 2 processor workers and 16 I/O workers; leave those flags unset unless tuning. #### VLM compatibility | Feature | K3 behavior | | - | - | | PD | Supported. Image processing and ViT run on prefill; the PD transfer then moves both paged MLA KV and KDA recurrent state as described in [PD disaggregation](#pd-disaggregation). | | EPD | Supported on the public `kimi-k3` branch. Use an `--encoder-only` vision role and a `--language-only` prefill role; add the normal decode role for full EPD. See the [EPD guide](../../../docs/advanced_features/epd_disaggregation). | | MM encoder DP | Built in. K3 shards complete images across TP ranks, so leave `--mm-enable-dp-encoder` unset in unified, PD-prefill, and encoder-only roles. | | MM feature transport | Processor-to-scheduler features only. EPD encoder output and PD KV/KDA transfer use their own backends. | | ViT BCG | Compatible with unified and encoder-only roles, but recommended only for repeated encoder shapes after measuring the HBM trade-off below. | #### Should ViT BCG be enabled? Keep ViT BCG **off** for general serving; enable `SGLANG_VIT_ENABLE_CUDA_GRAPH=1` only for ViT-only / EPD encoder workloads with recurring image shapes and spare HBM. * The win is confined to the encoder — no reliable end-to-end TTFT/TPOT gain in full-model serving. * Each captured graph retains HBM (graph + per-entry metadata); measure on your own shapes. * The default cache captures after two hits and falls back to eager above 6,144 tokens; do not enlarge it without measuring. #### Low-HBM VLM Use this profile when keeping HBM headroom matters more than peak concurrency. It removes the GPU feature pool, keeps ViT BCG disabled, halves the context window, caps concurrency, and lowers the static-memory target: ```bash Command theme={null} sglang serve \ --trust-remote-code \ --model-path moonshotai/Kimi-K3 \ --tp-size 8 \ --context-length 65536 \ --enable-symm-mem \ --mem-fraction-static 0.82 \ --mm-feature-transport cpu \ --reasoning-parser kimi_k3 \ --tool-call-parser kimi_k3 \ --host 0.0.0.0 \ --port 30000 ``` `--mem-fraction-static 0.82` is a conservative B300 starting point, not a portable minimum: raise it toward `0.85` if startup reports insufficient memory; if HBM must go back to other workloads, reduce context/concurrency first. The precision levers (`fp8_e4m3` KV, `bfloat16` SSM state) save far more but stay accuracy-gated. ### 3.6 Large-Scale Serving Presets (16–64 GPUs, Blackwell) **The KDA state pool is the concurrency ceiling** — DP, EP, and DCP do not shard it; only attention-TP width, SSM dtype, and cache strategy change the per-GPU bill. The MLA KV is cheap to shrink (fp8) or deduplicate (DCP). Two presets come out of this, at `N = 8k` GPUs: | Preset | What it trades | Pick it for | | - | - | - | | **Peak Throughput** — `dp = k`, attention-TP 8 | State shards 8-way. The per-step KDA all-reduce stays within one 8-GPU B200/B300 node, or spans two 4-GPU GB200/GB300 nodes over MNNVL. `--kv-cache-dtype fp8_e4m3` is load-bearing — bf16 KV does not fit 128 requests per replica. | Maximum sustained TPS — the default large-scale shape. | | **Peak Capacity (+DCP8)** — `dp = k` + `--dcp-size 8` | Deduplicates the attention-TP group's MLA KV: concurrency ceiling +72% at the same engine throughput, \~1.8× ITL. | Context ≥ \~16K, or per-replica concurrency past 128. | * **Radix cache** is independent of the preset: for prefix-free traffic (offline batch, evals) switch it off (Playground's **Prefix Cache** card) — one state slot per request instead of 4–5. * The fully data-parallel extreme (`--attn-dp-size` = GPU count, attention-TP 1) — the shape behind the 64-GPU sweep's \~3K tok/s per GPU — is not a preset: 288 GB GPUs only, radix forced off, no head-to-head against the preset shape. The Peak Throughput preset at 32 GPUs on B200/B300 (4 nodes × 8; every node runs the same command with its own `--node-rank`). On GB200/GB300 the same 32-GPU shape uses 8 nodes × 4, and the Playground emits `--nnodes 8`: ```bash Command theme={null} SGLANG_OPT_DEEPGEMM_MEGA_MOE_NUM_MAX_TOKENS_PER_RANK=20480 \ sglang serve \ --trust-remote-code \ --model-path moonshotai/Kimi-K3 \ --tp-size 32 --ep-size 32 \ --attn-dp-size 4 --enable-dp-lm-head \ --nnodes 4 --node-rank --dist-init-addr :20000 \ --moe-a2a-backend megamoe --moe-runner-backend deep_gemm \ --kv-cache-dtype fp8_e4m3 \ --mamba-ssm-dtype bfloat16 \ --mamba-radix-cache-strategy extra_buffer_lazy \ --mem-fraction-static 0.92 \ --reasoning-parser kimi_k3 --tool-call-parser kimi_k3 \ --host 0.0.0.0 --port 30000 ``` Scale by holding the per-replica shape fixed and moving only the replica count; pool sizing rides the calculator-driven `--mamba-full-memory-ratio`, which folds in DP, DCP, precision, and speculation: | GPUs | B200/B300 nodes | GB200/GB300 nodes | `--tp-size` / `--ep-size` | `--attn-dp-size` | | - | - | - | - | - | | 16 | 2×8 | 4×4 | 16 | 2 | | 32 | 4×8 | 8×4 | 32 | 4 | | 64 | 8×8 | 16×4 | 64 | 8 | For Peak Capacity, add `--dcp-size 8` and re-derive the pool split with the [Mamba ratio calculator](#mamba-ratio-calculator). Both presets are one click away in the [Playground above](#playground): pick a **Cluster Size** and a **Large-Scale Preset** and the full command composes onto whichever cell is showing. Decisions the preset already makes: * **MegaMoE + `deep_gemm`** — the fused DeepGEMM all-to-all/MoE path used by these large-scale DP/EP throughput presets, with K3's SiTU activation. * **SP-MoE and shared-expert overlap** engage automatically under EP a2a; the K3 all-reduce fusion does not. * **Spec Decode follows the Deploy knob.** Acceptance thins at large batch; spec × EP × DP-attention is validated only at 8-GPU EP8 × DP2 (full GSM8K) — experimental at these scales. > [!NOTE] > > No preset has a full serving round on final weights; the constants derive from measured single- and dual-node rounds plus a 64-GPU sweep. Validate throughput and accuracy on your workload before committing a fleet. # Kimi-Linear Source: https://docs.sglang.io/cookbook/autoregressive/Moonshotai/Kimi-Linear ## AMD GPU Support ## 1. Model Introduction Kimi Linear is a hybrid linear attention architecture that outperforms traditional full attention methods across various contexts, including short, long, and reinforcement learning (RL) scaling regimes. At its core is Kimi Delta Attention (KDA)—a refined version of Gated DeltaNet that introduces a more efficient gating mechanism to optimize the use of finite-state RNN memory. This generation delivers comprehensive upgrades across the board: Kimi Delta Attention (KDA): A linear attention mechanism that refines the gated delta rule with finegrained gating. Hybrid Architecture: A 3:1 KDA-to-global MLA ratio reduces memory usage while maintaining or surpassing the quality of full attention. Superior Performance: Outperforms full attention in a variety of tasks, including long-context and RL-style benchmarks on 1.4T token training runs with fair comparisons. High Throughput: Achieves up to 6× faster decoding and significantly reduces time per output token (TPOT). For more details, please refer to the \[official Kimi Linear GitHub Repository]: [https://github.com/MoonshotAI/Kimi-Linear](https://github.com/MoonshotAI/Kimi-Linear) ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model variant, deployment strategy, and thinking capabilities. Run this Command:

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Launch the docker

```shell Command theme={null}
docker pull lmsysorg/sglang:v0.5.7-rocm700-mi30x
```

```shell Command theme={null}
docker run -d -it --ipc=host --network=host --privileged \
  --cap-add=CAP_SYS_ADMIN \
  --device=/dev/kfd --device=/dev/dri --device=/dev/mem \
  --group-add video --cap-add=SYS_PTRACE \
  --security-opt seccomp=unconfined \
  -v /:/work \
  -e SHELL=/bin/bash \
  --name Kimi-linear \
  lmsysorg/sglang:v0.5.7-rocm700-mi30x \
  /bin/bash
```

#### 4.2.2 pre-installation steps inside the docker

```shell Command theme={null}
pip install sentencepiece tiktoken
```

#### 4.2.3 Launch the server

```shell Command theme={null}
export SGLANG_ROCM_FUSED_DECODE_MLA=0

SGLANG_ROCM_FUSED_DECODE_MLA=0 python3 -m sglang.launch_server \
  --model-path moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --tokenizer-path  moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --tp 4 \
  --trust-remote-code
```

## 5. Benchmark

### 5.1 Speed Benchmark

Test Environment:

Hardware: AMD MI300X GPU

Model: Kimi-Linear-48B-A3B-Instruct

Tensor Parallelism: 4

sglang version: 0.5.7

* **Model Deployment**

```bash Command theme={null}
SGLANG_ROCM_FUSED_DECODE_MLA=0 python3 -m sglang.launch_server \
  --model-path moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --tokenizer-path  moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --tp 4 \
  --trust-remote-code
```

### 5.1.1 Low Concurrency (Latency-Optimized)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  23.86
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4220
Total generated tokens (retokenized):    4001
Request throughput (req/s):              0.42
Input token throughput (tok/s):          255.70
Output token throughput (tok/s):         176.86
Peak output token throughput (tok/s):    190.00
Peak concurrent requests:                2
Total token throughput (tok/s):          432.56
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2383.93
Median E2E Latency (ms):                 1911.63
---------------Time to First Token----------------
Mean TTFT (ms):                          141.33
Median TTFT (ms):                        126.27
P99 TTFT (ms):                           294.76
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          5.32
Median TPOT (ms):                        5.33
P99 TPOT (ms):                           5.36
---------------Inter-Token Latency----------------
Mean ITL (ms):                           5.33
Median ITL (ms):                         5.32
P95 ITL (ms):                            5.44
P99 ITL (ms):                            5.58
Max ITL (ms):                            11.46
==================================================
```

### 5.1.2 Medium Concurrency (Balanced)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  31.38
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40805
Total generated tokens (retokenized):    39667
Request throughput (req/s):              2.55
Input token throughput (tok/s):          1264.13
Output token throughput (tok/s):         1300.37
Peak output token throughput (tok/s):    1801.00
Peak concurrent requests:                21
Total token throughput (tok/s):          2564.50
Concurrency:                             14.13
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5543.18
Median E2E Latency (ms):                 5755.31
---------------Time to First Token----------------
Mean TTFT (ms):                          175.25
Median TTFT (ms):                        137.87
P99 TTFT (ms):                           292.92
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.75
Median TPOT (ms):                        10.87
P99 TPOT (ms):                           16.74
---------------Inter-Token Latency----------------
Mean ITL (ms):                           10.54
Median ITL (ms):                         7.95
P95 ITL (ms):                            13.68
P99 ITL (ms):                            116.80
Max ITL (ms):                            299.89
==================================================

```

### 5.1.3 High Concurrency (Throughput-Optimized)

* Benchmark Command:

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100 \
  --request-rate inf
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  79.71
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252662
Total generated tokens (retokenized):    228448
Request throughput (req/s):              6.27
Input token throughput (tok/s):          3134.20
Output token throughput (tok/s):         3169.72
Peak output token throughput (tok/s):    6109.00
Peak concurrent requests:                110
Total token throughput (tok/s):          6303.92
Concurrency:                             94.80
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   15113.92
Median E2E Latency (ms):                 13851.52
---------------Time to First Token----------------
Mean TTFT (ms):                          564.46
Median TTFT (ms):                        226.04
P99 TTFT (ms):                           2683.14
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          29.63
Median TPOT (ms):                        31.28
P99 TPOT (ms):                           38.84
---------------Inter-Token Latency----------------
Mean ITL (ms):                           28.85
Median ITL (ms):                         16.29
P95 ITL (ms):                            123.42
P99 ITL (ms):                            157.80
Max ITL (ms):                            2481.11
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* Server Command

```shell Command theme={null}
SGLANG_ROCM_FUSED_DECODE_MLA=0 python3 -m sglang.launch_server \
  --model-path moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --tokenizer-path  moonshotai/Kimi-Linear-48B-A3B-Instruct \
  --tp 4 \
  --trust-remote-code
```

* Benchmark Command

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* **Result**:

```text Output theme={null}
Accuracy: 0.705
Invalid: 0.000
Latency: 11.855 s
Output throughput: 3224.982 token/s
```


# Nemotron3-Nano
Source: https://docs.sglang.io/cookbook/autoregressive/NVIDIA/Nemotron3-Nano



## 1. Model Introduction

`NVIDIA Nemotron3-Nano` is a 30B-parameter hybrid LLM that mixes Mixture-of-Experts (MoE) feed-forward layers, Mamba2 sequence-modeling layers, and standard self-attention layers in a single stack rather than classic “attention + MLP” transformer blocks.

The BF16 variant (`nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16`) is designed as a high-fidelity reference model. For optimized inference performance on modern NVIDIA GPUs, the FP8 variant (`nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8`) and the NVFP4 variant (`nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-NVFP4`) are supported.

At a high level:

* **Hybrid layer stack (Mamba2 + MoE + attention):** The network is composed of interleaved layers that are *either* Mamba2, *or* MoE feed-forward, *or* attention-only.
* **Non-uniform layer ordering:** The order and mix of these specialized layers is not a simple, rigid pattern, enabling the model to trade off sequence modeling, routing capacity, and expressivity across depth.
* **Deployment-friendly precision:** Use BF16 for accuracy-sensitive and evaluation workloads; use FP8 for latency- and throughput-critical serving on recent NVIDIA GPUs.

## 2. SGLang Installation

Refer to the [official SGLang installation guide](../../../docs/get-started/install), or install nightly wheel through:

```bash Command theme={null}
uv pip install --prerelease=allow sglang==0.5.6.post3.dev1278+gad1b4e472 --extra-index-url https://sgl-project.github.io/whl/nightly/
```

## 3. Model Deployment

This section provides a progressive guide from quick deployment to performance tuning.

### 3.1 Basic Configuration

The Nemotron3-Nano series offers models in various sizes and architectures, optimized for different hardware platforms including NVIDIA GPUs and Intel Arc Pro B-Series GPUs(codename: BMG (Battlemage)).

**Interactive Command Generator**: select hardware, model variant, and common knobs to generate a launch command.

Run this Command:


### 3.2 Configuration Tips

* **Attention backend**:

  **H200**: Use flash attention 3 backend by default.
  **B200**: Use flashinfer backend by default.

* **TP support**:

  To set tp size, use `--tp <1|2|4|8>`.

* **FP8 KV cache**:

  To enable fp8 kv cache, please append `--kv-cache-dtype fp8_e4m3`.

## 4. Model Invocation

### 4.1 Basic Usage (OpenAI-Compatible API)

SGLang provides an OpenAI-compatible endpoint. Example with the OpenAI Python client:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Summarize what MoE models are in 5 bullets."},
    ],
    temperature=0.7,
    max_tokens=256,
)

print(resp.choices[0].message.content)

```

Streaming chat completion

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

stream = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8",
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "What are the first 5 prime numbers?"}
    ],
    temperature=0.7,
    max_tokens=1024,
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta
    if delta and delta.content:
        print(delta.content, end="", flush=True)
```

### 4.2 Reasoning

To enable reasoning, `--reasoning-parser nemotron_3` should be appended to the launching command. The model supports two modes - Reasoning ON (default) vs OFF. This can be toggled by setting enable\_thinking to False, as shown below.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

# Reasoning on (default)
print("Reasoning on")
resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Write a haiku about GPUs."}
    ],
    temperature=0.7,
    max_tokens=512,
)
print(resp.choices[0].message.reasoning_content)

# Reasoning off
print("Reasoning off")
resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Write a haiku about GPUs."}
    ],
    temperature=0.6,
    max_tokens=256,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}}
)
print(resp.choices[0].message.reasoning_content)

```

### 4.3 Tool calling

To enable reasoning, `--tool-call-parser qwen3_coder` should be appended to the launching command. Call functions using the OpenAI Tools schema and inspect returned tool\_calls.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

# Tool calling via OpenAI tools schema
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "calculate_tip",
            "parameters": {
                "type": "object",
                "properties": {
                    "bill_total": {
                        "type": "integer",
                        "description": "The total amount of the bill"
                    },
                    "tip_percentage": {
                        "type": "integer",
                        "description": "The percentage of tip to be applied"
                    }
                },
                "required": ["bill_total", "tip_percentage"]
            }
        }
    }
]

completion = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8",
    messages=[
        {"role": "system", "content": ""},
        {"role": "user", "content": "My bill is $50. What will be the amount for 15% tip?"}
    ],
    tools=TOOLS,
    temperature=0.6,
    top_p=0.95,
    max_tokens=512,
    stream=False
)

print(completion.choices[0].message.reasoning_content)
print(completion.choices[0].message.tool_calls)
```

***

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU

**FP8 variant**

* Model Deployment Command:

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8 \
  --trust-remote-code \
  --max-running-requests 1024 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-FP8 \
  --dataset-name random \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 4096 \
  --max-concurrency 256
```

* **Serving benchmark results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 256
Successful requests:                     4096
Benchmark duration (s):                  183.18
Total input tokens:                      2081726
Total input text tokens:                 2081726
Total input vision tokens:               0
Total generated tokens:                  2116125
Total generated tokens (retokenized):    1076256
Request throughput (req/s):              22.36
Input token throughput (tok/s):          11364.25
Output token throughput (tok/s):         11552.04
Peak output token throughput (tok/s):    24692.00
Peak concurrent requests:                294
Total token throughput (tok/s):          22916.30
Concurrency:                             251.19
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   11233.74
Median E2E Latency (ms):                 11142.97
---------------Time to First Token----------------
Mean TTFT (ms):                          172.99
Median TTFT (ms):                        116.57
P99 TTFT (ms):                           1193.68
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          21.74
Median TPOT (ms):                        21.14
P99 TPOT (ms):                           41.12
---------------Inter-Token Latency----------------
Mean ITL (ms):                           21.45
Median ITL (ms):                         9.06
P95 ITL (ms):                            62.59
P99 ITL (ms):                            110.83
Max ITL (ms):                            5368.19
==================================================
```

**BF16 variant**

* Model Deployment Command:

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 \
  --trust-remote-code \
  --max-running-requests 1024 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 \
  --dataset-name random \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 4096 \
  --max-concurrency 256
```

* **Serving benchmark results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 256
Successful requests:                     4096
Benchmark duration (s):                  360.22
Total input tokens:                      2081726
Total input text tokens:                 2081726
Total input vision tokens:               0
Total generated tokens:                  2087288
Total generated tokens (retokenized):    1940652
Request throughput (req/s):              11.37
Input token throughput (tok/s):          5779.10
Output token throughput (tok/s):         5794.55
Peak output token throughput (tok/s):    9169.00
Peak concurrent requests:                276
Total token throughput (tok/s):          11573.65
Concurrency:                             249.76
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   21965.10
Median E2E Latency (ms):                 21706.35
---------------Time to First Token----------------
Mean TTFT (ms):                          211.54
Median TTFT (ms):                        93.06
P99 TTFT (ms):                           2637.66
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          43.27
Median TPOT (ms):                        43.04
P99 TPOT (ms):                           61.15
---------------Inter-Token Latency----------------
Mean ITL (ms):                           42.77
Median ITL (ms):                         28.46
P95 ITL (ms):                            71.85
P99 ITL (ms):                            113.20
Max ITL (ms):                            5237.28
==================================================

```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

**Environment**

* Hardware: NVIDIA B200 GPU
* Model: BF16 checkpoint

**Launch Model**

```bash Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 \
  --trust-remote-code \
  --reasoning-parser nemotron_3
```

**Run Benchmark with sgl-eval**

```bash Command theme={null}
pip install sgl-eval

sgl-eval run gsm8k --base-url http://127.0.0.1:30000/v1 --model nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 --num-threads 4 --max-tokens 16384 --thinking
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

**Historical lm-eval results (not measurements of the sgl-eval command above):**

```text Output theme={null}
|Tasks|Version|     Filter     |n-shot|  Metric   |   |Value |   |Stderr|
|-----|------:|----------------|-----:|-----------|---|-----:|---|-----:|
|gsm8k|      3|flexible-extract|     5|exact_match|↑  |0.5603|±  |0.0137|
|     |       |strict-match    |     5|exact_match|↑  |0.8453|±  |0.0100|
```


# Nemotron 3 Nano Omni
Source: https://docs.sglang.io/cookbook/autoregressive/NVIDIA/Nemotron3-Nano-Omni



## 1. Model Introduction

`NVIDIA Nemotron 3 Nano Omni` is a 30B-parameter hybrid MoE multimodal model that activates only 3B parameters per forward pass, combining vision and audio encoders into a unified architecture. Part of the Nemotron 3 family, it is designed to power multimodal sub-agents that perceive and reason across vision, audio, and language in a single inference loop — eliminating the fragmented stacks of separate models for each modality.

Architecture and key features:

* **Hybrid Transformer-Mamba Architecture (MoE):** Combines Mixture of Experts with a hybrid Transformer-Mamba architecture for efficient routing and sequence modeling.
* **30B total / 3B active parameters:** Delivers strong multimodal accuracy at a fraction of the cost of dense models.
* **1M token context window:** Sustains coherent agent state across extended multimodal workflows — screen history, document content, and audio context remain in view without re-ingestion.
* **Unified vision and audio encoders:** One model replaces fragmented multimodal stacks; vision and audio perception happen in the same forward pass.
* **3D Convolution (Conv3D):** Efficient temporal-spatial processing for video inputs.
* **Efficient Video Sampling (EVS):** Enables longer video processing at the same compute budget via temporal-aware perception and adaptive frame sampling.
* **FP8 and NVFP4 quantization:** FP8 supports deployment from workstation (RTX 6000, DGX Spark) to cloud (H100, H200, B200, A100, L40S); NVFP4 requires Blackwell hardware.
* **9x higher throughput** than other open omni models at the same interactivity level.
* **\~20% higher multimodal intelligence** compared to the best open alternative.
* **Post-trained with multi-environment reinforcement learning** via NVIDIA NeMo RL and NeMo Gym across text, image, audio, and video environments, improving instruction following and convergence to correct multimodal answers.

**Modalities:** Input: text, image, video, audio — Output: text

**Supported GPUs:** NVIDIA B200, H100, H200, A100, L40S, DGX Spark, RTX 6000

Available model variants on HuggingFace:

* [`nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16`](https://huggingface.co/nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16)
* [`nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-FP8`](https://huggingface.co/nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-FP8)
* [`nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-NVFP4`](https://huggingface.co/nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-NVFP4)

**Agentic workloads this model enables:**

* **Computer Use Agent:** Perception loop for agents navigating GUIs — reads screens, understands UI state over time, validates outcomes. Collapses vision and reasoning into a single loop.
* **Document Intelligence:** Interprets documents, charts, tables, screenshots, and mixed media inputs for enterprise analysis and compliance workflows.
* **Audio & Video Understanding Agents:** Maintains continuous audio-video context for customer service, research, and monitoring workflows, tying what was said, shown, and documented into a single reasoning stream.

## 2. SGLang Installation

Install SGLang via pip or from source:

```shell Command theme={null}
# Install via pip
pip install sglang

# Or install from source
uv pip install --prerelease=allow 'git+https://github.com/sgl-project/sglang.git#subdirectory=python'

# Or use Docker
docker pull lmsysorg/sglang:latest
```

For the full Docker setup and other installation methods, refer to the [official SGLang installation guide](../../../docs/get-started/install).

## 3. Model Deployment

This section provides a progressive guide from quick deployment to performance tuning.

### 3.1 Basic Configuration

**Interactive Command Generator**: select hardware, model variant, and common knobs to generate a launch command.

Run this Command:


### 3.2 Configuration Tips

* **Attention backend:**

  **H100/H200:** Use flash attention 3 backend by default.
  **B200:** Use flashinfer backend by default.

* **TP support:**

  To set tensor parallelism, use `--tp <1|2|4|8>`. A 4×H100 setup is recommended for the BF16 variant.

* **FP8 KV cache:**

  To enable FP8 KV cache, append `--kv-cache-dtype fp8_e4m3`. FP8 KV cache trades a small amount of accuracy for memory; omit the flag if you observe accuracy regressions on your workload.

* **Reasoning parser:**

  Append `--reasoning-parser deepseek-r1` to enable structured reasoning traces (`reasoning_content` field in the response).

* **Tool calling:**

  Append `--tool-call-parser qwen3_coder` to enable tool calling support.

## 4. Model Invocation

The command below launches the server for a 4×H100 setup with reasoning and tool calling enabled. See [Section 4.8](#4-8-fp8-and-nvfp4-deployment) for FP8 and NVFP4 variants.

```shell Command theme={null}
sglang serve \
  --model-path nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 \
  --host 0.0.0.0 \
  --port 30000 \
  --tp 4 \
  --trust-remote-code \
  --tool-call-parser qwen3_coder \
  --reasoning-parser deepseek-r1
```

### 4.1 Basic Usage (Text)

SGLang provides an OpenAI-compatible endpoint. Example with the OpenAI Python client:

```python Example theme={null}
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

resp = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "Give me 3 bullet points about SGLang."},
    ],
    temperature=0.6,
    max_tokens=512,
)
print(resp.choices[0].message.reasoning_content, resp.choices[0].message.content)
```

Output:

```text Output theme={null}
Reasoning: SGLang is a serving framework I know from my training data. Let me recall the key features...

Content:
- **Radix Attention** — SGLang reuses KV cache across requests sharing a common prefix, dramatically reducing memory and compute for multi-turn and few-shot workloads.
- **OpenAI-compatible API** — Drop-in replacement for the OpenAI Python client; no application code changes required to serve a locally-hosted model.
- **High-throughput serving** — Continuous batching, chunked prefill, and optimized CUDA kernels deliver state-of-the-art throughput on NVIDIA GPUs across A100, H100, and B200.
```

Streaming chat completion:

```python Example theme={null}
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

stream = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "What are the first 5 prime numbers?"},
    ],
    temperature=0.6,
    max_tokens=512,
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta
    if delta and delta.content:
        print(delta.content, end="", flush=True)
```

### 4.2 Image Understanding

Pass image inputs using the OpenAI vision format. Supports both URLs and base64-encoded images:

```python Example theme={null}
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

# From URL
resp = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg"},
                },
                {"type": "text", "text": "Describe this image in detail."},
            ],
        }
    ],
    temperature=0.6,
    max_tokens=512,
)
print(resp.choices[0].message.reasoning_content)
print(resp.choices[0].message.content)
```

For local images, encode as base64:

```python Example theme={null}
import base64
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

with open("screenshot.png", "rb") as f:
    image_b64 = base64.b64encode(f.read()).decode("utf-8")

resp = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/png;base64,{image_b64}"},
                },
                {"type": "text", "text": "What UI elements are visible on this screen? What action would you take next?"},
            ],
        }
    ],
    temperature=0.6,
    max_tokens=512,
)
print(resp.choices[0].message.content)
```

### 4.3 Video Understanding

Nemotron 3 Nano Omni uses Conv3D layers and Efficient Video Sampling (EVS) for temporal-spatial video reasoning, processing longer videos at the same compute budget:

```python Example theme={null}
import base64
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

with open("video.mp4", "rb") as f:
    video_b64 = base64.b64encode(f.read()).decode("utf-8")

resp = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "video_url",
                    "video_url": {"url": f"data:video/mp4;base64,{video_b64}"},
                },
                {"type": "text", "text": "Summarize what happens in this video step by step."},
            ],
        }
    ],
    temperature=0.6,
    max_tokens=1024,
)
print(resp.choices[0].message.reasoning_content)
print(resp.choices[0].message.content)
```

### 4.4 Audio Understanding

Pass audio inputs as base64-encoded WAV or MP3 data:

```python Example theme={null}
import base64
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

with open("audio.wav", "rb") as f:
    audio_b64 = base64.b64encode(f.read()).decode("utf-8")

resp = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_audio",
                    "input_audio": {"data": audio_b64, "format": "wav"},
                },
                {"type": "text", "text": "Transcribe and summarize what was said in this audio."},
            ],
        }
    ],
    temperature=0.6,
    max_tokens=512,
)
print(resp.choices[0].message.content)
```

### 4.5 Mixed Multimodal Input

Combine modalities in a single request. For example, an image alongside an audio question about it:

```python Example theme={null}
import base64
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

with open("chart.png", "rb") as f:
    image_b64 = base64.b64encode(f.read()).decode("utf-8")

resp = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/png;base64,{image_b64}"},
                },
                {"type": "text", "text": "Analyze this chart. What are the key trends and what conclusion does the data support?"},
            ],
        }
    ],
    temperature=0.6,
    max_tokens=1024,
)
print(resp.choices[0].message.reasoning_content)
print(resp.choices[0].message.content)
```

### 4.6 Reasoning

The model supports two modes — Reasoning ON (default) vs OFF. Toggle per-request by setting `enable_thinking` to `False`:

```python Example theme={null}
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

# Reasoning ON (default)
print("Reasoning on")
resp = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the derivative of x^3 sin(x)?"},
    ],
    temperature=0.6,
    max_tokens=1024,
)
print(f"Reasoning:\n{resp.choices[0].message.reasoning_content[:300]}...\nContent:\n{resp.choices[0].message.content}")
print("\n")

# Reasoning OFF
print("Reasoning off")
resp = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is 15% of 200?"},
    ],
    temperature=0.6,
    max_tokens=256,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)
print(f"Content:\n{resp.choices[0].message.content}")
```

Output:

```text Output theme={null}
Reasoning on
Reasoning:
The user wants the derivative of x^3 sin(x). I'll apply the product rule: d/dx[u·v] = u'v + uv'. Here u = x^3, v = sin(x). So u' = 3x^2, v' = cos(x). The result is 3x^2·sin(x) + x^3·cos(x)...
Content:
Using the product rule: d/dx[x³ sin(x)] = 3x² sin(x) + x³ cos(x)


Reasoning off
Content:
15% of 200 is **30**.
```

### 4.7 Tool Calling

Call functions using the OpenAI Tools schema. The server must be launched with `--tool-call-parser qwen3_coder`:

```python Example theme={null}
from openai import OpenAI

SERVED_MODEL_NAME = "nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16"
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City and state, e.g. San Francisco, CA",
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                    },
                },
                "required": ["location"],
            },
        },
    }
]

completion = client.chat.completions.create(
    model=SERVED_MODEL_NAME,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the weather like in Santa Clara, CA?"},
    ],
    tools=TOOLS,
    temperature=0.6,
    top_p=0.95,
    max_tokens=512,
    stream=False,
)
print(completion.choices[0].message.reasoning_content)
print(completion.choices[0].message.tool_calls)
```

Output:

```text Output theme={null}
The user is asking about weather in Santa Clara, CA. I have a get_weather function that takes a location and optional unit. I should call it with location="Santa Clara, CA".

[ChatCompletionMessageFunctionToolCall(id='call_abc123', function=Function(arguments='{"location": "Santa Clara, CA", "unit": "fahrenheit"}', name='get_weather'), type='function', index=0)]
```

### 4.8 FP8 and NVFP4 Deployment

**FP8 variant** (recommended for throughput-critical serving on H100/H200/B200):

```shell Command theme={null}
sglang serve \
  --model-path nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-FP8 \
  --host 0.0.0.0 \
  --port 30000 \
  --tp 4 \
  --trust-remote-code \
  --tool-call-parser qwen3_coder \
  --reasoning-parser deepseek-r1
```

**NVFP4 variant** (maximum efficiency on Blackwell B200):

```shell Command theme={null}
sglang serve \
  --model-path nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-NVFP4 \
  --host 0.0.0.0 \
  --port 30000 \
  --tp 4 \
  --trust-remote-code \
  --tool-call-parser qwen3_coder \
  --reasoning-parser deepseek-r1
```

***

## 5. Benchmark

### 5.1 Efficiency Benchmark

Nemotron 3 Nano Omni achieves **9x higher throughput** than other open omni models at the same interactivity level, delivering lower cost and better scalability without sacrificing responsiveness. It also achieves **\~20% higher multimodal intelligence** compared to the best open alternative across image, video, and audio reasoning tasks.

### 5.2 Speed Benchmark

**Test Environment:**

* Hardware: B200 (8×)
* Model: nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning
* Tensor Parallelism: 4
* SGLang Version: main branch

Model Deployment Command:

```shell Command theme={null}
sglang serve \
  --model-path nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 \
  --trust-remote-code \
  --tp 4 \
  --max-running-requests 1024 \
  --host 0.0.0.0 \
  --attention-backend flashinfer \
  --port 30000
```

Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 \
  --dataset-name random \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 4096 \
  --max-concurrency 256
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 256
Successful requests:                     4096
Benchmark duration (s):                  206.52
Total input tokens:                      2081726
Total input text tokens:                 2081726
Total generated tokens:                  2087288
Total generated tokens (retokenized):    1945477
Request throughput (req/s):              19.83
Input token throughput (tok/s):          10080.25
Output token throughput (tok/s):         10107.18
Peak output token throughput (tok/s):    20199.00
Peak concurrent requests:                291
Total token throughput (tok/s):          20187.44
Concurrency:                             250.83
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   12646.47
Median E2E Latency (ms):                 12371.84
P90 E2E Latency (ms):                    22889.81
P99 E2E Latency (ms):                    26528.70
---------------Time to First Token----------------
Mean TTFT (ms):                          220.66
Median TTFT (ms):                        97.67
P99 TTFT (ms):                           2068.63
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          24.98
Median TPOT (ms):                        24.36
P99 TPOT (ms):                           44.97
---------------Inter-Token Latency----------------
Mean ITL (ms):                           24.43
Median ITL (ms):                         10.91
P95 ITL (ms):                            62.68
P99 ITL (ms):                            100.60
Max ITL (ms):                            2171.93
==================================================
```

### 5.3 Accuracy Benchmark

**Environment**

* Hardware: B200 (8×)
* Model: nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning
* Tensor Parallelism: 4
* SGLang Version: main branch

**Launch Model**

```shell Command theme={null}
sglang serve \
  --model-path nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 \
  --trust-remote-code \
  --tp 4 \
  --attention-backend flashinfer \
  --reasoning-parser deepseek-r1
```

#### 5.3.1 GSM8K Benchmark

**Run Benchmark**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Test Results:**

```text Output theme={null}
Accuracy: 0.830
Invalid: 0.000
Latency: 13.970 s
Output throughput: 1611.623 token/s
```

#### 5.3.2 MMLU Benchmark

**Run Benchmark**

```shell Command theme={null}
sgl-eval run mmlu \
  --base-url http://127.0.0.1:30000/v1 \
  --num-threads 64 --max-tokens 2048
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Test Results:**

```text Output theme={null}
subject: abstract_algebra, #q:100, acc: 0.510
subject: anatomy, #q:135, acc: 0.711
subject: astronomy, #q:152, acc: 0.829
subject: business_ethics, #q:100, acc: 0.760
subject: clinical_knowledge, #q:265, acc: 0.781
subject: college_biology, #q:144, acc: 0.854
subject: college_chemistry, #q:100, acc: 0.560
subject: college_computer_science, #q:100, acc: 0.700
subject: college_mathematics, #q:100, acc: 0.590
subject: college_medicine, #q:173, acc: 0.775
subject: college_physics, #q:102, acc: 0.559
subject: computer_security, #q:100, acc: 0.750
subject: conceptual_physics, #q:235, acc: 0.821
subject: econometrics, #q:114, acc: 0.605
subject: electrical_engineering, #q:145, acc: 0.759
subject: elementary_mathematics, #q:378, acc: 0.638
subject: formal_logic, #q:126, acc: 0.524
subject: global_facts, #q:100, acc: 0.400
subject: high_school_biology, #q:310, acc: 0.906
subject: high_school_chemistry, #q:203, acc: 0.759
subject: high_school_computer_science, #q:100, acc: 0.860
subject: high_school_european_history, #q:165, acc: 0.812
subject: high_school_geography, #q:198, acc: 0.889
subject: high_school_government_and_politics, #q:193, acc: 0.933
subject: high_school_macroeconomics, #q:390, acc: 0.785
subject: high_school_mathematics, #q:270, acc: 0.496
subject: high_school_microeconomics, #q:238, acc: 0.887
subject: high_school_physics, #q:151, acc: 0.675
subject: high_school_psychology, #q:545, acc: 0.895
subject: high_school_statistics, #q:216, acc: 0.731
subject: high_school_us_history, #q:204, acc: 0.858
subject: high_school_world_history, #q:237, acc: 0.873
subject: human_aging, #q:223, acc: 0.740
subject: human_sexuality, #q:131, acc: 0.855
subject: international_law, #q:121, acc: 0.851
subject: jurisprudence, #q:108, acc: 0.815
subject: logical_fallacies, #q:163, acc: 0.847
subject: machine_learning, #q:112, acc: 0.598
subject: management, #q:103, acc: 0.864
subject: marketing, #q:234, acc: 0.910
subject: medical_genetics, #q:100, acc: 0.880
subject: miscellaneous, #q:783, acc: 0.881
subject: moral_disputes, #q:346, acc: 0.780
subject: moral_scenarios, #q:895, acc: 0.543
subject: nutrition, #q:306, acc: 0.814
subject: philosophy, #q:311, acc: 0.733
subject: prehistory, #q:324, acc: 0.852
subject: professional_accounting, #q:282, acc: 0.553
subject: professional_law, #q:1534, acc: 0.565
subject: professional_medicine, #q:272, acc: 0.779
subject: professional_psychology, #q:612, acc: 0.760
subject: public_relations, #q:110, acc: 0.709
subject: security_studies, #q:245, acc: 0.759
subject: sociology, #q:201, acc: 0.831
subject: us_foreign_policy, #q:100, acc: 0.910
subject: virology, #q:166, acc: 0.560
subject: world_religions, #q:171, acc: 0.807
Total latency: 67.512
Average accuracy: 0.737
```


# NVIDIA Nemotron3-Super
Source: https://docs.sglang.io/cookbook/autoregressive/NVIDIA/Nemotron3-Super



## 1. Model Introduction

`NVIDIA Nemotron3-Super` is a leading open model in the Nemotron 3 family, built for running many collaborating agents together. It is optimized for agentic systems that chain planning, reasoning, and tool use workloads that generate far more tokens than single turn chat and require strong reasoning at every step.

Nemotron 3 Super is a 120B parameter hybrid MoE model that activates only 12B parameters per forward pass, delivering strong accuracy for coding, tool calling, and instruction following at a fraction of the cost. It also supports a 1M token context window so agents can keep conversation history and plan state in view across long workflows.

Architecture and key features:

* **Hybrid Transformer-Mamba Architecture (MoE):** Combines Mixture of Experts with a hybrid Transformer-Mamba architecture, enabling efficient routing and sequence modeling in a single stack.
* **Highest throughput efficiency in its size category:** Delivers up to 5x higher throughput compared to the previous Nemotron Super model (Llama Nemotron Super 1.5).
* **Multi-Token Prediction (MTP):** By predicting several future tokens simultaneously in a single forward pass, MTP drastically accelerates the generation of long-form text.
* **Thinking Budget support:** Supports Thinking Budget for optimal accuracy with minimum reasoning token generation.

## 2. SGLang Installation

SGLang from the main branch is required for Nemotron3-Super. You can install from source and with a nightly docker.

```bash Command theme={null}
# Install from source
uv pip install --prerelease=allow 'git+https://github.com/sgl-project/sglang.git#subdirectory=python'

# Or use Docker
docker pull lmsysorg/sglang:latest
```

For the full Docker setup and other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/install).

## 3. Model Deployment

This section provides a progressive guide from quick deployment to performance tuning.

### 3.1 Basic Configuration

**Interactive Command Generator**: select hardware, tensor parallelism, and common knobs to generate a launch command.

Run this Command:


### 3.2 Configuration Tips

* **Attention backend**:

  **H200**: Use flash attention 3 backend by default.
  **B200**: Use flashinfer backend by default.

* **TP support**:

  To set tp size, use `--tp <2|4|8>`.

* **FP8 KV cache**:

  To enable fp8 kv cache, please append `--kv-cache-dtype fp8_e4m3`.

## 4. Model Invocation

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16 \
  --host 0.0.0.0 \
  --port 5000 \
  --trust-remote-code \
  --tp 4 \
  --tool-call-parser qwen3_coder \
  --reasoning-parser nemotron_3
```

### 4.1 Basic Usage (OpenAI-Compatible API)

SGLang provides an OpenAI-compatible endpoint. Example with the OpenAI Python client:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:5000/v1",
    api_key="EMPTY",
)

resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "Give me 3 bullet points about SGLang."},
    ],
    temperature=0.6,
    max_tokens=1024,
)
print("Reasoning:", resp.choices[0].message.reasoning_content, "\nContent:", resp.choices[0].message.content)
print("\n")
```

Output:

```text Output theme={null}
Reasoning: Okay, the user is asking for 3 bullet points about SGLang. Let me recall what I know about SGLang. It's a framework for serving large language models, right? Developed by the team at UC Berkeley and others.

First, I should verify the key features. SGLang is known for its high-performance serving capabilities, especially with features like Radix Attention and chunked prefill. Those are important points to mention...(more tokens)

Content: - SGLang introduces **Radix Attention**, an innovative attention mechanism that significantly reduces KV cache memory usage and improves computational efficiency during LLM serving by reusing intermediate states across tokens.
- It features **chunked prefill** for handling long prompts efficiently, breaking input sequences into manageable chunks to minimize latency and memory pressure while maintaining high throughput.
- Designed for **high-performance LLM serving**, SGLang achieves superior throughput and lower latency compared to traditional systems (like vLLM or TensorRT-LLM) through optimized kernel fusion, dynamic batching, and seamless integration with Hugging Face Transformers.
```

Streaming chat completion:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:5000/v1",
    api_key="EMPTY",
)

stream = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "What are the first 5 prime numbers?"}
    ],
    temperature=0.7,
    max_tokens=1024,
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta
    if delta and delta.content:
        print(delta.content, end="", flush=True)
```

Output:

```text Output theme={null}
The first 5 prime numbers are:
**2, 3, 5, 7, 11**.

### Explanation:
- A **prime number** is a natural number greater than 1 that has no positive divisors other than 1 and itself.
- **2** is the smallest and only even prime number.
- **3** is prime (divisible only by 1 and 3).
- **4** is not prime (divisible by 2).
- **5** is prime.
- **6** is not prime (divisible by 2 and 3).
- **7** is prime.
- **8, 9, 10** are not prime.
- **11** is prime (the fifth in the sequence).

Note: **1 is not considered a prime number** by definition, as it has only one positive divisor.
This list is universally accepted in mathematics. Let me know if you'd like to explore more primes or related concepts! 😊
```

### 4.2 Reasoning

The model supports two modes — Reasoning ON (default) vs OFF. This can be toggled by setting `enable_thinking` to `False`, as shown below.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:5000/v1",
    api_key="EMPTY",
)

# Reasoning on (default)
print("Reasoning on")
resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Write a haiku about GPUs. Please make thinking process short."}
    ],
    temperature=1,
    max_tokens=1024,
)
print(f"Reasoning: \n{resp.choices[0].message.reasoning_content[:200]}... \nContent: \n{resp.choices[0].message.content[:200]}...")
print("\n")
# Reasoning off
print("Reasoning off")
resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Give me 3 facts about SGLang."}
    ],
    temperature=0,
    max_tokens=256,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}}
)
print(f"Content: \n{resp.choices[0].message.reasoning_content[:200]}...")
```

Output:

```text Output theme={null}
Reasoning on
Reasoning:
We need to output a haiku about GPUs, with short thinking process. Probably we just need to produce the haiku. No extra commentary needed. Provide a haiku: 5-7-5 syllable lines about GPUs.

Let's deci...
Content:
Silicon hearts beat
Paint vivid worlds with bright light
GPU dreams rise...

Reasoning off
Content:
Certainly! Here are three accurate and informative facts about **SGLang**:

1. **SGLang is a high-performance serving system for large language models (LLMs)**
   Developed by researchers at UC Berk...
```

### 4.3 Tool Calling

Call functions using the OpenAI Tools schema and inspect returned `tool_calls`.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:5000/v1",
    api_key="EMPTY",
)

# Tool calling via OpenAI tools schema
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "calculate_tip",
            "parameters": {
                "type": "object",
                "properties": {
                    "bill_total": {
                        "type": "integer",
                        "description": "The total amount of the bill"
                    },
                    "tip_percentage": {
                        "type": "integer",
                        "description": "The percentage of tip to be applied"
                    }
                },
                "required": ["bill_total", "tip_percentage"]
            }
        }
    }
]

completion = client.chat.completions.create(
    model="nemotron",
    messages=[
        {"role": "system", "content": ""},
        {"role": "user", "content": "My bill is $50. What will be the amount for 15% tip?"}
    ],
    tools=TOOLS,
    temperature=0.6,
    top_p=0.95,
    max_tokens=512,
    stream=False
)

print(completion.choices[0].message.reasoning_content)
print(completion.choices[0].message.tool_calls)
```

Output:

```text Output theme={null}
The user wants to calculate a 15% tip on a $50 bill. I have a function called calculate_tip that takes bill_total and tip_percentage as parameters. The bill_total is $50, and tip_percentage is 15. I need to call the function with these values. Let me do that.

[ChatCompletionMessageFunctionToolCall(id='call_ced9a83a3baa448e9d587aaf', function=Function(arguments='{"bill_total": 50, "tip_percentage": 15}', name='calculate_tip'), type='function', index=0)]
```

### 4.4 Controlling Reasoning Budget

The `reasoning_budget` parameter allows you to limit the length of the model's reasoning trace. When the reasoning output reaches the specified token budget, the model will attempt to gracefully end the reasoning at the next newline character.

If no newline is encountered within 500 tokens after reaching the budget threshold, the reasoning trace will be forcibly terminated at `reasoning_budget + 500` tokens.

```python Example theme={null}
from typing import Any, Dict, List
import openai
from transformers import AutoTokenizer

class ThinkingBudgetClient:
    def __init__(self, base_url: str, api_key: str, tokenizer_name_or_path: str):
        self.base_url = base_url
        self.api_key = api_key
        self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path)
        self.client = openai.OpenAI(base_url=self.base_url, api_key=self.api_key)

    def chat_completion(
        self,
        model: str,
        messages: List[Dict[str, Any]],
        reasoning_budget: int = 512,
        max_tokens: int = 1024,
        **kwargs,
    ) -> Dict[str, Any]:
        assert (
            max_tokens > reasoning_budget
        ), f"reasoning_budget must be smaller than max_tokens. Given {max_tokens=} and {reasoning_budget=}"

        # 1. first call chat completion to get reasoning content
        response = self.client.chat.completions.create(
            model=model,
            messages=messages,
            max_tokens=reasoning_budget,
            **kwargs
        )

        reasoning_content = response.choices[0].message.reasoning_content or ""

        if "" not in reasoning_content:
            # reasoning content is too long, closed with a period (.)
            reasoning_content = f"{reasoning_content}.\n\n\n"

        reasoning_tokens_used = len(
            self.tokenizer.encode(reasoning_content, add_special_tokens=False)
        )
        remaining_tokens = max_tokens - reasoning_tokens_used

        assert (
            remaining_tokens > 0
        ), f"remaining tokens must be positive. Given {remaining_tokens=}. Increase max_tokens or lower reasoning_budget."

        # 2. append reasoning content to messages and call completion
        messages.append({"role": "assistant", "content": reasoning_content})
        prompt = self.tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            continue_final_message=True,
        )

        response = self.client.completions.create(
            model=model,
            prompt=prompt,
            max_tokens=remaining_tokens,
            **kwargs
        )

        response_data = {
            "reasoning_content": reasoning_content.strip().strip("").strip(),
            "content": response.choices[0].text,
            "finish_reason": response.choices[0].finish_reason,
        }
        return response_data
```

Usage example with `reasoning_budget=128`:

```python Example theme={null}
SERVED_MODEL_NAME = "nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16"

# Client
client = ThinkingBudgetClient(
    base_url="http://127.0.0.1:5000/v1",
    api_key="null",
    tokenizer_name_or_path=SERVED_MODEL_NAME
)

resp = client.chat_completion(
    model=SERVED_MODEL_NAME,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Write a haiku about GPUs."}
    ],
    temperature=1,
    max_tokens=512,
    reasoning_budget=128
)
print("Reasoning:", resp["reasoning_content"], "\nContent:", resp["content"])
```

Output:

```text Output theme={null}
Reasoning: Okay, the user wants a haiku about GPUs. Let me recall what a haiku is: a traditional Japanese poem with three lines, 5-7-5 syllable structure. So I need to make sure the syllable count is exact.

First, I should think about what makes GPUs interesting. They're used for graphics rendering, parallel processing, AI, gaming, etc. Maybe focus on their speed, power, or how they handle many tasks at once.

Let me brainstorm some words and phrases related to GPUs: silicon, cores, transistors, parallel, rendering, pixels, frames per second, CUDA, tensor.
Content:

Silicon minds awaken,
Thousands of cores hum in unison—
Lightning paints the void.
```

***

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: H200 (4x)

* Model: nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16

* Tensor Parallelism: 4

* SGLang Version: main branch

* Model Deployment Command:

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16 \
  --trust-remote-code \
  --tp 4 \
  --max-running-requests 1024 \
  --host 0.0.0.0 \
  --port 5000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 5000 \
  --model nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16 \
  --dataset-name random \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 4096 \
  --max-concurrency 256
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 256
Successful requests:                     4096
Benchmark duration (s):                  623.49
Total input tokens:                      2081726
Total input text tokens:                 2081726
Total generated tokens:                  2087288
Total generated tokens (retokenized):    2044666
Request throughput (req/s):              6.57
Input token throughput (tok/s):          3338.85
Output token throughput (tok/s):         3347.77
Peak output token throughput (tok/s):    6349.00
Peak concurrent requests:                270
Total token throughput (tok/s):          6686.62
Concurrency:                             250.35
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   38108.46
Median E2E Latency (ms):                 37186.80
P90 E2E Latency (ms):                    69325.24
P99 E2E Latency (ms):                    77776.90
---------------Time to First Token----------------
Mean TTFT (ms):                          436.49
Median TTFT (ms):                        114.90
P99 TTFT (ms):                           6938.11
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          75.02
Median TPOT (ms):                        76.02
P99 TPOT (ms):                           92.27
---------------Inter-Token Latency----------------
Mean ITL (ms):                           74.07
Median ITL (ms):                         38.45
P95 ITL (ms):                            230.42
P99 ITL (ms):                            242.70
Max ITL (ms):                            7181.72
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

**Environment**

* Hardware: H200 (4x)
* Model: nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16
* Tensor Parallelism: 4
* SGLang Version: main branch

**Launch Model**

```bash Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16 \
  --trust-remote-code \
  --tp 4 \
  --reasoning-parser nemotron_3
```

**Run Benchmark**

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Test Results:**

```text Output theme={null}
Accuracy: 0.950
Invalid: 0.000
Latency: 21.442 s
Output throughput: 996.815 token/s
```

#### 5.2.2 MMLU Benchmark

**Run Benchmark**

```bash Command theme={null}
sgl-eval run mmlu \
  --base-url http://127.0.0.1:30000/v1 \
  --num-threads 64 --max-tokens 2048
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Test Results:**

```text Output theme={null}
subject: abstract_algebra, #q:100, acc: 0.730
subject: anatomy, #q:135, acc: 0.830
subject: astronomy, #q:152, acc: 0.934
subject: business_ethics, #q:100, acc: 0.830
subject: clinical_knowledge, #q:265, acc: 0.879
subject: college_biology, #q:144, acc: 0.931
subject: college_chemistry, #q:100, acc: 0.620
subject: college_computer_science, #q:100, acc: 0.840
subject: college_mathematics, #q:100, acc: 0.820
subject: college_medicine, #q:173, acc: 0.821
subject: college_physics, #q:102, acc: 0.794
subject: computer_security, #q:100, acc: 0.880
subject: conceptual_physics, #q:235, acc: 0.919
subject: econometrics, #q:114, acc: 0.746
subject: electrical_engineering, #q:145, acc: 0.828
subject: elementary_mathematics, #q:378, acc: 0.926
subject: formal_logic, #q:126, acc: 0.857
subject: global_facts, #q:100, acc: 0.570
subject: high_school_biology, #q:310, acc: 0.952
subject: high_school_chemistry, #q:203, acc: 0.828
subject: high_school_computer_science, #q:100, acc: 0.940
subject: high_school_european_history, #q:165, acc: 0.861
subject: high_school_geography, #q:198, acc: 0.939
subject: high_school_government_and_politics, #q:193, acc: 0.990
subject: high_school_macroeconomics, #q:390, acc: 0.928
subject: high_school_mathematics, #q:270, acc: 0.700
subject: high_school_microeconomics, #q:238, acc: 0.966
subject: high_school_physics, #q:151, acc: 0.834
subject: high_school_psychology, #q:545, acc: 0.960
subject: high_school_statistics, #q:216, acc: 0.852
subject: high_school_us_history, #q:204, acc: 0.926
subject: high_school_world_history, #q:237, acc: 0.937
subject: human_aging, #q:223, acc: 0.879
subject: human_sexuality, #q:131, acc: 0.939
subject: international_law, #q:121, acc: 0.934
subject: jurisprudence, #q:108, acc: 0.898
subject: logical_fallacies, #q:163, acc: 0.914
subject: machine_learning, #q:112, acc: 0.821
subject: management, #q:103, acc: 0.903
subject: marketing, #q:234, acc: 0.944
subject: medical_genetics, #q:100, acc: 0.980
subject: miscellaneous, #q:783, acc: 0.945
subject: moral_disputes, #q:346, acc: 0.861
subject: moral_scenarios, #q:895, acc: 0.542
subject: nutrition, #q:306, acc: 0.902
subject: philosophy, #q:311, acc: 0.884
subject: prehistory, #q:324, acc: 0.920
subject: professional_accounting, #q:282, acc: 0.805
subject: professional_law, #q:1534, acc: 0.681
subject: professional_medicine, #q:272, acc: 0.923
subject: professional_psychology, #q:612, acc: 0.889
subject: public_relations, #q:110, acc: 0.800
subject: security_studies, #q:245, acc: 0.837
subject: sociology, #q:201, acc: 0.960
subject: us_foreign_policy, #q:100, acc: 0.920
subject: virology, #q:166, acc: 0.590
subject: world_religions, #q:171, acc: 0.906
Total latency: 150.267
Average accuracy: 0.841
```


# NVIDIA Nemotron3-Ultra
Source: https://docs.sglang.io/cookbook/autoregressive/NVIDIA/Nemotron3-Ultra

Deploy NVIDIA Nemotron3-Ultra with SGLang - 550B hybrid MoE model (55B active) with 1M context window, BF16/NVFP4 support, built for long-running autonomous agents.

## 1. Model Introduction

`NVIDIA Nemotron3-Ultra` is an open frontier reasoning model in the Nemotron 3 family, built for long-running autonomous agents. It is optimized for complex orchestration across coding, deep research, enterprise workflows, and EDA use cases where agents must sustain reasoning across many steps and large context windows.

Nemotron 3 Ultra is a 550B parameter hybrid MoE model that activates only 55B parameters per forward pass, delivering frontier reasoning accuracy with high-throughput inference. It supports a 1M token context window so agents can keep conversation history, tool outputs, and plan state in view across persistent workflows.

Architecture and key features:

* **Hybrid Transformer-Mamba Architecture (MoE):** Combines Mixture of Experts with a hybrid Transformer-Mamba architecture, enabling efficient routing and sequence modeling in a single stack.
* **Long-horizon agentic reasoning:** Tuned for agents that plan, call tools, inspect results, recover from failures, and continue working across long task horizons — coding, deep research, enterprise automation, and EDA.
* **1M token context window:** Sustains coherent agent state across extended workflows without re-ingestion.
* **BF16 and NVFP4 quantization:** Deployable from multi-node H100 down to a single Blackwell node with NVFP4.
* **Multi-environment RL post-training:** Post-trained with reinforcement learning across multiple environments for robust reasoning and reliable agentic behavior.
* **Open weights, open data, open recipes:** Customizable for domain-specific agents and deployable across your own infrastructure.

**Modalities:** Input: text — Output: text

**Supported GPUs:**

* **BF16:** 16×H100, 16×H200, 8×B200/B300
* **NVFP4:** 4/8×B200/B300, 4×GB200/GB300

Available model variants on HuggingFace:

* [`nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16`](https://huggingface.co/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16)
* [`nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4`](https://huggingface.co/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4)

## 2. SGLang Installation

Nemotron3-Ultra support is included in the latest stable release.

```bash Command theme={null}
docker pull lmsysorg/sglang:latest
```

## 3. Model Deployment

This section provides a progressive guide from quick deployment to performance tuning.

### 3.1 Basic Configuration

**Interactive Command Generator**: select model precision, hardware, tensor parallelism, and common knobs to generate a launch command.

The generator only emits a runnable command for combinations that NVIDIA / SGLang have validated. Selecting an unverified tuple (e.g. NVFP4 on H100/H200, BF16 with TP=4 on H100, …) is **blocked** — the command pane shows an explicit error and the verified support matrix instead of a launch line, so unvalidated commands can't be copied by accident.

Run this Command:


### 3.2 Configuration Tips

* **Attention backend**:

  **H100/H200**: Use flash attention 3 backend by default.
  **B200/GB200/B300/GB300**: Set `--attention-backend trtllm_mha`. The flashinfer default breaks the overlap scheduler on Blackwell, so `trtllm_mha` is required there.

* **Mamba scheduler strategy**:

  Always launch with `--mamba-radix-cache-strategy extra_buffer`. This hybrid Transformer-Mamba model requires the `extra_buffer` strategy for correct scheduling of its Mamba state.

* **Mamba backend**:

  The Mamba layers use the Triton SSM kernels by default. For better performance, set `--mamba-backend flashinfer` to use the FlashInfer Mamba kernels instead.

* **Mamba SSM precision**:

  The SSM state dtype defaults to the model config value. Set `--mamba-ssm-dtype float16` to store the Mamba states in FP16, which reduces mamba cache memory without significant accuracy loss.

* **Mamba SSM stochastic rounding**:

  When storing the Mamba states in FP16, add `--enable-mamba-cache-stochastic-rounding` to round SSM cache writes stochastically and reduce accumulation bias. It requires `--mamba-ssm-dtype float16` and CUDA; with the default `--mamba-backend triton` it additionally requires SM100. Use `--mamba-cache-philox-rounds` to control the number of Philox rounds (`0` uses the backend default).

* **TP support**:

  To set tp size, use `--tp <4|8|16>`. Recommended pairings:

  * BF16: `--tp 16` on H100/H200, `--tp 8` on B200/B300
  * NVFP4: `--tp 4` or `--tp 8` on B200/B300, `--tp 4` on GB200/GB300

* **Multi-node BF16 on H100**:

  The 16×H100 BF16 setup spans two nodes. Use `--dist-init-addr :5000 --nnodes 2 --node-rank <0|1>` on each node and keep `--tp 16`.

* **DP attention**:

  By default the attention layers are tensor-parallel (sharded across all TP ranks). Enabling DP attention (the toggle above, or `--attn-dp-size `) instead runs attention as `N` data-parallel groups: each DP rank serves its own slice of the requests with its own KV cache. `--attn-dp-size` must divide `--tp`.

* **Expert parallel (EP)**:

  This MoE only supports `ep_size == 1` (off) or `ep_size == tp_size`. To enable expert parallelism, set `--ep ` with the same value as `--tp`.

* **Multi-token prediction (MTP)**:

  Enable MTP speculative decoding (the toggle above) for low latency.

* **FP8 KV cache**:

  To enable fp8 kv cache, set `--kv-cache-dtype fp8_e4m3`. This is enabled by default on the NVFP4 checkpoint.

* **Reasoning parser**:

  Set `--reasoning-parser nemotron_3` to enable structured reasoning traces (`reasoning_content` field in the response).

* **Tool calling**:

  Set `--tool-call-parser qwen3_coder` to enable tool calling support.

## 4. Model Invocation

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16 \
  --trust-remote-code \
  --tp 8 \
  --mamba-radix-cache-strategy extra_buffer \
  --attention-backend trtllm_mha \
  --tool-call-parser qwen3_coder \
  --reasoning-parser nemotron_3
```

### 4.1 Basic Usage (OpenAI-Compatible API)

SGLang provides an OpenAI-compatible endpoint. Example with the OpenAI Python client:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "Give me 3 bullet points about SGLang."},
    ],
    temperature=0.6,
    max_tokens=1024,
)
print("Reasoning:", resp.choices[0].message.reasoning_content, "\nContent:", resp.choices[0].message.content)
print("\n")
```

Output:

```text Output theme={null}
Reasoning: The user wants 3 bullet points about SGLang. Let me recall what I know about SGLang — it's a high-performance serving framework for large language models with a focus on structured generation and efficient KV cache reuse...(more tokens)

Content: - **Radix Attention** — SGLang reuses KV cache across requests sharing a common prefix, dramatically reducing memory and compute for multi-turn agent loops and few-shot workloads.
- **OpenAI-compatible API and structured generation** — Drop-in replacement for the OpenAI client, with first-class support for constrained decoding (JSON schema, regex) and OpenAI-style tool calling.
- **High-throughput serving on NVIDIA GPUs** — Continuous batching, chunked prefill, FP8/NVFP4 quantization, and optimized CUDA kernels deliver state-of-the-art throughput across H100, H200, B200, and GB200.
```

Streaming chat completion:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

stream = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "What are the first 5 prime numbers?"}
    ],
    temperature=0.7,
    max_tokens=1024,
    stream=True,
)
for chunk in stream:
    delta = chunk.choices[0].delta
    if delta and delta.content:
        print(delta.content, end="", flush=True)
```

Output:

```text Output theme={null}
The first 5 prime numbers are:
**2, 3, 5, 7, 11**.

### Explanation:
- A **prime number** is a natural number greater than 1 whose only positive divisors are 1 and itself.
- **2** is the smallest prime and the only even prime.
- **3, 5, 7, 11** are each divisible only by 1 and themselves.
- **1** is not prime by definition (it has only one positive divisor).
- **4, 6, 8, 9, 10** are composite.
```

### 4.2 Reasoning

The model supports two modes — Reasoning ON (default) vs OFF. This can be toggled by setting `enable_thinking` to `False`, as shown below.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

# Reasoning on (default)
print("Reasoning on")
resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Plan a 3-step approach to debug a flaky integration test. Keep the thinking process short."}
    ],
    temperature=1,
    max_tokens=1024,
)
print(f"Reasoning: \n{resp.choices[0].message.reasoning_content[:200]}... \nContent: \n{resp.choices[0].message.content[:200]}...")
print("\n")
# Reasoning off
print("Reasoning off")
resp = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Give me 3 facts about SGLang."}
    ],
    temperature=0,
    max_tokens=256,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}}
)
print(f"Content: \n{resp.choices[0].message.content[:200]}...")
```

Output:

```text Output theme={null}
Reasoning on
Reasoning:
The user wants a short reasoning chain plus a 3-step debug plan for a flaky integration test. I'll think briefly about common causes (timing/race, shared state, external service variance) and pick a t...
Content:
1. **Reproduce deterministically** — run the test in a loop (e.g. 50–100x) with logging at the suspected race points to confirm the failure rate and surface ordering.
2. **Isolate state** — re-run with...

Reasoning off
Content:
Here are 3 facts about SGLang:

1. **High-performance LLM serving system** developed at UC Berkeley with contributions from a broad open-source community, focused on throughput and latency at scale.
...
```

### 4.3 Tool Calling

Call functions using the OpenAI Tools schema and inspect returned `tool_calls`. The server must be launched with `--tool-call-parser qwen3_coder`.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

# Tool calling via OpenAI tools schema
TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "search_codebase",
            "description": "Search the project codebase for a symbol or pattern.",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The symbol, function name, or regex to search for"
                    },
                    "path": {
                        "type": "string",
                        "description": "Optional sub-path to restrict the search to"
                    }
                },
                "required": ["query"]
            }
        }
    }
]

completion = client.chat.completions.create(
    model="nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16",
    messages=[
        {"role": "system", "content": "You are a coding agent. Use tools to inspect the repo before answering."},
        {"role": "user", "content": "Where is the `RadixCache` class defined?"}
    ],
    tools=TOOLS,
    temperature=0.6,
    top_p=0.95,
    max_tokens=512,
    stream=False
)

print(completion.choices[0].message.reasoning_content)
print(completion.choices[0].message.tool_calls)
```

Output:

```text Output theme={null}
The user is asking where the RadixCache class is defined. I should search the codebase for the symbol "RadixCache" to find the file and line. I'll call search_codebase with that query.

[ChatCompletionMessageFunctionToolCall(id='call_8a7f2c4e1b9d4a3e8c2f1d6b', function=Function(arguments='{"query": "class RadixCache"}', name='search_codebase'), type='function', index=0)]
```

### 4.4 Controlling Reasoning Budget

The `reasoning_budget` parameter allows you to limit the length of the model's reasoning trace. When the reasoning output reaches the specified token budget, the model will attempt to gracefully end the reasoning at the next newline character.

If no newline is encountered within 500 tokens after reaching the budget threshold, the reasoning trace will be forcibly terminated at `reasoning_budget + 500` tokens.

```python Example theme={null}
from typing import Any, Dict, List
import openai
from transformers import AutoTokenizer

class ThinkingBudgetClient:
    def __init__(self, base_url: str, api_key: str, tokenizer_name_or_path: str):
        self.base_url = base_url
        self.api_key = api_key
        self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path)
        self.client = openai.OpenAI(base_url=self.base_url, api_key=self.api_key)

    def chat_completion(
        self,
        model: str,
        messages: List[Dict[str, Any]],
        reasoning_budget: int = 512,
        max_tokens: int = 1024,
        **kwargs,
    ) -> Dict[str, Any]:
        assert (
            max_tokens > reasoning_budget
        ), f"reasoning_budget must be smaller than max_tokens. Given {max_tokens=} and {reasoning_budget=}"

        # 1. first call chat completion to get reasoning content
        response = self.client.chat.completions.create(
            model=model,
            messages=messages,
            max_tokens=reasoning_budget,
            **kwargs
        )

        reasoning_content = response.choices[0].message.reasoning_content or ""

        if "" not in reasoning_content:
            # reasoning content is too long, closed with a period (.)
            reasoning_content = f"{reasoning_content}.\n\n\n"

        reasoning_tokens_used = len(
            self.tokenizer.encode(reasoning_content, add_special_tokens=False)
        )
        remaining_tokens = max_tokens - reasoning_tokens_used

        assert (
            remaining_tokens > 0
        ), f"remaining tokens must be positive. Given {remaining_tokens=}. Increase max_tokens or lower reasoning_budget."

        # 2. append reasoning content to messages and call completion
        messages.append({"role": "assistant", "content": reasoning_content})
        prompt = self.tokenizer.apply_chat_template(
            messages,
            tokenize=False,
            continue_final_message=True,
        )

        response = self.client.completions.create(
            model=model,
            prompt=prompt,
            max_tokens=remaining_tokens,
            **kwargs
        )

        response_data = {
            "reasoning_content": reasoning_content.strip().strip("").strip(),
            "content": response.choices[0].text,
            "finish_reason": response.choices[0].finish_reason,
        }
        return response_data
```

Usage example with `reasoning_budget=256`:

```python Example theme={null}
SERVED_MODEL_NAME = "nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16"

# Client
client = ThinkingBudgetClient(
    base_url="http://127.0.0.1:30000/v1",
    api_key="null",
    tokenizer_name_or_path=SERVED_MODEL_NAME
)

resp = client.chat_completion(
    model=SERVED_MODEL_NAME,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Outline a research plan to evaluate the throughput of two MoE serving strategies."}
    ],
    temperature=1,
    max_tokens=1024,
    reasoning_budget=256
)
print("Reasoning:", resp["reasoning_content"], "\nContent:", resp["content"])
```

Output:

```text Output theme={null}
Reasoning: The user wants a research plan to compare throughput of two MoE serving strategies. I should outline goals, baselines, datasets, metrics (tokens/s, TTFT, ITL, MFU), variables to sweep (TP, batch size, sequence length, concurrency), and statistical handling. Keep it concise since reasoning_budget is 256...
Content:

**Research plan**

1. **Define goal & metrics** — peak token throughput (input+output), TTFT, P99 ITL, MFU; measured at fixed accuracy.
2. **Choose baselines** — Strategy A (TP-only) vs Strategy B (TP + expert-parallel). Hold model checkpoint, precision, and KV-cache dtype constant.
3. **Sweep** — `{batch ∈ 1,4,16,64, concurrency ∈ 16,64,256, seq_len ∈ 1k,8k,32k}` per strategy.
4. **Workload** — `sglang.bench_serving --dataset-name random` with matched input/output budgets.
5. **Analysis** — per-config throughput table + roofline overlay; bootstrap CIs over 3 reruns to bound noise.
```

***

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: GB200 (4x)

* Model: nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4

* Tensor Parallelism: 4

* SGLang Version: main branch

* Model Deployment Command:

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4 \
  --trust-remote-code \
  --tp 4 \
  --mamba-radix-cache-strategy extra_buffer \
  --attention-backend trtllm_mha \
  --max-running-requests 1024
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4 \
  --dataset-name random \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 4096 \
  --max-concurrency 256
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 256
Successful requests:                     4096
Benchmark duration (s):                  1184.58
Total input tokens:                      2081726
Total input text tokens:                 2081726
Total generated tokens:                  2087288
Total generated tokens (retokenized):    1990224
Request throughput (req/s):              3.46
Input token throughput (tok/s):          1757.35
Output token throughput (tok/s):         1762.05
Peak output token throughput (tok/s):    3150.00
Peak concurrent requests:                266
Total token throughput (tok/s):          3519.40
Concurrency:                             249.55
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   72169.95
Median E2E Latency (ms):                 71994.47
P90 E2E Latency (ms):                    99898.56
P99 E2E Latency (ms):                    107119.61
---------------Time to First Token----------------
Mean TTFT (ms):                          40057.33
Median TTFT (ms):                        41375.93
P99 TTFT (ms):                           46377.89
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          63.15
Median TPOT (ms):                        63.65
P99 TPOT (ms):                           78.16
---------------Inter-Token Latency----------------
Mean ITL (ms):                           63.14
Median ITL (ms):                         35.92
P95 ITL (ms):                            178.10
P99 ITL (ms):                            182.10
Max ITL (ms):                            2466.36
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

**Environment**

* Hardware: GB200 (4x)
* Model: nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4
* Tensor Parallelism: 4
* SGLang Version: main branch

**Launch Model**

```bash Command theme={null}
python3 -m sglang.launch_server \
  --model-path nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4 \
  --trust-remote-code \
  --tp 4 \
  --mamba-radix-cache-strategy extra_buffer \
  --attention-backend trtllm_mha \
  --reasoning-parser nemotron_3
```

**Run Benchmark**

```bash Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

**Test Results:**

```text Output theme={null}
Accuracy: 0.970
Invalid: 0.000
Latency: 29.129 s
Output throughput: 745.333 token/s
```

#### 5.2.2 MMLU Benchmark

**Run Benchmark**

```bash Command theme={null}
sgl-eval run mmlu \
  --base-url http://127.0.0.1:30000/v1 \
  --num-threads 64 --max-tokens 2048
```

**Test Results:**

```text Output theme={null}
TBD
```

***


# Nemotron3.5-Lightning
Source: https://docs.sglang.io/cookbook/autoregressive/NVIDIA/Nemotron3.5-Lightning

Deploy NVIDIA Nemotron 3.5 Lightning with SGLang — NVFP4 serving with MTP, DFlash, and DSpark speculative decoding, reasoning, and tool calling.

## Deployment

> **Install SGLang**
>
> For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel.
>
> **Python (pip / uv)**
>
> ```bash Command theme={null}
> pip install --upgrade pip
> pip install uv
> SGLANG_BUILD_RUST_EXTS=none uv pip install --prerelease=allow 'git+https://github.com/sgl-project/sglang.git#subdirectory=python'
> ```
>
> Then run the **Python** output of the command panel below in that environment.
>
> **Docker**
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev-nemotron3-5-lightning
> ```
>
> For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces.

Pick your hardware and recipe to generate the launch command. Every platform publishes four operating points: **Balanced** (no speculation) plus three speculative decoders — **MTP**, **DFlash**, and **DSpark**. Use the Playground below to explore knobs beyond them.

## Playground

The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing.

## 1. Model Introduction

**NVIDIA Nemotron 3.5 Lightning** is a 30B-A3B hybrid reasoning LLM. See the Hugging Face model cards below for architecture and evaluation details.

Checkpoint Precision Use
**[NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4)** NVFP4 Serving — the checkpoint this page deploys
**[NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-BF16)** BF16 Full-precision reference
**[NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4-DFlash](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4-DFlash)** W4A16 DFlash speculative draft model
**[NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4-DSpark](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4-DSpark)** W4A16 DSpark speculative draft model
MTP needs no separate download — the draft head is embedded in the target checkpoint. ## 2. Usage The server speaks the OpenAI API. With `--reasoning-parser nemotron_3` enabled, the thinking trace lands in `message.reasoning_content` and the answer in `message.content`. ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://127.0.0.1:8000/v1", api_key="null", ) response = client.chat.completions.create( model="nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Briefly explain: what is SGLang?"}, ], temperature=1.0, top_p=0.95, max_tokens=1024, ) choice = response.choices[0] print("Reasoning:", choice.message.reasoning_content) print("Content:", choice.message.content) ``` ### 2.1 Tool Calling With `--tool-call-parser qwen3_coder` enabled, structured tool calls are returned in `message.tool_calls`. ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://127.0.0.1:8000/v1", api_key="null", ) TOOLS = [ { "type": "function", "function": { "name": "calculate_tip", "parameters": { "type": "object", "properties": { "bill_total": {"type": "integer", "description": "The total amount of the bill"}, "tip_percentage": {"type": "integer", "description": "The percentage of tip to be applied"}, }, "required": ["bill_total", "tip_percentage"], }, }, } ] response = client.chat.completions.create( model="nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-NVFP4", messages=[{"role": "user", "content": "My bill is $50. What will be the amount for 15% tip?"}], tools=TOOLS, max_tokens=1024, ) choice = response.choices[0] print("Content:", choice.message.content) print("Tool calls:", choice.message.tool_calls) ``` # NVIDIA Nemotron 3.5 Super VL Source: https://docs.sglang.io/cookbook/autoregressive/NVIDIA/Nemotron3.5-Super Deploy Nemotron 3.5 Super VL 120B-A12B with SGLang on B200, H200, RTX PRO 6000, and DGX Spark, with NVFP4 or BF16 and optional MTP. ## Deployment The **Docker** commands use `lmsysorg/sglang:nemotron3-5-super`. The command panel selects either `nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4` or `nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-BF16`. Set `HF_TOKEN` in the panel's Env control if the checkpoint requires access. Choose **B200, H200, RTX PRO 6000, or DGX Spark** on one node. B200 offers NVFP4 and BF16. H200 offers BF16; NVFP4 is greyed out. RTX PRO 6000 and DGX Spark offer NVFP4; BF16 is greyed out. Choose `bfloat16` or `float32` in **Mamba SSM DType**; `bfloat16` is the default. **High Throughput** leaves MTP off. **Low Latency** adds EAGLE MTP with top-k 1, three steps, and four draft tokens. These names identify configuration choices; no throughput or latency comparison was measured. Both command tabs use `sglang serve`. ## Playground The Playground inherits the selected recipe and lets you toggle the reasoning and tool-call parsers. Parser changes are separate experiments. ## 1. Model introduction **NVIDIA Nemotron 3.5 Super VL 120B-A12B** is a vision-language checkpoint in the Nemotron-H hybrid MoE family. The early-access NGC checkpoint configuration identifies `NemotronH_Omni_Reasoning_V3` and includes a vision encoder. The command panel uses the [NVFP4](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4) and [BF16](https://huggingface.co/nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-BF16) Hugging Face IDs; the source runs used the [NGC model](https://registry.ngc.nvidia.com/orgs/0767305323357365/teams/super3-5-vl-ea-0911/models/nemotron-3.5-super-vl-120b-a12b-ea20261008). Check the checkpoint pages for access terms and model details. The SGLang model entry point is [`nano_nemotron_vl.py` on the `nemotron3-super-dev-20261015` branch](https://github.com/sgl-project/sglang/blob/nemotron3-super-dev-20261015/python/sglang/srt/models/nano_nemotron_vl.py), with its supporting kernels and runtime code on the same branch. The validation used text-only GSM8K prompts. It does **not** establish image or video request correctness, long-context behavior, or tool-call accuracy. ## 2. Configuration tips and validation * **B200, NVFP4 or BF16:** both strategies use one eight-GPU TP8 node with FP8 E4M3 KV cache and 16,384-token configured context. Select the Mamba state dtype in the wizard; SGLang selects the attention backend and memory limits by default. * **H200, BF16:** both strategies use one eight-GPU TP8 node with FA3 attention, Triton MoE, and `--disable-flashinfer-autotune`. * **RTX PRO 6000, NVFP4:** both strategies served at TP1 on GPU 1 of an eight-GPU G4 machine. The configured context was 262,144 tokens; only short prompts were tested. * **DGX Spark, NVFP4:** both strategies completed 300-question text-only GSM8K runs at TP1 with `bfloat16` Mamba state. The `float32` choice has no completed accuracy run. * **KV precision:** these recipes deliberately use `--kv-cache-dtype fp8_e4m3` to match the validated runs. KV precision can affect output quality; no BF16-KV comparison was measured. Server information confirmed `speculative_algorithm: null` for High Throughput and `EAGLE` for Low Latency. The runs used installed early-access NGC weights, not the Hugging Face checkpoint IDs in the command panel or the public Docker image. The Deployment panel’s Benchmark card shows text-only GSM8K accuracy for measured selections and a pending state for unmeasured selections. The existing green Verified status marks a recipe with a completed source-run. These results do not validate the public checkpoint IDs or Docker image. ## 3. Reasoning output The base recipes enable `--reasoning-parser nemotron_3`. In the tested chat completions, the thinking trace appeared in `message.reasoning_content` and the final answer in `message.content`. The tool-call parser is configured as `qwen3_coder`, but structured tool calls were not part of this accuracy check. > **Reasoning example (Python client)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://127.0.0.1:30000/v1", api_key="EMPTY") > model = client.models.list().data[0].id > response = client.chat.completions.create( > model=model, > messages=[{ > "role": "user", > "content": "Claire makes a 3 egg omelet every morning for breakfast. How many dozens of eggs will she eat in 4 weeks?\nSolve the problem and put the final numeric answer after ####.", > }], > ) > message = response.choices[0].message > print("Reasoning:", message.reasoning_content) > print("Content:", message.content) > ``` > **Example output from the B200 NVFP4 smoke run** > > ```text Output theme={null} > Reasoning: The user wants me to solve a math problem. > > Claire makes a 3 egg omelet every morning. > She eats 3 eggs per day. > 4 weeks = 4 × 7 = 28 days. > Total eggs = 3 × 28 = 84 eggs. > Dozens of eggs = 84 / 12 = 7 dozens. > > Final answer: 7. > > I need to put the final numeric answer after ####. > Content: Claire eats 3 eggs per day. > In 4 weeks, there are 4 × 7 = 28 days. > Total eggs eaten: 3 × 28 = 84 eggs. > Since 1 dozen = 12 eggs: 84 ÷ 12 = 7 dozens. > > #### 7 > ``` # GPT-OSS Source: https://docs.sglang.io/cookbook/autoregressive/OpenAI/GPT-OSS ## 1.Model Introduction [GPT-OSS](https://huggingface.co/openai/gpt-oss-20b) is an advanced large language model developed by OpenAI designed for power reasoning, agentic tasks, and versatile developer use cases. It has versions with two model sizes. * **gpt-oss-120b** — for production, general purpose, high reasoning use cases that fit into a single 80GB GPU (like NVIDIA H100 80GB or AMD MI300X 192GB) (117B parameters with 5.1B active parameters) * **gpt-oss-20b** — for lower latency, and local or specialized use cases (21B parameters with 3.6B active parameters) GPT-OSS introduces several groundbreaking innovations: * **Configurable reasoning effort**: Easily adjust the reasoning effort (low, medium, high) based on your specific use case and latency needs. * **Full chain-of-thought**: Gain complete access to the model’s reasoning process, facilitating easier debugging and increased trust in outputs. It’s not intended to be shown to end users. * **Fine-tunable**: Fully customize models to your specific use case through parameter fine-tuning. * **Agentic capabilities**: Use the models’ native capabilities for function calling, web browsing, Python code execution, and Structured Outputs. * **MXFP4 quantization**: The models were post-trained with MXFP4 quantization of the MoE weights, making gpt-oss-120b run on a single 80GB GPU (like NVIDIA H100 80GB or AMD MI300X 192GB) and the gpt-oss-20b model run within 16GB of memory. All evals were performed with the same MXFP4 quantization. ## 2.SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3.Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration The GPT-OSS series comes in two sizes. Recommended starting configurations vary depending on hardware. **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model size, quantization method, and thinking capabilities. Run this Command:

### 3.2 Configuration Tips

* **Native web search:** Set `EXA_API_KEY` in the SGLang server environment to enable built-in web search (Exa). No `--tool-server` is required, and requests are tagged with `x-exa-integration: sglang`.
* **Web search defaults:** `numResults=10`, search `type="auto"`, and `contents.highlights=true`. Override with `SGLANG_EXA_NUM_RESULTS`, `SGLANG_EXA_SEARCH_TYPE`, and `SGLANG_EXA_INCLUDE_HIGHLIGHTS`.
* **Python tool:** Add `--tool-server demo` to enable the Python interpreter. Runs in a Docker sandbox by default; set `PYTHON_EXECUTION_BACKEND=UV` to run on the host (model-generated code executes locally — use with care).
* **MCP tool servers:** For production, point SGLang at external MCP SSE servers with `--tool-server ip-1:port-1,ip-2:port-2`.
* **Responses API:** GPT-OSS supports OpenAI's Responses API (`client.responses.create`) in addition to the standard Chat Completions API (see section 4.2.4).
* **Use Python 3.12** when running the demo Python tool.
* **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4.Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

GPT-OSS supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections:

```shell Command theme={null}
python -m sglang.launch_server \
  --model openai/gpt-oss-120b \
  --reasoning-parser gpt-oss \
  --tp 8
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="openai/gpt-oss-120b",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
The user asks: "Solve this problem step by step: What is 15% of 240?" So we need to provide step-by-step solution. Compute 15% of 240: 0.15 * 240 = 36. Provide steps: convert percent to decimal, multiply, maybe use fraction. Provide answer.
=============== Content =================
**Step‑by‑step solution**

1. **Understand what “percent” means**
   “15 %” means 15 out of every 100 parts, i.e. the fraction \(\displaystyle \frac{15}{100}\).

2. **Convert the percent to a decimal (or fraction)**
   \[
   \frac{15}{100}=0.15
   \]

3. **Set up the multiplication**
   To find 15 % of 240 we multiply 240 by the decimal 0.15:
   \[
   240 \times 0.15
   \]

4. **Do the multiplication**
   One convenient way is to break it into two easier parts:
   \[
   240 \times 0.15 = 240 \times \left(\frac{15}{100}\right)
                = \frac{240 \times 15}{100}
   \]

   - First compute \(240 \times 15\):
     \[
     240 \times 15 = 240 \times (10 + 5) = 2400 + 1200 = 3600
     \]

   - Then divide by 100:
     \[
     \frac{3600}{100} = 36
     \]

5. **Write the result**
   \[
   15\% \text{ of } 240 = 36
   \]

---

**Answer:** \(36\)
```

#### 4.2.2 Tool Calling

GPT-OSS supports tool calling capabilities. Enable the tool call parser:

**Python Example (without Thinking Process):**

Start sglang server:

```shell Command theme={null}
python -m sglang.launch_server \
  --model openai/gpt-oss-120b \
  --tool-call-parser gpt-oss \
  --tp 8
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="openai/gpt-oss-120b",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                if tool_call.function:
                    print(f"🔧 Tool Call: {tool_call.function.name}")
                    print(f"   Arguments: {tool_call.function.arguments}")

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
🔧 Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

**Python Example (with Thinking Process):**

Start sglang server:

```shell Command theme={null}
python -m sglang.launch_server \
  --model openai/gpt-oss-120b \
  --reasoning-parser gpt-oss \
  --tool-call-parser gpt-oss \
  --tp 8
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="openai/gpt-oss-120b",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                if tool_call.function:
                    print(f"🔧 Tool Call: {tool_call.function.name}")
                    print(f"   Arguments: {tool_call.function.arguments}")

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
User asks: "What's the weather in Beijing?" We need to get current weather. Use function get_weather with location "Beijing". No unit specified; default? Probably use default (maybe Celsius). We can specify unit as "celsius". We'll call function.
=============== Content =================
🔧 Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="openai/gpt-oss-120b",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The current weather in Beijing is 22 °C and sunny. Let me know if you’d like a forecast for the next few days or any other details!"
```

#### 4.2.3 EAGLE3 Speculative Decoding

SGLang supports speculative decoding for GPT-OSS models using the EAGLE3 algorithm. This can significantly improve decoding speed, especially for small batch sizes.

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model-path openai/gpt-oss-120b \
  --speculative-algorithm EAGLE3 \
  --speculative-draft-model-path lmsys/EAGLE3-gpt-oss-120b-bf16 \
  --tp 2
```

> [!TIP]
>
> The spec-v2 overlap scheduler is enabled by default. It improves performance by overlapping draft and verification stages. Pass `--disable-overlap-schedule` to disable.

#### 4.2.4 Responses API and Built-in Tools

GPT-OSS supports the OpenAI Responses API with built-in tool use (web search and Python interpreter). Set `EXA_API_KEY` to enable native web search; add `--tool-server demo` only when you also want the Python tool:

```shell Command theme={null}
export EXA_API_KEY=YOUR_EXA_KEY
# Optional: server-side Exa tuning (defaults shown)
export SGLANG_EXA_NUM_RESULTS=10
export SGLANG_EXA_SEARCH_TYPE=auto
export SGLANG_EXA_INCLUDE_HIGHLIGHTS=true
# Optional: run Python tool on host instead of Docker (model code executes locally)
export PYTHON_EXECUTION_BACKEND=UV

python3 -m sglang.launch_server \
  --model-path openai/gpt-oss-120b \
  --tp 2
```

For production, use external MCP SSE servers instead of `demo`:

```shell Command theme={null}
mcp run -t sse browser_server.py:mcp
mcp run -t sse python_server.py:mcp

python -m sglang.launch_server \
  --model-path openai/gpt-oss-120b \
  --tool-server ip-1:port-1,ip-2:port-2 \
  --tp 2
```

**Example using Responses API:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(base_url="http://localhost:30000/v1", api_key="sk-123456")

search_tools = [{"type": "web_search"}]
python_tools = [{"type": "code_interpreter"}]

# Configurable reasoning effort: "high", "medium", or "low"
response = client.responses.create(
    model="openai/gpt-oss-120b",
    instructions="You are a helpful assistant.",
    reasoning_effort="high",
    input="In one sentence, explain the transformer architecture.",
)
print(response.output_text)

# Web search (requires EXA_API_KEY on the SGLang server)
response = client.responses.create(
    model="openai/gpt-oss-120b",
    instructions="You are a helpful assistant, you can search the web when needed.",
    input="Search the web for the latest news about Nvidia stock price",
    tools=search_tools,
)
print(response.output_text)

# Python tool (requires launching SGLang with --tool-server demo)
response = client.responses.create(
    model="openai/gpt-oss-120b",
    instructions="You are a helpful assistant, you could use python tool to execute code.",
    input="Use python tool to calculate the sum of 29138749187 and 29138749187",
    tools=python_tools,
)
print(response.output_text)
# Output: The sum is 58,277,498,374.
```

## 5.Benchmark

### 5.1 Speed Benchmark

* Hardware: NVIDIA B200 GPU (8x)
* Tensor Parallelism: 8
* Model: openai/gpt-oss-120b
* sglang version: 0.5.6

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios.

#### 5.1.1 Latency-Sensitive Benchmark

* Server Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model openai/gpt-oss-120b \
  --tp 8
```

* Test Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --num-prompt 100 \
  --max-concurrency 1
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     100
Benchmark duration (s):                  52.35
Total input tokens:                      33178
Total input text tokens:                 33178
Total input vision tokens:               0
Total generated tokens:                  21251
Total generated tokens (retokenized):    20868
Request throughput (req/s):              1.91
Input token throughput (tok/s):          633.76
Output token throughput (tok/s):         405.93
Peak output token throughput (tok/s):    433.00
Peak concurrent requests:                8
Total token throughput (tok/s):          1039.69
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   523.30
Median E2E Latency (ms):                 389.91
---------------Time to First Token----------------
Mean TTFT (ms):                          33.71
Median TTFT (ms):                        31.79
P99 TTFT (ms):                           108.98
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          2.31
Median TPOT (ms):                        2.31
P99 TPOT (ms):                           2.39
---------------Inter-Token Latency----------------
Mean ITL (ms):                           2.31
Median ITL (ms):                         2.31
P95 ITL (ms):                            2.35
P99 ITL (ms):                            2.38
Max ITL (ms):                            3.54
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Server Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model openai/gpt-oss-120b \
  --tp 8
```

* Test Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --num-prompt 1000 \
  --max-concurrency 100
```

**Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  24.76
Total input tokens:                      297156
Total input text tokens:                 297156
Total input vision tokens:               0
Total generated tokens:                  192432
Total generated tokens (retokenized):    187145
Request throughput (req/s):              40.39
Input token throughput (tok/s):          12003.57
Output token throughput (tok/s):         7773.26
Peak output token throughput (tok/s):    13780.00
Peak concurrent requests:                156
Total token throughput (tok/s):          19776.83
Concurrency:                             89.23
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2208.97
Median E2E Latency (ms):                 1591.11
---------------Time to First Token----------------
Mean TTFT (ms):                          102.94
Median TTFT (ms):                        31.53
P99 TTFT (ms):                           674.32
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          14.31
Median TPOT (ms):                        11.00
P99 TPOT (ms):                           91.28
---------------Inter-Token Latency----------------
Mean ITL (ms):                           11.00
Median ITL (ms):                         5.75
P95 ITL (ms):                            25.35
P99 ITL (ms):                            43.18
Max ITL (ms):                            621.42
==================================================
```

### 5.2 Accuracy Benchmark

### 5.2.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:8000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* **Results**:

  * GPT-OSS-120b

    ```text Output theme={null}
    Accuracy: 0.880
    Invalid: 0.005
    Latency: 5.262 s
    Output throughput: 12143.675 token/s
    ```

  * GPT-OSS-20b

    ```text Output theme={null}
    Accuracy: 0.535
    Invalid: 0.165
    Latency: 4.157 s
    Output throughput: 19589.165 token/s
    ```


# MiniCPM-V 4.6
Source: https://docs.sglang.io/cookbook/autoregressive/OpenBMB/MiniCPM-V-4_6



## 1. Model Introduction

MiniCPM-V 4.6 is the next-generation multimodal model from [OpenBMB](https://huggingface.co/openbmb), the team behind the MiniCPM-V series. The model combines a **Qwen3.5-style hybrid LLM backbone** (Gated Delta Net + full attention) with a **NaViT-packed vision encoder** that handles arbitrary aspect ratios and high-resolution slicing natively, plus end-to-end video support.

OpenBMB ships two variants on HuggingFace:

* [`openbmb/MiniCPM-V-4.6`](https://huggingface.co/openbmb/MiniCPM-V-4.6) — base instruct model. Use this for general multimodal serving; thinking mode is still available per-request via `chat_template_kwargs.enable_thinking=true`.
* [`openbmb/MiniCPM-V-4.6-Thinking`](https://huggingface.co/openbmb/MiniCPM-V-4.6-Thinking) — thinking-tuned variant with stronger chain-of-thought behavior. Pair with the same `--reasoning-parser qwen3` flag.

**Key Features:**

* **Hybrid LLM backbone**: Qwen3.5-style mix of Gated Delta Net (linear-attention) layers and full-attention layers, providing long-context efficiency without giving up modeling power.
* **Native variable-resolution vision**: NaViT-packed vision encoder with mid-ViT merger and per-image window attention. Images of any aspect ratio are processed without forced letterboxing.
* **High-resolution slicing**: Source image plus a configurable grid of slice tiles (up to 9 tiles in the open test variant) lets the model reason over fine detail in 1280×720+ images.
* **Video**: Frame-by-frame multi-modal data items routed through the same vision encoder; any number of frames per request.
* **Reasoning Parser**: switchable thinking mode (Qwen3.5 lineage), exposed via `chat_template_kwargs.enable_thinking` per request and SGLang's `--reasoning-parser qwen3` on the server side.
* **Tool Calling**: Qwen3.5-style `…` XML format, surfaced as OpenAI-compatible `message.tool_calls` via SGLang's `--tool-call-parser qwen3_coder`. Composes with thinking mode and with image / video inputs.

**License:** [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0).

## 2. SGLang Installation

Pull the nightly Docker image (rolling tag, tracks `main`):

```bash theme={null}
# CUDA 13 (Hopper / Blackwell, default)
docker pull lmsysorg/sglang:dev

# CUDA 12 (Ampere or older drivers). Final build: the CUDA 12 lane is retired,
# so this tag no longer tracks main.
docker pull lmsysorg/sglang:dev-cu12
```

For the general SGLang installation guide (PyPI, source, Docker) see the [official SGLang installation guide](../../../docs/get-started/install).

## 3. Model Deployment

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to generate the appropriate deployment command. The `Variant` toggle switches between `openbmb/MiniCPM-V-4.6` (base) and `openbmb/MiniCPM-V-4.6-Thinking`. The `Reasoning Parser` and `Tool Call Parser` toggles add `--reasoning-parser qwen3` and `--tool-call-parser qwen3_coder` respectively; see §4.4 for usage details.

Run this Command:


### 3.2 Configuration Tips

* **Mamba Radix Cache**: Qwen3.5's hybrid Gated Delta Networks architecture supports two mamba scheduling strategies via `--mamba-radix-cache-strategy`:
  * **V1 (`no_buffer`)**: Default. No overlap scheduler, lower memory usage. Required for AMD MI GPUs.
  * **V2 (`extra_buffer`)**: Enables overlap scheduling and branching point caching with `--mamba-radix-cache-strategy extra_buffer --page-size 64`. Requires FLA kernel backend (NVIDIA GPUs only). Trades higher mamba state memory for better throughput. Strictly superior in non-KV-cache-bound scenarios; in KV-cache-bound cases, weigh the overlap scheduling benefit against reduced max concurrency. `--page-size` must satisfy `FLA_CHUNK_SIZE % page_size == 0` or `page_size % FLA_CHUNK_SIZE == 0` (`FLA_CHUNK_SIZE` is currently 64).
* The `--mem-fraction-static` flag is recommended for optimal memory utilization, adjust it based on your hardware and workload.
* Context length defaults to 262,144 tokens. If you encounter OOM errors, consider reducing it, but maintain at least 128K to preserve thinking capabilities.
* To speed up weight loading for this large model, add `--model-loader-extra-config='{"enable_multithread_load": "true","num_threads": 64}'` to the launch command.
* **CUDA IPC Transport**: Add `SGLANG_USE_CUDA_IPC_TRANSPORT=1` as an environment variable to use CUDA IPC for transferring multimodal features, significantly improving TTFT (Time To First Token). Note: this consumes additional memory proportional to image size, so you may need to lower `--mem-fraction-static` or `--max-running-requests`.
* **Multimodal Attention Backend**: Use `--mm-attention-backend fa3` on H100/H200 for better vision performance, or `--mm-attention-backend fa4` on B200/B300.
* For processing large images or videos, you may need to lower `--mem-fraction-static` to leave room for image feature tensors.
* Multi-image and high-resolution images: the image processor produces one source patch plus per-slice tile patches; each is its own `MultimodalDataItem`. No special server-side flag needed.
* Video: decoded frame-by-frame through the same image-style slicer. No extra flag needed; pass `video_url` in the OpenAI chat completion request.
* **Chunked Prefill**: For high-concurrency vision benchmarking with many large/sliced images, pass `--chunked-prefill-size -1` to disable prefill chunking. The default chunked-prefill path can mis-split a request across an image boundary in `mm_utils.embed_mm_inputs` and crash the server; disabling chunking sidesteps this at the cost of higher TTFT under concurrency. For interactive serving leave the default on.

## 4. Model Invocation

Deploy the model on an H200:

```bash Command theme={null}
sglang serve --model-path openbmb/MiniCPM-V-4.6 \
  --trust-remote-code \
  --dtype bfloat16 \
  --mem-fraction-static 0.15 \
  --mamba-radix-cache-strategy extra_buffer \
  --page-size 64 \
  --host 0.0.0.0 --port 30000
```

### 4.1 Basic Usage (Image)

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

response = client.chat.completions.create(
    model="openbmb/MiniCPM-V-4.6",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://www.ilankelman.org/stopsigns/australia.jpg",
                    },
                },
                {"type": "text", "text": "Describe this image in one sentence."},
            ],
        }
    ],
    max_tokens=200,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)

print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
A black SUV drives past a Chinese-style gate with a red stop sign and traditional architecture, while storefronts and street signs line the sidewalk.
```

### 4.2 High-Resolution / Sliced Images

The image processor automatically picks a slice grid (up to 9 tiles) for high-resolution inputs. A 1280×720 source produces grid `[2, 3]`

* 7 patches with `tgt_sizes=[(24, 44), 6×(28, 36)]`, byte-for-byte matching the HF reference implementation.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

response = client.chat.completions.create(
    model="openbmb/MiniCPM-V-4.6",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/idefics-few-shot.jpg",
                    },
                },
                {"type": "text", "text": "Describe this image in one sentence."},
            ],
        }
    ],
    max_tokens=200,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)

print(response.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
The Statue of Liberty stands tall against a cloudy sky, holding a torch aloft and a document in her left hand, symbolizing freedom and enlightenment.
```

### 4.3 Video Input

```python Example theme={null}
from openai import OpenAI

client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

response = client.chat.completions.create(
    model="openbmb/MiniCPM-V-4.6",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "video_url",
                    "video_url": {"url": ""},
                },
                {"type": "text", "text": "Describe what happens in this video in one sentence."},
            ],
        }
    ],
    max_tokens=200,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)

print(response.choices[0].message.content)
```

**Output Example** (run against an 8-frame synthetic test mp4 of shifting colored squares):

```text Output theme={null}
The video shows a grid of colored squares moving in a random pattern.
```

### 4.4 Advanced Usage

#### 4.4.1 Reasoning Parser

Pass `--reasoning-parser qwen3` to the server (toggle "Reasoning Parser" on in §3.1, default) so SGLang splits each response on the `` / `` boundaries: the pre-`` block goes to `reasoning_content`, the post-`` text to `content`. Per-request, the chat template's `enable_thinking` flag toggles whether the model actually emits reasoning.

* **Thinking mode** (default, `enable_thinking=true`): assistant prompt ends with `\n`; the model writes reasoning, closes with ``, then the answer. `reasoning_content` and `content` are both populated.
* **Instruct mode** (`enable_thinking=false`): the chat template injects an empty `` placeholder so the model emits no thinking tokens; `reasoning_content` ends up empty.

```python Example (thinking mode) theme={null}
from openai import OpenAI

client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

response = client.chat.completions.create(
    model="openbmb/MiniCPM-V-4.6",
    messages=[{"role": "user", "content": "Reply with the single word 'hi'. No explanation."}],
    max_tokens=200,
)

msg = response.choices[0].message
print("reasoning_content:", msg.reasoning_content)
print("content          :", msg.content)
```

```text Output theme={null}
reasoning_content: Got it, let's see. The user wants a reply with "hi" and no explanation. So I need to just say "hi" as the response. ...
content          : hi
```

```python Example (instruct mode) theme={null}
response = client.chat.completions.create(
    model="openbmb/MiniCPM-V-4.6",
    messages=[{"role": "user", "content": "Reply with the single word 'hi'. No explanation."}],
    max_tokens=200,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)

msg = response.choices[0].message
print("reasoning_content:", msg.reasoning_content)
print("content          :", msg.content)
```

```text Output theme={null}
reasoning_content:
content          : hi
```

#### 4.4.2 Tool Calling

Pass `--tool-call-parser qwen3_coder` to the server (toggle "Tool Call Parser" on in §3.1) so SGLang extracts `` blocks from the model output into the OpenAI-style `message.tool_calls` field (with `finish_reason="tool_calls"`). The model speaks the Qwen3.5 XML tool-call format (`v`); the `qwen3_coder` parser is the right one. Tool calls compose with both reasoning modes and with image / video inputs.

> [!WARNING]
>
> Do **not** use `--tool-call-parser qwen` for MiniCPM-V 4.6 — that parser expects the older Qwen2.5 JSON format `{"name":..., "arguments":...}`, but both public 4.6 variants emit the Qwen3.5-style XML format with nested `` and `` tags. With `qwen` the outer `` markers match but the inner JSON parse fails, so `tool_calls` returns empty and the raw markup is left in `content`.

```python Example theme={null}
from openai import OpenAI

client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    },
]

response = client.chat.completions.create(
    model="openbmb/MiniCPM-V-4.6",
    messages=[{"role": "user", "content": "What is the weather in San Francisco? Use the tool."}],
    tools=tools,
    max_tokens=200,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}},
)

choice = response.choices[0]
print("finish_reason:", choice.finish_reason)
for tc in choice.message.tool_calls or []:
    print(f"  {tc.function.name}({tc.function.arguments})")
```

```text Output theme={null}
finish_reason: tool_calls
  get_weather({"location": "San Francisco", "unit": "celsius"})
```

To get the final natural-language answer, feed the tool's result back as a `tool` role message and call the API again with the same `tools` list — the model emits `finish_reason="stop"` with the answer in `content`.

## 5. Benchmark

**Common Test Environment (all benchmarks below):**

* Hardware: 1× NVIDIA H200 (141 GB), single GPU (no TP / DP)
* Docker Image: `lmsysorg/sglang:dev` (transformers 5.6.0, sgl-kernel 0.4.2.post1)
* Precision: BF16

**Common Server Launch Command:**

```bash Command theme={null}
CUDA_VISIBLE_DEVICES=0 python -m sglang.launch_server \
  --model-path openbmb/MiniCPM-V-4.6 \
  --trust-remote-code \
  --dtype bfloat16 \
  --mem-fraction-static 0.5 \
  --mamba-radix-cache-strategy extra_buffer \
  --chunked-prefill-size -1 \
  --host 0.0.0.0 --port 30000
```

(`--chunked-prefill-size -1` is required for the vision throughput run; see §3.2.)

### 5.1 Accuracy Benchmark

#### 5.1.1 MMMU Benchmark

* Benchmark Command

```bash Command theme={null}
python3 benchmark/mmmu/bench_sglang.py --port 30000 --concurrency 48 --max-new-tokens 2048
```

* Test Result

```
{'Accounting': {'acc': 0.767, 'num': 30},
 'Agriculture': {'acc': 0.533, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.4, 'num': 30},
 'Art': {'acc': 0.6, 'num': 30},
 'Art_Theory': {'acc': 0.667, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.533, 'num': 30},
 'Biology': {'acc': 0.333, 'num': 30},
 'Chemistry': {'acc': 0.333, 'num': 30},
 'Clinical_Medicine': {'acc': 0.467, 'num': 30},
 'Computer_Science': {'acc': 0.333, 'num': 30},
 'Design': {'acc': 0.533, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.333, 'num': 30},
 'Economics': {'acc': 0.633, 'num': 30},
 'Electronics': {'acc': 0.5, 'num': 30},
 'Energy_and_Power': {'acc': 0.633, 'num': 30},
 'Finance': {'acc': 0.533, 'num': 30},
 'Geography': {'acc': 0.367, 'num': 30},
 'History': {'acc': 0.533, 'num': 30},
 'Literature': {'acc': 0.7, 'num': 30},
 'Manage': {'acc': 0.367, 'num': 30},
 'Marketing': {'acc': 0.733, 'num': 30},
 'Materials': {'acc': 0.367, 'num': 30},
 'Math': {'acc': 0.567, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.333, 'num': 30},
 'Music': {'acc': 0.267, 'num': 30},
 'Overall': {'acc': 0.527, 'num': 900},
 'Overall-Art and Design': {'acc': 0.517, 'num': 120},
 'Overall-Business': {'acc': 0.607, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.553, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.617, 'num': 120},
 'Overall-Science': {'acc': 0.473, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.443, 'num': 210},
 'Pharmacy': {'acc': 0.667, 'num': 30},
 'Physics': {'acc': 0.767, 'num': 30},
 'Psychology': {'acc': 0.567, 'num': 30},
 'Public_Health': {'acc': 0.767, 'num': 30},
 'Sociology': {'acc': 0.667, 'num': 30}}
eval out saved to ./val_sglang.json
Overall accuracy: 0.527
```

### 5.2 Speed Benchmark

We use SGLang's built-in `bench_serving` tool with random text prompts (1000 input / 1000 output tokens) to characterize text-only serving performance.

#### 5.2.1 Latency Benchmark

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model openbmb/MiniCPM-V-4.6 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  7.47
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  4220
Total generated tokens (retokenized):    3554
Request throughput (req/s):              1.34
Input token throughput (tok/s):          816.44
Output token throughput (tok/s):         564.73
Peak output token throughput (tok/s):    690.00
Peak concurrent requests:                4
Total token throughput (tok/s):          1381.17
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   746.20
Median E2E Latency (ms):                 590.05
P90 E2E Latency (ms):                    1446.13
P99 E2E Latency (ms):                    1709.38
---------------Time to First Token----------------
Mean TTFT (ms):                          138.12
Median TTFT (ms):                        103.70
P99 TTFT (ms):                           330.79
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          1.44
Median TPOT (ms):                        1.44
P99 TPOT (ms):                           1.45
---------------Inter-Token Latency----------------
Mean ITL (ms):                           1.44
Median ITL (ms):                         1.45
P95 ITL (ms):                            1.49
P99 ITL (ms):                            1.57
Max ITL (ms):                            5.79
==================================================
```

#### 5.2.2 Throughput Benchmark

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model openbmb/MiniCPM-V-4.6 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 1000 \
  --max-concurrency 100 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  47.07
Total input tokens:                      502493
Total input text tokens:                 502493
Total generated tokens:                  500251
Total generated tokens (retokenized):    469844
Request throughput (req/s):              21.24
Input token throughput (tok/s):          10675.32
Output token throughput (tok/s):         10627.69
Peak output token throughput (tok/s):    25911.00
Peak concurrent requests:                130
Total token throughput (tok/s):          21303.01
Concurrency:                             97.24
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   4576.94
Median E2E Latency (ms):                 4331.97
P90 E2E Latency (ms):                    8634.07
P99 E2E Latency (ms):                    9636.44
---------------Time to First Token----------------
Mean TTFT (ms):                          206.50
Median TTFT (ms):                        184.72
P99 TTFT (ms):                           624.23
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          8.73
Median TPOT (ms):                        9.16
P99 TPOT (ms):                           13.63
---------------Inter-Token Latency----------------
Mean ITL (ms):                           8.75
Median ITL (ms):                         0.05
P95 ITL (ms):                            29.95
P99 ITL (ms):                            108.91
Max ITL (ms):                            448.40
==================================================
```

### 5.3 Vision Speed Benchmark

We use SGLang's built-in `bench_serving` tool with random images. Each request has 128 input text tokens, one 720p image, and 1024 output tokens.

#### 5.3.1 Latency Benchmark

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model openbmb/MiniCPM-V-4.6 \
  --dataset-name image \
  --image-count 1 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  10.26
Total input tokens:                      767
Total input text tokens:                 750
Total input vision tokens:               17
Total generated tokens:                  4220
Total generated tokens (retokenized):    4220
Request throughput (req/s):              0.97
Input token throughput (tok/s):          74.77
Output token throughput (tok/s):         411.39
Peak output token throughput (tok/s):    654.00
Peak concurrent requests:                2
Total token throughput (tok/s):          486.16
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   1024.04
Median E2E Latency (ms):                 897.99
P90 E2E Latency (ms):                    1584.25
P99 E2E Latency (ms):                    1781.78
---------------Time to First Token----------------
Mean TTFT (ms):                          416.94
Median TTFT (ms):                        403.18
P99 TTFT (ms):                           477.49
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          1.44
Median TPOT (ms):                        1.44
P99 TPOT (ms):                           1.45
---------------Inter-Token Latency----------------
Mean ITL (ms):                           1.44
Median ITL (ms):                         1.44
P95 ITL (ms):                            1.48
P99 ITL (ms):                            1.56
Max ITL (ms):                            2.89
==================================================
```

#### 5.3.2 Throughput Benchmark

```bash Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model openbmb/MiniCPM-V-4.6 \
  --dataset-name image \
  --image-count 1 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100 \
  --request-rate inf
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  360.01
Total input tokens:                      79925
Total input text tokens:                 78283
Total input vision tokens:               1642
Total generated tokens:                  510855
Total generated tokens (retokenized):    430289
Request throughput (req/s):              2.78
Input token throughput (tok/s):          222.01
Output token throughput (tok/s):         1419.01
Peak output token throughput (tok/s):    19620.00
Peak concurrent requests:                105
Total token throughput (tok/s):          1641.02
Concurrency:                             99.69
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   35888.57
Median E2E Latency (ms):                 35321.48
P90 E2E Latency (ms):                    41017.37
P99 E2E Latency (ms):                    60343.22
---------------Time to First Token----------------
Mean TTFT (ms):                          35096.32
Median TTFT (ms):                        34301.37
P99 TTFT (ms):                           59966.25
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          1.63
Median TPOT (ms):                        1.45
P99 TPOT (ms):                           10.15
---------------Inter-Token Latency----------------
Mean ITL (ms):                           1.58
Median ITL (ms):                         0.12
P95 ITL (ms):                            0.23
P99 ITL (ms):                            0.77
Max ITL (ms):                            2086.12
==================================================
```


# MiniCPM-V 4.7
Source: https://docs.sglang.io/cookbook/autoregressive/OpenBMB/MiniCPM-V-4_7

Deploy OpenBMB MiniCPM-V 4.7 with SGLang — 1B dense and 35B-A3B Mixture-of-Experts vision-language models on a hybrid Gated DeltaNet backbone, in BF16, FP8, or INT4, with DSpark speculative decoding on a single GB300 or H200.

## Deployment

> **Install SGLang**
>
> MiniCPM-V 4.7 support comes from [sgl-project/sglang#41993](https://github.com/sgl-project/sglang/pull/41993); both paths below use that PR's code. For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel.
>
> **Python (from source)**
>
> ```bash Command theme={null}
> git clone https://github.com/sgl-project/sglang.git
> cd sglang
> git fetch origin pull/41993/head:minicpm-v-4.7
> git checkout minicpm-v-4.7
> pip install --upgrade pip
> pip install -e "python"
> ```
>
> Then run the **Python** output of the command panel below in that environment.
>
> **Docker**
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev-minicpm-v-4.7
> ```
>
> For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces.

Pick the hardware, variant, and quantization to generate the launch command. Every recipe runs on a single GPU and is verified on GB300 and H200; the H100 recipes (1B, FP8, INT4) are unverified. The optional **DSPARK** row adds speculative decoding; see §2 for where it helps.

## Playground

The Playground is where you experiment with **SGLang features beyond the recipes above**. The Deploy panel emits this model's validated launch recipes; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing.

## 1. Model Introduction

MiniCPM-V 4.7 is the latest model in OpenBMB's MiniCPM-V series, covering single-image, multi-image, and video understanding. It ships in two sizes: a 1B dense model and a 35B-A3B Mixture-of-Experts model, the series' first MoE.

Both sizes use a Qwen3.5-style hybrid language backbone in which every fourth layer is full attention and the rest are Gated DeltaNet linear attention: 24 layers for 1B, and 40 layers with 256 experts (8 active per token) for 35B-A3B. Native context length is 262,144 tokens. The vision encoder compresses visual tokens early inside the ViT, slices high-resolution images into up to 9 tiles, and supports mixed 4x/16x visual token compression (see §3.3). Thinking is on by default.

**License:** [Apache-2.0](https://www.apache.org/licenses/LICENSE-2.0).

Checkpoint Precision Role on this page
[openbmb/MiniCPM-V-4.7-1B](https://huggingface.co/openbmb/MiniCPM-V-4.7-1B) BF16 1B dense base (1.55B parameters including the vision encoder).
[openbmb/MiniCPM-V-4.7-35B-A3B](https://huggingface.co/openbmb/MiniCPM-V-4.7-35B-A3B) BF16 35B-A3B MoE base (35.2B total parameters, about 3B active).
[openbmb/MiniCPM-V-4.7-35B-A3B-FP8](https://huggingface.co/openbmb/MiniCPM-V-4.7-35B-A3B-FP8) FP8 W8A8 (compressed-tensors) 35B-A3B FP8.
[openbmb/MiniCPM-V-4.7-35B-A3B-int4](https://huggingface.co/openbmb/MiniCPM-V-4.7-35B-A3B-int4) INT4 W4A16, group size 128 (compressed-tensors) 35B-A3B INT4.
[openbmb/MiniCPM-V-4.7-1B-DSpark](https://huggingface.co/openbmb/MiniCPM-V-4.7-1B-DSpark) BF16 draft Draft model for the 1B **DSPARK** row; not served on its own.
[openbmb/MiniCPM-V-4.7-35B-A3B-DSpark](https://huggingface.co/openbmb/MiniCPM-V-4.7-35B-A3B-DSpark) BF16 draft Draft model for the 35B-A3B **DSPARK** row; not served on its own.
OpenBMB also publishes AWQ, GPTQ, and GGUF exports and a 1B int4 checkpoint. They are not part of the matrix above. **Recommended generation:** `temperature=1.0`, `top_p=0.95`, `top_k=20`, from the 35B-A3B checkpoints' `generation_config.json`. SGLang applies these defaults, so do not hardcode them in client code. **Resources:** [Hugging Face (1B)](https://huggingface.co/openbmb/MiniCPM-V-4.7-1B) · [Hugging Face (35B-A3B)](https://huggingface.co/openbmb/MiniCPM-V-4.7-35B-A3B) · [OpenBMB documentation](https://github.com/OpenBMB/MiniCPM-V/blob/main/docs/minicpm_v4dot7_en.md) · [SGLang model support (#41993)](https://github.com/sgl-project/sglang/pull/41993). ## 2. Configuration Tips * Every generated command carries `--mamba-radix-cache-strategy extra_buffer`, the radix-cache strategy for the Gated DeltaNet hybrid backbone. The FP8 and INT4 commands also carry `--tokenizer-path openbmb/MiniCPM-V-4.7-35B-A3B` (see the note below). * Every recipe runs on one GPU. On H100 the 35B-A3B BF16 checkpoint (about 66 GB of weights) does not fit the default static memory fraction of an 80 GB card; use FP8 or INT4 there. * Pick the quantization by platform. On H200, quantization is a speed win: at concurrency 16, INT4 and FP8 reach 15,808 and 15,280 tokens/s per GPU against 12,103 for BF16, and INT4 has the fastest 35B-A3B decode (TPOT 3.47 ms at concurrency 1). On GB300, BF16 and FP8 decode at about the same speed at concurrency 1 (TPOT 4.36 vs 4.44 ms), and FP8 pulls ahead at concurrency 16 (16,059 vs 14,094 tokens/s per GPU). INT4 is slower on GB300 at every concurrency (TPOT 8.56 ms at concurrency 1), so use it there only to save memory. * SGLang detects FP8 and INT4 from the checkpoint's `quantization_config`; no `--quantization` flag is needed. * The **DSPARK** row adds `--speculative-algorithm DSPARK` and `--speculative-draft-model-path` pointing at the variant's DSpark checkpoint. On GB300, turn it on only for 35B-A3B BF16 and FP8 at low concurrency; on H200, turn it on for 35B-A3B BF16 at both measured concurrencies and for FP8 and INT4 at low concurrency; leave it off for 1B. The matched DSPARK on/off cells in the benchmark cards above back this. * Benchmark speculative decoding on real text. Random-token prompts collapse draft acceptance, so they say nothing about DSPARK. For a real-workload reference, GSM8K accept length is about 4.5 on 1B (measured at the final PR head); in the sharegpt benchmark, accept length is about 2.5 on 1B and 3.2-3.3 on the 35B-A3B variants. * Every command carries `--reasoning-parser auto --tool-call-parser auto`. SGLang resolves both from the chat template, to `qwen3` for reasoning and `qwen3_coder` for tool calls, so the thinking trace lands in `message.reasoning_content` and tool calls in `message.tool_calls` (see §3.1 and §3.2). To turn either off, toggle it in the **Parsers** card of the [Playground](#playground). * Thinking is on by default. To get a direct answer for one request, pass `"chat_template_kwargs": {"enable_thinking": false}` (in the OpenAI Python client, `extra_body={"chat_template_kwargs": {"enable_thinking": False}}`); `reasoning_content` then comes back empty. * Image and video requests need no extra server flags. > [!NOTE] > > The public FP8 and INT4 repos' `tokenizer_config.json` declares `auto_map.AutoProcessor = processing_minicpmv4_7.MiniCPMV4_7Processor`, but the repos do not ship that file, so SGLang cannot load their processor. The FP8 and INT4 commands therefore load the tokenizer and processor from the base repo with `--tokenizer-path openbmb/MiniCPM-V-4.7-35B-A3B`, which has the same `tokenizer.json` and chat template. Keep the flag until OpenBMB updates the FP8 and INT4 repos to ship the file or drop the `auto_map` entry. ## 3. Advanced Usage ### 3.1 Reasoning MiniCPM-V 4.7 thinks by default. The reasoning parser in every generated command returns the thinking trace in `message.reasoning_content` and the final answer in `message.content`. > **Reasoning (Python)** > > ```python Example theme={null} > import requests > > resp = requests.post( > "http://localhost:30000/v1/chat/completions", > json={ > "model": "openbmb/MiniCPM-V-4.7-35B-A3B", > "messages": [{"role": "user", "content": "What is 23*17?"}], > }, > ).json() > choice = resp["choices"][0] > print("finish_reason:", choice["finish_reason"]) > print("--- reasoning_content ---") > print(choice["message"]["reasoning_content"]) > print("--- content ---") > print(choice["message"]["content"]) > ``` > **Example Output** > > ```text Output theme={null} > finish_reason: stop > --- reasoning_content --- > The user is asking for the product of 23 and 17. I need to compute 23 * 17. > > Let me calculate: > 23 * 17 > I can break it down: > 23 * 10 = 230 > 23 * 7 = 161 > Now add: 230 + 161 = 391 > > Wait, let me double-check: > 23 * 17 > 23 * (10 + 7) = 23*10 + 23*7 > 23*10 = 230 > 23*7: 20*7=140, 3*7=21, so 140+21=161 > Now 230 + 161 = 391 > > So the product is 391. > > --- content --- > > > To find 23 × 17, I'll calculate the multiplication: > > 23 × 17 = 391 > > Answer: 391 > ``` > [!NOTE] > > On GSM8K-style prompts that ask for the answer in `\boxed{}`, the model can write the final answer inside the thinking block and stop without emitting ``, so the reasoning parser leaves `content` empty. Clients that read only `content`, such as accuracy-eval harnesses, should either serve without `--reasoning-parser` or also read `reasoning_content`. ### 3.2 Tool calling The tool-call parser in every generated command returns calls in `message.tool_calls`, with the arguments as a JSON string. Because thinking is on, print `reasoning_content` and `content` alongside the calls. > **Tool calling (Python)** > > ```python Example theme={null} > import json > > import requests > > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city.", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string", "description": "City name"}}, > "required": ["city"], > }, > }, > }] > > resp = requests.post( > "http://localhost:30000/v1/chat/completions", > json={ > "model": "openbmb/MiniCPM-V-4.7-35B-A3B", > "messages": [{"role": "user", "content": "What is the weather in Beijing today?"}], > "tools": tools, > }, > ).json() > choice = resp["choices"][0] > msg = choice["message"] > print("finish_reason:", choice["finish_reason"]) > print("--- reasoning_content ---") > print(msg["reasoning_content"]) > print("--- content ---") > print(repr(msg["content"])) > print("--- tool_calls ---") > print(json.dumps(msg["tool_calls"], indent=1)) > ``` > **Example Output** > > ```text Output theme={null} > finish_reason: tool_calls > --- reasoning_content --- > The user is asking about the weather in Beijing. I need to call the get_weather function with the city parameter set to Beijing. > > --- content --- > '\n\n' > --- tool_calls --- > [ > { > "id": "call_592d3b19eca4432eaf1a89f1", > "index": 0, > "type": "function", > "function": { > "name": "get_weather", > "arguments": "{\"city\": \"Beijing\"}" > } > } > ] > ``` To get the final answer, append the assistant message and a `tool` role message with the tool's result, then call the API again with the same `tools` list. ### 3.3 Per-request image processing OpenAI-compatible `/v1/chat/completions` and `/v1/completions` requests accept `mm_processor_kwargs`, which overrides the image processor for that request only: * `downsample_mode`: `"16x"` (default) or `"4x"`. `"4x"` keeps more visual tokens per tile. * `max_slice_nums`: the maximum number of high-resolution slices. `1` sends the image without slicing. > **Image token budget (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > IMAGE_URL = "https://www.ilankelman.org/stopsigns/australia.jpg" > > for overrides in ({}, {"downsample_mode": "4x"}, {"max_slice_nums": 1}): > resp = client.chat.completions.create( > model="openbmb/MiniCPM-V-4.7-35B-A3B", > messages=[{ > "role": "user", > "content": [ > {"type": "image_url", "image_url": {"url": IMAGE_URL}}, > {"type": "text", "text": "Describe this image in one sentence."}, > ], > }], > extra_body={"mm_processor_kwargs": overrides} if overrides else None, > ) > print(overrides or "default", "prompt_tokens =", resp.usage.prompt_tokens) > ``` Prompt token counts from the validation probes. The counts depend on the image sizes and the text prompt, so the example above, which uses a different image, returns different values. The first two rows send the same image and text prompt and differ only in `downsample_mode`.
Input `mm_processor_kwargs` Prompt tokens
One 1568×448 image none (`"16x"`) 355
One 1568×448 image `{"downsample_mode": "4x"}` 1291
Two images (1568×448 and 768×384) in one request none (`"16x"`) 556
One 768×384 image `{"max_slice_nums": 1}` 93
Overrides do not leak between requests: alternating `"16x"` and `"4x"` on the same image returns the matching token count and a correct answer each time. For more API examples, see the [SGLang Basic Usage Guide](/docs/basic_usage/send_request). # MiniCPM5-2B Source: https://docs.sglang.io/cookbook/autoregressive/OpenBMB/MiniCPM5-2B Deploy OpenBMB MiniCPM5-2B with SGLang — a 2.5B dense Llama-architecture on-device model with 131K context, thinking mode, XML tool calling and DSpark speculative decoding on H200, RTX PRO 6000, RTX 5090 and DGX Spark. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow "sglang>=0.5.12" > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your card to generate the launch command. MiniCPM5-2B is a 2.5B dense model and runs single-GPU at TP=1 on every supported card, so the page ships one operating point per card plus an optional **DSpark** speculative-decoding row. > [!NOTE] > > Speed numbers exist for the RTX 5090 and DGX Spark cells — a single card at > random 1024/1024, recorded as Mean. The H200 and RTX PRO 6000 cells are > pending measurement, and no accuracy numbers have been taken on any platform > yet. The DSpark overlay carries no speed numbers on any card. ## Playground The Playground is where you experiment with **SGLang features beyond the recipes above**. The Deploy panel emits this model's documented launch recipes; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction **MiniCPM5-2B** is the second model in OpenBMB's MiniCPM5 series, following MiniCPM5-1B. It is a dense 2B-class Transformer built for on-device assistants, local deployment, coding agents and tool-use workflows — scenarios where a compact model with a small deployment footprint is preferred. OpenBMB reports 2B-class open-source SOTA within its comparison set (average 53.9), with its clearest advantages in code reasoning, math reasoning, long-context understanding, tool use and agentic tasks. The checkpoint uses the standard `LlamaForCausalLM` architecture — no custom kernels and no model-code fork — so SGLang loads it through the stock Llama path. It is 2,516,756,480 parameters (1,981,982,720 non-embedding) over 42 layers with GQA (16 query heads, 2 KV heads), and a native context length of 131,072 tokens. Post-training runs SFT → RL → On-Policy Distillation, which merges 16 RL expert models into the single released checkpoint. Weights are released under the [Apache-2.0](https://github.com/OpenBMB/MiniCPM/blob/main/LICENSE) license.
Checkpoint Precision Role on this page
[openbmb/MiniCPM5-2B](https://huggingface.co/openbmb/MiniCPM5-2B) BF16 The served model in every cell above (final release, post-trained with RL + OPD).
[openbmb/MiniCPM5-2B-DSpark](https://huggingface.co/openbmb/MiniCPM5-2B-DSpark) BF16 draft Draft model loaded by the **DSPARK** row of the Deploy panel; not served on its own.
OpenBMB also publishes SFT-only, mid-training and base checkpoints, plus GGUF, MLX and GPTQ-Int4 exports for llama.cpp / Ollama / LM Studio / Apple Silicon. Those target other runtimes and are not part of the SGLang matrix above. **Recommended generation:** `temperature=1.0`, `top_p=0.95` (informational — SGLang reads the checkpoint's `generation_config.json`; do not hardcode these in client code). **Resources:** [HuggingFace](https://huggingface.co/openbmb/MiniCPM5-2B) · [ModelScope](https://www.modelscope.cn/models/OpenBMB/MiniCPM5-2B) · [GitHub](https://github.com/OpenBMB/MiniCPM) · [Tech report](https://arxiv.org/pdf/2506.07900). ## 2. Advanced Usage ### 2.1 Thinking Mode Thinking is controlled by the chat template's `enable_thinking` flag, passed per request through `chat_template_kwargs`. The `qwen3` reasoning parser — already in every generated command, and toggleable from the **Parsers** card in the [Playground above](#playground) — splits the `` segment into `message.reasoning_content` and leaves the final answer in `message.content`. Drop the flag and the thinking text stays inline in `content`, closing tag and all. > **Thinking On / Off (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > # Thinking on (chat-template default). > resp = client.chat.completions.create( > model="openbmb/MiniCPM5-2B", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > extra_body={"chat_template_kwargs": {"enable_thinking": True}}, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > > # Thinking off — a direct answer, no deliberation segment. > resp = client.chat.completions.create( > model="openbmb/MiniCPM5-2B", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > extra_body={"chat_template_kwargs": {"enable_thinking": False}}, > ) > print("Without thinking:", resp.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: We are asked: "What is 15% of 240?" This is a simple percentage calculation. To find 15% of 240, we multiply 240 by 15% (which is 0.15). So: 240 × 0.15 = 36. Alternatively, we can think of it as (15/100) × 240 = (15 × 240)/100 = 3600/100 = 36. So the answer is 36. > > We need to respond in a helpful way. The user might be testing or seeking quick answer. Let's provide a clear response with explanation if needed, but since it's straightforward, we can just give the answer directly or briefly explain. > > Answer: > > 15% of 240 is **36**. > > To calculate: > \( 240 \times 0.15 = 36 \) > Reasoning: None > Answer: To find 15% of 240, multiply 240 by 15% (which is 0.15): > > \[ > 240 \times 0.15 = 36 > \] > > So, 15% of 240 is **36**. > ``` ### 2.2 Tool Calling MiniCPM5-2B emits XML-style tool calls (`...`), and SGLang's built-in `minicpm5` detector converts them to OpenAI-compatible `tool_calls`, parallel calls included. The parser is already in every command the Deploy panel generates; the **Tool Call Parser** chip in the Playground's **Parsers** card is an opt-out, not an opt-in. > **Tool Calling (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city.", > "parameters": { > "type": "object", > "properties": { > "city": {"type": "string", "description": "City name"}, > "date": {"type": "string", "description": "YYYY-MM-DD"}, > }, > "required": ["city"], > }, > }, > }] > > resp = client.chat.completions.create( > model="openbmb/MiniCPM5-2B", > messages=[{"role": "user", "content": "What is the weather in Beijing today?"}], > tools=tools, > ) > > msg = resp.choices[0].message > # With the qwen3 reasoning parser on, the thinking segment lands in > # `reasoning_content` and `content` may be empty on a tool-call turn. > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Content:", msg.content) > for call in (msg.tool_calls or []): > print("Tool:", call.function.name, call.function.arguments) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: > The user is asking about the weather in Beijing today. I have access to a get_weather function that can help with this. Let me call it to get the current weather for Beijing. > > Content: > > > Tool: get_weather {"city": "Beijing"} > ``` # PPLX-Decider-v1-27B Source: https://docs.sglang.io/cookbook/autoregressive/Perplexity/PPLX-Decider-v1-27B Deploy PPLX-Decider-v1-27B with SGLang. Perplexity's decision model, fine-tuned from Qwen3.8-27B, returns calibrated probabilities for choice, yes or no, and score questions on /v1/systemone, on one NVIDIA H200 or GB300 in BF16. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. PPLX-Decider support landed after v0.5.21, so until a release includes it, install a [nightly build](/docs/get-started/install#nightly-builds). > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow --index-strategy unsafe-best-match --extra-index-url https://docs.sglang.ai/whl/cu130/ sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > The image is multi-arch, so the same tag runs on x86 H200 hosts and Arm GB300 hosts. For how to launch it, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your GPU to generate the launch command. The model runs on one GPU in BF16, and the decision support needs no flag: SGLang reads the checkpoint's `decision_config.json`, loads its decision readout, and answers on `/v1/systemone` with the prompt, answer codes, and calibrated temperature the model was trained with. The GB300 recipe adds `--disable-radix-cache` for speed, as explained in [Configuration Tips](#2-configuration-tips). > [!NOTE] > > The H200 recipe is the original one, validated against the checkpoint's own reference implementation on one H200 when support landed ([#42183](https://github.com/sgl-project/sglang/pull/42183)), and it has no speed numbers yet. The GB300 recipe adds `--disable-radix-cache` (see [Configuration Tips](#2-configuration-tips)) and was measured end to end on one GB300 at SGLang commit `70f0b7351e`: four request shapes from 1 to 256 concurrent requests, Belebele and WinoGrande accuracy, and per-question parity with the reference implementation. [§3](#3-benchmarks) has the method and the full tables. ## Playground The Playground layers SGLang features on top of the recipe above. Any override changes the badge to **Not Verified** until that exact configuration is tested end to end. The [Configuration Tips](#2-configuration-tips) say which overrides were measured on GB300 and what they did. Tensor parallelism times data-parallel replicas must fit the GPUs on one node. ## 1. Model Introduction **PPLX-Decider-v1-27B** is a decision model from Perplexity, fine-tuned from [Qwen3.8-27B](/cookbook/autoregressive/Qwen/Qwen3.8-27B) under the Apache-2.0 license. It replaces the language model head with a readout over 255 answer codes and answers choice, yes or no (`noul`), and score questions about a text state and optional images with a probability for every option, without generating text. Each question is one prefill pass, so the cost of a decision is the cost of reading its prompt. Its successor, [PPLX-Decider-v1.1-27B](/cookbook/autoregressive/Perplexity/PPLX-Decider-v1.1-27B), adds noncausal full attention and more training data. The backbone is the Qwen3.8-27B hybrid: 64 layers in which 48 Gated DeltaNet (linear attention) layers alternate with 16 gated full-attention layers, a 5120-wide hidden state, and the Qwen3.8 vision encoder, for 26.1B parameters (52 GB in BF16). The checkpoint ships a bare `Qwen3_5Model` backbone, the 255-row readout in `readout.safetensors`, and `decision_config.json` with the answer-code token ids and a calibrated temperature of 2.2076. SGLang serves it as `Qwen3_5ForConditionalGeneration` and writes the readout into the language model head rows of the code tokens, so the probabilities come out of the regular scoring path.
Property Value
Checkpoint [perplexity-ai/pplx-decider-v1-27b](https://huggingface.co/perplexity-ai/pplx-decider-v1-27b) (BF16)
Base model Qwen3.8-27B, one epoch of supervised fine-tuning on decision data
Question types `choice` (up to 255 options), `noul` (yes or no), `score` (up to 10 levels)
Inputs Text or JSON state, optional images
Prompt length Trained on question prompts of up to 8,192 tokens, and the backbone accepts 262,144
License Apache-2.0
Perplexity reports 85.71% overall accuracy across 11 public benchmarks for this checkpoint, against 74.76% for Qwen3.8-27B, measured through the Perplexity API. The per-benchmark table is on the model card. [§3](#3-benchmarks) measures accuracy and speed on SGLang. **Resources:** [HuggingFace](https://huggingface.co/perplexity-ai/pplx-decider-v1-27b), [reference inference code](https://huggingface.co/perplexity-ai/pplx-decider-v1-27b/blob/main/inference.py), [Decision models in SGLang](/docs/supported-models/decision_models). ## 2. Configuration Tips * **Route.** Send requests to `/v1/systemone`, the System One API the checkpoint was trained for. `/v1/decisions` refuses this checkpoint because its labels and prompt are not the ones the readout learned, and chat or generation requests are not meaningful without a language model head. * **Clients.** Clients of the System One API, including the TypeSafe SDKs, work by pointing their base URL at the server. See [System One compatible API](/docs/supported-models/decision_models#system-one-compatible-api) for the request and response reference. * **Images.** Pass each image in `images` as base64 bytes, a base64 data URL, or an `http(s)` URL. They precede the text in every question, as in the checkpoint's reference code. The checkpoint's processor resizes every image to between 65,536 and 262,144 pixels, so one image costs 64 to 256 prompt tokens: a 1024×768 screenshot is 234 tokens, and a 4K one is no more expensive than 1080p (252). Crop to the region that matters rather than sending a larger image. * **What a decision costs.** Each question is its own prompt: an \~84-token wrapper (system message, chat template, answer instructions), the state, the question, and its options, read in one prefill pass. Several questions in one request are scored together, but each re-reads the whole state, so the cost of a request is roughly *questions × state tokens*. * **Prefix cache.** On this hybrid model the prefix cache resumes from where an earlier prompt ended, because that is where the Gated DeltaNet state is saved, not from any shared prefix. An identical request measured 215 ms cold and 56 ms cached on GB300, but a different question about the same state, and the other questions in the same request, reused none of the state. The GB300 recipe therefore turns the cache off with `--disable-radix-cache`: unique-state traffic loses no reuse, each request holds one state slot instead of five, and the per-request state bookkeeping goes away, which took a short question from 59 to 51 ms and an image request from 126 to 87 ms with the attention kernel held fixed. Turn it back on only if your traffic repeats identical requests, the same state and the same question, often enough to matter. * **Prompt length.** The model was fine-tuned on question prompts of up to 8,192 tokens, and the reference code refuses longer ones. SGLang serves the backbone's full 262,144-token context, so keep states within the trained length. A longer prompt is answered, but its accuracy is untested. * **Throughput is compute-bound.** A decision is pure prefill, and one GB300 reads about 27,000 prompt tokens per second in BF16 once batches are full: about 71 requests per second for a 382-token question, and 3.3 for an 8K-token state. Past that point, more concurrency only adds queueing. The tables in [§3](#3-benchmarks) map concurrency to latency, so pick the highest concurrency that fits your latency budget. * **Memory.** The weights take 52 GB, and the default `--mem-fraction-static` hands the rest of the GPU to the KV and Gated DeltaNet state pools. The startup log line `max_running_requests is capped to ... by the mamba state cache` is expected: on GB300, each request reserves five state slots with the prefix cache on (a cap of 118) and one with it off (593). Even the lower cap only binds for questions shorter than about 140 tokens, because a prefill batch fills its 16,384-token chunk first. `--mamba-ssm-dtype bfloat16` halves the state pool but measured no faster, so keep the checkpoint's FP32 state. * **GB300 kernels.** With the prefix cache off, SGLang picks the TRT-LLM attention kernel with 64-token pages on GB300 (Triton with 1-token pages while the cache is on), and that kernel is where the long-state gain comes from: an 8K-token state drops from 377 to 325 ms and saturates at 3.30 instead of 2.87 requests per second, the same as forcing `--attention-backend trtllm_mha --page-size 64` with the cache on. FlashInfer's Gated DeltaNet prefill (`--linear-attn-prefill-backend flashinfer`) adds another 4-8% on text, taking the 8K-token state to 300 ms and 3.56 requests per second, but it made image requests slower (101 vs 87 ms alone, 9% less throughput), so the recipe leaves it to the Playground for text-only traffic. A larger prefill chunk (`--chunked-prefill-size 32768`) did not help: one 16,384-token chunk already keeps the GPU busy. * **More GPUs.** The model fits one GPU, so add throughput with data-parallel replicas: `--dp-size 2` on two GB300s served 139 short questions per second (1.96× one GPU) and 6.5 8K-token states per second, and because the questions of one request are spread over the replicas, it also cut four questions on a 1K-token state from 179 to 104 ms. The extra dispatch hop added about 15 ms to a lone short question. Tensor parallelism only pays off for latency on long states: `--tp 2` took an 8K-token state from 325 to 208 ms, but delivered less throughput than two replicas and made a short question slower (68 ms), because the all-reduce dominates small batches. SGLang Model Gateway does not route `/v1/systemone` yet, so to spread load over several servers instead of `--dp-size`, use a plain HTTP load balancer. * **FP8.** `--quantization fp8` quantizes the BF16 weights at load time and measured about 20% more throughput on GB300 (84 vs 70 requests per second for short questions), with the same Belebele and WinoGrande scores. But its probabilities moved by 0.010 on average and up to 0.20 against the reference implementation, four times the drift of any BF16 configuration, and 0.9% of answers changed their top option. The calibrated probabilities are this model's output, so the recipes stay in BF16, and the Playground offers FP8 for workloads that only use the top choice. * **Reproducibility.** Two launches of the same recipe returned bit-identical probabilities for the same requests at the same concurrency. Against the checkpoint's reference implementation, the largest probability difference per question averages 0.003 (see [§3](#3-benchmarks)), because batch composition and kernels differ, and near-ties at 0.500 can flip. ## 3. Benchmarks All numbers in this section come from one NVIDIA GB300 (288 GB) at SGLang commit `70f0b7351e`, with checkpoint revision `5117a6c`, served with the GB300 recipe above unless a row says otherwise. **Method.** A closed-loop client keeps a fixed number of `/v1/systemone` requests in flight. Every request carries a unique random state, so requests share nothing but the system message, and each concurrency level starts after 8 warmup requests and a cache flush. Latency is the median end-to-end time of a request, and prompt tokens come from each response's `usage.input_tokens`. Four request shapes cover the common cases: one four-option choice question about a 256-token state, four questions (two choice, one yes or no, one score) about a 1,024-token state, one question about an 8,192-token state, and one question about a 1024×768 JPEG with a 64-token state. ### 3.1 Speed
Request Concurrent Median latency Requests/s Prompt tokens/s
Short question, 382 tokens 1 51 ms 19.4 7,413
4 103 ms 32.8 12,525
16 267 ms 59.0 22,531
64 882 ms 70.8 27,039
256 3,521 ms 71.1 27,164
Four questions on a 1K-token state, 4,540 tokens 1 179 ms 5.6 (22 decisions/s) 25,291
8 1,321 ms 6.0 (24 decisions/s) 27,332
32 5,206 ms 6.0 (24 decisions/s) 27,208
8K-token state, 8,224 tokens 1 325 ms 3.08 25,297
4 1,220 ms 3.26 26,785
16 4,796 ms 3.30 27,175
One 1024×768 image, 429 tokens 1 87 ms 11.5 4,945
16 414 ms 37.5 16,078
64 1,170 ms 52.6 22,572
One GB300 tops out at about 27,000 prompt tokens per second for every text shape, so requests per second follow from prompt length. Latency rises with concurrency once that ceiling is reached, so choose the concurrency from the latency you can accept. A decision has no output tokens, so in the benchmark card above TTFT is the whole request latency, and TPOT and interactivity do not apply. ### 3.2 Accuracy and parity Both sets go through `/v1/systemone` as one `choice` question per item. Belebele sends the passage as the state, the question as the instructions, and the four answers as options `1` to `4`. WinoGrande sends the sentence as the state, asks which option fills the blank, and offers the two candidates. The reference row runs the same items through the checkpoint's own `DecisionModel` one at a time.
Implementation Belebele (eng\_Latn, 900) WinoGrande (xl dev, 1,267)
SGLang, GB300 recipe **96.67%** **84.21%**
SGLang, no extra flag 96.67% 84.37%
Checkpoint's reference `DecisionModel` (Transformers, BF16, GB300) 96.67% 84.37%
Perplexity, model card (Perplexity API, its own prompt conversion) 94.00% 83.30%
Against the reference implementation, the recipe picks the same option on 2,161 of 2,167 items, and each of the six differences is a near-tie that one side scores 0.500 against 0.500 and the other 0.486 against 0.514. Per item, the largest probability difference averages 0.003 (99th percentile 0.024, maximum 0.054). Perplexity's figures come from a different prompt conversion, so they are context rather than a target. ### 3.3 What else was measured
Change from the GB300 recipe Measured effect Verdict
Prefix cache on (no extra flag) Short question 58 ms alone, 8K-token state 377 ms alone and 2.87 requests/s saturated (recipe: 51 ms, 325 ms, 3.30) Only for traffic that repeats identical requests
`--linear-attn-prefill-backend flashinfer` Text 4-8% faster (8K-token state 300 ms, 3.56 requests/s), images slower (101 ms alone, 9% less throughput) Text-only traffic
`--dp-size 2` (2 GPUs) 139 short questions/s and 6.5 8K-token states/s, four questions on a 1K-token state in 104 ms, a lone short question 15 ms slower Scale-out
`--tp 2` (2 GPUs) 8K-token state 208 ms alone, 124 short questions/s saturated, a lone short question in 68 ms Long states with a latency target
`--quantization fp8` About 20% more throughput, same accuracy, probabilities shifted by 0.010 on average and up to 0.20 Only when you use the top choice alone
`--chunked-prefill-size 32768 --max-prefill-tokens 32768` No gain (within 4%) Keep the default
`--mamba-ssm-dtype bfloat16` No gain, though it halves the state pool Keep the default
> **Check accuracy on your deployment (Python)** > > ```python Example theme={null} > import asyncio > > import aiohttp > from datasets import load_dataset > > URL = "http://localhost:30000/v1/systemone" > > > async def main(): > rows = load_dataset("facebook/belebele", "eng_Latn", split="test") > limit = asyncio.Semaphore(32) > > async def ask(session, row): > body = { > "model": "perplexity-ai/pplx-decider-v1-27b", > "state": row["flores_passage"], > "questions": { > "answer": { > "type": "choice", > "instructions": row["question"], > "criteria": {str(k): row[f"mc_answer{k}"] for k in range(1, 5)}, > } > }, > } > async with limit, session.post(URL, json=body) as response: > response.raise_for_status() > answer = (await response.json())["answers"]["answer"] > return answer["choice"] == row["correct_answer_num"] > > async with aiohttp.ClientSession() as session: > correct = await asyncio.gather(*(ask(session, row) for row in rows)) > print(f"Belebele eng_Latn: {sum(correct)}/{len(correct)} = {100 * sum(correct) / len(correct):.2f}%") > > > asyncio.run(main()) > ``` > **Example Output** > > ```text Output theme={null} > Belebele eng_Latn: 870/900 = 96.67% > ``` > **Measure speed on your deployment (Python)** > > Run it as `python bench.py `. With 270 words, a request is 378 tokens, close to the short shape above. > > ```python Example theme={null} > import asyncio > import random > import statistics > import sys > import time > > import aiohttp > > BASE = "http://localhost:30000" > STATE_WORDS, CONCURRENCY, REQUESTS = int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]) > WORDS = ("customer payment refund invoice order delivery account login error update server outage " > "contract price plan report urgent today please help the a and with for from to of in on").split() > QUESTION = { > "type": "choice", > "instructions": "Which team should handle this request?", > "criteria": {"billing": "Charges and refunds", "technical_support": "Integration errors", > "sales": "Questions about buying a product", "legal": "Contracts and liability"}, > } > > > def body(rng): > # A unique random state per request, so no request reuses another's cache. > state = " ".join(rng.choices(WORDS, k=STATE_WORDS)) > return {"model": "perplexity-ai/pplx-decider-v1-27b", "state": state, "questions": {"q": QUESTION}} > > > async def main(): > rng = random.Random(0) > bodies = [body(rng) for _ in range(REQUESTS)] > latencies, tokens = [], 0 > async with aiohttp.ClientSession() as session: > for item in [body(rng) for _ in range(8)]: # warmup > async with session.post(f"{BASE}/v1/systemone", json=item) as response: > response.raise_for_status() > async with session.post(f"{BASE}/flush_cache") as response: > await response.read() > queue = iter(bodies) > > async def worker(): > nonlocal tokens > for item in queue: > start = time.perf_counter() > async with session.post(f"{BASE}/v1/systemone", json=item) as response: > response.raise_for_status() > tokens += (await response.json())["usage"]["input_tokens"] > latencies.append(time.perf_counter() - start) > > start = time.perf_counter() > await asyncio.gather(*(worker() for _ in range(CONCURRENCY))) > elapsed = time.perf_counter() - start > print(f"{REQUESTS / elapsed:.1f} req/s, {tokens / elapsed:.0f} prompt tok/s, " > f"P50 {1000 * statistics.median(latencies):.1f} ms, {tokens / REQUESTS:.0f} tokens/request") > > > asyncio.run(main()) > ``` > **Example Output** > > ```text Output theme={null} > $ python bench.py 270 1 64 > 19.6 req/s, 7393 prompt tok/s, P50 51.0 ms, 378 tokens/request > $ python bench.py 270 64 512 > 68.4 req/s, 25865 prompt tok/s, P50 899.0 ms, 378 tokens/request > ``` ## 4. Advanced Usage ### 4.1 Text Decisions > **Text Decision Example (Python)** > > ```python Example theme={null} > import requests > > response = requests.post( > "http://localhost:30000/v1/systemone", > json={ > "model": "perplexity-ai/pplx-decider-v1-27b", > "state": "My Stripe integration keeps failing. I'm losing sales. Please help ASAP.", > "questions": { > "routing": { > "type": "choice", > "instructions": "Which team should handle this request?", > "criteria": { > "billing": "Charges and refunds", > "technical_support": "Integration errors", > "sales": "Questions about buying a product", > }, > }, > "urgency": {"type": "noul", "instructions": "Does this message express urgency?"}, > }, > }, > timeout=60, > ) > response.raise_for_status() > for name, answer in response.json()["answers"].items(): > print(name, answer) > ``` > **Example Output** > > ```text Output theme={null} > routing {'type': 'choice', 'choice': 'technical_support', 'confidence': 0.987854396908662, 'probabilities': {'billing': 0.004840538662952211, 'technical_support': 0.9919029312724412, 'sales': 0.0032565300646064375}} > urgency {'type': 'noul', 'noul': 0.9929980993021188} > ``` ### 4.2 Image Decisions The example output below came from a mostly red test image. > **Image Decision Example (Python)** > > ```python Example theme={null} > import base64 > from pathlib import Path > > import requests > > image = base64.b64encode(Path("screenshot.png").read_bytes()).decode("ascii") > response = requests.post( > "http://localhost:30000/v1/systemone", > json={ > "model": "perplexity-ai/pplx-decider-v1-27b", > "state": "Look at the supplied image.", > "images": [image], > "questions": { > "color": { > "type": "choice", > "instructions": "What is the dominant color?", > "criteria": {"red": "Red", "green": "Green", "blue": "Blue", "other": "Another color"}, > } > }, > }, > timeout=60, > ) > response.raise_for_status() > print(response.json()["answers"]["color"]) > ``` > **Example Output** > > ```text Output theme={null} > {'type': 'choice', 'choice': 'red', 'confidence': 0.9498445161931509, 'probabilities': {'red': 0.9623833871448632, 'green': 0.009006826727044857, 'blue': 0.00926546931819573, 'other': 0.01934431680989631}} > ``` # PPLX-Decider-v1.1-27B Source: https://docs.sglang.io/cookbook/autoregressive/Perplexity/PPLX-Decider-v1.1-27B Deploy PPLX-Decider-v1.1-27B with SGLang. Perplexity's updated decision model reads the whole prompt in its full-attention layers and returns calibrated probabilities for choice, yes or no, and score questions on /v1/systemone, on one NVIDIA GB300 or H200 in BF16. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. PPLX-Decider-v1.1 support lands in [#42645](https://github.com/sgl-project/sglang/pull/42645), after v0.5.21, so until a release includes it, install a [nightly build](/docs/get-started/install#nightly-builds) built after that merge. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow --index-strategy unsafe-best-match --extra-index-url https://docs.sglang.ai/whl/cu130/ sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev > ``` > > The image is multi-arch, so the same tag runs on x86 H200 hosts and Arm GB300 hosts. For how to launch it, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your GPU to generate the launch command. The model runs on one GPU in BF16 and needs no flag: SGLang reads the checkpoint's `decision_config.json`, runs the full-attention layers over the whole prompt as the model was trained, and turns off the radix cache and chunked prefill, which would show those layers only part of the prompt. > [!NOTE] > > The GB300 recipe was measured end to end on one GB300 at [#42645](https://github.com/sgl-project/sglang/pull/42645): four request shapes from 1 to 256 concurrent requests, Belebele and WinoGrande accuracy, and per-question parity with the checkpoint's own reference implementation. The H200 command is the same and has not been run yet. [§3](#3-benchmarks) has the method and the full tables. ## Playground The Playground layers SGLang features on top of the recipe above. Any override changes the badge to **Not Verified** until that exact configuration is tested end to end. The [Configuration Tips](#2-configuration-tips) say which overrides were measured on GB300. Tensor parallelism times data-parallel replicas must fit the GPUs on one node. ## 1. Model Introduction **PPLX-Decider-v1.1-27B** is the successor to [PPLX-Decider-v1-27B](/cookbook/autoregressive/Perplexity/PPLX-Decider-v1-27B), Perplexity's decision model fine-tuned from [Qwen3.8-27B](/cookbook/autoregressive/Qwen/Qwen3.8-27B) under the Apache-2.0 license. Like v1, it replaces the language model head with a readout over 255 answer codes and answers choice, yes or no (`noul`), and score questions about a text state and optional images with a probability for every option, without generating text. Two things changed. The 16 full-attention layers no longer use a causal mask, so every token attends to the whole prompt, while the 48 Gated DeltaNet layers stay causal. And training grew from 73,000 to 626,033 rows, most of them from [tasksource](https://github.com/sileod/tasksource). The prompt format, answer codes, and readout layout are the same as v1's, but the calibrated temperature is 1.0087 instead of 2.2076, so probabilities from the two versions are not interchangeable.
Property Value
Checkpoint [perplexity-ai/pplx-decider-v1.1-27b](https://huggingface.co/perplexity-ai/pplx-decider-v1.1-27b) (BF16)
Base model Qwen3.8-27B, one epoch of supervised fine-tuning on 626,033 decision rows (530,103 from tasksource)
Attention Noncausal in the 16 full-attention layers, causal in the 48 Gated DeltaNet layers
Question types `choice` (up to 255 options), `noul` (yes or no), `score` (up to 10 levels)
Inputs Text or JSON state, optional images
Prompt length Trained on question prompts of up to 8,192 tokens, and the backbone accepts 262,144
License Apache-2.0
Perplexity reports a Decision Index of 61.56 for v1.1, up from 56.4 for v1:
Decision Index category Jev PPLX-Decider-v1-27B PPLX-Decider-v1.1-27B
Knowledge **51.4** 40.9 48.18
Language 62.0 63.5 **69.45**
Retrieval 55.4 54.9 **61.26**
Tools 75.1 **79.3** 78.88
Arts 37.7 39.4 **44.66**
**Overall** 57.9 56.4 **61.56**
**Resources:** [HuggingFace](https://huggingface.co/perplexity-ai/pplx-decider-v1.1-27b), [reference model code](https://huggingface.co/perplexity-ai/pplx-decider-v1.1-27b/blob/main/source/src/autojev/model.py), [Decision models in SGLang](/docs/supported-models/decision_models). ## 2. Configuration Tips * **Route.** Send requests to `/v1/systemone`, the System One API the checkpoint was trained for. `/v1/decisions` refuses this checkpoint because its labels and prompt are not the ones the readout learned, and chat or generation requests are not meaningful without a language model head. * **Clients.** Clients of the System One API, including the TypeSafe SDKs, work by pointing their base URL at the server. See [System One compatible API](/docs/supported-models/decision_models#system-one-compatible-api) for the request and response reference. * **Images.** Pass each image in `images` as base64 bytes, a base64 data URL, or an `http(s)` URL. They precede the text in every question. The processor resizes every image to between 65,536 and 262,144 pixels, so one image costs 64 to 256 prompt tokens. * **Noncausal attention is automatic.** SGLang reads `attention_mode: noncausal_full_attention` from `decision_config.json` and runs the full-attention layers as encoder layers, which the TRT-LLM, FlashInfer, and Triton attention backends support. It also turns off the radix cache and chunked prefill, logging `Radix cache and chunked prefill are disabled for a decision checkpoint with noncausal full attention`: a cached prefix or a prefill chunk would see only part of a prompt whose every position depends on the rest. These two settings override any flag you pass. A prompt longer than the 16,384-token prefill budget is still read in one pass: an 18,585-token prompt matched the reference implementation to four decimal places on GB300. * **No prefix reuse.** Because every layer output depends on the whole prompt, nothing carries over between requests, not even an identical one. The cost of a request is roughly *questions × prompt tokens*, as on v1. * **Prompt length.** Like v1, the model was trained on question prompts of up to 8,192 tokens, and the reference code refuses longer ones. SGLang serves longer prompts in one pass, but their accuracy is untested. * **Attention backend.** On GB300, Auto resolves to the TRT-LLM kernel with 64-token pages. `--attention-backend flashinfer` and `--attention-backend triton` matched the reference implementation as closely, with the same top option on 99.8% of the accuracy items. The H200 path has not been run yet. * **Speed.** One GB300 reads about 27,000 prompt tokens per second once batches are full, the same as v1. Measured back to back on the same GPU against v1's recipe, v1.1 was within 2% on short questions and four-question requests, and an 8K-token state saturated 6% lower (3.13 against 3.32 requests per second), because noncausal attention computes the full attention matrix in its 16 full-attention layers instead of half of it. * **More GPUs.** The backbone and prompt sizes are v1's, so the [v1 page's scaling measurements](/cookbook/autoregressive/Perplexity/PPLX-Decider-v1-27B#2-configuration-tips) are the reference: data-parallel replicas (`--dp-size N`) for throughput, tensor parallelism only for latency on long prompts. They were not repeated for v1.1. * **Upgrading from v1.** Re-check any thresholds you tuned on v1 probabilities: v1.1 has a different temperature and changed its top answer on 8% of the Belebele and WinoGrande items. ## 3. Benchmarks All numbers in this section come from one NVIDIA GB300 (288 GB) at [#42645](https://github.com/sgl-project/sglang/pull/42645), with checkpoint revision `3b45dea`, served with the GB300 recipe above unless a row says otherwise. The method and request shapes are those of the [v1 page](/cookbook/autoregressive/Perplexity/PPLX-Decider-v1-27B#3-benchmarks), whose speed script works here unchanged. ### 3.1 Speed
Request Concurrent Median latency Requests/s Prompt tokens/s
Short question, 382 tokens 1 53 ms 18.9 7,203
4 106 ms 37.6 14,362
16 275 ms 57.4 21,909
64 931 ms 67.5 25,770
256 3,489 ms 71.1 27,139
Four questions on a 1K-token state, 4,540 tokens 1 183 ms 5.5 (22 decisions/s) 24,782
8 1,315 ms 6.0 (24 decisions/s) 27,398
32 4,882 ms 6.1 (24 decisions/s) 27,649
8K-token state, 8,224 tokens 1 334 ms 2.99 24,620
4 1,280 ms 3.12 25,682
16 5,101 ms 3.13 25,726
One 1024×768 image, 429 tokens 1 118 ms 8.3 3,541
16 466 ms 33.6 14,398
64 1,197 ms 49.9 21,416
### 3.2 Accuracy and parity Both sets go through `/v1/systemone` as one `choice` question per item, with the same conversion as the v1 page. The reference rows run the same items through the checkpoint's own `DecisionModel` one at a time.
Implementation Belebele (eng\_Latn, 900) WinoGrande (xl dev, 1,267)
SGLang, GB300 recipe (TRT-LLM attention) **97.67%** **92.42%**
SGLang, `--attention-backend flashinfer` 97.67% 92.58%
SGLang, `--attention-backend triton` 97.67% 92.42%
Checkpoint's reference `DecisionModel` (Transformers, BF16, GB300) 97.67% 92.50%
v1.1 served with causal attention, as SGLang did before #42645 97.00% 88.87%
PPLX-Decider-v1-27B on SGLang, for comparison 96.67% 84.21%
Against the reference implementation, the recipe picks the same option on 2,164 of 2,167 items, and each of the three differences is a near-tie within 0.031 of an even split. Per item, the largest probability difference averages 0.002 (99th percentile 0.030, maximum 0.089). Prompts of 11,099 and 18,585 tokens, an image question, and a score question also matched the reference, the largest difference being 0.015 on the score question. Served with causal attention instead, v1.1 changed its top answer on 101 of the 2,167 items and lost 3.6 points on WinoGrande. > **Check accuracy on your deployment (Python)** > > ```python Example theme={null} > import asyncio > > import aiohttp > from datasets import load_dataset > > URL = "http://localhost:30000/v1/systemone" > > > async def main(): > rows = load_dataset("facebook/belebele", "eng_Latn", split="test") > limit = asyncio.Semaphore(32) > > async def ask(session, row): > body = { > "model": "perplexity-ai/pplx-decider-v1.1-27b", > "state": row["flores_passage"], > "questions": { > "answer": { > "type": "choice", > "instructions": row["question"], > "criteria": {str(k): row[f"mc_answer{k}"] for k in range(1, 5)}, > } > }, > } > async with limit, session.post(URL, json=body) as response: > response.raise_for_status() > answer = (await response.json())["answers"]["answer"] > return answer["choice"] == row["correct_answer_num"] > > async with aiohttp.ClientSession() as session: > correct = await asyncio.gather(*(ask(session, row) for row in rows)) > print(f"Belebele eng_Latn: {sum(correct)}/{len(correct)} = {100 * sum(correct) / len(correct):.2f}%") > > > asyncio.run(main()) > ``` > **Example Output** > > ```text Output theme={null} > Belebele eng_Latn: 879/900 = 97.67% > ``` ## 4. Advanced Usage ### 4.1 Text Decisions > **Text Decision Example (Python)** > > ```python Example theme={null} > import requests > > response = requests.post( > "http://localhost:30000/v1/systemone", > json={ > "model": "perplexity-ai/pplx-decider-v1.1-27b", > "state": "My Stripe integration keeps failing. I'm losing sales. Please help ASAP.", > "questions": { > "routing": { > "type": "choice", > "instructions": "Which team should handle this request?", > "criteria": { > "billing": "Charges and refunds", > "technical_support": "Integration errors", > "sales": "Questions about buying a product", > }, > }, > "urgency": {"type": "noul", "instructions": "Does this message express urgency?"}, > }, > }, > timeout=60, > ) > response.raise_for_status() > for name, answer in response.json()["answers"].items(): > print(name, answer) > ``` > **Example Output** > > ```text Output theme={null} > routing {'type': 'choice', 'choice': 'technical_support', 'confidence': 0.9977658531751561, 'probabilities': {'billing': 0.0014030901008239556, 'technical_support': 0.9985105687834377, 'sales': 8.634111573847184e-05}} > urgency {'type': 'noul', 'noul': 0.9995671977710632} > ``` ### 4.2 Image Decisions The example output below came from a 512×512 solid red test image. > **Image Decision Example (Python)** > > ```python Example theme={null} > import base64 > from pathlib import Path > > import requests > > image = base64.b64encode(Path("screenshot.png").read_bytes()).decode("ascii") > response = requests.post( > "http://localhost:30000/v1/systemone", > json={ > "model": "perplexity-ai/pplx-decider-v1.1-27b", > "state": "Look at the supplied image.", > "images": [image], > "questions": { > "color": { > "type": "choice", > "instructions": "What is the dominant color?", > "criteria": {"red": "Red", "green": "Green", "blue": "Blue", "other": "Another color"}, > } > }, > }, > timeout=60, > ) > response.raise_for_status() > print(response.json()["answers"]["color"]) > ``` > **Example Output** > > ```text Output theme={null} > {'type': 'choice', 'choice': 'red', 'confidence': 0.9989117512916561, 'probabilities': {'red': 0.9991838134687421, 'green': 6.743375714875418e-05, 'blue': 8.12085765657198e-05, 'other': 0.0006675441975434462}} > ``` # Laguna-M.1 Source: https://docs.sglang.io/cookbook/autoregressive/Poolside/Laguna-M.1 Deploy poolside's Laguna-M.1 — a 225B-parameter Mixture-of-Experts model (23B active) for agentic coding — with SGLang on NVIDIA H200, B200, B300, GB200, and GB300, across BF16, FP8, and NVFP4. ## Deployment > **Install SGLang** > > Laguna-M.1 support is already on SGLang `main` — **softplus per-element attention-output gating** ([PR #28400](https://github.com/sgl-project/sglang/pull/28400)) and a **global-attention fix** ([PR #28604](https://github.com/sgl-project/sglang/pull/28604), since M.1 is full-attention `sliding_window: 0`) — but not yet in a tagged release. The two paths below match the **Python / Docker** toggle in the command panel: install from `main` (Python tab), or use the **Docker** image, which bundles the same build (CUDA 13, covers H200 + all Blackwell). The model ships custom config code on the Hub, so `--trust-remote-code` is required (it is included in the launch commands). > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install -U uv > uv venv --python 3.12 && source .venv/bin/activate > > # Laguna-M.1 support is on SGLang main (PRs #28400 + #28604, plus #28649 for FP8), not yet in a > # tagged release — install from main. The serving runtime is in the base dependencies, no extra needed: > git clone https://github.com/sgl-project/sglang.git > cd sglang > uv pip install --prerelease=allow -e python > ``` > > Then run the **Python** output of the command panel below in that environment. The **Docker** tab is simpler — `lmsysorg/sglang:latest` bundles the CUDA-13 runtime and the M.1 code. > > **Docker** > > ```bash Command theme={null} > # CUDA 13 — covers H200 + all Blackwell: > docker pull lmsysorg/sglang:latest > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your hardware + quantization to generate the launch command. Laguna-M.1 ships a single **Balanced** recipe per cell — poolside's recommended operating point, a good speed/throughput trade-off for typical multi-user serving. The 8-GPU HGX platforms (H200 / B200 / B300) use `--tp 8`; the 4-GPU Grace-Blackwell single nodes (GB200 / GB300) use `--tp 4`. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs (parsers, DP-Attention, DeepEP / EP) on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction [Laguna-M.1](https://huggingface.co/poolside/Laguna-M.1) is an open-weight, **225B-parameter** Mixture-of-Experts model (**23B activated per token**) from [poolside](https://poolside.ai), built for agentic coding and long-horizon software-engineering work. It is released under Apache 2.0. **Key Features:** * **Large sparse MoE**: 70-layer transformer — the first 3 layers are dense SwiGLU, the remaining 67 are sparse MoE with **256 experts, top-16 routing** (+1 shared expert) and auxiliary-loss-free load balancing. * **Global attention with output gating**: global attention across all layers, 64 Q-heads / 8 KV-heads (head dim 128), with **softplus attention output gating** (requires [PR #28400](https://github.com/sgl-project/sglang/pull/28400)). * **Long context**: 262,144 tokens, RoPE with YaRN. * **Agentic coding**: competitive on SWE-bench Verified, SWE-bench Multilingual, SWE-Bench Pro, and Terminal-Bench 2.0. * **Native reasoning**: interleaved thinking between tool calls, toggled per request via `chat_template_kwargs={"enable_thinking": ...}`. **Available Quantizations:**
Quantization Hugging Face path
**BF16** [`poolside/Laguna-M.1`](https://huggingface.co/poolside/Laguna-M.1)
**FP8** [`poolside/Laguna-M.1-FP8`](https://huggingface.co/poolside/Laguna-M.1-FP8)
**NVFP4** [`poolside/Laguna-M.1-NVFP4`](https://huggingface.co/poolside/Laguna-M.1-NVFP4)
**License:** Apache 2.0 **Resources:** [Hugging Face](https://huggingface.co/poolside/Laguna-M.1) · [Release blog post](https://poolside.ai/blog/laguna-a-deeper-dive) · [Technical report](https://poolside.ai/assets/laguna/laguna-m1-xs2-technical-report.pdf) · [API platform](https://platform.poolside.ai). ## 2. Configuration Tips * **Trust remote code** (`--trust-remote-code`): Laguna-M.1 ships custom modeling/config code on the Hugging Face Hub, so this flag is required for the server to load the model. * **Long-context memory**: M.1 is global-attention (no sliding-window), so the 262,144-token KV cache is large. If you hit OOM at full context, lower `--mem-fraction-static` or cap `--context-length`. * **FP8**: On **Blackwell** the recipe adds `--fp8-gemm-backend triton` — the compressed-tensors block-FP8 weight scales aren't UE8M0-packed, so the default DeepGEMM path emits garbage on Blackwell (sm\_100); the Triton backend is correct (\~19% slower). Temporary workaround pending [PR #28662](https://github.com/sgl-project/sglang/pull/28662) (which fixes the scales and restores the DeepGEMM fast path). On **Hopper (H200)** FP8 uses DeepGEMM with no extra flag — pre-warm its multi-session JIT with `python3 -m sglang.compile_deep_gemm --model poolside/Laguna-M.1-FP8` to avoid paying it on each restart. * **Parsers** (`poolside_v1`): for agentic / tool-using deployments enable the **Reasoning Parser** and **Tool Call Parser** in the Playground above — they emit `--reasoning-parser poolside_v1` (thinking → `reasoning_content`) and `--tool-call-parser poolside_v1` (structured `tool_calls`). * **Thinking default**: thinking is **off by default**; opt in per request with `extra_body={"chat_template_kwargs": {"enable_thinking": True}}`. * **Served model id**: the server registers the model under whatever you pass to `--model-path`, so a client's `model` field must match it — `poolside/Laguna-M.1` (BF16) or `poolside/Laguna-M.1-FP8` / `-NVFP4` for the quantized cells. The §3 examples use the BF16 id; swap in the id you launched. * **Recommended sampling**: poolside benchmarks M.1 at `temperature=1.0`, `top_k=20` with thinking enabled. These are per-request sampling params (not launch flags) — e.g. `temperature=1.0, extra_body={"top_k": 20}` on the OpenAI client. ## 3. Advanced Usage ### 3.1 Reasoning Launch with `--reasoning-parser poolside_v1` (or toggle **Reasoning Parser** in the **Parsers** card of the Playground above). Reasoning is **opt-in**: the Laguna chat template gates it on `enable_thinking=True` (passed via `chat_template_kwargs`) — the generic `thinking` key is ignored. The `` trace then lands in `message.reasoning_content`, separate from the final answer in `message.content` — no client-side tag stripping needed. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="poolside/Laguna-M.1", > messages=[{"role": "user", "content": "What is 15% of 240? Explain briefly."}], > max_tokens=2048, > extra_body={"chat_template_kwargs": {"enable_thinking": True}}, > ) > > message = response.choices[0].message > print("=============== Reasoning ===============") > print(message.reasoning_content) > print("=============== Answer ==================") > print(message.content) > ``` > **Example Output** > > ```text Output theme={null} > =============== Reasoning =============== > Okay, so I need to find out what 15% of 240 is. Hmm, percentages can sometimes be > tricky, but let me think. I remember that "percent" means per hundred, right? So 15% > is the same as 15 per 100 or 15/100. Maybe I can convert that percentage into a decimal > first? ... 15 divided by 100 is 0.15. ... Now, to find 15% of 240, I just need to > multiply 240 by 0.15. ... 240 times 0.1 is 24 (10% of 240), and 240 times 0.05 is 12 > (half of that), so 24 + 12 = 36. > [… verifies the same result several more ways: 15/100 × 240, 240 × 15 ÷ 100, > 1% × 15, and the fraction 3/20 × 240 — all give 36 …] > So ... all methods are pointing to 36. I'm pretty confident that 15% of 240 is 36. > =============== Answer ================== > To find 15% of 240, convert the percentage to a decimal (0.15) and multiply by 240: > **240 × 0.15 = 36**. > > **Step-by-Step Explanation:** > 1. **Convert 15% to a decimal:** 15% = 15/100 = 0.15. > 2. **Multiply by 240:** > - Break it down: > - 10% of 240 = 24 (since 240 × 0.1 = 24). > - 5% of 240 = 12 (half of 24). > - Add them: 24 + 12 = **36**. > > **Answer:** 15% of 240 is **36**. > ``` > [!NOTE] > > Laguna-M.1's reasoning traces are long — the model explores and re-verifies an answer > multiple ways. Give it a generous `max_tokens` for harder problems (reasoning regularly > exceeds 3k tokens). The trace above is abbreviated; the model emits it in full. ### 3.2 Tool Calling Launch with `--tool-call-parser poolside_v1` (or toggle **Tool Call Parser** in the **Parsers** card of the Playground above). The parser converts Laguna's `` output into the standard OpenAI `tool_calls` structure. Tool calling works with reasoning off (`enable_thinking=False`, the default). > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["location"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="poolside/Laguna-M.1", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > > message = response.choices[0].message > if message.tool_calls: > for call in message.tool_calls: > print(f"Tool: {call.function.name}") > print(f"Args: {call.function.arguments}") > ``` > **Example Output** > > ```text Output theme={null} > Tool: get_weather > Args: {"location": "Beijing"} > ``` ### 3.3 Prefill-Decode (PD) Disaggregation [PD disaggregation](../../../docs/advanced_features/pd_disaggregation) runs prefill and decode on **separate** SGLang servers linked by an RDMA KV-transfer fabric (mooncake or NIXL), fronted by the PD router. Laguna-M.1 is **global-attention with a standard KV cache** (no sliding window, no sparse "index" side-buffer), so its KV pages transfer with **no model-specific flags** — just the `--disaggregation-*` knobs. Both roles auto-select the same attention backend (FlashAttention-3) and page size because they share the model and flags, so the KV layout lines up for transfer. **Supported / validated topology:** * **Equal tensor parallelism** — prefill and decode run the same `--tp`. * **Single pipeline stage** — PP = 1 (the default). * **mooncake or NIXL** transfer backend over RDMA / InfiniBand. * Validated on **2 × 8×H200** (TP8 prefill + TP8 decode, BF16), one node each, over an 8× 400 Gb/s NDR InfiniBand fabric. Launch the prefill server, then the decode server — the same recipe with `--disaggregation-mode decode` and no bootstrap port. Point `--disaggregation-ib-device` at your RDMA NIC(s). ```bash Prefill server (node A) theme={null} sglang serve \ --model-path poolside/Laguna-M.1 \ --trust-remote-code \ --reasoning-parser poolside_v1 \ --tool-call-parser poolside_v1 \ --tp 8 \ --disaggregation-mode prefill \ --disaggregation-transfer-backend mooncake \ --disaggregation-ib-device mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7 \ --host 0.0.0.0 --port 30000 \ --disaggregation-bootstrap-port 8998 ``` ```bash Decode server (node B) theme={null} sglang serve \ --model-path poolside/Laguna-M.1 \ --trust-remote-code \ --reasoning-parser poolside_v1 \ --tool-call-parser poolside_v1 \ --tp 8 \ --disaggregation-mode decode \ --disaggregation-transfer-backend mooncake \ --disaggregation-ib-device mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7 \ --host 0.0.0.0 --port 30001 ``` Then start the PD router, pointing it at the prefill bootstrap (URL plus its `--disaggregation-bootstrap-port`) and the decode endpoint: ```bash PD router theme={null} python3 -m sglang_router.launch_router \ --pd-disaggregation \ --prefill http://:30000 8998 \ --decode http://:30001 \ --policy round_robin \ --host 0.0.0.0 --port 8000 ``` Clients hit the router exactly like a single server — it splits each request across the two stages transparently: > **PD Client Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://:8000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="poolside/Laguna-M.1", > messages=[{"role": "user", "content": "What is 2 + 2?"}], > max_tokens=64, > ) > print(response.choices[0].message.content) > ``` > > **Output Example:** > > ```text Output theme={null} > 2 + 2 = 4 > ``` **Transfer backend — mooncake (recommended).** mooncake honors `--disaggregation-ib-device` and establishes its RDMA connection at registration, so the **first request is already fast** (no cold start). It works with a single NIC or all eight; using **all 8 NICs lowers TTFT** (more aggregate bandwidth for the KV payload — the gap widens at longer context). On 8×H200 (random isl=512 / osl=256, 16 concurrent) it served ≈ **717 tok/s** output (≈ 2.2k tok/s total), mean **TTFT 244 ms**, mean **TPOT 17.7 ms**; with a single `mlx5_0` NIC, ≈ 697 tok/s and TTFT 287 ms (TPOT unchanged — decode is compute-bound). **Transfer backend — NIXL (works, with two caveats).** > [!WARNING] > > The NIXL path **ignores `--disaggregation-ib-device`** — that flag is mooncake-only. NIXL uses its UCX backend, whose NIC is selected by the **`UCX_NET_DEVICES`** environment variable. **Set it** (e.g. `export UCX_NET_DEVICES=mlx5_0:1`) on both servers; without it UCX cannot establish a working cross-node path and every KV transfer hangs until it hits the 300 s timeout (`Request … timed out … in KVPoll.WaitingForInput`) and returns a 500. With `UCX_NET_DEVICES` pinned, NIXL matches mooncake on quality and steady-state speed (≈ 720 tok/s, TTFT 230 ms, TPOT 17.7 ms). One difference: the **first request after launch pays a \~38 s one-time UCX connection cold-start** (a single port or all eight behave the same). Warm the path with one throwaway request after startup, or raise `SGLANG_DISAGGREGATION_WAITING_TIMEOUT` (default 300 s) so the first real request isn't dropped while UCX connects. **Validation.** PD disaggregation preserves output quality — disaggregated output matches non-disaggregated serving, and GSM8K (no-thinking, 200-question subset via the router) scored **0.945** (mooncake, 8 NICs) / **0.940** (NIXL) / **0.950** (mooncake, 1 NIC), all with 100% stop-rate and 0% errors — in line with single-node BF16 (≈ 0.93 on the full split). Logs confirm the split: the prefill node logs `Prefill batch` (CUDA graph off), the decode node logs `Decode batch` (CUDA graph on). # Laguna-S-2.1 Source: https://docs.sglang.io/cookbook/autoregressive/Poolside/Laguna-S-2.1 Deploy poolside's Laguna-S-2.1 — a 118B hybrid-SWA Mixture-of-Experts model (8B active) for agentic coding — with SGLang on NVIDIA H200, B300, and GB300 in BF16, FP8, NVFP4, and INT4. ## Deployment > **Install SGLang** > > Laguna-S-2.1 uses the same `laguna` model architecture as [Laguna-XS-2.1](./Laguna-XS-2.1), which is fully supported in SGLang `main`. The model ships custom config code on the Hub, so `--trust-remote-code` is required (included in the launch commands). > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install -U uv > uv venv --python 3.12 && source .venv/bin/activate > > git clone https://github.com/sgl-project/sglang.git > cd sglang > uv pip install --prerelease=allow -e python > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your hardware + quantization + strategy to generate the launch command. The two serving strategies cover the common operating points: * **Low-latency** — DFlash speculative decoding with a matched draft model. Pick for chat and interactive agents. * **High-throughput** — plain serving. Best for batch workloads, where speculation's draft + rejection overhead costs more than it saves. On the 8-GPU HGX platforms (H200 / B300) all quantizations run `--tp 8`. The 4-GPU GB300 node runs `--tp 4` throughout. NVFP4 is Blackwell-only (B300 / GB300 only). ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations that have been signed off; the Playground lets you turn on additional knobs (TP degree, parsers) on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction [Laguna-S-2.1](https://huggingface.co/poolside/Laguna-S-2.1) is an open-weight **118B-parameter** hybrid sliding-window-attention MoE model (**\~8B active per token**) from [poolside](https://poolside.ai), built for agentic coding and long-horizon software engineering. It sits between [Laguna XS 2.1](./Laguna-XS-2.1) (33B/3B active) and Laguna M.1 (222B/23B active) in the Laguna family. **Key Features:** * **Sparse MoE**: 48 layers, 256 routed experts, top-10 routing, plus 1 shared expert. * **Hybrid attention**: 36 sliding-window layers (window 512) interleaved with 12 full-attention layers (1:3 global-to-SWA ratio); 8 KV heads, head dim 128; per-head sigmoid output gating with per-layer-type rotary scales. * **Long context**: 1,048,576 tokens. * **DFlash drafts**: matched draft models ship per quantization for low-latency serving. * **Hybrid reasoning**: `…` toggled per request via `chat_template_kwargs={"enable_thinking": …}`. **Available quantizations:**
Precision Target model Draft model
**BF16** [`poolside/Laguna-S-2.1`](https://huggingface.co/poolside/Laguna-S-2.1) [`poolside/Laguna-S-2.1-DFlash`](https://huggingface.co/poolside/Laguna-S-2.1-DFlash)
**FP8** [`poolside/Laguna-S-2.1-FP8`](https://huggingface.co/poolside/Laguna-S-2.1-FP8) [`poolside/Laguna-S-2.1-DFlash-FP8`](https://huggingface.co/poolside/Laguna-S-2.1-DFlash-FP8)
**NVFP4** [`poolside/Laguna-S-2.1-NVFP4`](https://huggingface.co/poolside/Laguna-S-2.1-NVFP4) [`poolside/Laguna-S-2.1-DFlash-NVFP4`](https://huggingface.co/poolside/Laguna-S-2.1-DFlash-NVFP4)
**INT4** [`poolside/Laguna-S-2.1-INT4`](https://huggingface.co/poolside/Laguna-S-2.1-INT4) [`poolside/Laguna-S-2.1-DFlash-INT4`](https://huggingface.co/poolside/Laguna-S-2.1-DFlash-INT4)
The drafts are small BF16 models, each *calibrated against its quantized target* — always pair a target with its matched draft (mixing precisions degrades accept-length). **License:** [OpenMDW-1.1](https://openmdw.ai/) **Resources:** [Hugging Face](https://huggingface.co/poolside/Laguna-S-2.1) · [Technical report](https://poolside.ai/assets/laguna/laguna-m1-xs2-technical-report.pdf) · [API platform](https://platform.poolside.ai) ## 2. Configuration Tips **Attention backend** Leave `--attention-backend` unset for High-throughput cells — auto-select is correct (`fa3` on Hopper, `trtllm_mha` on Blackwell). With DFlash active, auto-select instead falls back to `flashinfer`, which breaks this hybrid-SWA model at `tp ≥ 4` on Blackwell (reproduced on Laguna-XS-2.1, greedy GSM8K 76% → 28%), so the Low-latency commands pin the target backend explicitly. Leave `--speculative-draft-attention-backend` unset. Other attention backend choices have not been fully validated on Laguna; keep the default. **BF16 memory on H200** BF16 on H200 leaves less headroom for CUDA-graph capture and NCCL allocations than FP8/INT4. The High-throughput BF16 command carries `--mem-fraction-static 0.80`. FP8, INT4, and all B300/GB300 cells use the default heuristic. **FP8 shared expert** `SGLANG_SHARED_EXPERT_TP1=1` is required for FP8 cells on **all hardware** — confirmed on both H200 (TP=8) and GB300 (TP=4). The FP8 checkpoint block-quantizes the shared expert (128×128 scales), which cannot TP-shard cleanly at either TP degree on S-2.1. This env var replicates the shared expert instead of sharding it. INT4 keeps the shared expert in BF16 (no flag needed); BF16 is unquantized. Note: this differs from Laguna-XS-2.1 where TP=4 does not require the flag — the constraint is architecture-specific. **FP8 and NVFP4 DFlash drafts** Fixed upstream on 2026-07-21: all DFlash draft configs now use a flat top-level `rope_theta` (the `rope_parameters` block was removed). If a server crashes at draft-model load with `KeyError: 'rope_theta'`, you are serving a draft checkpoint cached before 2026-07-21 — re-download it (e.g. `hf download poolside/Laguna-S-2.1-DFlash-FP8`) to pick up the corrected config. **DFlash memory** Low-latency cells carry `--mem-fraction-static 0.7` (sufficient even for BF16 on H200). Dense cells use the default heuristic (except BF16 on H200 — see above). **BF16 reasoning length** BF16 reasons approximately 2× longer than FP8/INT4 on AIME25 (median 34.8 k vs 16.9 k tokens), consistently truncating at `max_tokens=64000`. FP8/INT4 truncate at ≈ 2%. For a valid BF16 AIME25 score, serve with `max_tokens ≥ 131072` (the model supports a 1 M context window). **Chat template** On transformers ≥ 5.10 the standalone `chat_template.jinja` auto-loads — no flag needed (the server logs `Auto-detected template features: reasoning_parser=poolside_v1, ...`). On older transformers (≤ \~5.8) pass `--chat-template /chat_template.jinja` explicitly. **Thinking** Off by default; opt in per request with `extra_body={"chat_template_kwargs": {"enable_thinking": True}}`. The template gates on `enable_thinking` — the generic `thinking` key is ignored. **Served model id** The server registers the model under whatever you pass to `--model-path`; a client's `model` field must match it (`poolside/Laguna-S-2.1`, or the `-FP8` / `-NVFP4` / `-INT4` id). ## 3. Advanced Usage ### 3.1 DFlash Speculative Decoding DFlash is a block-wise speculative decoder: the draft proposes a block of tokens and the target verifies the whole block in one forward pass — output quality is the target's by construction. The speedup lever is **accept-length**, the number of draft tokens surviving verification per target step. Best for interactive / few-stream serving. Under batch-saturated load prefer High-throughput: once the GPU is compute-bound, draft + rejected-token overhead costs aggregate throughput. The generated commands always pair the draft calibrated for the selected target precision. ### 3.2 Reasoning Launch with `--reasoning-parser poolside_v1` (baked into every generated command). Reasoning is opt-in via `enable_thinking=True`; the `` trace lands in `message.reasoning_content`, separate from the final answer in `message.content`. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="poolside/Laguna-S-2.1", > messages=[{"role": "user", "content": "What is 15% of 240? Explain briefly."}], > max_tokens=4096, > extra_body={"chat_template_kwargs": {"enable_thinking": True}}, > ) > > message = response.choices[0].message > print("=============== Reasoning ===============") > print(message.reasoning_content) > print("=============== Answer ==================") > print(message.content) > ``` > [!NOTE] > > Give generous `max_tokens` when thinking is enabled — hard problems regularly reason > for thousands of tokens. Keep thinking off for short-form tasks. ### 3.3 Tool Calling Launch with `--tool-call-parser poolside_v1` (baked into every generated command). The parser converts Laguna's `` output into the standard OpenAI `tool_calls` structure. Tool calling works with reasoning off (the default). > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["location"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="poolside/Laguna-S-2.1", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > > message = response.choices[0].message > if message.tool_calls: > for call in message.tool_calls: > print(f"Tool: {call.function.name}") > print(f"Args: {call.function.arguments}") > ``` # Laguna-XS-2.1 Source: https://docs.sglang.io/cookbook/autoregressive/Poolside/Laguna-XS-2.1 Deploy poolside's Laguna-XS-2.1 — a 33B hybrid-SWA Mixture-of-Experts model (3B active) for agentic coding — with SGLang on NVIDIA H200, B300, and GB300 in BF16, FP8, NVFP4, and INT4. ## Deployment > **Install SGLang** > > Laguna-XS-2.1 support is fully merged to SGLang `main` ([PR #29446](https://github.com/sgl-project/sglang/pull/29446): DFlash speculative decoding + shared-expert fix; [PR #29761](https://github.com/sgl-project/sglang/pull/29761): INT4 loader fix). Any build at or past their merge covers every cell below. > > The model ships custom config code on the Hub, so `--trust-remote-code` is required (included in the launch commands). > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install -U uv > uv venv --python 3.12 && source .venv/bin/activate > > git clone https://github.com/sgl-project/sglang.git > cd sglang > uv pip install --prerelease=allow -e python > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your hardware + quantization + strategy to generate the launch command. The two serving strategies cover the common operating points: * **Low-latency** — DFlash speculative decoding with a matched draft model. Pick for chat and interactive agents. * **High-throughput** — plain serving. Best for batch workloads, where speculation's draft + rejection overhead costs more than it saves. On the 8-GPU HGX platforms (H200 / B300), BF16 and NVFP4 run plain `--tp 8`; FP8 and INT4 run `--tp 8 --ep-size 8` because their quantization scales cannot shard the MoE 8-way (see [Configuration Tips](#2-configuration-tips)). The 4-GPU GB300 node runs plain `--tp 4` throughout. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations that have been signed off; the Playground lets you turn on additional knobs (TP degree, parsers) on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction [Laguna-XS-2.1](https://huggingface.co/poolside/Laguna-XS-2.1) is an open-weight **33B-parameter** hybrid sliding-window-attention MoE model (**\~3B active per token**) from [poolside](https://poolside.ai), built for agentic coding and long-horizon software engineering — the extra-small sibling of [Laguna-M.1](./Laguna-M.1). **Key Features:** * **Sparse MoE**: 40 layers, 256 routed experts, top-8 routing. * **Hybrid attention**: 30 sliding-window layers (window 512) interleaved with 10 full-attention layers; 48 Q / 8 KV heads. * **Long context**: 262,144 tokens (RoPE + YaRN on the full-attention layers). * **DFlash drafts**: matched draft models (5-layer, \~0.9 GB) ship per quantization for low-latency serving. * **Hybrid reasoning**: `…` toggled per request via `chat_template_kwargs={"enable_thinking": …}`. **Available quantizations:**
Precision Target model Draft model
**BF16** [`poolside/Laguna-XS-2.1`](https://huggingface.co/poolside/Laguna-XS-2.1) [`poolside/Laguna-XS-2.1-DFlash`](https://huggingface.co/poolside/Laguna-XS-2.1-DFlash)
**FP8** [`poolside/Laguna-XS-2.1-FP8`](https://huggingface.co/poolside/Laguna-XS-2.1-FP8) [`poolside/Laguna-XS-2.1-DFlash-FP8`](https://huggingface.co/poolside/Laguna-XS-2.1-DFlash-FP8)
**NVFP4** [`poolside/Laguna-XS-2.1-NVFP4`](https://huggingface.co/poolside/Laguna-XS-2.1-NVFP4) [`poolside/Laguna-XS-2.1-DFlash-NVFP4`](https://huggingface.co/poolside/Laguna-XS-2.1-DFlash-NVFP4)
**INT4** [`poolside/Laguna-XS-2.1-INT4`](https://huggingface.co/poolside/Laguna-XS-2.1-INT4) [`poolside/Laguna-XS-2.1-DFlash-INT4`](https://huggingface.co/poolside/Laguna-XS-2.1-DFlash-INT4)
The drafts themselves are small bf16 models, each *calibrated against its quantized target* — always pair a target with its matched draft (mixing precisions degrades accept-length). **License:** Apache 2.0 **Resources:** [Hugging Face](https://huggingface.co/poolside/Laguna-XS-2.1) · [Release blog post](https://poolside.ai/blog/laguna-a-deeper-dive) · [API platform](https://platform.poolside.ai). ## 2. Configuration Tips **Attention backend** Leave `--attention-backend` unset for High-throughput cells — auto-select is correct (`fa3` on Hopper, `trtllm_mha` on Blackwell). With DFlash active, auto-select instead falls back to `flashinfer`, which breaks this hybrid-SWA model at `tp ≥ 4` on Blackwell (greedy GSM8K 76% → 28%), so the Low-latency commands pin the target backend explicitly. Leave `--speculative-draft-attention-backend` unset. Never use `triton` attention with Laguna (GSM8K 13%). **Quantized checkpoints cap plain TP at 4** `moe_intermediate_size=512` with FP8 block `[128,128]` / INT4 `group_size=128` scales cannot shard 8-way (512/8 = 64 \< 128 granularity): FP8 fails at weight creation, INT4 crashes in the Marlin kernel, on any hardware. The generated 8-GPU FP8/INT4 commands therefore use `--tp 8 --ep-size 8` — expert parallelism keeps whole experts per rank, using all 8 GPUs on one instance. FP8 additionally needs `SGLANG_SHARED_EXPERT_TP1=1` (its shared expert is also block-quantized; INT4's stays bf16). Alternatives: plain `--tp 4`, or `--tp 4 --dp-size 2`. Accuracy is parallelism-independent within eval noise (verified tp1 ≡ tp4 on GB300 and tp4 ≡ tp8+ep8 on H200). **DFlash memory** Low-latency cells carry `--mem-fraction-static 0.7`: the default fraction OOMs in the draft vocab all-gather at `tp 4` on GB300. Dense cells use the default heuristic. **INT4 is mixed-precision** The INT4 checkpoint quantizes MoE layers in mixed 4-bit / 8-bit config groups. Builds older than [PR #29761](https://github.com/sgl-project/sglang/pull/29761) crash at load with `KeyError: 'Linear'`. **Chat template** On transformers ≥ 5.10 the standalone `chat_template.jinja` auto-loads — no flag needed (the server logs `Auto-detected template features: reasoning_parser=poolside_v1, ...`). On older transformers (≤ \~5.8) the `{% include %}` stub in `tokenizer_config.json` cannot resolve and the server silently falls back to a generic template — pass `--chat-template /chat_template.jinja` explicitly there. **Thinking** Off by default; opt in per request with `extra_body={"chat_template_kwargs": {"enable_thinking": True}}`. The template gates on `enable_thinking` — the generic `thinking` key is ignored. **Served model id** The server registers the model under whatever you pass to `--model-path`; a client's `model` field must match it (`poolside/Laguna-XS-2.1`, or the `-FP8` / `-NVFP4` / `-INT4` id). ## 3. Advanced Usage ### 3.1 DFlash Speculative Decoding DFlash is a block-wise speculative decoder: the 5-layer draft proposes a block of tokens and the target verifies the whole block in one forward pass, so only target-approved tokens are emitted — output quality is the target's by construction (GSM8K matches dense within noise on every quantization). The speedup lever is **accept-length**, the number of draft tokens surviving verification per target step: * Measured \~6 tokens/step at `tp 1`, \~4 at `tp 4` (greedy GSM8K, matched-precision pairs; \~3 under mixed reasoning-heavy traffic; FP8 reached 6.75 at `tp 8 + ep 8` on H200) — versus 1 token/step dense. * Best for interactive / few-stream serving. Under batch-saturated load prefer High-throughput: once the GPU is compute-bound, draft + rejected-token overhead costs aggregate throughput. * The generated commands always pair the draft calibrated for the selected target precision. ### 3.2 Reasoning Launch with `--reasoning-parser poolside_v1` (baked into every generated command). Reasoning is opt-in via `enable_thinking=True`; the `` trace lands in `message.reasoning_content`, separate from the final answer in `message.content`. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="poolside/Laguna-XS-2.1", > messages=[{"role": "user", "content": "What is 15% of 240? Explain briefly."}], > max_tokens=2048, > extra_body={"chat_template_kwargs": {"enable_thinking": True}}, > ) > > message = response.choices[0].message > print("=============== Reasoning ===============") > print(message.reasoning_content) > print("=============== Answer ==================") > print(message.content) > ``` > [!NOTE] > > XS-2.1 is an extra-small model — give it generous `max_tokens` when thinking is enabled > (hard problems regularly reason for thousands of tokens), and keep thinking off for > short-form tasks. ### 3.3 Tool Calling Launch with `--tool-call-parser poolside_v1` (baked into every generated command). The parser converts Laguna's `` output into the standard OpenAI `tool_calls` structure. Tool calling works with reasoning off (the default). > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["location"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="poolside/Laguna-XS-2.1", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > > message = response.choices[0].message > if message.tool_calls: > for call in message.tool_calls: > print(f"Tool: {call.function.name}") > print(f"Args: {call.function.arguments}") > ``` # Laguna-XS.2 Source: https://docs.sglang.io/cookbook/autoregressive/Poolside/Laguna-XS.2 ## 1. Model Introduction [Laguna-XS.2](https://huggingface.co/poolside/Laguna-XS.2) is an open-source hybrid sliding-window-attention MoE model from [Poolside](https://poolside.ai), built for agentic coding and long-horizon software engineering work. **Key Features:** * **MoE**: 33.4B total parameters, 3.0B active per token, 256 routed experts (top-8) plus 1 shared. * **Long context**: 131,072 tokens. * **Agentic coding**: Tuned for tool-using software engineering agents and long-horizon execution. * **Hybrid reasoning**: `...` segments toggled per request via `chat_template_kwargs={"enable_thinking": ...}`. **Available Quantizations:**
Variant Hugging Face path
**BF16** [`poolside/Laguna-XS.2`](https://huggingface.co/poolside/Laguna-XS.2)
**FP8** [`poolside/Laguna-XS.2-FP8`](https://huggingface.co/poolside/Laguna-XS.2-FP8)
**NVFP4** [`poolside/Laguna-XS.2-NVFP4`](https://huggingface.co/poolside/Laguna-XS.2-NVFP4)
**License:** Apache 2.0 For details, see the [Hugging Face model card](https://huggingface.co/poolside/Laguna-XS.2) and the [Laguna deeper-dive blog post](https://poolside.ai/blog/laguna-a-deeper-dive). ## 2. SGLang Installation Laguna-XS.2 support is on `main` but not yet in a tagged release; install from the SGLang nightly wheel index, or pull a pre-built Docker image: ```bash Command theme={null} # Install SGLang via pip (CUDA 13) — requires Python 3.10 (this nightly wheel is cp310 only) python3 -m pip install --upgrade pip python3 -m pip install --extra-index-url https://docs.sglang.ai/whl/cu130 \ "sglang[all]==0.5.12.dev20260509+g096ad02b0" # CUDA 12: swap to the cu129 index python3 -m pip install --extra-index-url https://docs.sglang.ai/whl/cu129 \ "sglang[all]==0.5.12.dev20260509+g096ad02b0" # Or use Docker (multi-arch amd64/arm64; CUDA 13, H200 / B200) docker pull lmsysorg/sglang:latest ``` For the full Docker setup and other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/install). ## 3. Model Deployment ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to generate a launch command for your hardware. Run this Command:

### 3.2 Configuration Tips

* **Trust remote code** (`--trust-remote-code`): Laguna-XS.2 ships custom modeling/config code on the Hugging Face Hub, so this flag is required for the server to load the model.
* **Quantization**: NVFP4 requires Blackwell (B200 / B300); BF16 and FP8 run on either H200 or B200. FP8's first launch triggers a multi-session DeepGEMM JIT pre-compile (\~10-20 min); pre-warm with `python3 -m sglang.compile_deep_gemm --model poolside/Laguna-XS.2-FP8` to avoid that cost on every restart.
* **Reasoning parser** (`--reasoning-parser poolside_v1`): Splits `...` segments into `reasoning_content` so `content` holds only the final answer. Disable only if you want the raw `` tags in `content`.
* **Tool call parser** (`--tool-call-parser poolside_v1`): Required for OpenAI-compatible tool-call streaming. Disable only for chat-only deployments.
* **DP attention**: For higher-throughput deployments, enable the DP-Attention toggle — it emits `--attn-dp-size ` with `--attn-dp-size` matching `--tp` (tune independently if needed).
* **Thinking default**: Thinking is **off by default** at the model level. Opt in per request with `extra_body={"chat_template_kwargs": {"enable_thinking": True}}`.

## 4. Model Invocation

The samples below assume the server is reachable at `http://localhost:30000/v1`.

### 4.1 Basic Chat

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

resp = client.chat.completions.create(
    model="poolside/Laguna-XS.2",
    messages=[
        {"role": "user", "content": "What is the difference between TCP and UDP?"}
    ],
    max_tokens=1024,
)
print(resp.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are two core protocols of the Internet Protocol (IP) suite, both used for network communication but with key differences:

## Connection Handling
- **TCP**: Connection-oriented protocol that establishes a connection before data transfer (like a phone call)
- **UDP**: Connectionless protocol that sends data without establishing a connection (like sending a letter)

## Reliability
- **TCP**: Guaranteed delivery with error checking, retransmission of lost packets, and flow control
- **UDP**: No guarantee of delivery; packets may be lost, duplicated, or arrive out of order

## Speed & Overhead
- **TCP**: Slower due to connection setup, acknowledgment overhead, and error correction mechanisms
- **UDP**: Faster with minimal overhead since it doesn't wait for acknowledgments or retransmit lost data

## Use Cases
- **TCP**: Web browsing (HTTP/HTTPS), email (SMTP), file transfers (FTP), database connections
- **UDP**: Video streaming, online gaming, VoIP calls, DNS queries, live broadcasts

In essence, TCP prioritizes reliability over speed, while UDP prioritizes speed over reliability.
```

### 4.2 Reasoning (Thinking Mode)

Laguna-XS.2 emits reasoning between `...` tags. The `--reasoning-parser poolside_v1` flag separates the thinking text into `reasoning_content` so `content` holds only the final answer. Thinking is opt-in per request:

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

resp = client.chat.completions.create(
    model="poolside/Laguna-XS.2",
    messages=[
        {"role": "user", "content": "If a train travels at 60 km/h for 2.5 hours, how far does it go?"}
    ],
    max_tokens=4096,
    extra_body={"chat_template_kwargs": {"enable_thinking": True}},
)

print("====== Reasoning Content ======")
print(resp.choices[0].message.reasoning_content)
print("====== Answer ======")
print(resp.choices[0].message.content)
```

**Output Example:**

```text Output theme={null}
====== Reasoning Content ======
The user is asking a straightforward math problem about distance, speed, and time. I need to calculate the distance using the formula:

Distance = Speed × Time

Given:
- Speed = 60 km/h
- Time = 2.5 hours

So the calculation would be:
Distance = 60 × 2.5 = 150 km

This is a simple multiplication problem. I should provide a clear, direct answer and maybe explain the calculation briefly.

====== Answer ======
To find the distance, use the formula:

Distance = Speed × Time
Distance = 60 km/h × 2.5 h = 150 km

The train travels **150 kilometers**.
```

To disable thinking, omit `extra_body` (off by default) or pass `chat_template_kwargs={"enable_thinking": False}` explicitly.

### 4.3 Tool Calling

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "The city name"},
                },
                "required": ["location"],
            },
        },
    }
]

resp = client.chat.completions.create(
    model="poolside/Laguna-XS.2",
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
    tools=tools,
)

msg = resp.choices[0].message
print("====== Reasoning Content ======")
print(msg.reasoning_content)
print("====== Content ======")
print(msg.content)
print("====== Tool Calls ======")
for tc in msg.tool_calls or []:
    print(f"  Function: {tc.function.name}")
    print(f"  Arguments: {tc.function.arguments}")
```

**Output Example:**

```text Output theme={null}
====== Reasoning Content ======
None
====== Content ======

I'll check the current weather in Tokyo for you.

====== Tool Calls ======
  Function: get_weather
  Arguments: {"location": "Tokyo"}
```

`reasoning_content` is `None` because thinking is off by default; `content` carries the brief assistant message that precedes the tool call. Add `extra_body={"chat_template_kwargs": {"enable_thinking": True}}` if you want interleaved reasoning before the tool call.

## 5. Benchmark

### 5.1 Accuracy Benchmark

**Test Environment:**

* Hardware: NVIDIA H200 (4×H200)
* Model: `poolside/Laguna-XS.2` (BF16)
* Tensor Parallelism: 4
* SGLang Version: `0.5.12.dev20260509+g096ad02b0` (nightly wheel containing the #24204 merge commit; same code path as the original PR runs)
* Reasoning Parser: `poolside_v1`
* Tool Call Parser: `poolside_v1`
* Sampling: `temperature=0.6`, `max_tokens=16384`, `chat_template_kwargs={"enable_thinking": true}`, `n_repeats=1`
* Grader: NeMo-Skills `math_verify` (math) and `eval_mcq` (multichoice)

**Results (from [PR #24204](https://github.com/sgl-project/sglang/pull/24204)):**

| Eval | Accuracy |
| - | -: |
| GPQA Diamond | 0.5556 |
| AIME 25 | 0.5667 |
| MMLU | 0.836 |
| SWE-Bench Verified | 0.6540 |

### 5.2 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA H200 (1×H200 for TP=1, 4×H200 for TP=4)
* Model: `poolside/Laguna-XS.2` (BF16)
* SGLang Version: `0.5.12.dev20260509+g096ad02b0` (nightly wheel containing the #24204 merge commit; same code path as the original PR runs)
* Workload: `sglang.bench_serving --backend sglang --dataset-name random` (defaults: `--random-input-len 1024 --random-output-len 1024 --random-range-ratio 0.0`)
* Server flags identical to the accuracy runs above.

#### 5.2.1 Latency Benchmark (10 prompts, concurrency = 1)

```bash Command theme={null}
python3 -m sglang.bench_serving --backend sglang \
  --host 0.0.0.0 --port 30000 \
  --dataset-name random --num-prompts 10 --max-concurrency 1
```

| Metric | TP=1 | TP=4 |
| - | -: | -: |
| Successful requests | 10 | 10 |
| Output token throughput (tok/s) | 193.10 | 238.88 |
| Total token throughput (tok/s) | 471.82 | 583.68 |
| Mean TTFT (ms) | 35.32 | 24.17 |
| Mean TPOT (ms) | 5.10 | 4.13 |
| Median ITL (ms) | 5.14 | 4.14 |

#### 5.2.2 Throughput Benchmark (1000 prompts, concurrency = 100)

```bash Command theme={null}
python3 -m sglang.bench_serving --backend sglang \
  --host 0.0.0.0 --port 30000 \
  --dataset-name random --num-prompts 1000 --max-concurrency 100
```

| Metric | TP=1 | TP=4 |
| - | -: | -: |
| Successful requests | 1000 | 1000 |
| Request throughput (req/s) | 7.32 | 14.61 |
| Output token throughput (tok/s) | 3739.30 | 7465.18 |
| Peak output token throughput (tok/s) | 4718.00 | 10133.00 |
| Total token throughput (tok/s) | 7485.82 | 14944.81 |
| Mean TTFT (ms) | 115.17 | 68.36 |
| Mean TPOT (ms) | 25.51 | 12.71 |
| Median ITL (ms) | 21.31 | 10.64 |

TP=4 delivers roughly 2.0× total-token throughput and \~1.7× lower mean TTFT compared to TP=1 on the `cc=100` random workload.


# Qwen2.5-VL
Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen2.5-VL



## 1. Model Introduction

**[Qwen2.5-VL](https://huggingface.co/collections/Qwen/qwen25-vl)** is a vision-language model series from the Qwen team, offering significant improvements over its predecessor in understanding, reasoning, and multi-modal processing.

**Key Features:**

* **Understand things visually**: Proficient in recognizing common objects such as flowers, birds, fish, and insects, and it is highly capable of analyzing texts, charts, icons, graphics, and layouts within images.
* **More Agentic**: Play as a visual agent that can reason and dynamically direct tools, which is capable of computer use and phone use.
* **Understanding long videos and capturing events**: Supports comprehending videos of over 1 hour, and this time it has a new ability of capturing event by pinpointing the relevant video segments.
* **Capable of visual localization in different formats**: Accurately localize objects in an image by generating bounding boxes or points, and it can provide stable JSON outputs for coordinates and attributes.
* **Generating structured outputs**: Supports structured outputs of the contents, benefiting usages in finance, commerce, etc for data like scans of invoices, forms, tables, etc.
* **Dynamic Resolution and Frame Rate Training for Video Understanding**: Extend dynamic resolution to the temporal dimension by adopting dynamic FPS sampling, enabling the model to comprehend videos at various sampling rates. Accordingly, we update mRoPE in the time dimension with IDs and absolute time alignment, enabling the model to learn temporal sequence and speed, and ultimately acquire the ability to pinpoint specific moments.
* **Multiple Sizes**: Available in 3B, 7B, 32B, and 72B variants to suit different deployment needs.
* **ROCm Support**: Compatible with AMD MI300X, MI325X and MI355X GPUs via SGLang (verified).

For more details, please refer to the [official Qwen2.5-VL GitHub Repository](https://github.com/QwenLM/Qwen3-VL).

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

For SGLang CPU installation, please refer to the [CPU version installation guide](../../../docs/hardware-platforms/cpu_server#installation).

## 3. Model Deployment

This section provides deployment configurations optimized for AMD MI300X, MI325X and MI355X as well as Intel Xeon CPU hardware platforms and different use cases.

### 3.1 Basic Configuration

The Qwen2.5-VL series offers models in various sizes. The following configurations have been verified on AMD MI300X, MI325X and MI355X GPUs as well as Intel Xeon CPUs.

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and model size.

Run this Command:


### 3.2 Configuration Tips

* **Memory Management**: For the 72B model on MI300X/MI325X/MI355X, we have verified successful deployment with `--context-length 128000`. Smaller context lengths can be used to reduce memory usage if needed.
* **Multi-GPU Deployment**: Use Tensor Parallelism (`--tp`) to scale across multiple GPUs. For example, use `--tp 8` for the 72B model and `--tp 2` for the 32B model on MI300X/MI325X/MI355X.
* **Xeon CPU service configuration**: Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Multi-Modal Inputs

Qwen2.5-VL supports image inputs. Here's a basic example with single image input:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                }
            },
            {
                "type": "text",
                "text": "Read all the text in the image."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="Qwen/Qwen2.5-VL-7B-Instruct",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example Output:**

```text Output theme={null}
Response costs: 2.31s
Generated text: Auntie Anne's

CINNAMON SUGAR
1 x 17,000
SUB TOTAL
17,000

GRAND TOTAL
17,000

CASH IDR
20,000

CHANGE DUE
3,000
```

**Multi-Image Input Example:**

Qwen2.5-VL can process multiple images in a single request for comparison or analysis:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://www.civitatis.com/f/china/hong-kong/guia/taxi.jpg"
                }
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://cdn.cheapoguides.com/wp-content/uploads/sites/7/2025/05/GettyImages-509614603-1280x600.jpg"
                }
            },
            {
                "type": "text",
                "text": "Compare these two images and describe the differences in 100 words or less."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="Qwen/Qwen2.5-VL-7B-Instruct",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example Output:**

```text Output theme={null}
Response costs: 13.79s
Generated text: The first image shows a single red taxi driving on a street with a few other taxis in the background. The second image shows a large number of taxis parked in a lot, with some appearing to be in various states of repair. The first image has a single taxi with a visible license plate, while the second image has multiple taxis with different license plates. The first image has a clear view of the street and surrounding area, while the second image is taken from an elevated perspective, showing a wider view of the parking lot and the surrounding area.
```

**Note:**

* You can also provide local file paths using `file://` protocol.
* For larger images, you may need more memory, adjust `--mem-fraction-static` accordingly.

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: AMD MI300X GPU (8x)
* Model: Qwen2.5-VL-72B-Instruct
* Tensor Parallelism: 8
* SGLang Version: 0.5.6

We use SGLang's built-in benchmarking tool to conduct performance evaluation with random images. To simulate real-world usage, you can specify different input and output lengths for each request. For example, each request can have 128 input tokens, two 720p images, and 1024 output tokens.

#### 5.1.1 Latency-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen2.5-VL-72B-Instruct \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen2.5-VL-72B-Instruct \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen2.5-VL-72B-Instruct \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  37.99
Total input tokens:                      24781
Total input text tokens:                 821
Total input vision tokens:               23960
Total generated tokens:                  4220
Total generated tokens (retokenized):    2365
Request throughput (req/s):              0.26
Input token throughput (tok/s):          652.26
Output token throughput (tok/s):         111.07
Peak output token throughput (tok/s):    128.00
Peak concurrent requests:                2
Total token throughput (tok/s):          763.34
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   3797.61
Median E2E Latency (ms):                 3140.90
P90 E2E Latency (ms):                    6545.54
P99 E2E Latency (ms):                    7939.56
---------------Time to First Token----------------
Mean TTFT (ms):                          504.45
Median TTFT (ms):                        510.93
P99 TTFT (ms):                           521.78
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          7.82
Median TPOT (ms):                        7.82
P99 TPOT (ms):                           7.84
---------------Inter-Token Latency----------------
Mean ITL (ms):                           10.07
Median ITL (ms):                         7.90
P95 ITL (ms):                            15.79
P99 ITL (ms):                            15.93
Max ITL (ms):                            23.60
==================================================
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen2.5-VL-72B-Instruct \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  454.68
Total input tokens:                      2481865
Total input text tokens:                 85865
Total input vision tokens:               2396000
Total generated tokens:                  510855
Total generated tokens (retokenized):    296466
Request throughput (req/s):              2.20
Input token throughput (tok/s):          5458.50
Output token throughput (tok/s):         1123.55
Peak output token throughput (tok/s):    5004.00
Peak concurrent requests:                106
Total token throughput (tok/s):          6582.05
Concurrency:                             98.63
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   44844.92
Median E2E Latency (ms):                 42866.15
P90 E2E Latency (ms):                    82798.20
P99 E2E Latency (ms):                    106306.30
---------------Time to First Token----------------
Mean TTFT (ms):                          4507.79
Median TTFT (ms):                        1180.83
P99 TTFT (ms):                           39975.22
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          80.26
Median TPOT (ms):                        82.38
P99 TPOT (ms):                           152.89
---------------Inter-Token Latency----------------
Mean ITL (ms):                           100.66
Median ITL (ms):                         13.26
P95 ITL (ms):                            428.45
P99 ITL (ms):                            1393.35
Max ITL (ms):                            31943.26
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 MMMU Benchmark

You can evaluate the model's accuracy using the MMMU dataset:

* Benchmark Command:

```shell Command theme={null}
python3 benchmark/mmmu/bench_sglang.py \
    --port 30000 \
    --concurrency 64
```

```text Output theme={null}
Benchmark time: 97.75084622902796
answers saved to: ./answer_sglang.json
Evaluating...
answers saved to: ./answer_sglang.json
{'Accounting': {'acc': 0.633, 'num': 30},
 'Agriculture': {'acc': 0.5, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.367, 'num': 30},
 'Art': {'acc': 0.767, 'num': 30},
 'Art_Theory': {'acc': 0.9, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.7, 'num': 30},
 'Biology': {'acc': 0.467, 'num': 30},
 'Chemistry': {'acc': 0.433, 'num': 30},
 'Clinical_Medicine': {'acc': 0.733, 'num': 30},
 'Computer_Science': {'acc': 0.567, 'num': 30},
 'Design': {'acc': 0.833, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.467, 'num': 30},
 'Economics': {'acc': 0.767, 'num': 30},
 'Electronics': {'acc': 0.433, 'num': 30},
 'Energy_and_Power': {'acc': 0.467, 'num': 30},
 'Finance': {'acc': 0.533, 'num': 30},
 'Geography': {'acc': 0.633, 'num': 30},
 'History': {'acc': 0.7, 'num': 30},
 'Literature': {'acc': 0.867, 'num': 30},
 'Manage': {'acc': 0.633, 'num': 30},
 'Marketing': {'acc': 0.733, 'num': 30},
 'Materials': {'acc': 0.333, 'num': 30},
 'Math': {'acc': 0.533, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.433, 'num': 30},
 'Music': {'acc': 0.367, 'num': 30},
 'Overall': {'acc': 0.62, 'num': 900},
 'Overall-Art and Design': {'acc': 0.717, 'num': 120},
 'Overall-Business': {'acc': 0.66, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.693, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.775, 'num': 120},
 'Overall-Science': {'acc': 0.553, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.443, 'num': 210},
 'Pharmacy': {'acc': 0.833, 'num': 30},
 'Physics': {'acc': 0.7, 'num': 30},
 'Psychology': {'acc': 0.767, 'num': 30},
 'Public_Health': {'acc': 0.733, 'num': 30},
 'Sociology': {'acc': 0.767, 'num': 30}}
eval out saved to ./val_sglang.json
Overall accuracy: 0.62
```


# Qwen3
Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3



## 1. Model Introduction

[Qwen3 series](https://github.com/QwenLM/Qwen3) are the most powerful vision-language models in the Qwen series to date, featuring advanced capabilities in multi-modal understanding, reasoning, and agentic applications.

This generation delivers comprehensive upgrades across the board:

* **Stronger general intelligence**: Significant improvements in instruction following, logical reasoning, text comprehension, mathematics, science, coding, and tool usage.
* **Broader multilingual knowledge**: Substantial gains in long-tail knowledge coverage across multiple languages.
* **More helpful & aligned responses**: Markedly better alignment with user preferences in subjective and open-ended tasks, enabling higher-quality, more useful text generation.
* **Extended context length**: Enhanced capabilities in understanding and reasoning over 256K-token long contexts.
* **Stronger agent interaction capabilities**: Improved tool use and search-based agent performance.
* **Flexible deployment options**: Available in Dense and MoE architectures that scale from edge to cloud, with Instruct and reasoning-enhanced Thinking editions.

For more details, please refer to the [official Qwen3 GitHub Repository](https://github.com/QwenLM/Qwen3).

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

The Qwen3 series offers models in various sizes and architectures, optimized for different hardware platforms including NVIDIA GPUs, AMD GPUs, Intel Arc Pro B-Series GPUs(codename: BMG (Battlemage)), and Intel Xeon CPUs. The recommended launch configurations vary by hardware and model size.

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model size, quantization method, and thinking capabilities.

Run this Command:


### 3.2 Configuration Tips

* **Memory Management:** Set lower `--context-length` to conserve memory. A value of `128000` is sufficient for most scenarios, down from the default 262K.
* **Expert Parallelism:** SGLang supports Expert Parallelism (EP) via `--ep`, allowing experts in MoE models to be deployed on separate GPUs for better throughput. One thing to note is that, for quantized models, you need to set `--ep` to a value that satisfies the requirement: `(moe_intermediate_size / moe_tp_size) % weight_block_size_n == 0, where moe_tp_size is equal to tp_size divided by ep_size.` Note that EP may perform worse in low concurrency scenarios due to additional communication overhead. Check out [Expert Parallelism Deployment](../../../docs/advanced_features/expert_parallelism) for more details.
* **Kernel Tuning:** For MoE Triton kernel tuning on your specific hardware, refer to [fused\_moe\_triton](https://github.com/sgl-project/sglang/tree/main/benchmark/kernels/fused_moe_triton).
* **Qwen3-4B and Qwen3-8B on H200:** For concurrent requests with long prompts, benchmark `--enable-mixed-chunk` to mix decode requests into chunked-prefill batches. This can reduce median time to first token (TTFT), but may increase time per output token (TPOT) and end-to-end tail latency. Compare these metrics and throughput on your workload before enabling it.
* **Speculative Decoding:** Using Speculative Decoding for latency-sensitive scenarios.
  * `--speculative-algorithm EAGLE3`: Speculative decoding algorithm
  * `--speculative-num-steps 3`: Number of speculative verification rounds
  * `--speculative-eagle-topk 1`: Top-k sampling for draft tokens
  * `--speculative-num-draft-tokens 4`: Number of draft tokens per step
  * `--speculative-draft-model-path`: The path of the draft model weights. This can be a local folder or a Hugging Face repo ID such as [`lmsys/SGLang-EAGLE3-Qwen3-235B-A22B-Instruct-2507-SpecForge-Meituan`](https://huggingface.co/lmsys/SGLang-EAGLE3-Qwen3-235B-A22B-Instruct-2507-SpecForge-Meituan).
* **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

Qwen3-235B-A22B supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-235B-A22B-Thinking-2507 \
  --reasoning-parser qwen3 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="Qwen/Qwen3-235B-A22B-Thinking-2507",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================

Okay, so I need to figure out what 15% of 240 is. Hmm, percentages can sometimes trip me up, but I think I remember some basics. Let me start by recalling that "percent" means "per hundred," so 15% is the same as 15 per 100, or 15/100. So, maybe I can convert 15% into a decimal first? Yeah, I think that's a common method.
...
So conclusion: The answer is 36.

=============== Content =================


To determine what 15% of 240 is, we can follow a systematic approach that involves converting the percentage to a decimal and then performing multiplication. Here's a step-by-step breakdown of the solution:

....

### Final Answer:

$$
\boxed{36}
$$

Thus, 15% of 240 is **36**.
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.3 Tool Calling

Qwen3 supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-235B-A22B-Thinking-2507 \
  --reasoning-parser qwen3 \
  --tool-call-parser qwen25 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="Qwen/Qwen3-235B-A22B-Thinking-2507",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"🔧 Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================

Okay, the user is asking for the weather in Beijing. Let me check the tools available. There's a function called get_weather that takes location and unit parameters. The location is required, so I need to specify Beijing as the location. The unit is optional and can be either celsius or fahrenheit. Since the user didn't specify the unit, maybe I should default to a common one. In China, they usually use celsius, so I'll set unit to celsius. I'll call the get_weather function with location: Beijing and unit: celsius. That should get the current weather for them.



=============== Content =================

🔧 Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="Qwen/Qwen3-235B-A22B-Thinking-2507",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The current weather in Beijing is **22°C** and **sunny**. A perfect day to enjoy outdoor activities! 🌞"
```

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8x)
* Model: Qwen3-235B-A22B-Instruct-2507
* Tensor Parallelism: 8
* sglang version: 0.5.6

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios.

#### 5.1.1 Standard Scenario Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --tp 8
```

##### 5.1.1.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  43.56
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  4210
Total generated tokens (retokenized):    4206
Request throughput (req/s):              0.23
Input token throughput (tok/s):          140.07
Output token throughput (tok/s):         96.65
Peak output token throughput (tok/s):    100.00
Peak concurrent requests:                2
Total token throughput (tok/s):          236.72
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   4353.63
Median E2E Latency (ms):                 3475.79
---------------Time to First Token----------------
Mean TTFT (ms):                          99.03
Median TTFT (ms):                        92.18
P99 TTFT (ms):                           166.05
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.12
Median TPOT (ms):                        10.12
P99 TPOT (ms):                           10.15
---------------Inter-Token Latency----------------
Mean ITL (ms):                           10.13
Median ITL (ms):                         10.12
P95 ITL (ms):                            10.49
P99 ITL (ms):                            10.70
Max ITL (ms):                            13.45
==================================================
```

##### 5.1.1.2 Medium Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  48.95
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  40725
Total generated tokens (retokenized):    40716
Request throughput (req/s):              1.63
Input token throughput (tok/s):          810.44
Output token throughput (tok/s):         832.04
Peak output token throughput (tok/s):    1151.00
Peak concurrent requests:                21
Total token throughput (tok/s):          1642.48
Concurrency:                             13.61
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   8326.72
Median E2E Latency (ms):                 8827.86
---------------Time to First Token----------------
Mean TTFT (ms):                          215.70
Median TTFT (ms):                        88.82
P99 TTFT (ms):                           727.08
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          16.36
Median TPOT (ms):                        16.12
P99 TPOT (ms):                           24.09
---------------Inter-Token Latency----------------
Mean ITL (ms):                           15.96
Median ITL (ms):                         14.52
P95 ITL (ms):                            16.04
P99 ITL (ms):                            67.69
Max ITL (ms):                            457.52
==================================================
```

##### 5.1.1.3 High Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  92.07
Total input tokens:                      249831
Total input text tokens:                 249831
Total input vision tokens:               0
Total generated tokens:                  252162
Total generated tokens (retokenized):    251124
Request throughput (req/s):              5.43
Input token throughput (tok/s):          2713.46
Output token throughput (tok/s):         2738.78
Peak output token throughput (tok/s):    4400.00
Peak concurrent requests:                110
Total token throughput (tok/s):          5452.24
Concurrency:                             90.50
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   16665.09
Median E2E Latency (ms):                 16060.10
---------------Time to First Token----------------
Mean TTFT (ms):                          260.55
Median TTFT (ms):                        122.68
P99 TTFT (ms):                           863.11
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          32.94
Median TPOT (ms):                        34.04
P99 TPOT (ms):                           41.19
---------------Inter-Token Latency----------------
Mean ITL (ms):                           32.59
Median ITL (ms):                         23.54
P95 ITL (ms):                            69.79
P99 ITL (ms):                            119.09
Max ITL (ms):                            577.70
==================================================
```

#### 5.1.2 Reasoning Scenario Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --tp 8
```

##### 5.1.2.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  457.45
Total input tokens:                      6101
Total input text tokens:                 6101
Total input vision tokens:               0
Total generated tokens:                  44452
Total generated tokens (retokenized):    44059
Request throughput (req/s):              0.02
Input token throughput (tok/s):          13.34
Output token throughput (tok/s):         97.17
Peak output token throughput (tok/s):    100.00
Peak concurrent requests:                2
Total token throughput (tok/s):          110.51
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   45742.42
Median E2E Latency (ms):                 49266.87
---------------Time to First Token----------------
Mean TTFT (ms):                          110.60
Median TTFT (ms):                        109.36
P99 TTFT (ms):                           167.43
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.23
Median TPOT (ms):                        10.24
P99 TPOT (ms):                           10.32
---------------Inter-Token Latency----------------
Mean ITL (ms):                           10.27
Median ITL (ms):                         10.26
P95 ITL (ms):                            10.71
P99 ITL (ms):                            10.97
Max ITL (ms):                            15.79
==================================================
```

##### 5.1.2.2 Medium Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  340.17
Total input tokens:                      39668
Total input text tokens:                 39668
Total input vision tokens:               0
Total generated tokens:                  318226
Total generated tokens (retokenized):    318104
Request throughput (req/s):              0.24
Input token throughput (tok/s):          116.61
Output token throughput (tok/s):         935.49
Peak output token throughput (tok/s):    1120.00
Peak concurrent requests:                19
Total token throughput (tok/s):          1052.10
Concurrency:                             13.85
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   58885.30
Median E2E Latency (ms):                 59238.70
---------------Time to First Token----------------
Mean TTFT (ms):                          169.71
Median TTFT (ms):                        101.61
P99 TTFT (ms):                           455.71
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          14.82
Median TPOT (ms):                        14.91
P99 TPOT (ms):                           15.20
---------------Inter-Token Latency----------------
Mean ITL (ms):                           14.76
Median ITL (ms):                         14.63
P95 ITL (ms):                            15.46
P99 ITL (ms):                            16.62
Max ITL (ms):                            104.94
==================================================
```

##### 5.1.2.3 High Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 320 \
  --max-concurrency 64
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  544.83
Total input tokens:                      158939
Total input text tokens:                 158939
Total input vision tokens:               0
Total generated tokens:                  1300705
Total generated tokens (retokenized):    1293015
Request throughput (req/s):              0.59
Input token throughput (tok/s):          291.72
Output token throughput (tok/s):         2387.34
Peak output token throughput (tok/s):    3008.00
Peak concurrent requests:                68
Total token throughput (tok/s):          2679.06
Concurrency:                             56.35
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   95937.70
Median E2E Latency (ms):                 99362.32
---------------Time to First Token----------------
Mean TTFT (ms):                          265.03
Median TTFT (ms):                        129.11
P99 TTFT (ms):                           823.85
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          23.66
Median TPOT (ms):                        24.07
P99 TPOT (ms):                           24.97
---------------Inter-Token Latency----------------
Mean ITL (ms):                           23.54
Median ITL (ms):                         23.07
P95 ITL (ms):                            25.92
P99 ITL (ms):                            63.87
Max ITL (ms):                            408.30
==================================================
```

#### 5.1.3 Summarization Scenario Benchmark

##### 5.1.3.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  44.82
Total input tokens:                      41941
Total input text tokens:                 41941
Total input vision tokens:               0
Total generated tokens:                  4210
Total generated tokens (retokenized):    4210
Request throughput (req/s):              0.22
Input token throughput (tok/s):          935.86
Output token throughput (tok/s):         93.94
Peak output token throughput (tok/s):    99.00
Peak concurrent requests:                2
Total token throughput (tok/s):          1029.80
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   4479.60
Median E2E Latency (ms):                 3622.99
---------------Time to First Token----------------
Mean TTFT (ms):                          139.90
Median TTFT (ms):                        114.85
P99 TTFT (ms):                           225.17
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.31
Median TPOT (ms):                        10.33
P99 TPOT (ms):                           10.51
---------------Inter-Token Latency----------------
Mean ITL (ms):                           10.33
Median ITL (ms):                         10.33
P95 ITL (ms):                            10.73
P99 ITL (ms):                            10.93
Max ITL (ms):                            14.48
==================================================
```

##### 5.1.3.2 Medium Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  50.68
Total input tokens:                      300020
Total input text tokens:                 300020
Total input vision tokens:               0
Total generated tokens:                  41589
Total generated tokens (retokenized):    41578
Request throughput (req/s):              1.58
Input token throughput (tok/s):          5920.41
Output token throughput (tok/s):         820.69
Peak output token throughput (tok/s):    1200.00
Peak concurrent requests:                20
Total token throughput (tok/s):          6741.10
Concurrency:                             13.90
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   8805.54
Median E2E Latency (ms):                 9368.79
---------------Time to First Token----------------
Mean TTFT (ms):                          284.29
Median TTFT (ms):                        168.48
P99 TTFT (ms):                           1027.21
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          16.81
Median TPOT (ms):                        16.66
P99 TPOT (ms):                           27.18
---------------Inter-Token Latency----------------
Mean ITL (ms):                           16.42
Median ITL (ms):                         13.68
P95 ITL (ms):                            17.23
P99 ITL (ms):                            90.75
Max ITL (ms):                            574.64
==================================================
```

##### 5.1.3.3 High Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-235B-A22B-Instruct-2507 \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 320 \
  --max-concurrency 64
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  94.77
Total input tokens:                      1273893
Total input text tokens:                 1273893
Total input vision tokens:               0
Total generated tokens:                  169680
Total generated tokens (retokenized):    169640
Request throughput (req/s):              3.38
Input token throughput (tok/s):          13441.86
Output token throughput (tok/s):         1790.43
Peak output token throughput (tok/s):    2687.00
Peak concurrent requests:                70
Total token throughput (tok/s):          15232.28
Concurrency:                             58.63
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   17364.14
Median E2E Latency (ms):                 17495.95
---------------Time to First Token----------------
Mean TTFT (ms):                          238.22
Median TTFT (ms):                        203.27
P99 TTFT (ms):                           510.48
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          32.50
Median TPOT (ms):                        34.27
P99 TPOT (ms):                           40.59
---------------Inter-Token Latency----------------
Mean ITL (ms):                           32.36
Median ITL (ms):                         22.50
P95 ITL (ms):                            97.81
P99 ITL (ms):                            151.55
Max ITL (ms):                            352.79
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* **Results**:

  * Qwen/Qwen3-235B-A22B-Instruct-2507
    ```text Output theme={null}
    Accuracy: 0.945
    Invalid: 0.000
    Latency: 11.980 s
    Output throughput: 2358.105 token/s
    ```


# Qwen3-Coder
Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3-Coder



## 1. Model Introduction

[Qwen3-Coder](https://huggingface.co/collections/Qwen/qwen3-coder) is the latest code-focused large language model series from the Qwen team. Built on the foundation of Qwen3, Qwen3-Coder delivers exceptional performance in code generation, understanding, and reasoning tasks.

**Key Features:**

* **State-of-the-art Coding Performance**: Achieves top-tier results on HumanEval, MBPP, LiveCodeBench, and other major coding benchmarks.
* **Tool Calling Support**: Native support for function calling and tool use, enabling seamless integration with external APIs and services.
* **Extended Context Length**: Supports up to 256K tokens for processing large codebases and long documents.
* **Multilingual Code Support**: Proficient in Python, JavaScript, TypeScript, Java, C++, Go, Rust, and many other programming languages.
* **MoE Architecture**: Efficient Mixture-of-Experts design for optimal performance-to-cost ratio.
* **ROCm Support**: Compatible with AMD MI300X, MI325X and MI355X GPUs via SGLang (verified).
* **NVIDIA GPU Support**: Compatible with NVIDIA GB200 and B200 GPUs via SGLang (verified).

For more details, please refer to the [official Qwen3-Coder GitHub Repository](https://github.com/QwenLM/Qwen3-Coder).

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

For SGLang CPU installation, please refer to the [CPU version installation guide](../../../docs/hardware-platforms/cpu_server#installation).

## 3. Model Deployment

This section provides deployment configurations verified on AMD MI300X, MI325X, MI355X, NVIDIA B200, GB200, and Intel Xeon CPU hardware platforms.

### 3.1 Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model size, and quantization method.

Run this Command:


### 3.2 Configuration Tips

**AMD (MI300X/MI325X/MI355X):**

* **Memory Management**: We have verified successful deployment on MI300X/MI325X/MI355X with `--context-length 8192`. Larger context lengths may be supported but require additional memory.
* **Expert Parallelism**: For 480B-A35B with FP8 quantization, `--ep 2` is required to satisfy the dimension alignment requirement.
* **Page Size**: `--page-size 32` is recommended for MoE models to optimize memory usage.
* **Environment Variable**: If you encounter aiter-related issues, try setting `SGLANG_USE_AITER=0`.

**NVIDIA (B200/GB200):**

* **GB200 Parallelism**: Use `--tp 4 --ep 4` on GB200. B200 uses the default NVIDIA settings generated above.
* **NVFP4 Quantization**: Requires `--quantization modelopt_fp4` and uses a different model path (`nvidia/Qwen3-Coder-...`).
* **DP Attention**: NVFP4 configuration supports DP attention (`--attn-dp-size `) for improved throughput.

**Intel Xeon CPU:**

* Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

**General:**

* **Tool Use**: To enable tool calling capabilities, add `--tool-call-parser qwen3_coder` to the launch command.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Code Generation Example

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": "Write a Python function that implements binary search on a sorted list. Include docstring and type hints."
    }
]

response = client.chat.completions.create(
    model="Qwen/Qwen3-Coder-480B-A35B-Instruct",
    messages=messages,
    max_tokens=2048,
    temperature=0.7
)

print(response.choices[0].message.content)
```

**Example Output:**

````text Output theme={null}
```python
from typing import List, Optional, TypeVar

T = TypeVar('T')

def binary_search(arr: List[T], target: T) -> Optional[int]:
    """
    Perform binary search on a sorted list to find the index of a target element.

    This function implements the binary search algorithm, which efficiently finds
    a target value in a sorted array by repeatedly dividing the search interval
    in half.

    Args:
        arr (List[T]): A sorted list of elements to search through.
        target (T): The element to search for in the list.

    Returns:
        Optional[int]: The index of the target element if found, None otherwise.

    Time Complexity:
        O(log n) where n is the number of elements in the array.

    Space Complexity:
        O(1) - iterative implementation uses constant extra space.

    Examples:
        >>> binary_search([1, 2, 3, 4, 5], 3)
        2
        >>> binary_search([1, 2, 3, 4, 5], 6)
        None
        >>> binary_search(['a', 'b', 'c', 'd'], 'b')
        1
        >>> binary_search([], 1)
        None
    """
    if not arr:
        return None

    left: int = 0
    right: int = len(arr) - 1

    while left <= right:
        mid: int = (left + right) // 2

        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1

    return None

# Alternative recursive implementation
def binary_search_recursive(arr: List[T], target: T, left: int = 0, right: Optional[int] = None) -> Optional[int]:
    """
    Perform binary search recursively on a sorted list to find the index of a target element.

    Args:
        arr (List[T]): A sorted list of elements to search through.
        target (T): The element to search for in the list.
        left (int): Left boundary of the search range (inclusive).
        right (Optional[int]): Right boundary of the search range (inclusive).

    Returns:
        Optional[int]: The index of the target element if found, None otherwise.

    Time Complexity:
        O(log n) where n is the number of elements in the array.

    Space Complexity:
        O(log n) due to recursive call stack.

    Examples:
        >>> binary_search_recursive([1, 2, 3, 4, 5], 3)
        2
        >>> binary_search_recursive([1, 2, 3, 4, 5], 6)
        None
    """
    if not arr:
        return None

    if right is None:
        right = len(arr) - 1

    if left > right:
        return None

    mid: int = (left + right) // 2

    if arr[mid] == target:
        return mid
    elif arr[mid] < target:
        return binary_search_recursive(arr, target, mid + 1, right)
    else:
        return binary_search_recursive(arr, target, left, mid - 1)
```

This implementation provides:

1. **Main function** (`binary_search`): An iterative implementation that's more memory-efficient
2. **Alternative function** (`binary_search_recursive`): A recursive implementation for educational purposes
3. **Type hints**: Using generics (`TypeVar`) to work with any comparable type
4. **Comprehensive docstring**: Including description, parameters, return value, complexity analysis, and examples
5. **Edge case handling**: Empty lists, elements not found, etc.
6. **Clear variable names**: Self-documenting code
7. **Examples**: Doctest-style examples in the docstring

The function works with any sorted list of comparable elements (integers, strings, etc.) and returns the index of the target element if found, or `None` if not found.
````

#### 4.2.2 Tool Calling Example

Qwen3-Coder supports tool calling capabilities. Enable the tool call parser during deployment. The following example uses 30B-A3B model:

```shell Command theme={null}
SGLANG_USE_AITER=0 python -m sglang.launch_server \
  --model Qwen/Qwen3-Coder-30B-A3B-Instruct \
  --tp 1 \
  --context-length 8192 \
  --page-size 32 \
  --tool-call-parser qwen3_coder
```

**Python Example:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "execute_code",
            "description": "Execute Python code and return the result",
            "parameters": {
                "type": "object",
                "properties": {
                    "code": {
                        "type": "string",
                        "description": "The Python code to execute"
                    }
                },
                "required": ["code"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="Qwen/Qwen3-Coder-30B-A3B-Instruct",
    messages=[
        {"role": "user", "content": "Calculate the factorial of 10 using Python"}
    ],
    tools=tools,
    temperature=0.7
)

# Check if the model wants to call a tool
if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    print(f"Tool: {tool_call.function.name}")
    print(f"Arguments: {tool_call.function.arguments}")
else:
    # Model may return tool call in content format
    print(response.choices[0].message.content)
```

**Example Output:**

```text Output theme={null}
Tool: execute_code
Arguments: {"code": "def factorial(n):\n    if n == 0 or n == 1:\n        return 1\n    else:\n        return n * factorial(n-1)\n\nresult = factorial(10)\nresult"}
```

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: AMD MI300X GPU (8x)
* Model: Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8
* Tensor Parallelism: 8
* Expert Parallelism: 2
* sglang version: 0.5.7

We use SGLang's built-in benchmarking tool to conduct performance evaluation with random dataset.

#### 5.1.1 AMD Standard Scenario Benchmark

* Model Deployment Command:

```shell Command theme={null}
SGLANG_USE_AITER=0 python -m sglang.launch_server \
  --model Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 \
  --tp 8 \
  --ep 2 \
  --context-length 8192 \
  --page-size 32 \
  --trust-remote-code
```

##### 5.1.1.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  73.79
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  4220
Total generated tokens (retokenized):    4104
Request throughput (req/s):              0.14
Input token throughput (tok/s):          82.68
Output token throughput (tok/s):         57.19
Peak output token throughput (tok/s):    59.00
Peak concurrent requests:                2
Total token throughput (tok/s):          139.86
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   7376.26
Median E2E Latency (ms):                 5851.51
P90 E2E Latency (ms):                    13351.89
P99 E2E Latency (ms):                    16908.32
---------------Time to First Token----------------
Mean TTFT (ms):                          191.93
Median TTFT (ms):                        126.06
P99 TTFT (ms):                           662.15
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          17.06
Median TPOT (ms):                        17.07
P99 TPOT (ms):                           17.08
---------------Inter-Token Latency----------------
Mean ITL (ms):                           17.06
Median ITL (ms):                         17.06
P95 ITL (ms):                            17.14
P99 ITL (ms):                            17.19
Max ITL (ms):                            18.53
==================================================
```

##### 5.1.1.2 Medium Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  87.04
Total input tokens:                      39668
Total input text tokens:                 39668
Total generated tokens:                  40805
Total generated tokens (retokenized):    40364
Request throughput (req/s):              0.92
Input token throughput (tok/s):          455.77
Output token throughput (tok/s):         468.83
Peak output token throughput (tok/s):    608.00
Peak concurrent requests:                20
Total token throughput (tok/s):          924.59
Concurrency:                             13.76
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   14966.88
Median E2E Latency (ms):                 15871.93
P90 E2E Latency (ms):                    24983.41
P99 E2E Latency (ms):                    29504.85
---------------Time to First Token----------------
Mean TTFT (ms):                          388.94
Median TTFT (ms):                        157.49
P99 TTFT (ms):                           1318.63
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          29.41
Median TPOT (ms):                        29.22
P99 TPOT (ms):                           43.48
---------------Inter-Token Latency----------------
Mean ITL (ms):                           28.64
Median ITL (ms):                         26.42
P95 ITL (ms):                            27.51
P99 ITL (ms):                            131.63
Max ITL (ms):                            995.11
==================================================
```

##### 5.1.1.3 High Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 320 \
  --max-concurrency 64
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  177.82
Total input tokens:                      158939
Total input text tokens:                 158939
Total generated tokens:                  170134
Total generated tokens (retokenized):    168387
Request throughput (req/s):              1.80
Input token throughput (tok/s):          893.84
Output token throughput (tok/s):         956.80
Peak output token throughput (tok/s):    1728.00
Peak concurrent requests:                70
Total token throughput (tok/s):          1850.64
Concurrency:                             58.88
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   32716.53
Median E2E Latency (ms):                 30896.37
P90 E2E Latency (ms):                    65605.24
P99 E2E Latency (ms):                    80970.63
---------------Time to First Token----------------
Mean TTFT (ms):                          372.97
Median TTFT (ms):                        181.67
P99 TTFT (ms):                           529.01
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          62.98
Median TPOT (ms):                        50.44
P99 TPOT (ms):                           204.24
---------------Inter-Token Latency----------------
Mean ITL (ms):                           60.95
Median ITL (ms):                         37.87
P95 ITL (ms):                            143.98
P99 ITL (ms):                            148.02
Max ITL (ms):                            36863.32
==================================================
```

#### 5.1.2 NVIDIA (B200/GB200) Standard Scenario Benchmark

The following runs use the same random dataset benchmark client commands as the AMD section. On B200, launch the server with the following command:

````bash theme={null}
sglang serve --model Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 --tp 8 --ep 8 --context-length 8192 --page-size 32 --trust-remote-code

##### 5.1.2.1 FP8 Model

- Low Concurrency:

```text Output
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  42.68
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  4220
Total generated tokens (retokenized):    4204
Request throughput (req/s):              0.23
Input token throughput (tok/s):          142.95
Output token throughput (tok/s):         98.88
Peak output token throughput (tok/s):    102.00
Peak concurrent requests:                2
Total token throughput (tok/s):          241.83
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   4266.06
Median E2E Latency (ms):                 3420.24
P90 E2E Latency (ms):                    7717.19
P99 E2E Latency (ms):                    9504.50
---------------Time to First Token----------------
Mean TTFT (ms):                          112.03
Median TTFT (ms):                        112.70
P99 TTFT (ms):                           115.35
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          9.87
Median TPOT (ms):                        9.86
P99 TPOT (ms):                           9.92
---------------Inter-Token Latency----------------
Mean ITL (ms):                           9.87
Median ITL (ms):                         9.87
P95 ITL (ms):                            10.06
P99 ITL (ms):                            10.18
Max ITL (ms):                            14.80
==================================================
````

* Medium Concurrency:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  60.80
Total input tokens:                      39668
Total input text tokens:                 39668
Total generated tokens:                  40805
Total generated tokens (retokenized):    40543
Request throughput (req/s):              1.32
Input token throughput (tok/s):          652.43
Output token throughput (tok/s):         671.13
Peak output token throughput (tok/s):    864.00
Peak concurrent requests:                20
Total token throughput (tok/s):          1323.57
Concurrency:                             13.93
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   10587.26
Median E2E Latency (ms):                 11486.18
P90 E2E Latency (ms):                    17374.75
P99 E2E Latency (ms):                    21107.18
---------------Time to First Token----------------
Mean TTFT (ms):                          155.27
Median TTFT (ms):                        121.57
P99 TTFT (ms):                           294.31
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          20.77
Median TPOT (ms):                        21.13
P99 TPOT (ms):                           23.62
---------------Inter-Token Latency----------------
Mean ITL (ms):                           20.49
Median ITL (ms):                         18.73
P95 ITL (ms):                            19.65
P99 ITL (ms):                            98.85
Max ITL (ms):                            536.87
==================================================
```

* High Concurrency:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  100.07
Total input tokens:                      158939
Total input text tokens:                 158939
Total generated tokens:                  170134
Total generated tokens (retokenized):    169119
Request throughput (req/s):              3.20
Input token throughput (tok/s):          1588.32
Output token throughput (tok/s):         1700.19
Peak output token throughput (tok/s):    2303.00
Peak concurrent requests:                71
Total token throughput (tok/s):          3288.51
Concurrency:                             57.93
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   18114.01
Median E2E Latency (ms):                 18279.15
P90 E2E Latency (ms):                    30557.22
P99 E2E Latency (ms):                    35889.84
---------------Time to First Token----------------
Mean TTFT (ms):                          346.40
Median TTFT (ms):                        129.75
P99 TTFT (ms):                           1370.20
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          33.76
Median TPOT (ms):                        34.62
P99 TPOT (ms):                           39.97
---------------Inter-Token Latency----------------
Mean ITL (ms):                           33.48
Median ITL (ms):                         25.70
P95 ITL (ms):                            99.36
P99 ITL (ms):                            132.30
Max ITL (ms):                            1132.39
==================================================
```

##### 5.1.2.2 NVFP4 Model

* Low Concurrency:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  34.49
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  4220
Total generated tokens (retokenized):    4218
Request throughput (req/s):              0.29
Input token throughput (tok/s):          176.87
Output token throughput (tok/s):         122.34
Peak output token throughput (tok/s):    127.00
Peak concurrent requests:                2
Total token throughput (tok/s):          299.21
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   3448.01
Median E2E Latency (ms):                 2768.11
P90 E2E Latency (ms):                    6225.73
P99 E2E Latency (ms):                    7668.26
---------------Time to First Token----------------
Mean TTFT (ms):                          104.55
Median TTFT (ms):                        105.38
P99 TTFT (ms):                           105.63
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          7.94
Median TPOT (ms):                        7.95
P99 TPOT (ms):                           7.97
---------------Inter-Token Latency----------------
Mean ITL (ms):                           7.94
Median ITL (ms):                         7.94
P95 ITL (ms):                            8.05
P99 ITL (ms):                            8.11
Max ITL (ms):                            24.64
==================================================
```

* Medium Concurrency:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  43.30
Total input tokens:                      39668
Total input text tokens:                 39668
Total generated tokens:                  40805
Total generated tokens (retokenized):    39975
Request throughput (req/s):              1.85
Input token throughput (tok/s):          916.16
Output token throughput (tok/s):         942.42
Peak output token throughput (tok/s):    1264.00
Peak concurrent requests:                21
Total token throughput (tok/s):          1858.57
Concurrency:                             13.90
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   7521.95
Median E2E Latency (ms):                 8246.89
P90 E2E Latency (ms):                    12370.93
P99 E2E Latency (ms):                    15023.96
---------------Time to First Token----------------
Mean TTFT (ms):                          137.27
Median TTFT (ms):                        109.59
P99 TTFT (ms):                           208.78
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          14.69
Median TPOT (ms):                        14.87
P99 TPOT (ms):                           17.63
---------------Inter-Token Latency----------------
Mean ITL (ms):                           14.51
Median ITL (ms):                         12.75
P95 ITL (ms):                            13.33
P99 ITL (ms):                            92.85
Max ITL (ms):                            113.70
==================================================
```

* High Concurrency:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  73.93
Total input tokens:                      158939
Total input text tokens:                 158939
Total generated tokens:                  170134
Total generated tokens (retokenized):    168841
Request throughput (req/s):              4.33
Input token throughput (tok/s):          2149.98
Output token throughput (tok/s):         2301.42
Peak output token throughput (tok/s):    3497.00
Peak concurrent requests:                71
Total token throughput (tok/s):          4451.40
Concurrency:                             58.28
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   13463.58
Median E2E Latency (ms):                 13498.74
P90 E2E Latency (ms):                    22957.10
P99 E2E Latency (ms):                    26656.95
---------------Time to First Token----------------
Mean TTFT (ms):                          239.00
Median TTFT (ms):                        113.42
P99 TTFT (ms):                           713.87
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          25.13
Median TPOT (ms):                        26.02
P99 TPOT (ms):                           30.90
---------------Inter-Token Latency----------------
Mean ITL (ms):                           24.92
Median ITL (ms):                         16.68
P95 ITL (ms):                            93.33
P99 ITL (ms):                            119.26
Max ITL (ms):                            548.82
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

##### AMD (MI300X/MI325X/MI355X)

* **Results**:

  * Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8
    ```
    Accuracy: 0.965
    Invalid: 0.000
    Latency: 23.084 s
    Output throughput: 1148.425 token/s
    ```

##### NVIDIA (B200/GB200)

For deployment commands, see [Section 3.1](#3-1-configuration).

* Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8
  ```
  Accuracy: 0.965
  Invalid: 0.000
  Latency: 14.870 s
  Output throughput: 1777.726 token/s
  ```

* nvidia/Qwen3-Coder-480B-A35B-Instruct-NVFP (NVFP4)
  ```
  Accuracy: 0.960
  Invalid: 0.000
  Latency: 13.948 s
  Output throughput: 1988.548 token/s
  ```


# Qwen3-Coder-Next
Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3-Coder-Next



## 1. Model Introduction

[Qwen3-Coder-Next](https://huggingface.co/Qwen/Qwen3-Coder-Next) is a cost-efficient code-focused language model from the Qwen team (Alibaba). With 80B total parameters but only 3B activated parameters, it achieves performance comparable to models with 10–20x more active parameters through its innovative hybrid architecture.

**Key Features:**

* **Hybrid Architecture**: Uses a 48-layer hybrid layout combining Gated DeltaNet and Gated Attention with Mixture-of-Experts (512 total experts, 10 activated, 1 shared), enabling exceptional efficiency.
* **Tool Calling Support**: Advanced agentic capabilities with native support for function calling and tool use via the `qwen3_coder` parser.
* **Extended Context Length**: Supports up to 256K tokens for processing large codebases and long documents.
* **Cost-Efficient Inference**: Only 3B parameters activated per token, making it ideal for local development and cost-effective deployment at scale.
* **IDE Integration**: Compatible with Claude Code, Qwen Code, Cline, and other IDE platforms.

For more details, please refer to the [Qwen3-Coder-Next model card](https://huggingface.co/Qwen/Qwen3-Coder-Next).

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

For SGLang CPU installation, please refer to the [CPU version installation guide](../../../docs/hardware-platforms/cpu_server#installation).

**Note:** Qwen3-Coder-Next requires SGLang v0.5.8 or later.

## 3. Model Deployment

This section provides a progressive guide from quick deployment to performance optimization, suitable for users at different levels.

### 3.1 Basic Configuration

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and deployment options.

Run this Command:


### 3.2 Configuration Tips

* **Context Length**: The model supports up to 256K tokens natively. If you encounter OOM issues, try `--context-length 32768`.
* **Tool Use**: To enable tool calling capabilities, use the `--tool-call-parser qwen3_coder` flag.
* **Sampling Parameters**: SGLang automatically applies the recommended sampling parameters from the model's `generation_config.json`. No manual configuration is needed.
* **Mamba Radix Cache**: Qwen3-Coder-Next's hybrid Gated Delta Networks architecture supports two mamba scheduling strategies via `--mamba-radix-cache-strategy`:
  * **V1 (`no_buffer`)**: Default. No overlap scheduler, lower memory usage.
  * **V2 (`extra_buffer`)**: Enables overlap scheduling and branching point caching with `--mamba-radix-cache-strategy extra_buffer --page-size 64`. Requires FLA kernel backend. Trades higher mamba state memory for better throughput. Strictly superior in non-KV-cache-bound scenarios; in KV-cache-bound cases, weigh the overlap scheduling benefit against reduced max concurrency. `--page-size` must satisfy `FLA_CHUNK_SIZE % page_size == 0` or `page_size % FLA_CHUNK_SIZE == 0` (`FLA_CHUNK_SIZE` is currently 64).
* **Xeon CPU service configuration**: Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4. Model Invocation

**Deployment Command:**

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Coder-Next \
  --tp 2 \
  --tool-call-parser qwen3_coder \
  --host 0.0.0.0 \
  --port 30000
```

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Code Generation Example

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="Qwen/Qwen3-Coder-Next",
    messages=[
        {"role": "user", "content": "Write a Python function that implements binary search on a sorted list. Include type hints."}
    ],
    max_tokens=2048
)

print(response.choices[0].message.content)
```

**Example Output:**

````text Output theme={null}
Here's a Python function implementing binary search on a sorted list, with comprehensive type hints:

```python
from typing import Sequence, TypeVar, Optional

T = TypeVar('T')

def binary_search(sorted_list: Sequence[T], target: T) -> Optional[int]:
    """
    Perform binary search on a sorted list to find the index of a target element.

    Args:
        sorted_list: A sequence (e.g., list, tuple) sorted in ascending order.
        target: The element to search for in the list.

    Returns:
        The index of the target element if found, or None if not found.

    Time Complexity: O(log n)
    Space Complexity: O(1)

    Note:
        The function assumes the list is sorted in ascending order.
        If the list contains duplicate elements, it returns the index of one of them.
    """
    left = 0
    right = len(sorted_list) - 1

    while left <= right:
        mid = (left + right) // 2
        mid_val = sorted_list[mid]

        if mid_val == target:
            return mid
        elif mid_val < target:
            left = mid + 1
        else:
            right = mid - 1

    return None
```

### Example usage:

```python
# Example 1: Finding an existing element
numbers = [1, 3, 5, 7, 9, 11]
print(binary_search(numbers, 7))  # Output: 3

# Example 2: Element not in the list
print(binary_search(numbers, 4))  # Output: None

# Example 3: Empty list
print(binary_search([], 5))  # Output: None

# Example 4: Single element
print(binary_search([1], 1))  # Output: 0
print(binary_search([1], 2))  # Output: None
```

### Key features:
- Uses `TypeVar` to support generic types (as long as comparison operations are defined)
- Returns `Optional[int]` to indicate either the index or no match found
- Uses `Sequence[T]` to accept any sequence type (list, tuple, etc.)
- Includes comprehensive docstring with time/space complexity
- Implements standard iterative binary search for O(1) space complexity
````

#### 4.2.2 Streaming Example

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="Qwen/Qwen3-Coder-Next",
    messages=[
        {"role": "user", "content": "Explain the difference between a stack and a queue in 3 sentences."}
    ],
    max_tokens=512,
    stream=True
)

for chunk in response:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
print()
```

**Example Output:**

```text Output theme={null}
A **stack** follows the **Last In, First Out (LIFO)** principle, meaning the last element added is the first one removed—operations like `push` (add) and `pop` (remove) occur at the same end, called the *top*. In contrast, a **queue** follows the **First In, First Out (FIFO)** principle, where elements are added at the *back* (enqueue) and removed from the *front* (dequeue), preserving the order of insertion. This structural difference makes stacks ideal for tasks like function call management and expression evaluation, while queues suit scheduling, buffering, and breadth-first traversal.
```

#### 4.2.3 Tool Calling Example

Qwen3-Coder-Next supports tool calling capabilities. Make sure `--tool-call-parser qwen3_coder` is included in the deployment command above.

**Python Example:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "execute_code",
            "description": "Execute Python code and return the result",
            "parameters": {
                "type": "object",
                "properties": {
                    "code": {
                        "type": "string",
                        "description": "The Python code to execute"
                    }
                },
                "required": ["code"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="Qwen/Qwen3-Coder-Next",
    messages=[
        {"role": "user", "content": "Calculate the factorial of 10 using Python"}
    ],
    tools=tools
)

# Check if the model wants to call a tool
if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    print(f"Tool: {tool_call.function.name}")
    print(f"Arguments: {tool_call.function.arguments}")
else:
    print(response.choices[0].message.content)
```

**Example Output:**

```text Output theme={null}
Tool: execute_code
Arguments: {"code": "import math\nmath.factorial(10)"}
```

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU (2x)
* Model: Qwen/Qwen3-Coder-Next
* Tensor Parallelism: 2
* sglang version: 0.5.8+

#### 5.1.1 Standard Scenario Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Coder-Next \
  --tp 2 \
  --host 0.0.0.0 \
  --port 30000
```

##### 5.1.1.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  27.86
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  4220
Total generated tokens (retokenized):    4218
Request throughput (req/s):              0.36
Input token throughput (tok/s):          219.00
Output token throughput (tok/s):         151.48
Peak output token throughput (tok/s):    166.00
Peak concurrent requests:                2
Total token throughput (tok/s):          370.48
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2784.14
Median E2E Latency (ms):                 2258.08
P90 E2E Latency (ms):                    5044.43
P99 E2E Latency (ms):                    6130.52
---------------Time to First Token----------------
Mean TTFT (ms):                          161.68
Median TTFT (ms):                        168.09
P99 TTFT (ms):                           183.26
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          6.19
Median TPOT (ms):                        6.23
P99 TPOT (ms):                           6.32
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.23
Median ITL (ms):                         6.23
P95 ITL (ms):                            6.51
P99 ITL (ms):                            6.64
Max ITL (ms):                            13.45
==================================================
```

##### 5.1.1.2 Medium Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  39.06
Total input tokens:                      39668
Total input text tokens:                 39668
Total generated tokens:                  40805
Total generated tokens (retokenized):    40789
Request throughput (req/s):              2.05
Input token throughput (tok/s):          1015.62
Output token throughput (tok/s):         1044.73
Peak output token throughput (tok/s):    1664.00
Peak concurrent requests:                21
Total token throughput (tok/s):          2060.34
Concurrency:                             14.16
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   6910.97
Median E2E Latency (ms):                 7248.27
P90 E2E Latency (ms):                    11612.63
P99 E2E Latency (ms):                    13933.91
---------------Time to First Token----------------
Mean TTFT (ms):                          183.48
Median TTFT (ms):                        156.50
P99 TTFT (ms):                           311.46
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          13.61
Median TPOT (ms):                        13.59
P99 TPOT (ms):                           21.11
---------------Inter-Token Latency----------------
Mean ITL (ms):                           13.22
Median ITL (ms):                         9.76
P95 ITL (ms):                            10.43
P99 ITL (ms):                            158.04
Max ITL (ms):                            394.39
==================================================
```

##### 5.1.1.3 High Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  102.81
Total input tokens:                      249831
Total input text tokens:                 249831
Total generated tokens:                  252662
Total generated tokens (retokenized):    252536
Request throughput (req/s):              4.86
Input token throughput (tok/s):          2429.99
Output token throughput (tok/s):         2457.53
Peak output token throughput (tok/s):    5299.00
Peak concurrent requests:                109
Total token throughput (tok/s):          4887.52
Concurrency:                             94.28
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   19385.20
Median E2E Latency (ms):                 17584.09
P90 E2E Latency (ms):                    36762.15
P99 E2E Latency (ms):                    42518.35
---------------Time to First Token----------------
Mean TTFT (ms):                          270.62
Median TTFT (ms):                        159.65
P99 TTFT (ms):                           938.90
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          38.57
Median TPOT (ms):                        41.78
P99 TPOT (ms):                           53.28
---------------Inter-Token Latency----------------
Mean ITL (ms):                           37.90
Median ITL (ms):                         18.26
P95 ITL (ms):                            167.82
P99 ITL (ms):                            311.45
Max ITL (ms):                            993.20
==================================================
```

#### 5.1.2 Reasoning Scenario Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Coder-Next \
  --tp 2 \
  --host 0.0.0.0 \
  --port 30000
```

##### 5.1.2.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  285.02
Total input tokens:                      6101
Total input text tokens:                 6101
Total generated tokens:                  44462
Total generated tokens (retokenized):    44432
Request throughput (req/s):              0.04
Input token throughput (tok/s):          21.41
Output token throughput (tok/s):         156.00
Peak output token throughput (tok/s):    173.00
Peak concurrent requests:                2
Total token throughput (tok/s):          177.40
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   28499.54
Median E2E Latency (ms):                 30424.65
P90 E2E Latency (ms):                    49132.26
P99 E2E Latency (ms):                    51075.28
---------------Time to First Token----------------
Mean TTFT (ms):                          95.51
Median TTFT (ms):                        93.86
P99 TTFT (ms):                           112.56
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          6.24
Median TPOT (ms):                        6.30
P99 TPOT (ms):                           6.60
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.39
Median ITL (ms):                         6.34
P95 ITL (ms):                            7.16
P99 ITL (ms):                            7.42
Max ITL (ms):                            12.48
==================================================
```

##### 5.1.2.2 Medium Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  237.77
Total input tokens:                      39668
Total input text tokens:                 39668
Total generated tokens:                  318306
Total generated tokens (retokenized):    315646
Request throughput (req/s):              0.34
Input token throughput (tok/s):          166.83
Output token throughput (tok/s):         1338.72
Peak output token throughput (tok/s):    1727.00
Peak concurrent requests:                19
Total token throughput (tok/s):          1505.55
Concurrency:                             13.88
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   41266.21
Median E2E Latency (ms):                 41010.10
P90 E2E Latency (ms):                    77574.22
P99 E2E Latency (ms):                    82688.04
---------------Time to First Token----------------
Mean TTFT (ms):                          140.73
Median TTFT (ms):                        84.52
P99 TTFT (ms):                           365.86
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.32
Median TPOT (ms):                        10.38
P99 TPOT (ms):                           10.87
---------------Inter-Token Latency----------------
Mean ITL (ms):                           10.34
Median ITL (ms):                         10.19
P95 ITL (ms):                            10.75
P99 ITL (ms):                            11.18
Max ITL (ms):                            206.79
==================================================
```

##### 5.1.2.3 High Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 8000 \
  --num-prompts 320 \
  --max-concurrency 64
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  384.82
Total input tokens:                      158939
Total input text tokens:                 158939
Total generated tokens:                  1301025
Total generated tokens (retokenized):    1299908
Request throughput (req/s):              0.83
Input token throughput (tok/s):          413.02
Output token throughput (tok/s):         3380.83
Peak output token throughput (tok/s):    4317.00
Peak concurrent requests:                69
Total token throughput (tok/s):          3793.85
Concurrency:                             56.42
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   67847.54
Median E2E Latency (ms):                 70724.38
P90 E2E Latency (ms):                    120888.83
P99 E2E Latency (ms):                    133234.48
---------------Time to First Token----------------
Mean TTFT (ms):                          212.24
Median TTFT (ms):                        115.96
P99 TTFT (ms):                           652.93
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          16.76
Median TPOT (ms):                        16.99
P99 TPOT (ms):                           18.18
---------------Inter-Token Latency----------------
Mean ITL (ms):                           16.64
Median ITL (ms):                         15.83
P95 ITL (ms):                            31.64
P99 ITL (ms):                            90.85
Max ITL (ms):                            576.60
==================================================
```

#### 5.1.3 Summarization Scenario Benchmark

##### 5.1.3.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  29.42
Total input tokens:                      41941
Total input text tokens:                 41941
Total generated tokens:                  4220
Total generated tokens (retokenized):    4220
Request throughput (req/s):              0.34
Input token throughput (tok/s):          1425.35
Output token throughput (tok/s):         143.42
Peak output token throughput (tok/s):    169.00
Peak concurrent requests:                3
Total token throughput (tok/s):          1568.77
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2941.19
Median E2E Latency (ms):                 2411.84
P90 E2E Latency (ms):                    5661.26
P99 E2E Latency (ms):                    6497.45
---------------Time to First Token----------------
Mean TTFT (ms):                          139.46
Median TTFT (ms):                        160.33
P99 TTFT (ms):                           184.30
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          6.56
Median TPOT (ms):                        6.65
P99 TPOT (ms):                           7.29
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.65
Median ITL (ms):                         6.68
P95 ITL (ms):                            7.39
P99 ITL (ms):                            7.51
Max ITL (ms):                            16.34
==================================================
```

##### 5.1.3.2 Medium Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  41.62
Total input tokens:                      300020
Total input text tokens:                 300020
Total generated tokens:                  41669
Total generated tokens (retokenized):    41664
Request throughput (req/s):              1.92
Input token throughput (tok/s):          7208.67
Output token throughput (tok/s):         1001.19
Peak output token throughput (tok/s):    1536.00
Peak concurrent requests:                21
Total token throughput (tok/s):          8209.86
Concurrency:                             14.27
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   7421.29
Median E2E Latency (ms):                 7985.77
P90 E2E Latency (ms):                    12122.09
P99 E2E Latency (ms):                    14595.05
---------------Time to First Token----------------
Mean TTFT (ms):                          248.49
Median TTFT (ms):                        179.25
P99 TTFT (ms):                           915.90
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          14.13
Median TPOT (ms):                        14.28
P99 TPOT (ms):                           24.02
---------------Inter-Token Latency----------------
Mean ITL (ms):                           13.80
Median ITL (ms):                         10.46
P95 ITL (ms):                            11.00
P99 ITL (ms):                            173.14
Max ITL (ms):                            823.32
==================================================
```

##### 5.1.3.3 High Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-Coder-Next \
  --dataset-name random \
  --random-input-len 8000 \
  --random-output-len 1000 \
  --num-prompts 320 \
  --max-concurrency 64
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 64
Successful requests:                     320
Benchmark duration (s):                  85.74
Total input tokens:                      1273893
Total input text tokens:                 1273893
Total generated tokens:                  170000
Total generated tokens (retokenized):    169983
Request throughput (req/s):              3.73
Input token throughput (tok/s):          14858.12
Output token throughput (tok/s):         1982.80
Peak output token throughput (tok/s):    3734.00
Peak concurrent requests:                70
Total token throughput (tok/s):          16840.92
Concurrency:                             59.75
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   16008.12
Median E2E Latency (ms):                 15460.65
P90 E2E Latency (ms):                    27705.81
P99 E2E Latency (ms):                    32874.74
---------------Time to First Token----------------
Mean TTFT (ms):                          476.99
Median TTFT (ms):                        177.50
P99 TTFT (ms):                           3014.39
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          29.81
Median TPOT (ms):                        31.19
P99 TPOT (ms):                           45.53
---------------Inter-Token Latency----------------
Mean ITL (ms):                           29.29
Median ITL (ms):                         15.75
P95 ITL (ms):                            173.94
P99 ITL (ms):                            202.00
Max ITL (ms):                            2783.23
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200 \
  --num-threads 64
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

* **Test Results:**

```text Output theme={null}
Accuracy: 0.965
Invalid: 0.000
Latency: 26.407 s
Output throughput: 929.132 token/s
```

#### 5.2.2 MMLU Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run mmlu \
  --base-url http://127.0.0.1:30000/v1 \
  --num-threads 64 --max-tokens 2048
```

Historical results below use the removed harness and are not measurements of the sgl-eval command above.

* **Test Results:**

```text Output theme={null}
subject: abstract_algebra, #q:100, acc: 0.780
subject: anatomy, #q:135, acc: 0.807
subject: astronomy, #q:152, acc: 0.921
subject: business_ethics, #q:100, acc: 0.820
subject: clinical_knowledge, #q:265, acc: 0.860
subject: college_biology, #q:144, acc: 0.944
subject: college_chemistry, #q:100, acc: 0.590
subject: college_computer_science, #q:100, acc: 0.820
subject: college_mathematics, #q:100, acc: 0.800
subject: college_medicine, #q:173, acc: 0.803
subject: college_physics, #q:102, acc: 0.775
subject: computer_security, #q:100, acc: 0.880
subject: conceptual_physics, #q:235, acc: 0.936
subject: econometrics, #q:114, acc: 0.807
subject: electrical_engineering, #q:145, acc: 0.834
subject: elementary_mathematics, #q:378, acc: 0.854
subject: formal_logic, #q:126, acc: 0.802
subject: global_facts, #q:100, acc: 0.610
subject: high_school_biology, #q:310, acc: 0.971
subject: high_school_chemistry, #q:203, acc: 0.803
subject: high_school_computer_science, #q:100, acc: 0.920
subject: high_school_european_history, #q:165, acc: 0.891
subject: high_school_geography, #q:198, acc: 0.929
subject: high_school_government_and_politics, #q:193, acc: 0.969
subject: high_school_macroeconomics, #q:390, acc: 0.903
subject: high_school_mathematics, #q:270, acc: 0.689
subject: high_school_microeconomics, #q:238, acc: 0.962
subject: high_school_physics, #q:151, acc: 0.854
subject: high_school_psychology, #q:545, acc: 0.947
subject: high_school_statistics, #q:216, acc: 0.815
subject: high_school_us_history, #q:204, acc: 0.907
subject: high_school_world_history, #q:237, acc: 0.937
subject: human_aging, #q:223, acc: 0.821
subject: human_sexuality, #q:131, acc: 0.840
subject: international_law, #q:121, acc: 0.934
subject: jurisprudence, #q:108, acc: 0.870
subject: logical_fallacies, #q:163, acc: 0.847
subject: machine_learning, #q:112, acc: 0.812
subject: management, #q:103, acc: 0.922
subject: marketing, #q:234, acc: 0.923
subject: medical_genetics, #q:100, acc: 0.970
subject: miscellaneous, #q:783, acc: 0.941
subject: moral_disputes, #q:346, acc: 0.850
subject: moral_scenarios, #q:895, acc: 0.726
subject: nutrition, #q:306, acc: 0.915
subject: philosophy, #q:311, acc: 0.859
subject: prehistory, #q:324, acc: 0.889
subject: professional_accounting, #q:282, acc: 0.723
subject: professional_law, #q:1534, acc: 0.648
subject: professional_medicine, #q:272, acc: 0.923
subject: professional_psychology, #q:612, acc: 0.845
subject: public_relations, #q:110, acc: 0.782
subject: security_studies, #q:245, acc: 0.796
subject: sociology, #q:201, acc: 0.925
subject: us_foreign_policy, #q:100, acc: 0.950
subject: virology, #q:166, acc: 0.572
subject: world_religions, #q:171, acc: 0.883
Total latency: 208.985
Average accuracy: 0.834
```


# Qwen3-Next
Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3-Next



## 1. Model Introduction

[Qwen3-Next](https://huggingface.co/collections/Qwen/qwen3-next) is an advanced large language model architecture developed by Alibaba's Qwen team, designed to enhance efficiency and performance in handling extensive contexts and large-scale parameters. It features advanced capabilities in reasoning, function calling, and multilingual understanding.

Qwen3-Next introduces several groundbreaking innovations:

* **Hybrid Attention Mechanism**: Replaces standard attention with a combination of **Gated DeltaNet** (linear attention) and **Full Attention**, enabling efficient processing of context lengths up to 262,144 tokens. This hybrid approach makes it ideal for analyzing lengthy documents such as entire books or contracts.

* **Highly Sparse Mixture-of-Experts (MoE)**: Features an 80-billion parameter architecture where only 3 billion parameters are active during inference. This design reduces computational costs by up to 90% while maintaining high performance, drastically reducing FLOPs per token without compromising model capacity.

* **Multi-Token Prediction (MTP)**: Enables generation of multiple tokens per inference step, significantly reducing latency and enhancing user experience in real-time applications. This innovation boosts both pretraining performance and inference speed.

* **Multilingual Support**: Natively supports 119 languages, facilitating seamless cross-lingual tasks and making it versatile for global applications.

* **Enterprise-Ready Deployment**: Released under the Apache 2.0 license, offering flexible deployment options including on-premises, virtual private cloud (VPC), and private cloud environments, ensuring security and compliance for enterprise use.

* **Advanced Reasoning & Stability**: Demonstrates clear improvement in reasoning performance with support for tool use during inference. Includes stability optimizations such as **zero-centered** and **weight-decayed layernorm** for robust pre-training and post-training.

For more details, please refer to the [official Qwen3-Next blog](https://qwen.ai/blog?id=4074cca80393150c248e508aa62983f9cb7d27cd\&from=research.latest-advancements-list).

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

The Qwen3-Next series comes in only one size but offers different thinking modes. Recommended starting configurations vary depending on hardware.

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model size, quantization method, and thinking capabilities.

Run this Command:


### 3.2 Configuration Tips

* `--max-mamba-cache-size`: Adjust `--max-mamba-cache-size` to increase mamba cache space and max running requests capability. It will decrease KV cache space as a trade-off. You can adjust it according to workload.

* `--mamba-ssm-dtype`: `bfloat16` or `float32`, use `bfloat16` to save mamba cache size and `float32` to get more accurate results. The default setting is `float32`.

* `--mamba-full-memory-ratio`: Adjust `--mamba-full-memory-ratio` to set the ratio of mamba state memory to full kv cache memory. The default setting is `0.9`.

* **Mamba Radix Cache**: Qwen3-Next's hybrid Gated Delta Networks architecture supports two mamba scheduling strategies via `--mamba-radix-cache-strategy`:
  * **V1 (`no_buffer`)**: Default. No overlap scheduler, lower memory usage.
  * **V2 (`extra_buffer`)**: Enables overlap scheduling and branching point caching with `--mamba-radix-cache-strategy extra_buffer --page-size 64`. Requires FLA kernel backend. Trades higher mamba state memory for better throughput. Strictly superior in non-KV-cache-bound scenarios; in KV-cache-bound cases, weigh the overlap scheduling benefit against reduced max concurrency. `--page-size` must satisfy `FLA_CHUNK_SIZE % page_size == 0` or `page_size % FLA_CHUNK_SIZE == 0` (`FLA_CHUNK_SIZE` is currently 64).

* **Xeon CPU service configuration**: Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

1. **Streaming with Thinking Process:**

   Qwen3-Next-80B-A3B-Thinking only supports thinking mode. Enable the reasoning parser during deployment to separate the thinking and the content sections.

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Next-80B-A3B-Thinking \
  --reasoning-parser qwen3 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="Qwen/Qwen3-Next-80B-A3B-Thinking",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
Okay, let's see. I need to find 15% of 240. Hmm, percentages. Right, "percent" means per hundred, so 15% is 15 per 100, or 15/100. To find a percentage of a number, I think you multiply the number by the percentage as a decimal. So first, maybe convert 15% to a decimal. To convert a percentage to a decimal, you divide by 100. So 15 divided by 100 is 0.15. Then, multiply that by 240. Let me check that. So 0.15 times 240. Let's calculate that. Maybe break it down. 10% of 240 is 24, because 10% is just moving the decimal one place left, so 240 becomes 24. Then 5% would be half of 10%, so half of 24 is 12. So 10% + 5% = 15%, so 24 + 12 = 36. Oh, that's another way to do it. Let me verify with the multiplication. 0.15 * 240. Let's do 240 * 0.1 = 24, 240 * 0.05 = 12, so 24 + 12 = 36. Yep, that works. Alternatively, 240 * 15 = 3600, then divide by 100, which is 36. Because 15% of 240 is (15/100)*240 = (15*240)/100. 15*240: 10*240=2400, 5*240=1200, so 2400+1200=3600. Then 3600/100=36. So that's 36. So the answer should be 36. Let me make sure. 15% of 240. If I take 240 and multiply by 0.15, 240*0.15. Let's compute 240*0.1=24, 240*0.05=12, so 24+12=36. Yep, that's right. So 15% of 240 is 36.

=============== Content =================

To find **15% of 240**, follow these steps:

---

### **Step 1: Understand what "percent" means**
- "Percent" means **per hundred**, so **15% = 15/100 = 0.15** in decimal form.

---

### **Step 2: Multiply the number by the decimal**
- To find 15% of 240, multiply:
  $$
  240 \times 0.15
  $$

---

### **Step 3: Break it down for clarity (optional but helpful)**
- **10% of 240** = $ 240 \times 0.1 = 24 $
- **5% of 240** = $ 240 \times 0.05 = 12 $
- Add them together:
  $$
  24 + 12 = 36
  $$

---

### **Step 4: Confirm with direct multiplication**
- $ 240 \times 0.15 = 36 $

---

### ✅ Final Answer:
$$
\boxed{36}
$$
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

2. **Turn off Thinking:**

   Qwen3-Next-80B-A3B-Instruct only supports instruct (non-thinking) mode.

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Next-80B-A3B-Instruct \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Turn off thinking process
response = client.chat.completions.create(
    model="Qwen/Qwen3-Next-80B-A3B-Instruct",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True,
    extra_body={"chat_template_kwargs": {"enable_thinking": False}}
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
To find **15% of 240**, follow these steps:

---

### **Step 1: Understand what percentage means**
"Percent" means "per hundred," so **15%** is the same as **15 per 100**, or the fraction:

$$
\frac{15}{100}
$$

---

### **Step 2: Multiply the fraction by the number**
To find 15% of 240, multiply:

$$
\frac{15}{100} \times 240
$$

---

### **Step 3: Simplify the multiplication**
You can simplify this in a couple of ways.

#### **Option A: Multiply first, then divide**
$$
15 \times 240 = 3600
$$
Then divide by 100:
$$
\frac{3600}{100} = 36
$$

#### **Option B: Simplify the fraction first**
$$
\frac{15}{100} = \frac{3}{20} \quad \text{(divided numerator and denominator by 5)}
$$
Now multiply:
$$
\frac{3}{20} \times 240 = \frac{3 \times 240}{20} = \frac{720}{20} = 36
$$

---

### **Step 4: Final Answer**
$$
\boxed{36}
$$

So, **15% of 240 is 36**.
```

#### 4.2.2 Tool Calling

Qwen/Qwen3-Next-80B-A3B-Instruct | Qwen/Qwen3-Next-80B-A3B-Thinking both support tool calling capabilities. Enable the tool call parser:

**Python Example (without Thinking Process):**

Start sglang server:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Next-80B-A3B-Instruct \
  --tool-call-parser qwen \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="Qwen/Qwen3-Next-80B-A3B-Instruct",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                if tool_call.function:
                    print(f"🔧 Tool Call: {tool_call.function.name}")
                    print(f"   Arguments: {tool_call.function.arguments}")

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}

{"name": "get_weather", "arguments": {"location": "Beijing"}}

```

**Python Example (with Thinking Process):**

Start sglang server:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Next-80B-A3B-Thinking \
  --reasoning-parser qwen3 \
  --tool-call-parser qwen \
  --tp 8 \
  --host 0.0.0.0 \
  --port 8000
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:8000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="Qwen/Qwen3-Next-80B-A3B-Thinking",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                if tool_call.function:
                    print(f"🔧 Tool Call: {tool_call.function.name}")
                    print(f"   Arguments: {tool_call.function.arguments}")

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
Okay, the user is asking for the weather in Beijing. Let me check the available tools. There's a get_weather function that requires location and optionally unit. The location is needed, so I need to provide Beijing as the location. The unit is optional, but the user didn't specify Celsius or Fahrenheit. Since the default might be Celsius, but maybe I should check if the parameters require unit. Wait, the required field is only location, so unit is optional. So I can just call get_weather with location "Beijing" and not include the unit. Let me confirm the parameters. The parameters for get_weather have location as required, and unit is an enum with celsius or fahrenheit, but not required. So the correct call is to send location as Beijing, and omit unit. So the tool call should be {"name": "get_weather", "arguments": {"location": "Beijing"}}.


{"name": "get_weather", "arguments": {"location": "Beijing"}}

```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="Qwen/Qwen3-Next-80B-A3B-Thinking",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The weather in Beijing is currently 22°C and sunny."
```

#### 4.2.3 Processing Ultra-Long Texts

Qwen3-Next natively supports context lengths of up to 262,144 tokens. For conversations where the total length (including both input and output) significantly exceeds this limit, we recommend using RoPE scaling techniques to handle long texts effectively. We have validated the model's performance on context lengths of up to 1 million tokens using the YaRN method.

**Qwen3-Next-80B-A3B-Instruct**

```shell Command theme={null}
SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 python -m sglang.launch_server --model Qwen/Qwen3-Next-80B-A3B-Instruct    --tp 8   --host 0.0.0.0   --port 8000 --json-model-override-args '{"rope_scaling":{"rope_type":"yarn","factor":4.0,"original_max_position_embeddings":262144}}' --context-length 1010000

```

**Qwen3-Next-80B-A3B-Thinking**

```shell Command theme={null}
SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 python -m sglang.launch_server --model Qwen/Qwen3-Next-80B-A3B-Thinking   --reasoning-parser qwen3     --tp 8   --host 0.0.0.0   --port 8000 --json-model-override-args '{"rope_scaling":{"rope_type":"yarn","factor":4.0,"original_max_position_embeddings":262144}}' --context-length 1010000

```

#### 4.2.4 Multi-Token Prediction (NEXTN Speculative Decoding)

Qwen3-Next ships built-in Multi-Token Prediction (MTP) layers and supports [EAGLE-style speculative decoding](../../../docs/advanced_features/speculative_decoding#eagle-decoding) through the `NEXTN` algorithm. The MTP weights are bundled in the main checkpoint, so no separate draft model is required.

```shell Command theme={null}
python3 -m sglang.launch_server \
  --model Qwen/Qwen3-Next-80B-A3B-Instruct \
  --speculative-algorithm NEXTN \
  --speculative-num-steps 3 \
  --speculative-eagle-topk 1 \
  --speculative-num-draft-tokens 4 \
  --tp 4
```

Tune `--speculative-num-steps`, `--speculative-eagle-topk`, and `--speculative-num-draft-tokens` for your workload with [bench\_speculative.py](https://github.com/sgl-project/sglang/blob/main/scripts/playground/bench_speculative.py). See [PR #10233](https://github.com/sgl-project/sglang/pull/10233) for implementation details.

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8x)
* Tensor Parallelism: 8
* Model: Qwen/Qwen3-Next-80B-A3B-Instruct
* sglang version: 0.5.6

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios.

#### 5.1.1 Latency-Sensitive Benchmark

* Server Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Next-80B-A3B-Instruct \
  --tp 8
```

* Test Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --num-prompt 100 \
  --max-concurrency 1
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     100
Benchmark duration (s):                  146.52
Total input tokens:                      33839
Total input text tokens:                 33839
Total input vision tokens:               0
Total generated tokens:                  21640
Total generated tokens (retokenized):    21619
Request throughput (req/s):              0.68
Input token throughput (tok/s):          230.95
Output token throughput (tok/s):         147.70
Peak output token throughput (tok/s):    164.00
Peak concurrent requests:                6
Total token throughput (tok/s):          378.65
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   1464.81
Median E2E Latency (ms):                 1077.48
---------------Time to First Token----------------
Mean TTFT (ms):                          127.88
Median TTFT (ms):                        132.88
P99 TTFT (ms):                           212.85
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          6.19
Median TPOT (ms):                        6.17
P99 TPOT (ms):                           6.64
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.21
Median ITL (ms):                         6.16
P95 ITL (ms):                            6.51
P99 ITL (ms):                            6.71
Max ITL (ms):                            10.07
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Server Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-Next-80B-A3B-Instruct \
  --tp 8 \
```

* Test Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --num-prompt 1000 \
  --max-concurrency 100
```

**Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  100.32
Total input tokens:                      302118
Total input text tokens:                 302118
Total input vision tokens:               0
Total generated tokens:                  195775
Total generated tokens (retokenized):    195016
Request throughput (req/s):              9.97
Input token throughput (tok/s):          3011.69
Output token throughput (tok/s):         1951.60
Peak output token throughput (tok/s):    5909.00
Peak concurrent requests:                120
Total token throughput (tok/s):          4963.29
Concurrency:                             93.05
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   9333.98
Median E2E Latency (ms):                 6054.12
---------------Time to First Token----------------
Mean TTFT (ms):                          161.77
Median TTFT (ms):                        137.94
P99 TTFT (ms):                           503.29
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          50.87
Median TPOT (ms):                        50.28
P99 TPOT (ms):                           122.87
---------------Inter-Token Latency----------------
Mean ITL (ms):                           47.11
Median ITL (ms):                         13.84
P95 ITL (ms):                            195.33
P99 ITL (ms):                            289.56
Max ITL (ms):                            486.38
==================================================
```

### 5.2 Accuracy Benchmark

### 5.2.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:8000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* **Results**:

  * Qwen3-Next-80B-A3B-Instruct

    ```
    Accuracy: 0.960
    Invalid: 0.000
    Latency: 12.673 s
    Output throughput: 2538.255 token/s
    ```

  * Qwen3-Next-80B-A3B-Thinking
    ```
    Accuracy: 0.935
    Invalid: 0.000
    Latency: 9.912 s
    Output throughput: 3288.737 token/s
    ```

### 5.2.2 MMLU Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run mmlu \
  --base-url http://127.0.0.1:30000/v1 \
  --num-threads 64 --max-tokens 2048
```

The command evaluates all 57 subjects. Historical results below use the removed 10-subject harness and are not measurements of the sgl-eval command above.

* **Results**:

  * Qwen3-Next-80B-A3B-Instruct

    ```
    subject: abstract_algebra, #q:100, acc: 0.800
    subject: anatomy, #q:135, acc: 0.807
    subject: astronomy, #q:152, acc: 0.947
    subject: business_ethics, #q:100, acc: 0.810
    subject: clinical_knowledge, #q:265, acc: 0.894
    subject: college_biology, #q:144, acc: 0.972
    subject: college_chemistry, #q:100, acc: 0.680
    subject: college_computer_science, #q:100, acc: 0.860
    subject: college_mathematics, #q:100, acc: 0.780
    subject: college_medicine, #q:173, acc: 0.861
    Total latency: 10.098
    Average accuracy: 0.856
    ```

  * Qwen3-Next-80B-A3B-Thinking
    ```
    subject: abstract_algebra, #q:100, acc: 0.780
    subject: anatomy, #q:135, acc: 0.815
    subject: astronomy, #q:152, acc: 0.941
    subject: business_ethics, #q:100, acc: 0.870
    subject: clinical_knowledge, #q:265, acc: 0.894
    subject: college_biology, #q:144, acc: 0.965
    subject: college_chemistry, #q:100, acc: 0.670
    subject: college_computer_science, #q:100, acc: 0.840
    subject: college_mathematics, #q:100, acc: 0.770
    subject: college_medicine, #q:173, acc: 0.861
    Total latency: 10.236
    Average accuracy: 0.855
    ```


# Qwen3-VL
Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3-VL



## 1. Model Introduction

[Qwen3-VL series](https://github.com/QwenLM/Qwen3-VL) are the most powerful vision-language models in the Qwen series to date, featuring advanced capabilities in multi-modal understanding, reasoning, and agentic applications.

This generation delivers comprehensive upgrades across the board:

* **Superior text understanding & generation**: Qwen3-VL-235B-A22B-Instruct was ranked as the [#1 open model for text on lmarena.ai](https://x.com/arena/status/1973151703563460942)
* **Deeper visual perception & reasoning**: Enhanced image and video understanding capabilities.
* **Extended context length**: Supports up to 262K tokens for processing long documents and videos.
* **Enhanced spatial and video dynamics comprehension**: Better understanding of spatial relationships and temporal dynamics.
* **Stronger agent interaction capabilities**: Improved tool use and search-based agent performance.
* **Flexible deployment options**: Available in Dense and MoE architectures that scale from edge to cloud, with Instruct and reasoning-enhanced Thinking editions.

For more details, please refer to the [official Qwen3-VL GitHub Repository](https://github.com/QwenLM/Qwen3-VL).

## 2. SGLang Installation

SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements.

Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions.

For SGLang CPU installation, please refer to the [CPU version installation guide](../../../docs/hardware-platforms/cpu_server#installation).

## 3. Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

The Qwen3-VL series offers models in various sizes and architectures, optimized for different hardware platforms including NVIDIA and AMD GPUs, as well as Intel Xeon CPUs. The recommended launch configurations vary by hardware and model size.

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model size, quantization method, and thinking capabilities.

Run this Command:


### 3.2 Configuration Tips

* **Multimodal attention backend** : Usually, `--mm-attention-backend` is default to `fa3` on H100/H200/A100 for better performance, but it is default to `triton_attn` on B200 for compatibility.
* **TTFT Optimization** : Set `SGLANG_USE_CUDA_IPC_TRANSPORT=1` to use CUDA IPC for transferring multimodal features, which significantly improves TTFT. This consumes additional memory and may require adjusting `--mem-fraction-static` and/or `--max-running-requests`. (additional memory is proportional to image size \* number of images in current running requests.)
* **Memory Management** : Set lower `--context-length` to conserve memory. A value of `128000` is sufficient for most scenarios, down from the default 262K.
* **Expert Parallelism** : SGLang supports Expert Parallelism (EP) via `--ep`, allowing experts in MoE models to be deployed on separate GPUs for better throughput. One thing to note is that, for quantized models, you need to set `--ep` to a value that satisfies the requirement: `(moe_intermediate_size / moe_tp_size) % weight_block_size_n == 0, where moe_tp_size is equal to tp_size divided by ep_size.` Note that EP may perform worse in low concurrency scenarios due to additional communication overhead. Check out [Expert Parallelism Deployment](../../../docs/advanced_features/expert_parallelism) for more details.
* **Kernel Tuning** : For MoE Triton kernel tuning on your specific hardware, refer to [fused\_moe\_triton](https://github.com/sgl-project/sglang/tree/main/benchmark/kernels/fused_moe_triton).

**Hardware-specific notes:**

* **H100 (FP8):** Use the `Qwen/Qwen3-VL-235B-A22B-Instruct-FP8` checkpoint for best memory efficiency.
* **A100 / H100 (BF16):** Use standard multimodal parameters to manage throughput and GPU memory usage.
* **H200 / B200:** Runs out of the box, supporting full context length plus concurrent image + video processing.

**Additional multimodal server parameters:**

* `--mm-feature-transport=cuda_ipc`: Keep multimodal feature tensors in a bounded GPU pool shared over CUDA IPC to avoid device-to-host memory copies, improving performance for high-frequency inference.

**Example with full multimodal optimizations:**

```bash Command theme={null}
SGLANG_USE_CUDA_IPC_TRANSPORT=1 \
SGLANG_VLM_CACHE_SIZE_MB=0 \
python -m sglang.launch_server \
  --model-path Qwen/Qwen3-VL-235B-A22B-Instruct \
  --host 0.0.0.0 \
  --port 30000 \
  --trust-remote-code \
  --tp-size 8 \
  --enable-cache-report \
  --log-level info \
  --max-running-requests 64 \
  --mem-fraction-static 0.65 \
  --chunked-prefill-size 8192 \
  --attention-backend fa3 \
  --mm-attention-backend fa3 \
  --enable-metrics
```

* **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Multi-Modal Inputs

Qwen3-VL supports both image and video inputs. Here's a basic example with image input:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                }
            },
            {
                "type": "text",
                "text": "Read all the text in the image."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="Qwen/Qwen3-VL-235B-A22B-Instruct",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example Output:**

```text Output theme={null}
Response costs: 3.37s
Generated text: Auntie Anne's

CINNAMON SUGAR
1 x 17,000                    17,000

SUB TOTAL                    17,000

GRAND TOTAL                  17,000

CASH IDR                     20,000

CHANGE DUE                  3,000
```

**Multi-Image Input Example:**

Qwen3-VL can process multiple images in a single request for comparison or analysis:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://www.civitatis.com/f/china/hong-kong/guia/taxi.jpg"
                }
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://cdn.cheapoguides.com/wp-content/uploads/sites/7/2025/05/GettyImages-509614603-1280x600.jpg"
                }
            },
            {
                "type": "text",
                "text": "Compare these two images and describe the differences in 100 words or less. Focus on the key visual elements, colors, textures, and any notable contrasts between the two scenes. Be specific about what you see in each image."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="Qwen/Qwen3-VL-235B-A22B-Instruct",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example Output:**

```text Output theme={null}
Response costs: 10.18s
Generated text: The two images present starkly different portrayals of Hong Kong’s iconic red taxis, contrasting a dynamic street-level moment with a static, large-scale gathering.

The first image is a close-up, eye-level shot capturing a single red Toyota Crown taxi (license plate RX 5004) in motion or paused at an urban intersection. Its glossy red paint gleams under daylight, reflecting the vibrant, cluttered backdrop of a Hong Kong street — neon signs, glass-fronted shops displaying sunglasses, and Chinese characters. The taxi’s chrome grille, clear headlights, and black trim provide visual contrast. A green “4 SEATS” sticker and a “的士 TAXI” sign on the side reinforce its identity. The composition is intimate, focusing on the vehicle’s details — the texture of its paint, the slight reflections on the windows, and the crispness of its license plate. Other red taxis flank it, suggesting a bustling city rhythm, but the central taxi dominates the frame, conveying movement and immediacy.

In contrast, the second image is an elevated, wide-angle shot of dozens of red taxis — along with a few green ones — parked in neat, grid-like rows on what appears to be a highway or staging area. The scene is static, almost ceremonial. Many taxis have their hoods open, suggesting maintenance, inspection, or protest. People are scattered among the vehicles, some inspecting engines, others conversing — adding a human, documentary element. The dominant color remains red, but the repetition creates a visual pattern rather than individual focus. The green taxis offer a subtle color contrast, hinting at different service zones (green for New Territories, red for urban areas). The setting is more utilitarian — concrete barriers, metal railings, and sparse vegetation — with an overpass looming in the background. The texture here is less about polished paint and more about the collective mass of vehicles, the asphalt, and the functional layout.

Key contrasts emerge: the first image is kinetic and personal, emphasizing the taxi as a working vehicle in the city’s daily flow; the second is static and collective, portraying the taxis as a fleet, possibly for logistical or political purposes. The lighting in both is bright daylight, but the first has richer color saturation and depth due to its proximity and urban backdrop, while the second feels flatter, more documentary in tone. The first image invites you into the city’s pulse; the second invites you to observe a system — organized, perhaps even paused — from a distance.

In essence, the first image celebrates the individual taxi in its natural habitat; the second reveals the scale and structure behind the fleet, transforming the familiar red icon into a symbol of coordination, maintenance, or collective action. Both are quintessentially Hong Kong, yet they offer vastly different narratives — one of motion and commerce, the other of assembly and purpose.
```

**Video Input Example:**

Qwen3-VL supports video understanding by processing video URLs:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "video_url",
                "video_url": {
                    "url": "https://videos.pexels.com/video-files/4114797/4114797-uhd_3840_2160_25fps.mp4"
                }
            },
            {
                "type": "text",
                "text": "Describe what happens in this video."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="Qwen/Qwen3-VL-235B-A22B-Instruct",
    messages=messages,
    max_tokens=2048
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Note:**

* For video processing, ensure you have sufficient context length configured (up to 262K tokens)
* Video processing may require more memory; adjust `--mem-fraction-static` accordingly
* You can also provide local file paths using `file://` protocol

**Example Output:**

```text Output theme={null}
Response costs: 3.89s
Generated text: A person wearing blue gloves is using a microscope. They are adjusting the focus knob with one hand while holding a pipette with the other, suggesting they are preparing or examining a sample on the slide beneath the objective lens. The microscope's 40x objective lens is positioned over the slide, indicating a high-magnification observation. The person carefully manipulates the slide and the microscope controls, likely to achieve a clear view of the specimen.
```

#### 4.2.2 Reasoning Parser

Qwen3-VL-Thinking supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-VL-235B-A22B-Thinking \
  --reasoning-parser qwen3 \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="Qwen/Qwen3-VL-235B-A22B-Thinking",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
To solve this problem, I need to calculate 15% of 240.
Step 1: Convert 15% to decimal: 15% = 0.15
Step 2: Multiply 240 by 0.15
Step 3: 240 × 0.15 = 36
=============== Content =================

The answer is 36. To find 15% of 240, we multiply 240 by 0.15, which equals 36.
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.3 Tool Calling

Qwen3-VL supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-VL-235B-A22B-Thinking \
  --reasoning-parser qwen3 \
  --tool-call-parser qwen \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="Qwen/Qwen3-VL-235B-A22B-Thinking",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"🔧 Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
The user is asking about the weather in Beijing. I need to use the get_weather function to retrieve this information.
I should call the function with location="Beijing".
=============== Content =================

🔧 Tool Call: get_weather
   Arguments: {"location": "Beijing", "unit": "celsius"}
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="Qwen/Qwen3-VL-235B-A22B-Thinking",
    messages=messages,
    temperature=0.7
)

print(final_response.choices[0].message.content)
# Output: "The weather in Beijing is currently 22°C and sunny."
```

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8x)
* Model: Qwen3-VL-235B-A22B-Instruct
* Tensor Parallelism: 8
* sglang version: 0.5.6

We use SGLang's built-in benchmarking tool to conduct performance evaluation with random images. To simulate real-world usage, you can specify different input and output lengths for each request. For example, each request can have 128 input tokens, two 720p images, and 1024 output tokens.

#### 5.1.1 Latency-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-VL-235B-A22B-Instruct \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-VL-235B-A22B-Instruct \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  45.97
Total input tokens:                      18348
Total input text tokens:                 708
Total input vision tokens:               17640
Total generated tokens:                  4220
Total generated tokens (retokenized):    3423
Request throughput (req/s):              0.22
Input token throughput (tok/s):          399.17
Output token throughput (tok/s):         91.81
Peak output token throughput (tok/s):    96.00
Peak concurrent requests:                2
Total token throughput (tok/s):          490.98
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   4594.52
Median E2E Latency (ms):                 3725.04
---------------Time to First Token----------------
Mean TTFT (ms):                          193.35
Median TTFT (ms):                        196.32
P99 TTFT (ms):                           222.75
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.44
Median TPOT (ms):                        10.44
P99 TPOT (ms):                           10.47
---------------Inter-Token Latency----------------
Mean ITL (ms):                           11.78
Median ITL (ms):                         10.48
P95 ITL (ms):                            21.01
P99 ITL (ms):                            31.40
Max ITL (ms):                            31.92
==================================================
```

**Optimized Results (with CUDA IPC Transport):**

For further TTFT optimization, enable CUDA IPC Transport for multimodal features by setting `SGLANG_USE_CUDA_IPC_TRANSPORT=1`. This significantly reduces TTFT by using CUDA IPC for transferring multimodal features.

* Model Deployment Command:

```shell Command theme={null}
SGLANG_USE_CUDA_IPC_TRANSPORT=1 python -m sglang.launch_server \
  --model Qwen/Qwen3-VL-235B-A22B-Instruct \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-VL-235B-A22B-Instruct \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 100 \
  --max-concurrency 1
```

* **Test Results:**

  With `SGLANG_USE_CUDA_IPC_TRANSPORT=1`, TTFT improves significantly:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     100
Benchmark duration (s):                  566.84
Total input tokens:                      183667
Total input text tokens:                 7267
Total input vision tokens:               176400
Total generated tokens:                  52444
Total generated tokens (retokenized):    28702
Request throughput (req/s):              0.18
Input token throughput (tok/s):          324.02
Output token throughput (tok/s):         92.52
Peak output token throughput (tok/s):    96.00
Peak concurrent requests:                3
Total token throughput (tok/s):          416.54
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   5667.50
Median E2E Latency (ms):                 5830.00
---------------Time to First Token----------------
Mean TTFT (ms):                          191.16
Median TTFT (ms):                        182.58
P99 TTFT (ms):                           244.58
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          10.46
Median TPOT (ms):                        10.46
P99 TPOT (ms):                           10.48
---------------Inter-Token Latency----------------
Mean ITL (ms):                           13.91
Median ITL (ms):                         10.56
P95 ITL (ms):                            21.35
P99 ITL (ms):                            31.55
Max ITL (ms):                            42.36
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model Qwen/Qwen3-VL-235B-A22B-Instruct \
  --tp 8 \
  --host 0.0.0.0 \
  --port 30000
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model Qwen/Qwen3-VL-235B-A22B-Instruct \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  584.65
Total input tokens:                      1839015
Total input text tokens:                 75015
Total input vision tokens:               1764000
Total generated tokens:                  510855
Total generated tokens (retokenized):    284284
Request throughput (req/s):              1.71
Input token throughput (tok/s):          3145.50
Output token throughput (tok/s):         873.78
Peak output token throughput (tok/s):    2855.00
Peak concurrent requests:                107
Total token throughput (tok/s):          4019.29
Concurrency:                             98.35
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   57502.05
Median E2E Latency (ms):                 54301.08
---------------Time to First Token----------------
Mean TTFT (ms):                          5802.23
Median TTFT (ms):                        1444.75
P99 TTFT (ms):                           46675.92
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          100.22
Median TPOT (ms):                        105.43
P99 TPOT (ms):                           144.37
---------------Inter-Token Latency----------------
Mean ITL (ms):                           134.20
Median ITL (ms):                         25.57
P95 ITL (ms):                            558.14
P99 ITL (ms):                            1449.01
Max ITL (ms):                            33453.23
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 MMMU Benchmark

You can evaluate the model's accuracy using the MMMU dataset with `lmms_eval`:

* Benchmark Command:

```shell Command theme={null}
uv pip install lmms_eval

python3 -m lmms_eval \
  --model openai_compatible \
  --model_args "model=Qwen/Qwen3-VL-235B-A22B-Instruct,api_key=EMPTY,base_url=http://127.0.0.1:30000/v1/" \
  --tasks mmmu_val \
  --batch_size 128 \
  --log_samples \
  --log_samples_suffix "openai_compatible" \
  --output_path ./logs \
  --gen_kwargs "max_new_tokens=4096"
```

* **Test Results:**

```text Output theme={null}
Tasks Version Filter n-shot Metric Value Stderr
mmmu_val 0 none 0 mmmu_acc ↑ 0.6567 ± N/A
``` # Qwen3.5 Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3.5 ## 1. Model Introduction [Qwen3.5-397B-A17B](https://huggingface.co/Qwen/Qwen3.5-397B-A17B) is the latest flagship model in the Qwen series developed by Alibaba, representing a significant leap forward with unified vision-language foundation, efficient hybrid architecture, and scalable reinforcement learning. Qwen3.5 features a Gated Delta Networks combined with sparse Mixture-of-Experts architecture (397B total parameters, 17B activated), delivering high-throughput inference with minimal latency. It supports multimodal inputs (text, image, video) and natively handles context lengths of up to 262,144 tokens, extensible to over 1M tokens. **Architecture details:** * **Hybrid Attention:** Gated Delta Networks (linear, O(n) complexity) combined with full attention every 4th layer — linear layers provide low-cost long-context processing while periodic full attention ensures high associative recall. * **MoE routing:** Top-10 active out of 512 routed experts plus a dedicated shared expert for universal features, keeping 17B parameters active from 397B total. * **Native multimodal:** DeepStack Vision Transformer with Conv3d temporal encoding for image and video understanding without separate visual encoders. **Key Features:** * **Unified Vision-Language Foundation**: Early fusion training on multimodal tokens achieves cross-generational parity with Qwen3 and outperforms Qwen3-VL models * **Efficient Hybrid Architecture**: Gated Delta Networks + sparse MoE (397B total / 17B active) for high-throughput inference * **Hybrid Reasoning**: Thinking mode enabled by default with step-by-step reasoning, can be disabled for direct responses * **Tool Calling**: Built-in tool calling support with `qwen3_coder` parser * **Multi-Token Prediction (MTP)**: Speculative decoding support for lower latency * **201 Language Support**: Expanded multilingual coverage across 201 languages and dialects **Available Models:**
Model BF16 (Full precision) FP8 (8-bit Quantized) FP4 (4-bit Quantized)
Qwen3.5-397B-A17B [Qwen/Qwen3.5-397B-A17B](https://huggingface.co/Qwen/Qwen3.5-397B-A17B) [Qwen/Qwen3.5-397B-A17B-FP8](https://huggingface.co/Qwen/Qwen3.5-397B-A17B-FP8) NVIDIA NVFP4: [nvidia/Qwen3.5-397B-A17B-NVFP4-V2](https://huggingface.co/nvidia/Qwen3.5-397B-A17B-NVFP4-V2)\ AMD MXFP4: [amd/Qwen3.5-397B-A17B-MXFP4-AttnFP8-V2](https://huggingface.co/amd/Qwen3.5-397B-A17B-MXFP4-AttnFP8-V2)
Qwen3.5-122B-A10B [Qwen/Qwen3.5-122B-A10B](https://huggingface.co/Qwen/Qwen3.5-122B-A10B) [Qwen/Qwen3.5-122B-A10B-FP8](https://huggingface.co/Qwen/Qwen3.5-122B-A10B-FP8) -
Qwen3.5-35B-A3B [Qwen/Qwen3.5-35B-A3B](https://huggingface.co/Qwen/Qwen3.5-35B-A3B) [Qwen/Qwen3.5-35B-A3B-FP8](https://huggingface.co/Qwen/Qwen3.5-35B-A3B-FP8) -
Qwen3.5-27B [Qwen/Qwen3.5-27B](https://huggingface.co/Qwen/Qwen3.5-27B) [Qwen/Qwen3.5-27B-FP8](https://huggingface.co/Qwen/Qwen3.5-27B-FP8) -
Qwen3.5-9B [Qwen/Qwen3.5-9B](https://huggingface.co/Qwen/Qwen3.5-9B) - -
Qwen3.5-4B [Qwen/Qwen3.5-4B](https://huggingface.co/Qwen/Qwen3.5-4B) - -
Qwen3.5-2B [Qwen/Qwen3.5-2B](https://huggingface.co/Qwen/Qwen3.5-2B) - -
Qwen3.5-0.8B [Qwen/Qwen3.5-0.8B](https://huggingface.co/Qwen/Qwen3.5-0.8B) - -
**License:** Apache 2.0 ## 2. SGLang Installation SGLang from the main branch is required for Qwen3.5. You can install from source or use a Docker image: ```bash Command theme={null} # Install from source uv pip install --prerelease=allow 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' # Or use Docker (NVIDIA GPUs) docker pull lmsysorg/sglang:latest # Or use Docker (AMD MI300X/MI325X) docker pull lmsysorg/sglang-rocm:v0.5.22-rocm720-mi30x-20261020 # Or use Docker (AMD MI355X) docker pull lmsysorg/sglang-rocm:v0.5.22-rocm720-mi35x-20261020 ``` For the full Docker setup and other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/install). ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms including NVIDIA GPUs, AMD GPUs, Intel Arc Pro B-Series GPUs(codename: BMG (Battlemage)), and Intel Xeon CPUs. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and capabilities. Run this Command:

### 3.2 Configuration Tips

* Speculative decoding (MTP) can significantly reduce latency for interactive use cases.
* **H100 / B200 / B300 FP8:** Add `--enable-symm-mem` to enable NCCL symmetric memory for faster collectives and better performance under multi-GPU settings. It only helps when tp > 1, so on B200/B300 it applies to the 397B-A17B FP8 recipe (tp=4); the 122B-A10B and 35B-A3B FP8 recipes are single-GPU there.
* **AMD GPUs (MI300X / MI325X / MI355X):** Use `SGLANG_USE_AITER=1` and `SGLANG_USE_AITER_UNIFIED_ATTN=1` with `--attention-backend aiter`, which requires `--page-size 16` and can also enable `--enable-aiter-allreduce-fusion`. Additionally set `AITER_FLYDSL_FORCE=1` to force the AITER FlyDSL MoE kernels and `SGLANG_MAMBA_SSM_DTYPE=bfloat16` to store the Mamba SSM state in bfloat16 (instead of the default float32). For the **MXFP4 checkpoint on MI355X**, set `ROCM_QUICK_REDUCE_QUANTIZATION=INT4` to route multi-GPU collectives through INT4-quantized ROCm quick all-reduce, and drop `--enable-aiter-allreduce-fusion` (the two are mutually exclusive; quick all-reduce is preferred for this recipe).
* **KV cache offloading (MXFP4 on MI355X):** Selecting **Host DRAM (HiCache)** adds a host-memory tier below the device KV cache, which lets long-context agentic workloads keep more prefix cached and reach higher concurrency than the device KV pool alone allows. It emits `--enable-hierarchical-cache --hicache-ratio 1.5 --hicache-write-policy write_through --hicache-io-backend kernel --hicache-mem-layout page_first`. HiCache extends the radix cache, so the generated command drops `--disable-radix-cache` — the two options are mutually exclusive and SGLang rejects them together at startup. `--hicache-ratio 1.5` sizes the host tier at 1.5x the device KV cache, so make sure the node has that much free CPU DRAM per server on top of the model weights. Leave this **Disabled** for fixed-length throughput serving, where the extra host traffic buys nothing.
* **KV cache offloading (397B FP8 on MI355X):** A separate recipe from the MXFP4 one above, for long-context agentic serving of the FP8 checkpoint. Selecting **Host DRAM (HiCache)** emits `--tp 4` instead of the tp=2 that merely fits the weights, `--enable-hierarchical-cache --hicache-ratio 1.5 --hicache-write-policy write_through --hicache-io-backend kernel --hicache-mem-layout page_first`, `--kv-cache-dtype fp8_e4m3` to halve device KV bytes, and the scheduler and tokenizer tuning `--chunked-prefill-size 16384 --max-prefill-tokens 16384 --scheduler-recv-interval 60 --stream-interval 50 --tokenizer-worker-num 6`. `write_through` mirrors every page to the host tier as it is written. `--hicache-ratio 1.5` is the default sizing; the benchmarked high-concurrency points instead pin `--hicache-size` per rank (253 GB at concurrency 32-56, 374 GB at 64-80), which overrides the ratio — add it if you want a fixed host tier. This arm keeps `--enable-aiter-allreduce-fusion` and does not set `ROCM_QUICK_REDUCE_QUANTIZATION`; the MXFP4 recipe does the opposite. Read the FP8 KV cache warning below before using it for reasoning-heavy work.
* **Watchdog timeout:** Increase `--watchdog-timeout` to `1200` or higher for this large model, as weight loading can take significant time.
* **Mamba Radix Cache**: Qwen3.5's hybrid Gated Delta Networks architecture supports two mamba scheduling strategies via `--mamba-radix-cache-strategy`:
  * **V1 (`no_buffer`)**: Default. No overlap scheduler, lower memory usage. Required for AMD MI GPUs.
  * **V2 (`extra_buffer`)**: Enables overlap scheduling and branching point caching with `--mamba-radix-cache-strategy extra_buffer --page-size 64`. Requires FLA kernel backend (NVIDIA GPUs only). Trades higher mamba state memory for better throughput. Strictly superior in non-KV-cache-bound scenarios; in KV-cache-bound cases, weigh the overlap scheduling benefit against reduced max concurrency. `--page-size` must satisfy `FLA_CHUNK_SIZE % page_size == 0` or `page_size % FLA_CHUNK_SIZE == 0` (`FLA_CHUNK_SIZE` is currently 64).
* The `--mem-fraction-static` flag is recommended for optimal memory utilization, adjust it based on your hardware and workload.
* Context length defaults to 262,144 tokens. If you encounter OOM errors, consider reducing it, but maintain at least 128K to preserve thinking capabilities.
* To speed up weight loading for this large model, add `--model-loader-extra-config='{"enable_multithread_load": "true","num_threads": 64}'` to the launch command.
* **CUDA IPC Transport**: Add `SGLANG_USE_CUDA_IPC_TRANSPORT=1` as an environment variable to use CUDA IPC for transferring multimodal features, significantly improving TTFT (Time To First Token). Note: this consumes additional memory proportional to image size, so you may need to lower `--mem-fraction-static` or `--max-running-requests`.
* **Multimodal Attention Backend**: Use `--mm-attention-backend fa3` on H100/H200 for better vision performance, or `--mm-attention-backend fa4` on B200/B300.
* **B200 (FP8)**: Add `--enable-flashinfer-allreduce-fusion` for optimized throughput on Blackwell.
* **B200 / B300 (FP8 MoE)**: Add `--moe-runner-backend flashinfer_trtllm` to route the fused MoE through the trtllm-gen kernels on Blackwell. This is not picked up automatically — SGLang's auto-selection of `flashinfer_trtllm` is limited to the DeepSeek architecture family, so an FP8 Qwen3.5 MoE run otherwise falls back to the Triton MoE runner. It applies to the MoE sizes (397B-A17B / 122B-A10B / 35B-A3B); the dense sizes have no MoE layers. The NVFP4 recipes already set it.
* **B200 / B300 (FP8)**: Add `--linear-attn-prefill-backend flashinfer` to run GDN (linear attention) prefill on the FlashInfer CuTe-DSL kernel. SGLang auto-selects it only inside a narrow validated domain (a chunked prefill size of at most 8192 and a bfloat16 mamba state pool, among other conditions), which these FP8 recipes fall outside of, so the override has to be explicit. Requires CUDA 13+ and flashinfer >= 0.6.14 — SGLang raises at startup on SM100 with an older CUDA. Applies to every Qwen3.5 size, since all of them are hybrid GDN models.
* For processing large images or videos, you may need to lower `--mem-fraction-static` to leave room for image feature tensors.
* Hardware requirements:
  * **BF16**: \~397B parameters require \~800GB of GPU memory for weights.
    * **H100 (80GB)** requires tp=16 (2 nodes) since each rank needs \~100GB at tp=8.
    * **H200 (141GB)** runs with tp=8.
    * **B200 (183GB)** runs with tp=8.
    * **B300 (275GB)** runs with tp=4.
    * **MI300X (192GB)** runs with tp=8.
    * **MI325X (256GB)** runs with tp=4.
    * **MI355X (288GB)** runs with tp=4.
  * **FP8**: The FP8 quantized model requires \~400GB for weights, cutting memory in half.
    * **H100 (80GB)** runs with tp=8.
    * **H200 (141GB)** runs with tp=4.
    * **B200 (183GB)** runs with tp=4.
    * **B300 (275GB)** runs with tp=2.
    * **MI300X (192GB)** runs with tp=4.
    * **MI325X (256GB)** runs with tp=2.
    * **MI355X (288GB)** runs with tp=2.
  * **FP4**: The FP4 quantized model requires \~250GB for weights, cutting memory by almost 4x. NVFP4 ([nvidia/Qwen3.5-397B-A17B-NVFP4-V2](https://huggingface.co/nvidia/Qwen3.5-397B-A17B-NVFP4-V2)) requires B200/B300 (Blackwell architecture); AMD provides an MXFP4 checkpoint with FP8 attention ([amd/Qwen3.5-397B-A17B-MXFP4-AttnFP8-V2](https://huggingface.co/amd/Qwen3.5-397B-A17B-MXFP4-AttnFP8-V2)) for MI355X.
    * **B200 (183GB)** runs with tp=4 (tp=2 with expert parallelism 2 when MTP is enabled). (NVFP4)
    * **B300 (275GB)** runs with tp=2. (NVFP4)
    * **MI355X (288GB)** runs with tp=2 (use tp=4 for low concurrency). (MXFP4)

Hardware Memory BF16 TP FP8 TP FP4 TP
H100 80GB 16 8 N/A
H200 141GB 8 4 N/A
B200 183GB 8 4 4 / 2 + EP2 (MTP)
B300 275GB 4 2 2
MI300X 192GB 8 4 N/A
MI325X 256GB 4 2 N/A
MI355X 288GB 4 2 / 4 (agentic) 2 / 4 (MXFP4)
> [!WARNING] > > **FP8 KV Cache**: `--kv-cache-dtype fp8_e4m3` quantizes the KV cache to FP8 at runtime. Since these FP8 model checkpoints do not include pre-calibrated KV cache scaling factors, SGLang defaults to a scale of 1.0, which may cause noticeable accuracy degradation on reasoning-heavy tasks. It is emitted for the MXFP4-on-MI355X recipe and for the 397B FP8-on-MI355X agentic recipe (Host DRAM / HiCache selected), where it is part of the tuned configuration; for every other combination the generated commands leave it out, so add it manually only if memory constraints require the trade-off. * **Xeon CPU service configuration**: Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings. ### 3.3 Agentic Long-Context Deployment Agentic workloads, such as coding agents and other multi-turn, tool-using assistants, send long prompts whose prefixes grow and repeat from turn to turn. Serving them well depends on reusing the KV cache across turns, offloading it beyond GPU memory, and keeping each session on the workers that already hold its prefix. This section gives complete launch commands for such deployments of Qwen3.5-397B-A17B, each benchmarked in [SemiAnalysis InferenceX](https://inferencex.semianalysis.com/) and linked to the run that measured it. Pick a hardware platform, checkpoint, deployment shape, concurrency, KV cache offloading mechanism and router to get every process of the deployment as a raw command, one tab per process in launch order. * **Router.** Each configuration was submitted behind one front door: Dynamo (`dynamo.frontend` with `dynamo.sglang` workers) or SGLang (`sglang.launch_server`, behind `sglang_router` when there are several workers or DP-attention ranks). * **KV offload.** Choose among these KV cache offloading mechanisms: none (GPU KV only), HiCache (host DRAM), or a Mooncake store attached through the external linker. The Mooncake option needs an image whose SGLang build includes `--enable-unified-cache-external-linker`. * **Container image.** Run the commands inside the image listed for each configuration. Several are SGLang nightly images, so flag names follow that image. ## 4. Model Invocation **NVIDIA:** Deploy Qwen3.5-397B-A17B with the following command (H200, all features enabled): ```shell Command theme={null} sglang serve \ --model-path Qwen/Qwen3.5-397B-A17B \ --tp 8 \ --reasoning-parser qwen3 \ --tool-call-parser qwen3_coder \ --speculative-algo NEXTN \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --mem-fraction-static 0.8 \ --host 0.0.0.0 \ --port 30000 ``` **AMD:** Deploy Qwen3.5-397B-A17B with the following command (MI300X/MI325X/MI355X): ```shell Command theme={null} SGLANG_USE_AITER=1 \ SGLANG_USE_AITER_UNIFIED_ATTN=1 \ AITER_FLYDSL_FORCE=1 \ SGLANG_MAMBA_SSM_DTYPE=bfloat16 \ python3 -m sglang.launch_server \ --model-path Qwen/Qwen3.5-397B-A17B \ --tp 8 \ --reasoning-parser qwen3 \ --tool-call-parser qwen3_coder \ --trust-remote-code \ --page-size 16 \ --mem-fraction-static 0.8 \ --attention-backend aiter \ --enable-aiter-allreduce-fusion \ --model-loader-extra-config '{"enable_multithread_load": true}' \ --watchdog-timeout 1200 \ --host 0.0.0.0 \ --port 30000 ``` > **Note:** To enable MTP (speculative decoding), append `--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) ### 4.2 Vision Input Qwen3.5 supports image and video inputs as a unified vision-language model. Here is an example with an image: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="Qwen/Qwen3.5-397B-A17B", messages=[ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://qianwen-res.oss-accelerate.aliyuncs.com/Qwen3.5/demo/CI_Demo/mathv-1327.jpg" } }, { "type": "text", "text": "Describe this image in detail." } ] } ], max_tokens=2048, stream=True ) thinking_started = False has_thinking = False has_answer = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) if delta.content: if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user wants a detailed description of the provided image. 1. **Identify the main components:** * There is a central square. * There are four circles of varying sizes. 2. **Analyze the arrangement and relationships:** * **The Square:** It's in the middle, oriented upright (sides are vertical and horizontal). It's drawn with a thin black line. * **The Circles:** * **Top Right:** A large circle. It overlaps the top right corner of the square. A significant portion of the circle is outside the square, but a chunk of it is inside. * **Bottom Left:** A large circle, roughly the same size as the top right one. It overlaps the bottom left corner of the square. Again, a chunk is inside, most is outside. * **Top Left:** A smaller circle. It is positioned near the top left corner of the square. It overlaps the corner slightly. * **Bottom Right:** A smaller circle, roughly the same size as the top left one. It is positioned near the bottom right corner of the square. It overlaps the corner slightly. 3. **Synthesize the description:** * Start with a general overview: A geometric line drawing. * Describe the central shape: A square. * Describe the surrounding shapes: Four circles. * Detail the positioning: * Two large circles are diagonally opposite (bottom-left and top-right). * Two smaller circles are diagonally opposite (top-left and bottom-right). * Describe the interaction/overlap: The shapes are not just touching; they intersect. The lines cross over each other. The square acts as a central anchor. The circles seem to be "orbiting" or clustered around the corners of the square. * Mention the style: Black lines on a white background. Minimalist. No shading or color. 4. **Refine the details:** * Let's look closer at the overlaps. * **Top Left Circle:** It sits mostly above and to the left of the square's top-left corner. The bottom-right part of this small circle cuts into the square. * **Top Right Circle:** This is the largest circle (or tied for largest). Its bottom-left quadrant overlaps significantly with the top-right quadrant of the square. * **Bottom Left Circle:** This is also a large circle. Its top-right quadrant overlaps significantly with the bottom-left quadrant of the square. * **Bottom Right Circle:** This is a small circle. Its top-left part overlaps with the bottom-right corner of the square. 5. **Final Polish:** Structure the description logically. Start with the big picture, then break down each element's position relative to the center. * *Drafting the description:* The image shows a black and white line drawing of geometric shapes. In the center is a square. Surrounding it are four circles of two different sizes. * *Adding detail:* There are two large circles and two small circles. * *Positioning:* * A large circle is in the bottom left. It overlaps the bottom-left corner of the square. * A large circle is in the top right. It overlaps the top-right corner of the square. * A small circle is in the top left. It overlaps the top-left corner of the square. * A small circle is in the bottom right. It overlaps the bottom-right corner of the square. * *Visual style:* The lines are thin and black. The background is white. The shapes are transparent (wireframe style), so you can see the lines of the square through the circles and vice versa where they overlap. 6. **Final Review against the image:** Does this match? Yes. The description is accurate. The "transparency" point is important because it's a line drawing, not solid shapes. The lines cross. * Wait, let me look really closely at the "Top Left" circle. It actually looks like it's touching the top edge and left edge. It overlaps the corner. * Let me look at the "Bottom Right" circle. It overlaps the bottom right corner. * The arrangement creates a sort of diagonal symmetry. Large-Large on one diagonal, Small-Small on the other. Let's write the final output based on these observations. =============== Content ================= Based on the image provided, here is a detailed description: **Overview** The image is a minimalist, black-and-white line drawing featuring geometric shapes. It consists of a central square surrounded by four circles of varying sizes. The lines are thin and black against a plain white background. The shapes are drawn in a "wireframe" style, meaning they are transparent outlines; where shapes overlap, the lines cross over each other rather than one blocking the other. **Detailed Breakdown** 1. **The Central Square:** * There is a single square positioned in the center of the composition. It is oriented upright with vertical and horizontal sides. 2. **The Circles:** * There are four circles arranged around the corners of the square. They appear in two distinct sizes: two large circles and two smaller circles. * **Top Right:** A large circle is positioned at the top right. It overlaps significantly with the top-right corner of the square. A portion of the circle's interior is inside the square's boundary. * **Bottom Left:** Another large circle (roughly the same size as the top right one) is positioned at the bottom left. It overlaps significantly with the bottom-left corner of the square. * **Top Left:** A smaller circle is positioned near the top left corner. It overlaps slightly with the top-left corner of the square. * **Bottom Right:** A smaller circle (roughly the same size as the top left one) is positioned near the bottom right corner. It overlaps slightly with the bottom-right corner of the square. **Composition** The arrangement creates a diagonal symmetry. The two largest circles are on a diagonal from bottom-left to top-right, while the two smallest circles are on a diagonal from top-left to bottom-right. The intersecting lines create a complex web of curves and angles in the center of the image. ``` ### 4.3 Advanced Usage #### 4.3.1 Reasoning Parser Qwen3.5 supports Thinking mode **by default**. Enable the reasoning parser during deployment to separate the thinking and content sections. The thinking process is returned via `reasoning_content` in the streaming response. To disable thinking and use Instruct mode, pass `chat_template_kwargs` at request time: * **Thinking mode** (default): The model performs step-by-step reasoning before answering. No extra parameters needed. * **Instruct mode** (`{"enable_thinking": false}`): The model responds directly without a thinking process. **Example 1: Thinking Mode (Default)** Thinking mode is enabled by default. The model will reason step-by-step before answering, and the thinking process is returned via `reasoning_content`: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Thinking mode is enabled by default, no extra parameters needed response = client.chat.completions.create( model="Qwen/Qwen3.5-397B-A17B", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], max_tokens=2048, stream=True ) # Process the stream has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print answer content if delta.content: # Close thinking section and add content header if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= Thinking Process: 1. **Analyze the Request:** The user wants to solve a math problem: "What is 15% of 240?" and expects a step-by-step explanation. 2. **Identify the Core Operation:** The problem asks for a percentage of a number. The formula is: $\text{Percentage} \times \text{Number} = \text{Result}$. * Percentage: $15\%$ * Number: $240$ 3. **Determine the Steps:** * Step 1: Convert the percentage to a decimal or fraction. * Step 2: Multiply the converted value by the number. * Step 3: Calculate the final result. * Alternative Step (Mental Math): Break down 15% into 10% + 5%. 4. **Draft the Explanation (Method 1: Decimal Conversion):** * Convert $15\%$ to $0.15$. * Multiply $0.15 \times 240$. * Calculation: $15 \times 24 = 360$, adjust decimal places $\rightarrow 36.0$. 5. **Draft the Explanation (Method 2: Fraction Conversion):** * Convert $15\%$ to $\frac{15}{100}$ or $\frac{3}{20}$. * Multiply $\frac{3}{20} \times 240$. * $240 / 20 = 12$. * $3 \times 12 = 36$. 6. **Draft the Explanation (Method 3: Breaking it down - often easier for step-by-step):** * Find 10% of 240. * Find 5% of 240 (which is half of 10%). * Add them together. * 10% of 240 = 24. * 5% of 240 = 12. * $24 + 12 = 36$. 7. **Select the Best Presentation:** Method 3 is very intuitive for "step-by-step" requests as it shows logical reasoning without heavy multiplication. However, the standard decimal multiplication (Method 1) is the most formal. I will present the standard method clearly, perhaps mentioning the breakdown method as a check or alternative way to understand it. Let's stick to the standard multiplication method for clarity but explain the conversion clearly. Actually, providing the breakdown method is often more helpful for understanding *why*. I'll provide the standard calculation method as the primary steps. * Step 1: Convert percentage to decimal. * Step 2: Multiply. * Step 3: State answer. Let's refine the calculation for the final output. $15\% = 0.15$ $0.15 \times 240$ $= \frac{15}{100} \times 240$ $= 15 \times 2.4$ $= 36$ Or: $10\% = 24$ $5\% = 12$ $15\% = 36$ I will write out the solution using the decimal/fraction multiplication method as it's universally applicable, but I'll make the steps very clear. 8. **Final Review:** Does this answer the prompt accurately and step-by-step? Yes. * Step 1: Convert 15% to a decimal. * Step 2: Multiply by 240. * Step 3: Calculate. Let's write it out. Step 1: Convert the percentage to a decimal. $15\% = 0.15$ Step 2: Multiply the decimal by the number. $0.15 \times 240$ Step 3: Perform the multiplication. $15 \times 240 = 3600$ Adjust decimal (2 places): $36.00$ Result: 36. Wait, $0.15 \times 240$. $15 \times 24 = 360$. One zero from 240 cancels one decimal place? $0.15 \times 240 = 15 \times 2.4 = 36$. Or $\frac{15}{100} \times 240 = \frac{15 \times 240}{100} = \frac{3600}{100} = 36$. This looks correct. I will also include the "10% + 5%" method as an alternative way to think about it, as it's often easier for mental math. Plan: 1. Define the formula. 2. Convert percent to decimal/fraction. 3. Multiply. 4. Provide the alternative mental math method for completeness. 5. State final answer clearly. Actually, keeping it simple is better. Just one clear path. I'll use the fraction/decimal multiplication path. Step 1: Convert 15% to a decimal. Step 2: Multiply 240 by 0.15. Step 3: Final result. Let's go.cw =============== Content ================= Here is the step-by-step solution to find 15% of 240: **Step 1: Convert the percentage to a decimal.** To convert a percentage to a decimal, divide by 100. $$15\% = \frac{15}{100} = 0.15$$ **Step 2: Multiply the decimal by the number.** Now, multiply 0.15 by 240. $$0.15 \times 240$$ **Step 3: Calculate the result.** You can think of this as: $$15 \times 240 = 3600$$ Since there are two decimal places in 0.15, move the decimal point in the result two places to the left: $$3600 \rightarrow 36.00$$ **Alternative Method (Mental Math):** * Find 10% of 240: $240 \div 10 = 24$ * Find 5% of 240 (half of 10%): $24 \div 2 = 12$ * Add them together (10% + 5% = 15%): $24 + 12 = 36$ **Answer:** 15% of 240 is **36**. ``` **Example 2: Instruct Mode (Thinking Off)** To disable thinking and get a direct response, pass `{"enable_thinking": false}` via `chat_template_kwargs`: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Disable thinking mode via chat_template_kwargs response = client.chat.completions.create( model="Qwen/Qwen3.5-397B-A17B", messages=[ {"role": "user", "content": "What is 15% of 240?"} ], extra_body={"chat_template_kwargs": {"enable_thinking": False}}, max_tokens=2048, stream=True ) # In Instruct mode, the model responds directly without reasoning_content for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} To find 15% of 240, you can follow these steps: ### Step-by-Step Deduction 1. **Convert the percentage to a decimal **: To convert a percentage to a decimal, divide by 100. $$15\% = \frac{15}{100} = 0.15$$ 2. **Multiply the decimal by the number**: Multiply $0.15$ by $240$. $$0.15 \times 240$$ *Alternative Method (Mental Math)*: - Find 10% of 240: $240 \times 0.10 = 24$ - Find 5% of 240 (which is half of 10%): $24 / 2 = 12$ - Add them together ($10\% + 5\% = 15\%$): $24 + 12 = 36$ 3. **Calculation**: $$240 \times 0.15 = 36$$ ### Final Conclusion 15% of 240 is **36**. ``` #### 4.3.2 Tool Calling Qwen3.5 supports tool calling capabilities. Enable the tool call parser during deployment. Thinking mode is on by default; to disable it for tool calling requests, pass `extra_body={"chat_template_kwargs": {"enable_thinking": False}}`. **Python Example (with Thinking Process):** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) # Define available tools tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] # Make request with streaming to see thinking process response = client.chat.completions.create( model="Qwen/Qwen3.5-397B-A17B", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, stream=True ) # Process streaming response thinking_started = False has_thinking = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta # Print thinking process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) # Print tool calls if hasattr(delta, 'tool_calls') and delta.tool_calls: # Close thinking section if needed if has_thinking and thinking_started: print("\n=============== Content =================", flush=True) thinking_started = False for tool_call in delta.tool_calls: if tool_call.function: print(f"Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") # Print content if delta.content: print(delta.content, end="", flush=True) print() ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= The user is asking about the weather in Beijing. I have access to a get_weather function that can provide current weather information for a location. Let me check the parameters: - location (required): "Beijing" - this is provided by the user - unit (optional): The user didn't specify a temperature unit, so I won't include this optional parameter I should call the get_weather function with Beijing as the location. =============== Content ================= Tool Call: get_weather Arguments: Tool Call: None Arguments: { Tool Call: None Arguments: "location": "Beijing" Tool Call: None Arguments: } ``` #### 4.3.3 Semantic Decisions Qwen3.5-35B-A3B can answer typed questions about an input with a probability for every option through `/v1/decisions`, without generating text. The server turns thinking off for these requests, so the answer is read after a closed think block, and the same server keeps serving chat traffic. No launch flag is needed. Until a release contains `/v1/decisions`, install a [nightly build](/docs/get-started/install#nightly-builds). With a server started by `sglang serve --model-path Qwen/Qwen3.5-35B-A3B --host 127.0.0.1 --port 30000`: ```python Example theme={null} import requests response = requests.post( "http://127.0.0.1:30000/v1/decisions", json={ "input": "I've been trying to connect my Stripe account for 3 days and the integration keeps failing.", "questions": [ { "id": "team", "type": "choice", "question": "Which team should handle this ticket?", "options": [{"name": "billing"}, {"name": "technical"}, {"name": "sales"}], }, {"id": "urgent", "type": "yes_no", "question": "The customer needs an answer today."}, ], }, timeout=60, ) response.raise_for_status() answers = response.json()["answers"] print(answers["team"]["choice"], answers["team"]["probabilities"]) print(answers["urgent"]["probabilities"]["yes"]) ``` See [Decision models](/docs/supported-models/decision_models) for the request reference, how the probabilities are computed, and the limits. ## 5. Benchmark ### 5.1 Accuracy Benchmark #### 5.1.1 GSM8K Benchmark * Benchmark Command ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 \ --num-threads 64 ``` Historical results below use the removed harness and are not measurements of the sgl-eval command above. * Test Result ```text Output theme={null} 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████| 200/200 [00:31<00:00, 6.43it/s] Accuracy: 0.975 Invalid: 0.005 Latency: 31.784 s Output throughput: 998.166 token/s ``` #### 5.1.2 Full GSM8K with sgl-eval ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://localhost:30000/v1 \ --model Qwen/Qwen3.5-397B-A17B \ --num-examples 1319 --num-threads 256 --max-tokens 2048 --thinking ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. #### 5.1.3 MMMU Benchmark * Benchmark Command ```bash Command theme={null} python3 benchmark/mmmu/bench_sglang.py --concurrency 128 --port 30000 --max-new-tokens 512 ``` * Test Result ```text Output theme={null} {'Accounting': {'acc': 1.0, 'num': 3}, 'Agriculture': {'acc': 1.0, 'num': 4}, 'Art': {'acc': 1.0, 'num': 9}, 'Art_Theory': {'acc': 1.0, 'num': 5}, 'Basic_Medical_Science': {'acc': 1.0, 'num': 2}, 'Biology': {'acc': 1.0, 'num': 1}, 'Chemistry': {'acc': 1.0, 'num': 1}, 'Computer_Science': {'acc': 1.0, 'num': 1}, 'Design': {'acc': 0.909, 'num': 11}, 'Diagnostics_and_Laboratory_Medicine': {'acc': 1.0, 'num': 1}, 'Economics': {'acc': 1.0, 'num': 5}, 'Finance': {'acc': 1.0, 'num': 2}, 'Geography': {'acc': 1.0, 'num': 3}, 'History': {'acc': 1.0, 'num': 3}, 'Literature': {'acc': 0.938, 'num': 16}, 'Manage': {'acc': 1.0, 'num': 2}, 'Marketing': {'acc': 1.0, 'num': 5}, 'Math': {'acc': 1.0, 'num': 1}, 'Overall': {'acc': 0.978, 'num': 91}, 'Overall-Art and Design': {'acc': 0.96, 'num': 25}, 'Overall-Business': {'acc': 1.0, 'num': 17}, 'Overall-Health and Medicine': {'acc': 1.0, 'num': 7}, 'Overall-Humanities and Social Science': {'acc': 0.966, 'num': 29}, 'Overall-Science': {'acc': 1.0, 'num': 8}, 'Overall-Tech and Engineering': {'acc': 1.0, 'num': 5}, 'Pharmacy': {'acc': 1.0, 'num': 2}, 'Physics': {'acc': 1.0, 'num': 2}, 'Psychology': {'acc': 1.0, 'num': 4}, 'Public_Health': {'acc': 1.0, 'num': 2}, 'Sociology': {'acc': 1.0, 'num': 6}} eval out saved to ./val_sglang.json Overall accuracy: 0.978 ``` ### 5.2 Speed Benchmark **Test Environment:** * Hardware: H200 (8x) * Model: Qwen3.5-397B-A17B * Tensor Parallelism: 8 * SGLang Version: main branch Server Launch Command: ```bash Command theme={null} SGLANG_USE_CUDA_IPC_TRANSPORT=1 python -m sglang.launch_server \ --model Qwen/Qwen3.5-397B-A17B \ --tp 8 \ --reasoning-parser qwen3 \ --tool-call-parser qwen3_coder \ --speculative-algo NEXTN \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --mem-fraction-static 0.8 \ --host 0.0.0.0 \ --port 30000 ``` #### 5.2.1 Latency Benchmark ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model Qwen/Qwen3.5-397B-A17B \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 1 Successful requests: 10 Benchmark duration (s): 18.94 Total input tokens: 6101 Total input text tokens: 6101 Total generated tokens: 4220 Total generated tokens (retokenized): 4211 Request throughput (req/s): 0.53 Input token throughput (tok/s): 322.16 Output token throughput (tok/s): 222.84 Peak output token throughput (tok/s): 289.00 Peak concurrent requests: 3 Total token throughput (tok/s): 545.00 Concurrency: 1.00 Accept length: 3.12 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 1892.35 Median E2E Latency (ms): 1410.85 P90 E2E Latency (ms): 3749.34 P99 E2E Latency (ms): 4216.52 ---------------Time to First Token---------------- Mean TTFT (ms): 190.40 Median TTFT (ms): 208.46 P99 TTFT (ms): 261.27 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 3.96 Median TPOT (ms): 3.79 P99 TPOT (ms): 4.96 ---------------Inter-Token Latency---------------- Mean ITL (ms): 4.04 Median ITL (ms): 3.15 P95 ITL (ms): 6.65 P99 ITL (ms): 12.60 Max ITL (ms): 58.03 ================================================== ``` #### 5.2.2 Throughput Benchmark ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model Qwen/Qwen3.5-397B-A17B \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 1000 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} ============ Serving Benchmark Result ============ Backend: sglang Traffic request rate: inf Max request concurrency: 100 Successful requests: 1000 Benchmark duration (s): 283.04 Total input tokens: 502493 Total input text tokens: 502493 Total generated tokens: 500251 Total generated tokens (retokenized): 498222 Request throughput (req/s): 3.53 Input token throughput (tok/s): 1775.37 Output token throughput (tok/s): 1767.45 Peak output token throughput (tok/s): 3630.00 Peak concurrent requests: 108 Total token throughput (tok/s): 3542.82 Concurrency: 96.71 Accept length: 3.31 ----------------End-to-End Latency---------------- Mean E2E Latency (ms): 27372.05 Median E2E Latency (ms): 26660.21 P90 E2E Latency (ms): 39951.91 P99 E2E Latency (ms): 48405.51 ---------------Time to First Token---------------- Mean TTFT (ms): 14247.21 Median TTFT (ms): 14932.44 P99 TTFT (ms): 20998.45 -----Time per Output Token (excl. 1st token)------ Mean TPOT (ms): 26.16 Median TPOT (ms): 26.13 P99 TPOT (ms): 41.33 ---------------Inter-Token Latency---------------- Mean ITL (ms): 26.29 Median ITL (ms): 11.38 P95 ITL (ms): 72.10 P99 ITL (ms): 149.57 Max ITL (ms): 1220.68 ================================================== ``` ### 5.3 Vision Speed Benchmark We use SGLang's built-in benchmarking tool to conduct performance evaluation with random images. Each request has 128 input tokens, two 720p images, and 1024 output tokens. #### 5.3.1 Latency Benchmark ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang-oai-chat \ --host 127.0.0.1 \ --port 30000 \ --model Qwen/Qwen3.5-397B-A17B \ --dataset-name image \ --image-count 2 \ --image-resolution 720p \ --random-input-len 128 \ --random-output-len 1024 \ --num-prompts 10 \ --max-concurrency 1 \ --request-rate inf ``` ```text Output theme={null} TODO ``` #### 5.3.2 Throughput Benchmark ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang-oai-chat \ --host 127.0.0.1 \ --port 30000 \ --model Qwen/Qwen3.5-397B-A17B \ --dataset-name image \ --image-count 2 \ --image-resolution 720p \ --random-input-len 128 \ --random-output-len 1024 \ --num-prompts 1000 \ --max-concurrency 100 \ --request-rate inf ``` ```text Output theme={null} TODO ``` # Qwen3.6 Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3.6 ## 1. Model Introduction The Qwen3.6 series is developed by Alibaba. Built on direct feedback from the community, Qwen3.6 prioritizes stability and real-world utility, delivering substantial upgrades in agentic coding and thinking preservation. Two size/sparsity variants are released: * [Qwen3.6-35B-A3B](https://huggingface.co/Qwen/Qwen3.6-35B-A3B) — **Sparse MoE** (35B total, 3B active) on a Gated Delta Networks backbone. * [Qwen3.6-27B](https://huggingface.co/Qwen/Qwen3.6-27B) — **Dense** hybrid GDN; smaller weights footprint, single-GPU friendly. Both variants share the same hybrid reasoning, tool-calling, and multimodal interface and natively handle context lengths of up to 262,144 tokens, extensible to over 1M tokens. **Key Features:** * **Agentic Coding**: Handles frontend workflows and repository-level reasoning with greater fluency and precision * **Thinking Preservation**: New option to retain reasoning context from historical messages, streamlining iterative development * **Efficient Hybrid Architecture**: Gated Delta Networks backbone; sparse MoE (35B / 3B active) or dense 27B variant * **Hybrid Reasoning**: Thinking mode enabled by default with step-by-step reasoning, can be disabled for direct responses * **Tool Calling**: Built-in tool calling support with `qwen3_coder` parser * **Multi-Token Prediction (MTP)**: Speculative decoding support for lower latency; both MoE and Dense variants ship `mtp.safetensors` * **Multimodal**: Unified vision-language model supporting text, image, and video inputs **Available Models:**
Model Architecture Weights
Qwen3.6-35B-A3B (BF16) MoE 35B / 3B active [Qwen/Qwen3.6-35B-A3B](https://huggingface.co/Qwen/Qwen3.6-35B-A3B)
Qwen3.6-35B-A3B (FP8) MoE 35B / 3B active [Qwen/Qwen3.6-35B-A3B-FP8](https://huggingface.co/Qwen/Qwen3.6-35B-A3B-FP8)
Qwen3.6-35B-A3B (NVFP4) MoE 35B / 3B active (Blackwell) [nvidia/Qwen3.6-35B-A3B-NVFP4](https://huggingface.co/nvidia/Qwen3.6-35B-A3B-NVFP4)
Qwen3.6-27B (BF16) Dense 27B [Qwen/Qwen3.6-27B](https://huggingface.co/Qwen/Qwen3.6-27B)
Qwen3.6-27B (FP8) Dense 27B [Qwen/Qwen3.6-27B-FP8](https://huggingface.co/Qwen/Qwen3.6-27B-FP8)
Qwen3.6-27B (NVFP4) Dense 27B (Blackwell) [nvidia/Qwen3.6-27B-NVFP4](https://huggingface.co/nvidia/Qwen3.6-27B-NVFP4)
**License:** Apache 2.0 ## 2. SGLang Installation SGLang `>=0.5.10` is required for Qwen3.6. You can install from PyPI, from source, or use a Docker image: ```bash Command theme={null} # Install from PyPI uv pip install --prerelease=allow sglang # Or install from source uv pip install --prerelease=allow 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' # Or use Docker (NVIDIA GPUs; also serves the NVFP4 variants) docker pull lmsysorg/sglang:latest ``` For the full Docker setup and other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/install). For SGLang CPU installation, please refer to the [CPU version installation guide](../../../docs/hardware-platforms/cpu_server#installation). On Ascend NPUs (Atlas 800I A3), follow [SGLang installation with NPU support](/docs/hardware-platforms/ascend-npus/getting-started/installation) and the [Ascend NPU quickstart](/docs/hardware-platforms/ascend-npus/getting-started/quick_start) to select a compatible container image and host driver. The A3 recipes below require the Ascend software stack; the CUDA image above does not provide it. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and capabilities, including Ascend NPU (Atlas 800I A3) scenarios. Run this Command:

### RTX Spark: 35B-A3B NVFP4

Select **RTX Spark** in the generator above to use the single-node, single-GPU recipe for
[nvidia/Qwen3.6-35B-A3B-NVFP4](https://huggingface.co/nvidia/Qwen3.6-35B-A3B-NVFP4)
on [NVIDIA RTX Spark](https://www.nvidia.com/en-us/products/rtx-spark/), which
pairs a Blackwell RTX GPU with a Grace CPU and offers up to 128GB of unified
memory. The contributor tested this command on SGLang `main`. The recipe uses
the FlashInfer CUTLASS MoE runner,
`extra_buffer` Mamba radix caching, and a static memory fraction of `0.8`.
Speculative decoding is not enabled.

The contributor reported **75 output tokens/s for a single request** on SGLang
`main`. The exact commit, OS/runtime, memory configuration, input/output lengths,
and timing method were not provided. This is a reported generation speed, not
an input-plus-output throughput measurement or a measured P50 TPOT. The Docker
selector uses the nightly `dev` fallback; that image was not the reported test
environment.

### 3.2 Configuration Tips

* Speculative decoding (MTP) can significantly reduce latency for interactive use cases.
* **Mamba Radix Cache**: Qwen3.6's hybrid Gated Delta Networks architecture supports two mamba scheduling strategies via `--mamba-radix-cache-strategy`:
  * **V1 (`no_buffer`)**: Default. No overlap scheduler, lower memory usage.
  * **V2 (`extra_buffer`)**: Enables overlap scheduling and branching point caching with `--mamba-radix-cache-strategy extra_buffer --page-size 64`. Requires FLA kernel backend (NVIDIA GPUs only). Trades higher mamba state memory for better throughput.
* The `--mem-fraction-static` flag is recommended for optimal memory utilization, adjust it based on your hardware and workload.
* Context length defaults to 262,144 tokens. If you encounter OOM errors, consider reducing it, but maintain at least 128K to preserve thinking capabilities.
* **CUDA IPC Transport**: Add `SGLANG_USE_CUDA_IPC_TRANSPORT=1` as an environment variable to use CUDA IPC for transferring multimodal features, significantly improving TTFT (Time To First Token). Note: this consumes additional memory proportional to image size, so you may need to lower `--mem-fraction-static` or `--max-running-requests`.
* **Multimodal Attention Backend**: Use `--mm-attention-backend fa3` on H100/H200 for better vision performance, or `--mm-attention-backend fa4` on B200/B300.
* For processing large images or videos, you may need to lower `--mem-fraction-static` to leave room for image feature tensors.
* **Ascend NPU (Atlas 800I A3):** Each card has 2 dies, so `--tp-size` is twice the card count (1 card → `--tp-size 2`). Add `--attention-backend ascend --device npu` and `--mamba-ssm-dtype bfloat16`, run speculative decoding with the built-in MTP weights via `--speculative-algorithm NEXTN`. See [Deploying on Ascend NPUs](#ascend-npu-deployment) below.
* Hardware requirements for the GPU recipes:
  * **35B-A3B BF16**: \~70GB for weights. TP=1 fits on all supported hardware.
  * **35B-A3B FP8**: \~35GB for weights. TP=1 fits on all supported hardware.
  * **35B-A3B NVFP4**: \~23GB for weights. TP=1 fits on B200/B300 and RTX Spark.
  * **27B BF16**: \~54GB for weights. TP=1 fits on all supported hardware.
  * **27B FP8**: \~27GB for weights. TP=1 fits on all supported hardware.
  * **27B NVFP4**: \~22GB for weights. TP=1 fits on B200/B300.

All Qwen3.6 variants (MoE 35B-A3B and Dense 27B) fit on a single supported GPU. The table below covers B200/B300 NVFP4; the 35B-A3B RTX Spark recipe is provided above:

Hardware Memory BF16 TP FP8 TP NVFP4 TP
H100 80GB 1 1 —
H200 141GB 1 1 —
B200 183GB 1 1 1
B300 275GB 1 1 1
* **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings. Referenced by the configuration tips above. Verify before removing. ### 3.3 Deploying on Ascend NPUs (Atlas 800I A3) The Ascend model tutorials document support for [Qwen3.6-27B](/docs/hardware-platforms/ascend-npus/model-deployment/tutorials/qwen3_6_27b) and [Qwen3.6-35B-A3B](/docs/hardware-platforms/ascend-npus/model-deployment/tutorials/qwen3_6_35b_a3b) starting with SGLang v0.5.16. The generator provides a baseline for single-node deployment with prefill and decode on the same node (PD mixed mode). Use the complete scenario recipes below for workload-specific tuning. Launch a compatible container using the [Ascend NPU quickstart](/docs/hardware-platforms/ascend-npus/getting-started/quick_start), including its driver, firmware, and runtime mounts, then run the generated `sglang serve` command inside it. Select the device IDs for your cards: one A3 card exposes two dies. For example, a 1-card deployment using dies 0 and 1 needs `--device /dev/davinci0 --device /dev/davinci1`, together with the management devices and mounts in the quickstart. **Weights:** BF16 checkpoints are available from [Qwen](https://huggingface.co/Qwen) and mirrored on ModelScope. To download from ModelScope, install the `modelscope` Python package and set `SGLANG_USE_MODELSCOPE=1`. Alternatively, pre-download the weights and set `--model-path` to their local directory. The generator offers the following card counts. Weight sizes exclude KV cache, Mamba state, and runtime buffers; choose capacity and concurrency for your workload.
Model Checkpoint Weights 1 card (TP 2) 2 cards (TP 4)
Qwen3.6-27B [Qwen/Qwen3.6-27B](https://huggingface.co/Qwen/Qwen3.6-27B) \~54 GB (BF16) Available Available
Qwen3.6-35B-A3B [Qwen/Qwen3.6-35B-A3B](https://huggingface.co/Qwen/Qwen3.6-35B-A3B) \~70 GB (BF16) Available Available
**Published scenario references (PD mixed, single node):** The TPOT values below are reproduced from the linked Ascend best-practice pages. They describe those pages' full configurations and workloads, not measurements of the generator's baseline command. Follow each scenario's host tuning, environment variables, launch flags, and benchmark command when reproducing it.
Model Cards Quantization Dataset Source TPOT
Qwen3.6-27B 1 BF16 [1024x1024 (30)+1024](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_27b#qwen3-6-27b-1p-in1024x1024-30-out1024-50ms) 50ms
Qwen3.6-27B 1 BF16 [1080p\_30+256](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_27b#qwen3-6-27b-1p-in1080p-30-out256-50ms) 50ms
Qwen3.6-27B 1 BF16 [64k+1k (90% prefix cache hit rate)](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_27b#qwen3-6-27b-1p-in64k-out1k-prefix90-50ms) 50ms
Qwen3.6-35B-A3B 1 BF16 [254k+1k](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-1p-in254k-out1k-16-1ms) 16.1ms
Qwen3.6-35B-A3B 1 BF16 [3.5k+1.5k](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-1p-in3k5-out1k5-50ms) 50ms
Qwen3.6-35B-A3B 1 BF16 [64k+1k](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-1p-in64k-out1k-50ms) 50ms
Qwen3.6-35B-A3B 1 BF16 [64k+1k (90% prefix cache hit rate)](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-1p-in64k-out1k-prefix90-50ms) 50ms
Qwen3.6-35B-A3B 1 BF16 [128k+1k](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-1p-in128k-out1k-50ms) 50ms
Qwen3.6-35B-A3B 1 BF16 [128k+1k (90% prefix cache hit rate)](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-1p-in128k-out1k-prefix90-50ms) 50ms
Qwen3.6-35B-A3B 1 BF16 [1024x1024 (30)+1024](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-1p-in1024x1024-30-out1024-50ms) 50ms
Qwen3.6-35B-A3B 1 BF16 [1080p\_30+256](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-1p-in1080p-30-out256-50ms) 50ms
Qwen3.6-35B-A3B 2 BF16 [984k+1k](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b#qwen3-6-35b-a3b-2p-in984k-out1k-40-91ms) 40.91ms
See the [27B best practices](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_27b) and [35B-A3B best practices](/docs/hardware-platforms/ascend-npus/model-deployment/best-practices/qwen3_6_35b_a3b) for the full scenario lists. > [!NOTE] > > * Multimodal serving on A3 additionally enables `--enable-multimodal --mm-attention-backend ascend_attn`; see the image-input best-practice scenarios for the full flag set. > * The generator leaves the NPU Mamba cache strategy to the installed SGLang version. Ascend prefix-cache recipes use `--mamba-radix-cache-strategy extra_buffer`; copy the complete matching recipe when enabling prefix caching. > * Use a version-matched Ascend stack and check output quality with the [accuracy evaluation guide](/docs/hardware-platforms/ascend-npus/evaluation/accuracy_evaluation) before [performance testing](/docs/hardware-platforms/ascend-npus/evaluation/performance_testing). Successful checkpoint loading alone does not establish generation accuracy. ## 4. Model Invocation Deploy Qwen3.6 with the following command (H200, all features enabled). Swap `--model-path` to `Qwen/Qwen3.6-27B-FP8` for the dense 27B variant — all other flags carry over: ```shell Command theme={null} sglang serve \ --model-path Qwen/Qwen3.6-35B-A3B-FP8 \ --reasoning-parser qwen3 \ --tool-call-parser qwen3_coder \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --mem-fraction-static 0.8 \ --host 0.0.0.0 \ --port 30000 ``` ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) ### 4.2 Vision Input Qwen3.6 supports image and video inputs as a unified vision-language model. **Image Input Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="Qwen/Qwen3.6-35B-A3B-FP8", messages=[ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": "https://qianwen-res.oss-accelerate.aliyuncs.com/Qwen3.5/demo/CI_Demo/mathv-1327.jpg" } }, { "type": "text", "text": "Describe this image in detail." } ] } ], max_tokens=2048, stream=True ) thinking_started = False has_thinking = False has_answer = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) if delta.content: if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Video Input Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="Qwen/Qwen3.6-35B-A3B-FP8", messages=[ { "role": "user", "content": [ { "type": "video_url", "video_url": { "url": "https://qianwen-res.oss-accelerate.aliyuncs.com/Qwen3.5/demo/video/N1cdUjctpG8.mp4" } }, { "type": "text", "text": "Describe what happens in this video." } ] } ], max_tokens=2048, stream=True ) thinking_started = False has_thinking = False has_answer = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) if delta.content: if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` ### 4.3 Advanced Usage #### 4.3.1 Reasoning Parser Qwen3.6 supports Thinking mode **by default**. Enable the reasoning parser during deployment to separate the thinking and content sections. The thinking process is returned via `reasoning_content` in the streaming response. To disable thinking and use Instruct mode, pass `chat_template_kwargs` at request time: * **Thinking mode** (default): The model performs step-by-step reasoning before answering. No extra parameters needed. * **Instruct mode** (`{"enable_thinking": false}`): The model responds directly without a thinking process. **Example 1: Thinking Mode (Default)** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="Qwen/Qwen3.6-35B-A3B-FP8", messages=[ {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"} ], max_tokens=2048, stream=True ) has_thinking = False has_answer = False thinking_started = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) if delta.content: if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` **Example 2: Instruct Mode (Thinking Off)** To disable thinking and get a direct response, pass `{"enable_thinking": false}` via `chat_template_kwargs`: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="Qwen/Qwen3.6-35B-A3B-FP8", messages=[ {"role": "user", "content": "What is 15% of 240?"} ], extra_body={"chat_template_kwargs": {"enable_thinking": False}}, max_tokens=2048, stream=True ) for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) print() ``` #### 4.3.2 Thinking Preservation Qwen3.6 has been trained to preserve and leverage thinking traces from historical messages. Enable this for agent scenarios where maintaining full reasoning context improves decision consistency: ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="Qwen/Qwen3.6-35B-A3B-FP8", messages=[ {"role": "user", "content": "Help me plan a web app architecture."} ], extra_body={"chat_template_kwargs": {"preserve_thinking": True}}, max_tokens=2048, stream=True ) thinking_started = False has_thinking = False has_answer = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) if delta.content: if has_thinking and not has_answer: print("\n=============== Content =================", flush=True) has_answer = True print(delta.content, end="", flush=True) print() ``` #### 4.3.3 Tool Calling Qwen3.6 supports tool calling capabilities. Enable the tool call parser during deployment. ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] response = client.chat.completions.create( model="Qwen/Qwen3.6-35B-A3B-FP8", messages=[ {"role": "user", "content": "What's the weather in Beijing?"} ], tools=tools, stream=True ) thinking_started = False has_thinking = False for chunk in response: if chunk.choices and len(chunk.choices) > 0: delta = chunk.choices[0].delta if hasattr(delta, 'reasoning_content') and delta.reasoning_content: if not thinking_started: print("=============== Thinking =================", flush=True) thinking_started = True has_thinking = True print(delta.reasoning_content, end="", flush=True) if hasattr(delta, 'tool_calls') and delta.tool_calls: if has_thinking and thinking_started: print("\n=============== Content =================", flush=True) thinking_started = False for tool_call in delta.tool_calls: if tool_call.function: print(f"Tool Call: {tool_call.function.name}") print(f" Arguments: {tool_call.function.arguments}") if delta.content: print(delta.content, end="", flush=True) print() ``` # Qwen3.8 Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3.8 Deploy Qwen3.8 with SGLang — day-0 recipes for Qwen's 2.4T-parameter (95B active) hybrid GDN/GQA Mixture-of-Experts model on NVIDIA and AMD. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > uv pip install --prerelease=allow sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > **NVIDIA GPUs** (H200 / B200 / B300 / GB300) — the launch image, since this is a day-0 model with no release cut yet: > > ```bash Command theme={null} > docker pull lmsysorg/sglang:qwen38 > ``` > > **AMD GPUs** — pinned `v0.5.17` builds. The two are **not** interchangeable: they target different GPU architectures *and* different ROCm versions, so pick the one matching your hardware or AITER's kernels won't load. > > MI350X / MI355X (CDNA4, gfx950 — ROCm 7.20): > > ```bash Command theme={null} > docker pull lmsysorg/sglang-rocm:v0.5.17-rocm720-mi35x-20260812 > ``` > > MI300X (CDNA3, gfx942 — ROCm 7.00): > > ```bash Command theme={null} > docker pull lmsysorg/sglang-rocm:v0.5.17-rocm700-mi30x-20260813 > ``` > > For how to launch either image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with whatever the command generator below produces. Pick your hardware + quantization to generate the launch command. Three of the strategies are operating points on the throughput/latency curve; the fourth swaps the speculative decoder: * **Low Latency** — fastest reply for a single user. Pick for chat. * **Balanced** — good speed with several users at once. Use for typical multi-user serving. * **High Throughput** — most tokens per second across many users. Best for batch jobs. * **DSpark** — the trained [DSpark draft model](#3-3-dspark-and-replayssm-speculative-decoding) instead of the checkpoint's built-in MTP head. Only offered where DSpark's constraints allow it (see [3.3](#3-3-dspark-and-replayssm-speculative-decoding)). ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. The knobs come in two flavors: * **Built-in SGLang features** — TP / DP-Attention, MoE backend + EP (including WideEP), reasoning / tool-call parsers, speculative-decoding presets, prefill/decode disaggregation, and HiCache tiers. * **Qwen3.8 specific features** — the **DSpark** speculative-decoding preset and its **ReplaySSM** opt-out, plus the GDN radix-cache-strategy and KV-cache-precision knobs (see [Configuration Tips](#2-configuration-tips) and [3.3 DSpark and ReplaySSM](#3-3-dspark-and-replayssm-speculative-decoding) below). ## 1. Model Introduction **Qwen3.8** (`Qwen3.8-2.4T-A95B`) is Qwen's largest open-weight model to date: **2.4T total parameters, 95B active per token**. It continues the hybrid-attention design of the Qwen3.5 / Qwen3.6 series, scaled up to 92 layers. * **Hybrid Attention** — 23 repeats of `3 × (Gated DeltaNet → MoE) → 1 × (Gated Attention → MoE)`, so 69 linear-attention layers to 23 full-attention ones. Gated Attention runs 64 query heads over 4 KV heads at head dimension 256. This balances linear computational complexity against long-context modeling quality. * **GDN (Gated Delta Network)** — the linear-attention layers pair a State Space Model with causal convolution (CausalConv1d), 128 V heads and 16 QK heads at head dimension 128. A fixed-size recurrent state replaces the growing KV cache, so memory is `O(1)` per layer while compute stays `O(N)`. * **Sparse Mixture-of-Experts** — 512 experts, 10 routed plus 1 shared active per token, expert intermediate dimension 2048. Hidden dimension 8192, vocabulary 248,320. * **MTP** — the checkpoint ships multi-token-prediction weights trained with multiple steps. That is what the NEXTN speculative recipes on this page decode against. **License:** [Qwen3.8-2.4T-A95B](https://huggingface.co/Qwen/Qwen3.8-2.4T-A95B/blob/main/LICENSE). **Context length:** 262,144 native, extensible to 1,010,000 tokens. **Recommended generation:** `temperature=1.0`, `top_p=0.95`, `top_k=20`, `min_p=0.0`, `presence_penalty=0.0`, `repetition_penalty=1.0`. Raising `presence_penalty` toward 2 curbs runaway repetition at some risk of language mixing. For agentic work Qwen suggests allowing 262,144 tokens of reasoning and 131,072 for the final response. **Resources:** Each precision is its own repo — [BF16](https://huggingface.co/Qwen/Qwen3.8-2.4T-A95B) · [FP8](https://huggingface.co/Qwen/Qwen3.8-2.4T-A95B-FP8) · [NVFP4, NVIDIA Blackwell (RadixArk)](https://huggingface.co/RadixArk/Qwen3.8-2.4T-A95B-NVFP4) · [MXFP4, AMD CDNA4 (Qwen)](https://huggingface.co/Qwen/Qwen3.8-2.4T-A95B-FP8-MXFP4). Speculative-decoding draft model: [`RadixArk/Qwen3.8-2.4T-A95B-DSpark`](https://huggingface.co/RadixArk/Qwen3.8-2.4T-A95B-DSpark) (see [3.3](#3-3-dspark-and-replayssm-speculative-decoding)). ## 2. Configuration Tips Four cells are marked **Not Verified** — **GB300 BF16** and the three GB300 **DSpark** strategies. They have launch recipes but no completed validation run; every other cell on the page has been run, including B300 NVFP4 DSpark. **Weight size decides the topology.** At 2.4T parameters BF16 is ≈4.8TB, FP8 ≈2.4TB, NVFP4 ≈1.2TB. FP8 fits no single node here — not even B300, whose 8 × 288GB = 2.30TB misses by a hair — so every FP8 recipe is multi-node. Single-node means FP4: NVFP4 on B300, MXFP4 on MI355X/MI350X. B200 NVFP4 would fit one node but pipelines two, because \~25GB per GPU after weights is too little to serve against. BF16 does not fit 16 GPUs either, so its one recipe is TP32 across 8 GB300 nodes — the only platform where a flat TP32 stays on rack-scale NVLink. **Two distinct FP4 checkpoints.** [NVFP4](https://huggingface.co/RadixArk/Qwen3.8-2.4T-A95B-NVFP4) is Blackwell-only; [MXFP4](https://huggingface.co/Qwen/Qwen3.8-2.4T-A95B-FP8-MXFP4) is MI350X/MI355X-only and hybrid (MXFP4 experts, FP8 attention/dense). MI300X is CDNA3 with no hardware MX matmul, so it serves FP8. Leave `--moe-runner-backend` unset on both and the runner resolves from the checkpoint's own `quant_method` — except the NVFP4 wide-EP tier, which pairs `flashinfer_trtllm_routed` with `--moe-a2a-backend flashinfer` by hand because auto cannot resolve that combination. ### GDN state is the scarce resource, not KV Two thirds of the layers are Gated DeltaNet, and their recurrent state lives in its own pool. That pool, not KV, is usually what caps concurrency — and a request's cost depends on the caching strategy:
Strategy State slots per request
`--disable-radix-cache` 1
`no_buffer` 3
`extra_buffer` (this model's `auto`) 5, or 4 where PP disables the overlap scheduler
So `--max-mamba-cache-size` has to match the ratio in force, or it silently clamps `max_running_requests` to a fraction of the target — every cell leaves the pool to `--mamba-full-memory-ratio` except GB300 FP8 Balanced and Low Latency, whose pins are part of tuned capacity sets — Low Latency's `--max-mamba-cache-size 80` is exactly its 16 concurrent requests × 5 slots. And `extra_buffer` needs radix caching on: `mamba_extra_buffer_of()` requires `disable_radix_cache` false, so adding `--disable-radix-cache` makes the strategy inert and drops the budget to one slot. ### NEXTN caps concurrency at 48 MTP weights ship inside the checkpoint, so NEXTN needs no draft model and the 3/1/4 preset fills in automatically. But a speculative cell with no `--max-running-requests` gets **48** from the speculative hook rather than a memory-derived ceiling — pin it explicitly to serve more. `pp_size > 1` rules speculative decoding out entirely in aggregated serving, which is why the H200, B200/B300 FP8, B200 NVFP4 and MI300X recipes carry no MTP. ### Linear-attention backends differ by GPU generation `--mamba-ssm-dtype bfloat16` is load-bearing on SM100: the flashinfer GDN decode default is gated on it, and without it decode silently falls back to Triton. On SM90 the GDN default is Triton for *both* halves, which is why H200 is the one cell pinning `--linear-attn-decode-backend flashinfer` too. The flashinfer GDN prefill default only covers chunk sizes up to 8192, so any cell with a larger `--chunked-prefill-size` must state `--linear-attn-prefill-backend flashinfer` itself. `--attention-backend trtllm_mha` is SM100-only. On Blackwell cells that leave it unset, the model hook picks it together with `--page-size 64` — and returns early when the backend *is* named, so an explicit backend also drops that paired page size and nothing then depends on `--speculative-eagle-topk` to keep the backend off Triton. ### GB300 tiers The FP8 ladder spans the whole curve on 4 nodes × 4 GPUs:
Tier Shape Spec
Low Latency TP16 narrow EP NEXTN 3+1
Balanced DP4×TP4 + EP16 NEXTN 3+1
High Throughput DP4×TP4 + EP16 off
Balanced and High Throughput share one shape and differ only in capacity. Low Latency is the odd one out: narrow EP wins at low concurrency, where spending ranks on expert parallelism costs more than it returns. MTP is off at saturation because draft-plus-verify overhead outweighs the speedup. NVFP4 has only two tiers — its recipes span different GPU counts (8 vs 16) and the wide-EP one holds capacity fixed across its whole concurrency list, so no third operating point exists. Extra build requirements: FP8 Balanced and High Throughput need the **DeepEP v2 wheel** (`2.1.0+01dc3aa`), since their `--moe-a2a-backend deepep_v2` flags do not exist upstream. NVFP4 High Throughput needs `nvfp4_agg_wideep_dep16_flashinfer_setup.sh` run first, and its `SGLANG_FLASHINFER_NUM_MAX_DISPATCH_TOKENS_PER_RANK=8192` is not optional — unset it falls back to 1024 and startup raises once `1024 × ep_size` no longer covers the largest CuteDSL MoE forward. ### GB300 PD disaggregation layouts The PD role selector adds the role and transfer flags to the selected base recipe. It does not resize the prefill and decode workers. Use separate workers with the layouts below for the measured GB300 operating points: | Checkpoint and operating point | Prefill workers | Decode worker | Capacity setting | | - | - | - | - | | FP8, high throughput | 2 × TP1 / PP16 | DP4-attention / TP4 / EP16, DeepEP v2 + EPLB | Keep frontend concurrency above the decode MRR so prefill remains queued | | NVFP4, high throughput | 2 × TP1 / PP6 | DP2-attention / TP4 / EP8, FlashInfer one-sided A2A | Prefill MRR 128 per worker; decode MRR 512; frontend concurrency 1536 | | NVFP4, low latency | TP4 / PP2 | TP16 | Decode MRR 1 and frontend concurrency 1 at the latency endpoint | For NVFP4 with NEXTN, use the 3/1/4 settings on both roles so the prefill worker transfers the draft state. Enable ReplaySSM on the decode role. The generated router command sets the main policy to `round_robin`, which applies to prefill, and keeps the decode policy explicit; the server-side `--load-balance-method` does not configure router worker selection. Round robin is the measured choice for the fixed-shape throughput runs above. For agentic workloads with substantial repeated-prefix reuse, consider cache-aware routing, especially on the prefill side, and validate the cache-locality versus load-balance tradeoff on the target workload. ### AllReduce fusion The four cells running one flat TP group — GB300 FP8 Low Latency, GB300 NVFP4 Low Latency, GB300 BF16, B300 NVFP4 — set `SGLANG_FLASHINFER_MNNVL_CUTEDSL_AR_FUSION`, the Qwen3.5 CuteDSL path whose single workspace fuses AllReduce + Residual + RMSNorm with the MoE finalize. Worth 6–13% over the legacy path. Don't pass `--flashinfer-allreduce-fusion-backend` alongside it — the env suppresses the flag with a warning. Nothing else can use it: the fusion needs DP-attention off and the built-in TP MoE, so the wide-EP tiers are out, and the pipelined cells put their cross-node traffic on IB rather than NVLink. The three GB300 cells also carry `NCCL_NVLS_ENABLE=1`, because SGLang forces NVLS collectives off when that variable is unset. ### AMD Recommended: **MI355X + MXFP4, single node, TP8**. MI350X emits the identical command (same gfx950, same 288GB, same `mi35x` image); MI300X is CDNA3, takes the `mi30x` image, and needs two nodes for the FP8 weights. * **`--mem-fraction-static` looks aggressive on purpose.** With the aiter backend above 8192 context SGLang multiplies it by **0.85** before allocating, so MI355X's `0.9` lands at ≈0.765 and MI300X's `1.0` at ≈0.85. Don't "fix" these downward. MI300X must stay at 1.0 or the weights stop fitting. * **`--disable-custom-all-reduce` belongs on every MI300X rank** — SGLang resolves it per process, so setting it on one node would leave the two pipeline stages reducing through different code paths. * MI300X runs `--kv-cache-dtype fp8_e4m3` with `--page-size 16`: at 8 × 192GB per node the shape is memory-bound. ### ReplaySSM A GDN layer's recurrent state overwrites itself every token, so speculative verify has to be rewindable. Snapshotting the whole K×V state per draft step costs 64 KiB per request, layer and head at K=V=128, times γ+1 steps — scratch taken out of the same budget as the persistent state pool. [ReplaySSM](https://tridao.me/blog/2026/replayssm/) stores each draft step's raw inputs `Sᵢ = (vᵢ, kᵢ, gᵢ, βᵢ)` instead, a few hundred bytes written by the verify kernel on its way through. Once the sampler fixes the accepted length, one fold kernel replays the accepted prefix from the committed checkpoint and advances it in place. The fold is a verbatim clone of the verify recurrence, so the rebuilt state is bit-identical to the recurrent baseline; draft-step scratch shrinks by roughly two orders of magnitude and is never allocated. Folding on every commit is what lets it compose with radix prefix caching over the mutable GDN state: every `--mamba-track-interval` tokens the state is handed to the radix tree, and under `extra_buffer` it goes to a second slot so the running request keeps mutating its own. It is off by default — see [3.3](#3-3-dspark-and-replayssm-speculative-decoding). ## 3. Advanced Usage > [!NOTE] > > The `model` argument in the examples below is the BF16 repo id. Every precision is a **separate repo**, so `model` has to be the checkpoint the server was actually launched with — `…-A95B-FP8`, `…-A95B-NVFP4`, or `…-A95B-FP8-MXFP4`. The Deploy panel's cURL snippet always shows the right id for the cell you have selected. ### 3.1 Reasoning Qwen3.8 **always** reasons — thinking cannot be turned off, and every response opens with a `…` block. The `qwen3` reasoning parser (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) splits that block into `reasoning_content`, leaving `content` as the answer alone. Depth is tunable per request with `reasoning_effort` — `xhigh` (the default), `medium`, or `low`. `preserve_thinking` carries reasoning from earlier turns into context and is on by default. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="Qwen/Qwen3.8-2.4T-A95B", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > reasoning_effort="xhigh", # xhigh (default) | medium | low > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Pending update — a sample transcript will be added here. > ``` ### 3.2 Tool Calling Enable the `qwen3_coder` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["location"], > }, > }, > } > ] > > resp = client.chat.completions.create( > model="Qwen/Qwen3.8-2.4T-A95B", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Content:", msg.content) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Pending update — a sample transcript will be added here. > ``` ### 3.3 DSpark and ReplaySSM (Speculative Decoding) We trained a **DSpark** draft model for Qwen3.8 with SpecForge. Turn it on with the **DSpark** chip in the **Speculative Decoding** card of the [Playground above](#playground) — it emits: ```bash Command theme={null} --speculative-algorithm DSPARK \ --speculative-draft-model-path RadixArk/Qwen3.8-2.4T-A95B-DSpark ``` **ReplaySSM is a separate opt-in.** `--enable-linear-replayssm-spec` defaults off and DSpark does not turn it on, so add it with the **ReplaySSM (spec)** row in the flag-select list. With it on (see [Configuration Tips](#2-configuration-tips) above for how it works), the verify kernel stores each draft step's raw inputs instead of snapshotting the full K×V GDN state, and a single fold kernel replays the accepted prefix from the last committed checkpoint. It's a pure side channel behind a ring buffer — the verify output is bitwise unchanged — so there's no accuracy tradeoff, only a memory one. **DSpark does not compose with every cell.** `_handle_dspark` rejects the run outright rather than degrading, so check these before turning the chip on: * **`--pp-size` must be 1.** The H200, B200, B300 (FP8) and MI300X cells are all pipelined, so DSpark is unavailable on them. * **With DP-Attention it additionally requires `--enable-dp-lm-head`**, the built-in TP MoE (`--moe-a2a-backend none`), and no context parallel. That rules out the GB300 wide-EP tiers, which run DP attention over DeepEP v2 or FlashInfer A2A. * `--speculative-num-steps` is forced to 1, and an omitted `--speculative-draft-model-path` only works if the target checkpoint bundles the draft weights. The Playground greys the DSpark chip out on the combinations above. The **DSpark** strategy chip in the Deploy panel emits this substitution on the four hw × quantization combinations that clear those constraints: GB300 FP8 (on the low-latency shape — the balanced tier's DeepEP v2 a2a rules DSpark out), GB300 NVFP4, GB300 BF16 and B300 NVFP4. Everything else on the page is either pipelined or wide-EP. Because the draft model needs its own weights and KV, those cells run tighter than their NEXTN counterparts — the validated B300 recipe drops `--mem-fraction-static` to 0.80 and trims `--context-length` to 200000 to buy the room back. ReplaySSM composes with radix prefix caching, overlap scheduling, and PD decode, so DSpark speculative decoding runs alongside the rest of the stack (WideEP, PD disaggregation, HiCache) rather than requiring any of them to be turned off. # Qwen3.8-27B Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3.8-27B Deploy Qwen3.8-27B with SGLang — dense hybrid GDN vision-language model with BF16/FP8/NVFP4 W4A4 checkpoints and in-checkpoint MTP, single-GPU on H200, RTX PRO 6000, RTX 5090 and DGX Spark. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install --upgrade pip > pip install uv > > uv pip install --prerelease=allow sglang > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your card + checkpoint precision to generate the launch command. The model runs single-GPU on every supported card — H200, RTX PRO 6000, RTX 5090 and DGX Spark — and ships one operating point. > [!NOTE] > > `--mamba-full-memory-ratio` is the one sizing flag that matters for throughput > on hybrid GDN models: the default (0.9) over-provisions the KV pool and silently > clamps concurrency. Set your average request length in the > [Mamba ratio calculator](#mamba-ratio-calculator) below; everything else follows > the panels, and the computed value is pinned into the command. > [!NOTE] > > Every cell above — RTX 5090, RTX PRO 6000 and DGX Spark, across all five > checkpoints and every Speculative Decoding / Serving Strategy / SSM dtype > combination — is measured on **v0.5.19**. That is 202 cells, each one served > and scored on the full 1319-question GSM8K (93.18-95.15%). The serving > envelope behind the pins is ISL 8192 / OSL 1024 at concurrency 1; throughput > and acceptance-length numbers were not re-taken in that sweep. ### Mamba ratio calculator Average request length Input + output tokens — the ratio's only free parameter Target concurrency Requests in flight — sizes the explicit pin, not the ratio Serving configuration (follows the Deploy panel and Playground) state/slot MB · KV/token KB · the ratio prices state slots per request; the pin counts S = , so concurrent requests pin slots. > **How --mamba-full-memory-ratio is calculated** > > Hybrid GDN models split post-weight memory into a worst-case-reserved **GDN > state pool** (sets the concurrency ceiling) and a paged **attention KV pool**, > divided by `--mamba-full-memory-ratio`. Every parameter below except `L` and the > target concurrency is read live from the Deploy panel and Playground selection; > the balanced value is the per-request cost ratio: > > ```text Formula theme={null} > ratio = (S + D) x state_bytes / (L x kv_bytes_per_token) > ``` > > * `S` — state slots per running request: `extra_buffer=5` (default), > `extra_buffer_lazy=4`, `no_buffer=3`, disabled radix cache `=1`. For the two > `extra_buffer` strategies, `SGLANG_OPT_MAMBA_SKIP_DECODE_LOCK=1` frees one > slot, and `extra_buffer` frees one more with the overlap scheduler off; the > calculator reads both knobs. > * `D` — verify intermediate states under speculative decoding: > `--speculative-num-draft-tokens` for EAGLE/MTP (4 at the recommended 3/1/4) > and for DFLASH (8, DFlash2's block size); > `--speculative-dspark-block-size + 1` for DSPARK, where the block size falls > back to the draft checkpoint's `block_size` when the flag is omitted (7 for > `RadixArk/Qwen3.8-27B-DSpark`, so `D = 8`); 0 with speculation off or with > `--enable-linear-replayssm-spec`, which keeps the verify intermediates on a > fixed ring instead of per-request slots. > * `state_bytes` — one state slot, from the fixed geometry > (48 GDN layers x 48 heads x 128 x 128 at `--mamba-ssm-dtype`, plus bf16 conv > state): 153.9 MB at fp32, 78.4 MB at bf16. > * `kv_bytes_per_token` — 16 attention layers x GQA 4 x 256 x K+V: > 32.8 KB at fp8, 65.5 KB at bf16. > * `L` — average total request length in tokens: input + output. > > `--max-mamba-cache-size = target_concurrency x S` is the equivalent explicit > pin and overrides the ratio; the calculator emits it alongside. `D` is not a > term here: the engine divides the state pool by `S` alone and sizes the > speculative verify buffer separately, so folding `D` into the pin would > over-provision the pool. After boot, verify with the `max_running_requests` > line in the server log — it should not be capped below your target concurrency. ## Playground The Playground is where you experiment with **SGLang features beyond the recipes above**. The Deploy panel emits this model's documented launch recipes; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction **Qwen3.8-27B** is a dense hybrid Gated Delta Networks (GDN) **vision-language** model: a 27B causal language model paired with a vision encoder, with native image and video understanding alongside text. SGLang serves it through the Qwen3-VL path, so the vision tower is live on the recipes below. The language model is 64 layers, laid out as 16 repeats of *3 × (Gated DeltaNet → FFN)* followed by *1 × (Gated Attention → FFN)* — 48 linear-attention layers to 16 full-attention ones. Gated DeltaNet runs 48 value heads and 16 QK heads at head\_dim 128; Gated Attention is GQA 24/4 at head\_dim 256 with a 64-dim rotary slice. Hidden size is 5120 over a 17,408-dim FFN, and the checkpoint ships an MTP head trained with multiple steps. Context is 262,144 tokens natively, extensible to 1,000,000. The serving-relevant architecture is identical to Qwen3.6-27B. Thinking mode is on by default and can be disabled per request; reasoning depth is tunable with `reasoning_effort`, and `preserve_thinking` retains reasoning context from earlier messages.
Model Quantization Weights
Qwen3.8-27B BF16 [Qwen/Qwen3.8-27B](https://huggingface.co/Qwen/Qwen3.8-27B)
Qwen3.8-27B-FP8 FP8 (blockwise) [Qwen/Qwen3.8-27B-FP8](https://huggingface.co/Qwen/Qwen3.8-27B-FP8)
Qwen3.8-27B-NVFP4 (FP4 head) NVFP4 W4A4 + FP8 projections, `lm_head` packed to FP4 [RadixArk/Qwen3.8-27B-NVFP4](https://huggingface.co/RadixArk/Qwen3.8-27B-NVFP4)
Qwen3.8-27B-NVFP4 (BF16 head) Same body, `lm_head` left dense in BF16 [RadixArk/Qwen3.8-27B-NVFP4-BF16-LMHead](https://huggingface.co/RadixArk/Qwen3.8-27B-NVFP4-BF16-LMHead)
Qwen3.8-27B-NVFP4 (NVIDIA) NVIDIA's ModelOpt export of the same W4A4 body, `lm_head` packed to FP4 [nvidia/Qwen3.8-27B-NVFP4](https://huggingface.co/nvidia/Qwen3.8-27B-NVFP4)
The two RadixArk NVFP4 exports differ only in the `lm_head`: one packs it to FP4, the other leaves it dense in BF16. The dense head is \~1.7 GB larger on disk and \~3.2 GB larger at runtime, so it is the harder of the two to fit — every recipe on this page was measured against it, and the FP4-head cells reuse those pins unchanged. NVIDIA's own export is that same W4A4 body with that same FP4 head: identical quantized-layer map (FP8 attention and GDN projections, NVFP4 MLPs), identical tensor set, identical 21.9 GB on disk. On GB300, RTX PRO 6000 and DGX Spark its cells reuse the FP4-head pins unchanged, and both SM12x grids have been re-measured against this export on v0.5.19: all 16 overlay combinations per card serve and score 94.01-95.00% (RTX PRO 6000) and 94.16-95.07% (DGX Spark) on the full 1319-question GSM8K. The RTX 5090 is measured too — all 15 overlay combinations it offers serve and score 93.93-94.92% — and every winning launch command there is identical to the FP4-head export's, which is the strongest form of the claim above. What the 32GB card does need is the draft-model rows pinning their own pools: those recipes pin `--max-running-requests 1`, but nothing caps the pools to match, so the KV pool sizes itself for 127,332 tokens against the 9,216 one 8192-in/1024-out request needs, and the engine's default split then leaves the GDN state pool far short of the slots it needs once the draft model's weights are counted against `--mem-fraction-static`. The DSPARK row therefore pins `--max-total-tokens` and a measured `--mamba-full-memory-ratio`, as do DFLASH2 and MTP on the dense-lm\_head export at float32 state. Those pins override the calculator's live value for the selections that carry them. The no-speculation row needs none of it and runs at the pins shown. The two RadixArk checkpoints declare `kv_cache_quant_algo: FP8`, so SGLang's default `--kv-cache-dtype auto` already puts their KV pool in `fp8_e4m3`. The NVIDIA export ships no `kv_cache_scheme`, so `auto` would leave its pool in BF16 instead. Every recipe on this page pins `--kv-cache-dtype fp8_e4m3` explicitly, so all three run the same `fp8_e4m3` pool regardless; the difference only shows up if you switch the Playground's **KV Cache Precision** row back to Auto. ## 2. Configuration Tips * **SM120/SM121 (RTX PRO 6000 Blackwell, RTX 5090, DGX Spark)**: use `--attention-backend flashinfer`; `trtllm_mha` is SM100-only. MTP with the FlashInfer backend requires a FlashInfer build whose prefill `plan` accepts `uniform_q_len` (newer than 0.6.15.post1); otherwise run spec with `--attention-backend triton`. On DGX Spark the 128GB is unified memory shared with the host CPU, so all three checkpoints fit, and its cells reuse the RTX PRO 6000 recipe at `--mem-fraction-static 0.80` rather than a separate operating point. The one lower pin is the unified pool pricing the host's memory too: 0.85 of 128GB leaves \~8GB for the OS — exactly DGX OS earlyoom's SIGTERM threshold — and the first long prefill or boot-time graph capture dips under it and gets the scheduler killed with `exit code -15` and no traceback (`journalctl -u earlyoom` shows the kill). At 0.85, 15 of the 48 cells were killed that way, and which cells is margin noise; at 0.80 every cell served on every attempt. **Validated on SM121 / aarch64**: all 80 configurations (5 checkpoints x Speculative Decoding x Serving Strategy x Mamba SSM Dtype, DFLASH2 included) served on GB10 on `v0.5.19` at ISL 8192 / OSL 1024, concurrency 1, and each scored the full 1319-question GSM8K (93.18-95.15%); the float32 and bfloat16 halves ran on two separate GB10 boxes. No throughput or acceptance-length numbers were re-taken. The sweep exercises the FlashInfer `plan` / `uniform_q_len` path above, which raised no arity error on that build. Three host quirks when reproducing on GB10: docker GPU access is CDI-only (`--device nvidia.com/gpu=all`, as no `nvidia` runtime is registered); `nvidia-smi` reports `Not Supported` for memory because it is unified with the CPU — gate a relaunch on `MemAvailable` in `/proc/meminfo` instead; and the BF16 checkpoint takes \~6.5 minutes just to load its 18 shards from NVMe, so budget \~10 minutes to READY before calling a boot hung. * **H200 (SM90)**: BF16 and FP8 only — the card has no FP4 tensor cores, so an NVFP4 checkpoint's MLP would fall back to the Marlin W4A16 weight-only path, and all three NVFP4 cells are greyed out. The H200 recipes use 32768-token prefill chunks (SM90 prefill is fast enough that a big chunk barely stalls decode, unlike the SM120 guidance below), and the FlashInfer GDN prefill backend engages by default under them. `--attention-backend fa3` is a valid alternative, measured slightly faster at bs=1. * **MTP**: `--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4` uses the in-checkpoint MTP head. (This recipe was originally documented with `NEXTN`, an alias of `EAGLE` — same algorithm.) * **DSpark**: the trained draft model is a separate checkpoint — add `--speculative-algorithm DSPARK --speculative-draft-model-path RadixArk/Qwen3.8-27B-DSpark` (the Playground's Speculative Decoding card emits this pair). DSpark does **not** take `--speculative-num-draft-tokens`: its verify window is `--speculative-dspark-block-size` (gamma) **+ 1**, and gamma is auto-inferred from the draft checkpoint when the flag is omitted (7 for this checkpoint, so D = 8). That `D` is a term in the balanced ratio — `r = (S + D) x token_equiv / L`, where `token_equiv` is the state slot expressed in KV tokens, `state_bytes / kv_bytes_per_token` (4698 at fp32 state / 2394 at bf16, over fp8 KV) — so DSpark needs a materially higher `--mamba-full-memory-ratio` than no-spec at the same `S`, and pinning a different gamma changes the ratio with it. MTP is the opposite case: with `--enable-linear-replayssm-spec` its draft intermediates move onto a fixed ring, so `D = 0` and the ratio returns to the no-spec value. The [calculator](#mamba-ratio-calculator) applies both rules. * **DFlash2**: a trained block-diffusion draft in a separate checkpoint — add `--speculative-algorithm DFLASH --speculative-draft-model-path incoai/Qwen3.8-27B-DFlash2 --speculative-num-draft-tokens 8` (8 is the draft's block size, and it is the `D` term in the ratio, same value as DSpark's). Runs on Ascend NPUs as well ([#35629](https://github.com/sgl-project/sglang/pull/35629)): the selector verify falls back to argmax there, matching what EAGLE and first-generation DFlash drafts (such as `z-lab/Qwen3-8B-DFlash-b16`) already do on NPU. Therefore, NPU currently guarantees lossless verification only for greedy requests; use `temperature=0` and `top_k=1`. Non-greedy requests log a warning; both draft proposal and target verification fall back to greedy, so their requested sampling distribution is not preserved. The selector projects candidates through the target `lm_head`, including quantized heads, so it runs on the NVFP4 checkpoint (whose head is NVFP4-packed; the BF16 and FP8 checkpoints keep a dense head). The Ascend comparison in #35629 used an A3 Series device with BF16 target weights, `--tp-size 2 --attention-backend ascend --mamba-ssm-dtype bfloat16 --mamba-radix-cache-strategy extra_buffer`, and disabled RadixCache for both baseline and DFlash2 to exclude cache warm-up and prefix reuse. The DFlash2 run added the three flags shown above. That comparison's accuracy used zero-shot GSM8K with greedy sampling, `max_new_tokens=2048`, 128 examples, and concurrency levels 1, 2, 4, 8 and 16 — a different protocol from this page's own sweep below. Validation: every SM12x cell on this page is measured end to end on v0.5.19 — 202 cells over the five checkpoints, four speculative options, two serving tiers and two GDN state dtypes, full 1319-question GSM8K on each, 93.18-95.15%. The RTX PRO 6000 and DGX Spark recipes need no changes. On the 32GB RTX 5090 the panel applies the measured pins automatically: DFlash2 at `--mem-fraction-static 0.91` with `--chunked-prefill-size 1024` — at 0.91 the pools fit but a 2048-token chunk's activations do not — DSpark at 0.88 (bfloat16), 0.91 (float32) and 0.92 on the dense-lm\_head export, all three with their pools pinned and the last two also cutting the prefill chunk to 1024 and 512, EAGLE at 0.93 (bfloat16) and 0.94 (float32), and no-speculation at 0.90. Whether float32 is available with a draft model depends on the `lm_head`: on the BF16-head export it is greyed out for both DSpark and DFlash2, since the dense head's \~3.2 GB leave no fp32 state pool that also clears prefill graph capture. The FP4-head export frees that headroom back — DSpark serves at 0.91 and DFlash2 High-Throughput at 0.895 with `--mamba-full-memory-ratio 10` overriding the balanced value — and only DFlash2 Low-Latency stays out of reach, where five fp32 slots and a full request's KV never coexist. bfloat16 remains the faster choice regardless: DFlash2 posts 4.92 ms median TPOT at an accept length of 4.29, the best result on this card. * **Hardware fit**: FP8 weights \~28.5GB (not serviceable beyond bs≤2 on 32GB cards); NVFP4 weights \~16.5GB (recommended for RTX 5090-class GPUs). * `--mamba-radix-cache-strategy extra_buffer_lazy` lowers the state cost per request from 5 slots to 4 at no accuracy cost. On small-VRAM cards (RTX 5090 32GB) the state pool bounds concurrency long before KV does — prefer lowering `S` (lazy strategy, or `--disable-radix-cache` for S=1); the [calculator](#mamba-ratio-calculator) re-derives the ratio for the new `S`. The balanced ratio itself is VRAM-independent. * `--mamba-ssm-dtype`: the GDN state slot is **153.9 MB at `float32`** (the checkpoint's declared precision) and **78.4 MB at `bfloat16`**, so bf16 roughly halves the state pool and hands the difference to KV — measured on an RTX 5090 with no speculation, 97,280 KV tokens at bf16 against 68,588 at fp32. On 32GB cards it also decides whether a config fits at all: EAGLE needs `--mem-fraction-static 0.94` at fp32 but 0.92 at bf16. Speed is **not** a one-way trade — with speculative decoding fp32 sometimes wins (NVFP4 + EAGLE: 152.9 vs 144.5 tok/s/user) and sometimes loses (FP8 + EAGLE: 106.3 vs 116.1); measure both for your quantization. Treat `bfloat16` as an accuracy gate and validate it for your workload. On SM120 both precisions run the Triton linear-attn prefill path — the FlashInfer GDN prefill fast path gates on SM100, where its validated domain is in fact a bf16 state pool — so no dtype forces an extra flag here. One interaction to know: `--enable-linear-replayssm-spec` auto-selects fp32 state when `--mamba-ssm-dtype` is unset, and an explicit non-fp32 value logs a state-drift warning at boot. The SSM dtype row always emits the flag explicitly, so the bf16 + EAGLE cells run with that warning — accounted for in their validation. * `--chunked-prefill-size 2048`: decode steps stall behind each prefill chunk on hybrid GDN models, and 8192-token chunks stall them \~600ms at a time. 2048 keeps decode inter-token latency smooth under mixed load and also improves single-wave TTFT. ## 3. Agent Harnesses Agent harnesses drive the model through the OpenAI-compatible endpoint — or, for Claude Code, through SGLang's Anthropic-compatible one — so any of them works once three things line up. **The parsers ship in the command.** Every recipe above carries `--reasoning-parser qwen3 --tool-call-parser qwen3_coder`, because without them a harness receives tool calls as raw text instead of structured `tool_calls`. The **Parsers** card in the [Playground](#playground) is therefore an opt-out — both chips start on, and turning one off strips its flag. `qwen3_coder` is the right tool-call parser for this checkpoint: its chat template instructs the model to reply with an inner `` / `` block nested in ``, which is exactly what that parser decodes. The Hermes parser (`--tool-call-parser hermes`) reads a *different* payload — bare JSON inside `` — so pointing a Hermes-format harness at this model without switching the flag yields tool calls that never parse. `--reasoning-parser qwen3` matches the template's `enable_thinking` toggle, which defaults to on. **Endpoint and model id.** The base URL is `http://:30000/v1`. The `model` string a harness sends must equal the server's `--model-path` — the OpenAI `/v1/models` name defaults to it — unless you override it with `--served-model-name`, which is usually worth doing to keep harness configs short. SGLang also serves an Anthropic-compatible `/v1/messages`, which is what [§3.3](#3-3-claude-code) uses. It converts each request to the OpenAI shape, hands it to the same chat-serving path, and converts the response back — so the parser flags above apply there identically. **Auth.** `--api-key` is unset by default, so the server accepts unauthenticated requests. Harnesses that insist on a key can send any placeholder; set `--api-key` on the server if the endpoint is reachable beyond localhost. ### 3.1 OpenCode [OpenCode](https://opencode.ai/docs/providers/) reaches a self-hosted endpoint through a provider entry in `opencode.json`. > **Register SGLang as an OpenCode provider** > > Store the credential first — pick **Other**, give the provider an id, and enter > any placeholder when the server has no `--api-key`: > > ```bash Command theme={null} > opencode > /connect > ``` > > Then declare the provider in `opencode.json`: > > ```json Config theme={null} > { > "$schema": "https://opencode.ai/config.json", > "provider": { > "sglang": { > "npm": "@ai-sdk/openai-compatible", > "name": "SGLang (Qwen3.8-27B)", > "options": { > "baseURL": "http://localhost:30000/v1" > }, > "models": { > "RadixArk/Qwen3.8-27B-NVFP4": { > "name": "Qwen3.8-27B NVFP4" > } > } > } > } > } > ``` > > `npm` selects the transport — `@ai-sdk/openai-compatible` is the one for a plain > OpenAI-shaped endpoint. `apiKey` is optional and takes a `"{env:VAR_NAME}"` > reference rather than a literal. The `models` keys are the ids sent on the wire, > so they must match the served model name. Confirm with `/models`. ### 3.2 Pi [Pi](https://pi.dev/docs/latest/custom-provider) (`@earendil-works/pi-coding-agent`) registers providers from an extension rather than a config file. > **Register SGLang as a Pi provider** > > ```javascript Extension theme={null} > pi.registerProvider("sglang", { > baseUrl: "http://localhost:30000/v1", > api: "openai-completions", > apiKey: "$SGLANG_API_KEY", > models: [ > { > id: "RadixArk/Qwen3.8-27B-NVFP4", > name: "Qwen3.8-27B", > reasoning: true, > input: ["text", "image"], > cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, > contextWindow: 262144, > maxTokens: 32768, > }, > ], > }); > ``` > > `api: "openai-completions"` is what selects the OpenAI-compatible transport, and > `apiKey` takes a `$ENV_VAR` reference rather than a literal. `contextWindow` is > the checkpoint's native 262,144; set `maxTokens` to whatever output cap you want > per turn. Confirm registration with `pi --list-models`. ### 3.3 Claude Code Claude Code speaks the Anthropic API, so it points at SGLang's `/v1/messages` rather than the OpenAI endpoint. > [!WARNING] > > Anthropic documents that routing Claude Code to non-Claude models through a > gateway is **not supported**. The wiring below works because SGLang implements > the Anthropic message format, but it sits outside what Claude Code is tested > against — expect newer Claude Code features to degrade or fail. > **Point Claude Code at SGLang** > > `ANTHROPIC_BASE_URL` is the server origin — Claude Code appends `/v1/messages` > itself, so leave the `/v1` suffix off: > > ```bash Command theme={null} > export ANTHROPIC_BASE_URL=http://localhost:30000 > export ANTHROPIC_AUTH_TOKEN=placeholder > ``` > > The two credential variables travel in different headers: > `ANTHROPIC_AUTH_TOKEN` goes out as `Authorization: Bearer`, `ANTHROPIC_API_KEY` > as `x-api-key`. Either satisfies a server started without `--api-key`; with > `--api-key` set, pick the variable matching the header your server reads. A > credential variable also takes precedence over a saved claude.ai login for that > session. > > The same pair can live in a settings file instead, which persists across shells > and wins over a shell export: > > ```json Config theme={null} > { > "env": { > "ANTHROPIC_BASE_URL": "http://localhost:30000", > "ANTHROPIC_AUTH_TOKEN": "placeholder" > } > } > ``` > > Run `/status` in Claude Code to confirm which base URL and credential source the > session picked up. ### 3.4 Hermes Agent [Hermes Agent](https://github.com/NousResearch/hermes-agent) (Nous Research, MIT) selects a self-hosted endpoint through its setup wizard or its config file. > **Point Hermes Agent at SGLang** > > ```bash Command theme={null} > hermes model > # choose "Custom endpoint (self-hosted / VLLM / etc.)", then enter the > # base URL, an API key (blank for a local server) and the model name > ``` > > Equivalently, in `~/.hermes/config.yaml`: > > ```yaml Config theme={null} > model: > default: RadixArk/Qwen3.8-27B-NVFP4 > provider: custom > base_url: http://localhost:30000/v1 > api_key: "" > context_length: 262144 > ``` > > For several endpoints at once, declare them under `providers:` and switch with > `/model custom:` mid-session: > > ```yaml Config theme={null} > providers: > workstation: > api: http://localhost:30000/v1 > server: > api: https://gpu-host.internal:30000/v1 > key_env: SGLANG_API_KEY > ``` ## 4. Semantic Decisions Qwen3.8-27B can answer typed questions about an input with a probability for every option through `/v1/decisions`, without generating text. The server turns thinking off for these requests, so the answer is read after a closed think block, and the same server keeps serving chat traffic. No launch flag is needed. Until a release contains `/v1/decisions`, install a [nightly build](/docs/get-started/install#nightly-builds). With a server started by `sglang serve --model-path Qwen/Qwen3.8-27B --host 127.0.0.1 --port 30000`: ```python Example theme={null} import requests response = requests.post( "http://127.0.0.1:30000/v1/decisions", json={ "input": "I've been trying to connect my Stripe account for 3 days and the integration keeps failing.", "questions": [ { "id": "team", "type": "choice", "question": "Which team should handle this ticket?", "options": [{"name": "billing"}, {"name": "technical"}, {"name": "sales"}], }, {"id": "urgent", "type": "yes_no", "question": "The customer needs an answer today."}, ], }, timeout=60, ) response.raise_for_status() answers = response.json()["answers"] print(answers["team"]["choice"], answers["team"]["probabilities"]) print(answers["urgent"]["probabilities"]["yes"]) ``` See [Decision models](/docs/supported-models/decision_models) for the request reference, how the probabilities are computed, and the limits. # Qwen3.8-Flash-Next Source: https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3.8-Flash-Next Deploy Qwen3.8-Flash-Next with SGLang — day-0 recipes for Qwen's 176B-parameter (6B active) GDN + QSA hybrid Mixture-of-Experts preview of the Qwen4 architecture, on NVIDIA and AMD. ## Deployment > **Install SGLang** > > Use an SGLang build that includes Qwen3.8-Flash-Next support (v0.5.22 or later). > > ```bash Command theme={null} > docker pull lmsysorg/sglang:latest > ``` > > The deployment panel can render a complete `docker run` command for the selected hardware and options. See [Install SGLang with Docker](/docs/get-started/install#method-3-using-docker) for host setup. Pick your hardware + quantization to generate the launch command. > **DGX Spark notes (1x GB10 with the N-gram table on NVMe, or 2x GB10 TP=2)** > > The NVFP4 checkpoint is 126 GiB (78 GiB of experts and dense weights plus a 47.7 GiB FP8 N-gram table), so it does not fit one DGX Spark's 128 GB of unified memory, and `--ple-offload-embedding` does not help there: on GB10 the "offloaded" pinned-host table comes out of the same pool as the GPU weights. The two-node shape is TP=2 across two Sparks over the ConnectX-7 200GbE link, with `--no-ple-offload-embedding` keeping the table GPU-resident and sharded (\~65 GB of weights per node). A single Spark works only with the table file-backed on NVMe (see the Single Spark bullet below). > > * **Launch order.** Start rank 1 first, then rank 0 within a few seconds. When re-launching, stop both ranks and confirm nothing listens on the rendezvous port before starting again: a new rank 1 attaching to a stale rank 0 store fails with a gloo "Connection reset by peer". > * **NCCL.** The cross-node decode CUDA-graph deadlock seen on an earlier DGX Spark stack was on NCCL 2.28.x; both builds these images load have been verified here for TP=2 across two Sparks: `dev-qwen38-next-local` runs its pip NCCL 2.29.7 (a system 2.28.3 is also present but not loaded), `qwen38flashnext` its 2.30.7. Confirm with the startup log line `sglang is using nccl==…`, which reports the library actually loaded. If your Sparks also have a slower management NIC, pin `NCCL_SOCKET_IFNAME` / `GLOO_SOCKET_IFNAME` to the 200GbE interface; with `--dist-init-addr` on the 200GbE address the verified runs picked it without pinning. > * **Memory.** Both cells run `--mem-fraction-static 0.85`, which leaves \~8–12 GiB of host memory free per node under load (measured through GSM8K at full concurrency and a 100k-token prefill). Two precautions for long-context work beyond that: `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` stops variable-shape chunked-prefill buffers from fragmenting the caching allocator at 200k+ contexts, and a host-side watchdog that kills the server when `MemAvailable` drops below a few GiB, because a unified-memory exhaustion can take the whole box down and needs a power cycle to recover. > * **Concurrency.** The hybrid GDN/QSA model reserves mamba state slots per running request (5 with the default `extra_buffer` radix strategy, 4 with `extra_buffer_lazy`), and the scheduler caps `--max-running-requests` to what the mamba pool admits; read the effective value from the startup log, not from `/get_server_info`. The cells pin `--max-mamba-cache-size` to requests × slots (24 × 5 = 120 for low latency, 96 × 4 = 384 for high throughput); raising concurrency further takes memory from the KV pool one-for-one. > * **Flags.** The cells are the model card's TP=2 recipe without `--mamba-track-interval 64`: the default of 256 tokens satisfies the constraints (a multiple of the 64-token page, at least the 4 draft tokens) and leaves a \~40% larger KV pool (1.48M tokens at 24 concurrent with MTP, 1.07M at 96 without), at the cost of coarser prefix-cache reuse of the recurrent state. `--trust-remote-code` is not needed; the architecture is native to SGLang. > * **Measured.** 100k-token prefill at 2,400–2,840 tok/s; MTP accept length 3.5–3.7 of 4 draft tokens on non-thinking output (lower, \~2.5, on thinking output). > * **Single Spark (file-backed PLE table).** One GB10 holds the checkpoint only if the 47.7 GiB FP8 N-gram table leaves memory entirely: with **PLE Offload = On (NVMe file)** (`--ple-offload-embedding --ple-offload-backend file`, from [#37068](https://github.com/sgl-project/sglang/pull/37068), merged into `qwen4-main-squashed`) SGLang creates a sparse 47.7 GiB file under `$SGLANG_CACHE_DIR/ple/` (relocate with `--ple-offload-dir`; put it on the local NVMe and mount that directory into the container), fills it on boot, and the gather kernel reads rows through the host page tables; the table's resident set stays at 0 while serving, with hot pages in page cache (capped at 8 GiB by `SGLANG_QWEN4_PLE_FILE_RSS_BUDGET_GB`). The 78.3 GiB of experts and dense weights stay resident (the server logs \~80 GB after load, which also counts the CUDA context and allocator overhead) and `--mem-fraction-static 0.85` leaves \~12–18 GB for the pools, so concurrency is pinned low: **8 requests with MTP** (40 fp32 mamba slots of \~113 MB each) or **24 without** (96 slots on `extra_buffer_lazy`). Measured on `4ccff141db`: MTP cell 27.5 tok/s single-stream (TPOT 33.6 ms) and 71.7 tok/s output at 8; no-MTP cell 15.9 tok/s single-stream and 83 tok/s output at 24; host memory never below 10 GiB. **Boot-time caveat:** every boot rewrites the whole table through the mapping; on an already-populated file that is a read-modify-write per 4 KiB page with readahead disabled (`MADV_RANDOM`), \~17 MB/s and \~55 minutes; on a fresh sparse file it fills at GB/s and the boot takes \~10 minutes. Until that is fixed upstream, delete the previous `ple_table_*.bin` before each boot. > * **NVIDIA export (NVFP4 (NVDA)).** `nvidia/Qwen3.8-Flash-Next-NVFP4` is a ModelOpt MIXED\_PRECISION checkpoint (NVFP4 experts, FP8 N-gram table, FP8 block-scaled MTP experts) and needs the loader from [#38121](https://github.com/sgl-project/sglang/pull/38121), merged into `qwen4-main-squashed` (the branch the Python install path builds and the `lmsysorg/sglang:dev-qwen38-next-local` image ships); the `qwen38flashnext` image predates it and cannot load this export. Do not pass `--quantization` for it (it resolves to `modelopt_mixed`), and pass `--moe-runner-backend flashinfer_cutlass` explicitly: the mixed-precision auto-default picks `flashinfer_trtllm` on GB10, which the NVFP4 MoE method rejects at autotune. Its MTP experts are FP8 block-scaled with 128-wide blocks and cannot be split across two ranks (640 / 2 = 320), so the two-node low-latency cell reads the MTP draft from the RadixArk export, the same trained head kept in BF16 there. On a single Spark (TP=1, file-backed table) nothing is sharded, so the export's own MTP head loads directly. The single-Spark NVDA cells use the same pins as the RDXA ones (8 requests with MTP, 24 without); the smaller fp8 draft leaves a 174k-token KV pool with MTP, against 93k for the RadixArk cell. Measured on the `qwen4-main-squashed` tip `4ccff141db` (#38121 merged) at TP=2: 47.4 tok/s single-stream with MTP, 253 tok/s output at 96 concurrent without, the same as the RadixArk export. > **RTX PRO 6000 notes (1x 96 GB, TP=1)** > > The NVFP4 checkpoint fits a single 96 GB RTX PRO 6000 Blackwell (SM120) only with the 47.7 GiB FP8 N-gram table in **CPU pinned memory** (`--ple-offload-embedding`, the forced setting of the PLE Offload row on this hardware): the other 78 GiB of the checkpoint loads onto the card. After the loader's temporaries are collected, 74.7 GiB stays resident without speculative decoding and 81.8 GiB with it (the draft head is 0.5 GiB; the rest is memory the loader still holds), leaving 19.4 GiB and 12.3 GiB of the 94.2 GiB the process can use. `--mem-fraction-static` keeps (1 − fraction) × 94.2 GiB of that as runtime slack and the pools take the rest: 6.6 GiB of slack and 12.8 GiB of pools at 0.93, 3.8 GiB and 8.3 GiB at 0.96. (The 81 GiB "mem usage" in the load log is the delta before that collection.) The host needs ≥ 64 GB of free RAM for the locked table (plus page cache for the checkpoint) and Docker needs `--ulimit memlock=-1`, or the pinned allocation fails. > > * **Concurrency.** The hybrid model reserves mamba state slots per running request, and the scheduler caps `--max-running-requests` to what the state pool admits: with the default `extra_buffer` strategy (5 fp32 slots per request at 0.109 GiB) that is 3 requests with MTP and 12 without on this card. The cells keep prefix caching on and get to 16 / 64 with three levers: `--mamba-radix-cache-strategy extra_buffer_lazy` (4 slots per request), `SGLANG_OPT_MAMBA_SKIP_DECODE_LOCK=1` (3; a running request's prefix state is no longer pinned in the radix tree during decode, so it can be evicted, which trades cache retention, not numerics), and `--mamba-ssm-dtype bfloat16` (0.055 GiB per slot). `--max-mamba-cache-size` is pinned to requests × 3 (48 / 192). The ceilings from the pool arithmetic are \~20 requests with MTP (each request carries 4 intermediate draft states) and \~70 without; turning prefix caching off (`--disable-radix-cache`, 1 slot per request) reaches 24 / 96 on this card and was verified too, but re-prefills every prompt. > > * **Linear-attention kernels.** Left on auto. On SM120 the server resolves decode, prefill and verify to triton — the same GDN kernels the fp32 runs and the DGX Spark cells use; the bf16-state FlashInfer GDN auto-default applies only to SM100. An explicit `--linear-attn-decode-backend flashinfer` also runs on this card and measured the same TPOT (within 0.3 ms) and accuracy, so there is nothing to gain from pinning either. > > * **Memory headroom.** With the state pool pinned, the KV pool absorbs the rest of the static budget, so `--mem-fraction-static` is what sets the activation headroom. 4096-token prefill chunks of ShareGPT-length prompts peak 1.5–2.6 GB above the post-graph-capture level, and cells left with 2.4 GB free OOMed in the GDN short-conv during prefill. The cells keep ≥ 4 GB free after graph capture and ≥ 2.3 GB at the measured peak: 0.96 with MTP (78k-token KV pool, \~4.9k per request at 16) and 0.93 without (98k tokens, \~1.5k per request at 64; 0.94 gives 138k tokens with 2.3 GB at peak). `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` is set on both. > > * **Accuracy.** Full GSM8K, 1,319 questions, on the `lmsysorg/sglang:dev-qwen38-next-local` image, in two protocols. Chat completions API with thinking off, greedy, an 8,192-token budget, answer parsed from a final "The answer is N" line (the protocol of the DGX Spark rows, and the figure on the benchmark card): 96.9% for the MTP cell and 96.9% for the no-MTP cell (RadixArk export); 97.3% and 97.0% for the NVIDIA export. `python -m sglang.test.run_eval --eval-name gsm8k --num-examples 1319 --max-tokens 16384` (5-shot, greedy, last-number scorer, chat template with thinking on): 97.72% / 97.79% (RadixArk), 97.41% / 97.72% (NVIDIA). Measured on the `4ccff141db` build, which carries the #36811 and #38290 router fixes. > > * **Measured (1024-in / 256-out random prompts, `ignore_eos`).** MTP vs no-MTP at 1 request: TTFT 115 vs 116 ms median, TPOT 5.9 vs 11.4 ms, 148 vs 83 tok/s. At 16: TPOT 19.3 vs 25.6 ms, 613 vs 524 tok/s. No-MTP at 64: TPOT 55 ms, 861 tok/s, 3.4 req/s. ShareGPT chat (thinking off, ≤ 512 output tokens): 785 tok/s at 16-way with MTP, 1,258 tok/s at 64-way without. MTP accept length 3.3 of 4 on GSM8K / random prompts, 2.9 on long-form ShareGPT answers. On the `dev-qwen38-next-local` image (`4ccff141db`): 6.0 / 11.44 ms TPOT at 1 request (MTP / no MTP), 685 / 561 tok/s at 16, 909 tok/s at 64 without MTP, accept length 3.16. > > * **NVIDIA export (NVFP4 (NVDA)).** `nvidia/Qwen3.8-Flash-Next-NVFP4` runs on this card with the same shape, pools and flags as the RadixArk cells on the `lmsysorg/sglang:dev-qwen38-next-local` image (it carries the loader from [#38121](https://github.com/sgl-project/sglang/pull/38121); `qwen38flashnext` cannot load this export). Do not pass `--quantization`: the checkpoint resolves to `modelopt_mixed`. Low latency keeps the in-checkpoint MTP head: at TP=1 its fp8 block-scaled experts need no sharding, and #38121 runs them on triton under the `flashinfer_cutlass` pin. The RadixArk BF16 draft measured the same here (accept 3.33 vs 3.31, TPOT 18.5 vs 19.1 ms at 16), so the cell stays single-checkpoint. Verified on that image (`4ccff141db`): full GSM8K in the Accuracy bullet above; 6.02 ms TPOT at 1 request with MTP, 675 output tok/s at 16; 906 output tok/s at 64 without, the same as the RadixArk export. The smaller fp8 draft leaves a \~170k-token KV pool at 16 concurrent. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## Agentic Long-Context Deployment Agentic workloads, such as coding agents and other multi-turn, tool-using assistants, send long prompts whose prefixes grow and repeat from turn to turn. Serving them well depends on reusing the KV cache across turns, offloading it beyond GPU memory, and keeping each session on the workers that already hold its prefix. This section gives complete launch commands for such deployments, each benchmarked in [SemiAnalysis InferenceX](https://inferencex.semianalysis.com/) and linked to the run that measured it. Pick a hardware platform, checkpoint, deployment shape, concurrency, KV cache offloading mechanism and router to get every process of the deployment as a raw command, one tab per process in launch order. * **Router.** Each configuration was submitted behind one front door: Dynamo (`dynamo.frontend` with `dynamo.sglang` workers) or SGLang (`sglang.launch_server`, behind `sglang_router` when there are several workers or DP-attention ranks). * **KV offload.** Choose among these KV cache offloading mechanisms: none (GPU KV only), HiCache (host DRAM), or a Mooncake store attached through the external linker. The Mooncake option needs an image whose SGLang build includes `--enable-unified-cache-external-linker`. * **Container image.** Run the commands inside the image listed for each configuration. Several are SGLang nightly images, so flag names follow that image. ## 1. Model Introduction **Qwen3.8-Flash-Next** is a multimodal Mixture-of-Experts model released as an early preview of the architecture Qwen4 is being built on — the same role Qwen3-Next played for Qwen3.5, whose hybrid Gated DeltaNet + Gated Attention design then carried through the Qwen3.5, Qwen3.6, Qwen3.7 and Qwen3.8 series. Qwen is publishing the architectural changes ahead of the full Qwen4 family so the community can evaluate them independently. It has **176B total parameters — 51B of which is an N-gram embedding table — and 6B active per token**. Against Qwen3.7-Plus it cuts both training and inference cost substantially (training takes roughly 1/9 as much) while holding comparable overall quality. It takes text and images in, and the hosted production variant is served as `qwen3.8-flash` on QwenCloud. The upgrades span four axes: * **Attention — GDN + QSA hybrid.** Three of every four layers use Gated DeltaNet, which compresses history into a fixed-size recurrent state; the fourth is global attention running **Qwen Sparse Attention (QSA)**. A lightweight indexer aggregates the sequence into micro-blocks, scores importance at block level, and selects the relevant regions — so the indexing overhead shrinks along with the attention itself. Unlike approaches that reuse indices across layers, QSA compresses independently per layer, which suits an architecture that interleaves GDN and attention. Qwen measures up to 10.2× prefill and 6.6× decode speedups for the QSA attention kernel at 1M tokens. * **Residual — Gated Residual (GR).** The single residual stream widens into four parallel branches, with an element-wise dynamic gate controlling how much each layer reads from and writes back to each branch. Qwen reports one branch naturally becoming a long-range bus. The gate also suppresses activation outliers, and the residual state can be held in FP8. * **Embedding — N-gram Embedding.** Lookups keyed on the local context (current token plus a few preceding ones) rather than a single token, adding 51B parameters at almost no extra per-token compute. Because lookup addresses are known in advance, the table can live in host memory and be prefetched asynchronously alongside model compute. The final model uses a single such layer near the start of the network. * **Optimization — Muon.** Muon for the genuine 2-D linear maps (attention, GDN and MoE expert weights), AdamW for embeddings, the MoE router and GR's low-rank parameters, with fused QKV / SwiGLU / GDN projections split before orthogonalization. The scaling law was refit for the new architecture, and batch-size warmup was dropped — it cost 18.8% more optimizer steps without improving the result. Carried over from Qwen3-Next and refined through the Qwen3.5–Qwen3.8 series: an ultra-sparse MoE (large expert pool, few routed experts per token plus one shared expert) with global load balancing; a **multi-step-trained MTP module**, whose own full-attention layers are QSA as well, which is what keeps speculative acceptance high in practice; and the training-stability set of zero-centered RMSNorm with weight decay on norm weights, attention output gating, and normalized MoE router initialization. **Context length:** 262,144 native, extensible to 1,000,000 tokens with YaRN. **License:** see [the model card's LICENSE](https://huggingface.co/Qwen/Qwen3.8-Flash-Next/blob/main/LICENSE). **Recommended generation:** Qwen has not published sampling recommendations for this preview. SGLang applies the checkpoint's own `generation_config.json`, so leave `temperature` / `top_p` unset unless you have a measured reason not to. Each precision is its own repository:
Precision Repository Where it runs
**BF16** [Qwen/Qwen3.8-Flash-Next](https://huggingface.co/Qwen/Qwen3.8-Flash-Next) H200, B200, B300, GB300, MI350X, MI355X
**FP8** [Qwen/Qwen3.8-Flash-Next-FP8](https://huggingface.co/Qwen/Qwen3.8-Flash-Next-FP8) H200, B200, B300, GB300, MI350X, MI355X
**NVFP4 (RDXA)** [RadixArk/Qwen3.8-Flash-Next-NVFP4](https://huggingface.co/RadixArk/Qwen3.8-Flash-Next-NVFP4) B200, B300, GB300, RTX PRO 6000, 1x or 2x DGX Spark (Blackwell only)
**NVFP4 (NVDA)** [nvidia/Qwen3.8-Flash-Next-NVFP4](https://huggingface.co/nvidia/Qwen3.8-Flash-Next-NVFP4) (ModelOpt MIXED\_PRECISION) RTX PRO 6000, 1x or 2x DGX Spark (needs [#38121](https://github.com/sgl-project/sglang/pull/38121): the `dev-qwen38-next-local` image or the Python install path)
**Resources:** [Qwen's announcement](https://qwen.ai/blog?id=qwen3.8-flash-next). ## 2. Advanced Usage > [!NOTE] > > The `model` argument in the examples below is the BF16 repo id. Every precision is a **separate repo**, so `model` has to be the checkpoint the server was actually launched with — `…-Flash-Next-FP8` or `…-Flash-Next-NVFP4`. The Deploy panel's cURL snippet always shows the right id for the cell you have selected. ### 2.1 Reasoning Qwen3.8-Flash-Next **always** reasons — thinking cannot be turned off. `--reasoning-parser auto` (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) lets SGLang pick the matching parser from the checkpoint's chat template, and splits the thinking into `reasoning_content`, leaving `content` as the answer alone. The resolved name is logged at startup if you want to pin it explicitly later. Depth is requested with `reasoning_effort`. Qwen documents `xhigh` (the default), `medium` and `low` for the hosted model; SGLang forwards whatever you pass into the checkpoint's chat template. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="Qwen/Qwen3.8-Flash-Next", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > reasoning_effort="xhigh", # xhigh (default) | medium | low > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Pending update — a sample transcript will be added here once the weights are public. > ``` ### 2.2 Tool Calling Add `--tool-call-parser auto` (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. As with the reasoning parser, SGLang resolves the concrete detector from the chat template at startup. No Deploy cell sets it, so this is an opt-in: add the flag to the generated command, or flip the chip in the Playground. Because this model always thinks, the final assistant turn can put text in `reasoning_content` rather than `content` — print both so a bare `None` doesn't mislead you. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": { > "location": {"type": "string", "description": "The city name"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["location"], > }, > }, > } > ] > > resp = client.chat.completions.create( > model="Qwen/Qwen3.8-Flash-Next", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Content:", msg.content) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Pending update — a sample transcript will be added here once the weights are public. > ``` # Flint Source: https://docs.sglang.io/cookbook/autoregressive/Recursive/Flint Deploy Recursive's Flint with SGLang — a 40B Mixture-of-Experts model for fast, local agentic coding with a 262K context window — on NVIDIA H200, B200, B300, GB300, and DGX Spark. ## Deployment > **Install SGLang** > > Flint runs on the `lmsysorg/sglang:dev-flint` Docker image: > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-flint > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). The **Docker** toggle in the command panel below produces the full `docker run` command; the **Python** toggle produces the inner `sglang serve ...` to run inside the container. Pick your hardware to generate the launch command. ## 1. Model Introduction **[Flint](https://huggingface.co/RecursiveSI/flint)** is a new open-weight **40B Mixture-of-Experts** model from Recursive, built for fast, local AI coding. Flint was developed using Recursive's Eureka Machine for automated AI research and is released under Apache 2.0.
Model Total params Context Use
**[Flint](https://huggingface.co/RecursiveSI/flint)** 40B (MoE) 262,144 Fast, local agentic coding
**License:** Apache 2.0 **Resources:** [Hugging Face](https://huggingface.co/RecursiveSI/flint). ## 2. Advanced Usage ### 2.1 Reasoning Launch with `--reasoning-parser flint` (included in the commands above). Thinking is separated into `message.reasoning_content`, and the final answer is returned in `message.content`. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="flint", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > ) > > message = response.choices[0].message > print("=============== Reasoning ===============") > print(message.reasoning_content) > print("=============== Answer ===============") > print(message.content) > ``` > **Example Output** > > ```text Output theme={null} > =============== Reasoning =============== > We need answer simple. Need maybe show calculation. User asks "What is 15% of 240?" We can answer. Need be careful maybe just 36. Let's craft concise. > =============== Answer =============== > 15% of 240 is **36**. > ``` ### 2.2 Tool Calling Launch with `--tool-call-parser flint` (included in the commands above) to surface structured tool calls via `message.tool_calls`. > **Tool Calling Example (Python)** > > ```python Example theme={null} > import json > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string"}}, > "required": ["city"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="flint", > messages=[{"role": "user", "content": "What's the weather in Paris?"}], > tools=tools, > ) > > message = response.choices[0].message > print("=============== Reasoning ===============") > print(getattr(message, "reasoning_content", None)) > print("=============== Content ===============") > print(message.content) > print("=============== Tool Calls ===============") > for call in message.tool_calls or []: > print(call.function.name, json.loads(call.function.arguments)) > ``` > **Example Output** > > ```text Output theme={null} > =============== Reasoning =============== > The user asked for the weather in Paris, and I have a get_weather tool available that takes a city parameter. I should call it with city 'Paris' to get the current weather. > =============== Content =============== > I'll get the current weather for Paris for you. > =============== Tool Calls =============== > get_weather {'city': 'Paris'} > ``` # Dots3-Note Source: https://docs.sglang.io/cookbook/autoregressive/RedNote/Dots3-Note Deploy RedNote dots3.note with SGLang — a native multimodal omni model (MoE ViT + Whisper-derived audio encoder + native video flattening) on the dots3 hybrid MLA/SWA language model, with DSA and full-sharing MTP speculative decoding. ## Deployment > **Install SGLang** > > dots3.note support is in [SGLang PR #33829](https://github.com/sgl-project/sglang/pull/33829). Until that PR is included in a tagged SGLang release, install from a build that contains the PR. > > **Python (pip / uv)** > > ```bash Command theme={null} > pip install -U uv > uv venv --python 3.12 && source .venv/bin/activate > > git clone https://github.com/sgl-project/sglang.git > cd sglang > git fetch origin pull/33829/head && git checkout FETCH_HEAD > uv pip install --prerelease=allow -e python > ``` > > Then run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-dots3-note > ``` > > This image packages SGLang with the dots3.note support from PR #33829 and is the recommended way to deploy until the PR lands in a tagged SGLang release — it saves you from building the branch yourself. > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick the hardware and the checkpoint precision. The recipe runs on a single 8-GPU Hopper node with DP8 attention × TP8 × EP8 and DeepEP as the MoE all-to-all transport. Blackwell is not supported yet. **Precision** — selects the MoE path, not just the weights. The BF16 cells pin `--moe-runner-backend deep_gemm` with BF16 DeepEP dispatch output (JIT DeepGEMM is enabled via `SGLANG_ENABLE_JIT_DEEPGEMM=1`). The FP8 cells leave both at `auto` and let SGLang resolve the runner from the checkpoint's quantization config. **Spec Decode** — NEXTN is on in every cell: 3 draft steps, 4 draft tokens per step, and the draft model path pointing at the target checkpoint itself. dots3's MTP layer is full-sharing — it carries the dots3 sliding-window attention geometry and reuses the target LM head — so no separate draft checkpoint is needed. Target verification and draft extension run on the paged, absorbed SWA-MLA FA3 path. ## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations signed off on this page; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. ## 1. Model Introduction dots3.note is RedNote's native multimodal omni model, built on the dots3 language model. It accepts text, image, audio, and native video input. * **Native multimodality** — a custom MoE vision transformer and a Whisper-derived audio encoder run in-process with the language model, loaded from the same checkpoint directory. Image and audio placeholders are expanded by a model-specific processor. * **Native video pipeline** — the server jointly samples and interleaves frames, timestamps, and audio segments under a token budget, reproducing the training-time flattening algorithm. A generic uniform-frame video processor would silently change the modality ordering and token allocation (inference/training mismatch), so the pipeline is vendored into the serving path. * **Hybrid attention** — dots3 combines MLA with full-attention and sliding-window layers of different geometry, attention gates, and optional DSA indexing on full-attention layers. * **MTP speculative decoding** — a full-sharing MTP/NextN architecture exposes one recursively shared, SWA-shaped MTP layer and shares the target LM head. **Available checkpoints:** * **BF16**: [dots-studio/dots3-note-prev](https://huggingface.co/dots-studio/dots3-note-prev) * **FP8**: [dots-studio/dots3-note-prev-fp8](https://huggingface.co/dots-studio/dots3-note-prev-fp8) **Resources:** [Hugging Face (BF16)](https://huggingface.co/dots-studio/dots3-note-prev) · [Hugging Face (FP8)](https://huggingface.co/dots-studio/dots3-note-prev-fp8) · [SGLang PR #33829](https://github.com/sgl-project/sglang/pull/33829) ## 2. Configuration Tips **Hybrid KV pool.** dots3 mixes full-attention and sliding-window layers, and its MTP draft layer is an ordinary SWA layer — not a full-attention one. SGLang sizes the pool accordingly, with `--swa-full-tokens-ratio 0.03` setting the ratio of SWA-layer KV tokens to full-layer KV tokens (`swa_tokens ≈ full_tokens × ratio`). Lower it when long full-attention contexts dominate and the full pool fills first; raise it when the SWA pool is the bottleneck. **MoE runner.** Leave the runner at the cell default: `deep_gemm` for BF16 checkpoints, `auto` for quantized ones. DeepEP is the all-to-all transport in every cell (`--moe-a2a-backend deepep`, dispatch tokens per rank tuned via `SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=128`). **Attention backend.** FA3 across the board: prefill, decode, and draft (`--prefill-attention-backend fa3 --decode-attention-backend fa3 --speculative-draft-attention-backend fa3`) with `--page-size 64`. MTP target verification uses FA3's absorbed SWA-MLA fallback, which consumes the same paged latent KV view as decode. **DSA.** DSA indexing on full-attention layers is on by default. To disable it, add `--json-model-override-args '{"index_topk":null}'`. **CUDA graphs.** The cells enable decode-side CUDA graphs only (`--cuda-graph-backend-decode full --cuda-graph-backend-prefill disabled`, max batch size 32) and are sized for GPUs with at least 120 GiB of memory. On smaller GPUs, switch to `--cuda-graph-backend-decode disabled` (and expect `--deepep-mode normal` to be the better fit). **Context length.** `--context-length 524288` is the model's window. Like other SGLang models, it bounds the longest accepted request; it does not size the KV pool. **Language-only mode.** Add `--language-only` to skip constructing the vision and audio towers entirely — the freed memory goes to the language model. This is also the language role of an encoder/LLM-disaggregated (EPD) deployment; see [EPD](#epd-disaggregation) below. ## 3. Advanced Usage ### 3.1 Native video input dots3.note accepts a native `video_url`. The server decodes the remote video in memory and applies the training-consistent flattening pipeline — interleaving timestamps, frames, and audio under a token budget, with a deterministic seed derived from the video and the question. > **Video Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="dots3.note", > messages=[ > { > "role": "user", > "content": [ > { > "type": "video_url", > "video_url": {"url": "https://example.com/sample.mp4"}, > }, > {"type": "text", "text": "Summarize what happens in this video."}, > ], > } > ], > extra_body={ > "video_config": { > "seq": 131072, > "audio_cap": 0.5, > "audio_sr": 16000, > "k_mode": "eval_ek", > }, > }, > ) > > print(response.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > Pending update... > ``` Per-request video preprocessing controls are grouped under `video_config` in `extra_body`:
Field Default Purpose
`seq` `131072` Total sequence budget used by the video flattener.
`audio_cap` `1.0` Maximum fraction of the input budget assigned to audio; `0` disables audio processing.
`audio_sr` `16000` Audio sample rate.
`k_mode` `eval_ek` Deterministic evaluation/sampling mode of the flattener.
These controls are request-scoped so that evaluation jobs with different context budgets can share one server. For example: `extra_body={"video_config": {"seq": 131072, "audio_cap": 0.5}}`. The flattener reserves room for `max_new_tokens` inside the budget and falls back to visual-only processing if audio would exceed the configured token budget. A request may carry several videos, and videos can be mixed with image and audio parts. Each video is flattened independently under the same per-request budget, and the flattened frames and audio segments are spliced back at the position of their `video_url` part, so the modality ordering of the prompt is preserved. ### 3.2 Image and audio input Outside the native-video path, images and audio clips use the standard OpenAI multimodal message format. `--enable-multimodal` is in every cell; the vision and audio towers run in-process, so no extra server is needed. > **Image Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="dots3.note", > messages=[ > { > "role": "user", > "content": [ > { > "type": "image_url", > "image_url": {"url": "https://example.com/sample.jpg"}, > }, > {"type": "text", "text": "Describe this image."}, > ], > } > ], > ) > > print(response.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > Pending update... > ``` ### 3.3 Tool Calling Toggle **Tool Call Parser** (`--tool-call-parser dots`) and **Reasoning Parser** (`--reasoning-parser dots`) in the **Parsers** card of the [Playground above](#playground). Structured tool calls then surface via `message.tool_calls`. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string"}}, > "required": ["city"], > }, > }, > }] > resp = client.chat.completions.create( > model="dots3.note", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > print(resp.choices[0].message.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Pending update... > ``` ### 3.4 Encoder/LLM Disaggregation (EPD) `Dots3NoteForCausalLM` supports both roles of an encoder/LLM-disaggregated deployment: * **Encoder role** — serve with `--encoder-only`; the instance runs only the vision and audio towers. * **Language role** — serve with `--language-only`; the instance skips tower construction, leaving the memory to the language model. See the [EPD guide](../../../docs/advanced_features/epd_disaggregation) for how to wire the roles together. # Beam 1.0 Source: https://docs.sglang.io/cookbook/autoregressive/Reflection/Beam-1_0 Deploy Reflection Beam 1.0 with SGLang on B300, GB300, and H200: NVFP4, FP8, and BF16 recipes for low latency and high throughput. ## Deployment > **Install SGLang** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:beam > ``` > > For host setup, see [Install SGLang with Docker](/docs/get-started/install#method-3-using-docker). The command panel below has a **Python / Docker** toggle, with Python selected by default. The Python output is the bare `sglang serve` command: run it inside a container started from this image. The Docker output wraps the same command in `docker run`. Select your hardware, strategy, and quantization to generate the launch command. * **Low-Latency** uses TP with the [DFlash2 drafter](https://huggingface.co/reflection/Beam-1.0-501B-A23B-DFlash2) at block size 8. * **High-Throughput** disables DFlash2. H200 BF16 uses TP8 with an automatic static memory fraction; the other recipes use TP + DPA. Blackwell NVFP4 also enables EP and FlashInfer MegaMoE. Each GSM8K score covers all 1,319 test problems; the benchmark notes identify the evaluation harness. NVFP4 requires B300 or GB300. **GB300 BF16 uses two four-GPU nodes**: set the head-node address and node rank in **Env**, then run the command on both nodes with rank 0 on the head and rank 1 on the peer. ## TPU Support Beam 1.0 has day-0 TPU support through SGLang-TorchTPU, a native PyTorch backend for LLM, VLM, and diffusion model inference on TPUs. It combines TPU acceleration with SGLang features such as RadixAttention and HiCache to enable cost-efficient, production-ready serving for agentic workloads. TPU recipes for Beam 1.0 and access to SGLang-TorchTPU will be available soon. Sign up through this [Google Form](https://docs.google.com/forms/d/e/1FAIpQLSe2Y8hzyU3KGB2StA-0huulrVsq79A0tSxcBQwjj8vlhLhYuQ/viewform?usp=publish-editor) to receive the latest updates. ## Usage All recipes serve the model as `beam` on port 30000. For GB300 BF16, connect to the head node. > **Chat completion (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > response = client.chat.completions.create( > model="beam", > messages=[{"role": "user", "content": "Explain tensor parallelism briefly."}], > ) > message = response.choices[0].message > print("Reasoning:", message.reasoning_content) > print("Answer:", message.content) > ``` # Step-3.7-Flash Source: https://docs.sglang.io/cookbook/autoregressive/StepFun/Step-3.7-Flash ## 1. Model Introduction [Step-3.7-Flash](https://huggingface.co/stepfun-ai/Step-3.7-Flash) is a 198B-parameter Mixture-of-Experts (MoE) vision-language model that combines a 196B-parameter language backbone with a 1.8B-parameter vision encoder for native image understanding. Engineered for high-frequency production workloads, it activates approximately 11B parameters per token and supports a 256k context window with three selectable reasoning levels (low, medium, and high). The model is available in multiple quantization formats (BF16, FP8, NVFP4). Step-3.7-Flash is built for developers who need to scale agentic workflows that combine perception, search, and reasoning — from parsing massive financial reports in one pass, to running multi-step search loops with cross-source verification, to operating concurrent coding agents in high-throughput pipelines. ## 2. SGLang Installation Step-3.7-Flash is currently available in SGLang via Docker image install. ### Docker (NVIDIA) ```bash Command theme={null} # Pull the docker image docker pull lmsysorg/sglang:latest # Launch the container docker run -it --gpus all \ --shm-size=32g \ --ipc=host \ --network=host \ lmsysorg/sglang:latest bash ``` ## 3. Model Deployment This section provides deployment configurations optimized for different use cases. ### 3.1 Basic Configuration The Step-3.7-Flash series comes in one size with multiple quantization options. Recommended starting configurations vary depending on hardware. **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization method, and capabilities. Run this Command:

### 3.2 Configuration Tips

* **Memory**: Requires GPUs with high VRAM capacity. Supported platforms: H200 (4x, TP=4), B200/B300 (4x, TP=4), GB200/GB300 (4x, TP=4).
* **NVFP4 Quantization**: NVFP4 provides the smallest memory footprint. Requires `--quantization modelopt_fp4 --kv-cache-dtype fp8_e4m3 --moe-runner-backend flashinfer_trtllm`.
* **Trust Remote Code**: All Step-3.7-Flash variants require `--trust-remote-code` due to the custom model architecture.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Multi-Modal Inputs

Step-3.7-Flash supports image inputs alongside text. Here's a basic example:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                }
            },
            {
                "type": "text",
                "text": "Read all the text in the image."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="stepfun-ai/Step-3.7-Flash",
    messages=messages,
    max_tokens=2048,
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Multi-Image Input Example:**

Step-3.7-Flash can process multiple images in a single request for comparison or analysis:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://www.civitatis.com/f/china/hong-kong/guia/taxi.jpg"
                }
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://cdn.cheapoguides.com/wp-content/uploads/sites/7/2025/05/GettyImages-509614603-1280x600.jpg"
                }
            },
            {
                "type": "text",
                "text": "Compare these two images and describe the differences in 100 words or less."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="stepfun-ai/Step-3.7-Flash",
    messages=messages,
    max_tokens=2048,
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

#### 4.2.2 Reasoning Parser

Step-3.7-Flash supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections:

```shell Command theme={null}
sglang serve \
  --model-path stepfun-ai/Step-3.7-Flash \
  --tp 4 \
  --trust-remote-code \
  --reasoning-parser step3p5
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="stepfun-ai/Step-3.7-Flash",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

#### 4.2.3 Tool Calling

Step-3.7-Flash supports tool calling capabilities. Enable the tool call parser:

**Start sglang server:**

```shell Command theme={null}
sglang serve \
  --model-path stepfun-ai/Step-3.7-Flash \
  --tp 4 \
  --trust-remote-code \
  --reasoning-parser step3p5 \
  --tool-call-parser step3p5
```

```python Example theme={null}
from openai import OpenAI
import json

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# 1. define tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "The city name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit"}
                },
                "required": ["location"]
            }
        }
    }
]

# 2. tool run
def get_weather(location, unit="celsius"):
    return f"The weather in {location} is 22 {unit[0].upper()} and sunny."

# 3. send first request
print("--- Sending first request ---")
response = client.chat.completions.create(
    model="stepfun-ai/Step-3.7-Flash",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=1.0,
    stream=False
)

message = response.choices[0].message

# 4. Handle Reasoning Content
reasoning = getattr(message, 'reasoning_content', None)
if reasoning:
    print("=============== Thinking =================")
    print(reasoning)
    print("==========================================")

# 5. Handle Tool Calls
if message.tool_calls:
    print("\nTool Calls detected:")
    history_messages = [
        {"role": "user", "content": "What's the weather in Beijing?"},
        message
    ]

    for tool_call in message.tool_calls:
        print(f"   Tool: {tool_call.function.name}")
        print(f"   Args: {tool_call.function.arguments}")

        args = json.loads(tool_call.function.arguments)
        tool_result = get_weather(args.get("location"), args.get("unit", "celsius"))

        history_messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": tool_result
        })

    print("\n--- Sending tool results ---")
    final_response = client.chat.completions.create(
        model="stepfun-ai/Step-3.7-Flash",
        messages=history_messages,
        temperature=1.0,
        stream=False
    )

    print("=============== Final Content =================")
    print(final_response.choices[0].message.content)

else:
    if message.content:
        print("=============== Content =================")
        print(message.content)
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

## 5. Benchmark

*Benchmark results will be added soon.*


# Step 5 Preview
Source: https://docs.sglang.io/cookbook/autoregressive/StepFun/Step-5-Preview

Deploy StepFun's Step 5 Preview with SGLang — a 600B-parameter (27B active) Mixture-of-Experts model for agentic work with region-sparse attention, three-layer MTP and 1M context, on NVIDIA Blackwell and Hopper.

## Deployment

> **Install SGLang**
>
> For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel.
>
> **Python (pip / uv)**
>
> Step 5 Preview support has **not shipped in an SGLang release yet**, so a stock `pip install sglang` cannot serve it. Use the preview Docker image.
>
> **Docker**
>
> Every recipe on this page uses the preview image `lmsysorg/sglang:step-5-preview` (B300 and H200); the command panel picks it automatically. The image already includes the FlashInfer patches Step 5 Preview needs.
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:step-5-preview
>
> docker run --gpus all \
>     --shm-size 32g \
>     -p 30000:30000 \
>     -v ~/.cache/huggingface:/root/.cache/huggingface \
>     --env "HF_TOKEN=" \
>     --ipc=host \
>     lmsysorg/sglang:step-5-preview \
>     sglang serve 
> ```
>
> For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker).

Pick your hardware and parallelism, then the model, MoE backend and serving options. Recommended starting points:

* **Lowest latency** (Blackwell) — TP4 with the FlashInfer TRT-LLM MoE on four B300 GPUs. Fastest reply for a single user.
* **Multi-user serving** (Blackwell) — TP4 with MegaMoE, which speeds up prefill and decode once several requests share a batch.
* **Highest throughput** (Blackwell) — ATTN DP2: TP8 with DP attention 2 and EP8 on eight B300 GPUs, with either MoE backend. Most tokens per second across many users.
* **Hopper** — EP8: TP8 + EP8 on eight H200 GPUs with FA3 attention and Triton MoE. The FP8 weights do not fit four H200 GPUs. ATTN DP2 is also available on Hopper (TP8 with DP attention 2 and EP8, `--mem-fraction-static 0.85`).

## Playground

The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations the SGLang team has signed off on; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing.

## 1. Model Introduction

**Step 5 Preview** is StepFun's flagship model for agentic work, with particular strength in software engineering, professional knowledge work and finance. It is a sparse Mixture-of-Experts model with 600B total parameters and 27B active parameters. It supports a 1M-token context, takes image input through a built-in vision encoder, and ships three MTP layers for speculative decoding.

**Architecture.** The language model has 92 layers. In each MoE layer, a token is routed to 8 of 352 experts, alongside one shared expert. Attention repeats a four-layer pattern: three sliding-window layers that attend to the most recent 512 tokens, then one sparse-attention layer.

**Sparse attention.** The sparse layers split the KV history into 8-token regions. A lightweight indexer scores a summary of each region and selects up to 512 historical regions; attention then reads the token-level keys and values of those regions plus the current region, with causal masking.

**Precision.** Routed-expert weights are FP8 (E4M3, 128×128 block scales) except in the last three MoE layers, which stay BF16. SGLang runs every layer at its released precision.

**Reasoning.** Step 5 Preview always thinks before answering. `reasoning_effort` sets the depth: `low`, `medium` or `high`; when unset, it defaults to `high`.

**Recommended generation:** `temperature=1.0`, `top_p=0.95`, `top_k=0` (StepFun's recommended settings; informational — do not hardcode them in application code).

**License:** [StepFun Model License 1.0](https://huggingface.co/stepfun-ai/Step-5-Preview/blob/main/LICENSE.txt).

**Resources:** [HuggingFace (FP8)](https://huggingface.co/stepfun-ai/Step-5-Preview) · [HuggingFace (NVFP4)](https://huggingface.co/stepfun-ai/Step-5-Preview-NVFP4) · [Model page](https://www.stepfun.com/step-5-preview) · [Documentation](https://platform.stepfun.ai/docs/en/guides/models/step-5-preview).

## 2. Configuration Tips

**MoE runner.** On B300, the default runner is the FlashInfer TRT-LLM MoE. Picking **MegaMoE** in the **MoE** row adds `--moe-a2a-backend megamoe`, which runs the FP8 routed experts on MegaMoE; the BF16 routed experts in the last three MoE layers stay on TRT-LLM. MegaMoE also works with ATTN DP2. On H200, the recipe uses the Triton MoE for all expert layers, including the three BF16 ones, because the TRT-LLM MoE kernels are Blackwell-only.

**NVFP4 checkpoint.** Pick **NVFP4** in the **Model** row to serve `stepfun-ai/Step-5-Preview-NVFP4` on Blackwell. Its routed experts are NVFP4 (the last three MoE layers stay BF16) and run on the FlashInfer FP4 MoE kernels; the smaller weights leave more GPU memory for the KV cache. It runs with TP4, EP4 and ATTN DP2, does not support MegaMoE, and is not available on H200.

**Attention backend.** On Blackwell, Step 5 Preview selects FA4 automatically. On H200, keep `--attention-backend fa3` from the recipe.

**KV cache.** Every recipe uses BF16 KV cache. On both Blackwell and Hopper, pick **FP8** in the **KV Cache** row of the command panel for `--kv-cache-dtype fp8_e4m3` (full-attention layers only): it increases KV capacity but is lossy, so re-verify accuracy before using it.

**Prefill CUDA graph.** Step 5 Preview runs prefill on Breakable CUDA Graph by default, including with ATTN DP2, so the commands do not set it. ATTN DP2 runs TP8 with DP attention 2 and EP8; with DP attention on, the vision encoder and projector use replicated weights.

**FlashInfer patches.** The TRT-LLM MoE path needs Step 5 Preview's FlashInfer patches. They are already in `lmsysorg/sglang:step-5-preview`; for a custom build, see the README under `docker/patches/step5` in the SGLang repository.

**First start.** The first launch compiles FlashInfer modules (about 15 minutes on B300); later launches take about 6 minutes. Persist `FLASHINFER_WORKSPACE_BASE` and `~/.cache/sglang` across restarts.

**HiCache.** Turn it on in the **HiCache** row to keep evicted prefixes in host memory. Size `--hicache-ratio` to the host memory available per rank; larger ratios need proportionally more host RAM.

**Per-platform notes:**

Platform Topology Notes
B300 1×4 TP4, or TP4 + EP4 TRT-LLM MoE or MegaMoE; FA4 attention
B300 1×8 TP8 + DP attention 2 + EP8 TRT-LLM MoE or MegaMoE; FA4 attention
H200 1×8 TP8 + EP8, or TP8 + DP attention 2 + EP8 FA3 attention, Triton MoE; BF16 or FP8 KV cache
## 3. Advanced Usage ### 3.1 Reasoning The `step5` reasoning parser (already in every recipe) returns the thinking in `reasoning_content` and the answer in `content`. Pass `reasoning_effort` (`low`, `medium` or `high`) per request to trade depth for latency. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="stepfun-ai/Step-5-Preview", > messages=[{"role": "user", "content": "What is 15% of 240?"}], > reasoning_effort="low", > ) > msg = resp.choices[0].message > print("Reasoning:", msg.reasoning_content) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: We need answer simple. Need maybe compute 36. Need provide perhaps concise. Use reasoning low but final. 15% of 240 = 0.15*240=36. final. > Answer: 36 > ``` ### 3.2 Tool Calling The `step5` tool-call parser (already in every recipe) returns structured tool calls in `message.tool_calls`. > **Tool Calling Example (Python)** > > ```python Example theme={null} > import json > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > tools = [{ > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city", > "parameters": { > "type": "object", > "properties": {"city": {"type": "string", "description": "City name"}}, > "required": ["city"], > }, > }, > }] > messages = [{"role": "user", "content": "What's the weather like in Beijing right now?"}] > > resp = client.chat.completions.create( > model="stepfun-ai/Step-5-Preview", messages=messages, tools=tools, > ) > msg = resp.choices[0].message > for call in msg.tool_calls: > print("Tool call:", call.function.name, call.function.arguments) > > call = msg.tool_calls[0] > messages.append(msg) > messages.append({ > "role": "tool", > "tool_call_id": call.id, > "content": json.dumps({"city": "Beijing", "temperature_c": 18, "condition": "Sunny"}), > }) > final = client.chat.completions.create( > model="stepfun-ai/Step-5-Preview", messages=messages, tools=tools, > ) > print("Reasoning:", final.choices[0].message.reasoning_content) > print("Answer:", final.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > Tool call: get_weather {"city": "Beijing"} > Reasoning: The weather in Beijing is 18°C and sunny. > Answer: The weather in Beijing right now is **sunny** with a temperature of **18°C** — a pleasant day! ☀️ > ``` ### 3.3 Image Input > **Image Input Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > resp = client.chat.completions.create( > model="stepfun-ai/Step-5-Preview", > messages=[{ > "role": "user", > "content": [ > {"type": "image_url", "image_url": {"url": "https://raw.githubusercontent.com/sgl-project/sglang/main/examples/assets/example_image.png"}}, > {"type": "text", "text": "Describe this image in one sentence."}, > ], > }], > ) > print(resp.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > A man in a yellow hoodie irons a blue shirt on an ironing board attached to the back of a yellow SUV on a city street, with a yellow taxi behind him. > ``` ### 3.4 Speculative Decoding (MTP) Every recipe enables multi-layer MTP with the checkpoint's three MTP layers (`--speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 --enable-multi-layer-eagle`). Each verification round can advance generation by up to four tokens: three accepted draft tokens plus one target-model token. To turn MTP off, pick **Off** in the **Spec Decode** row of the command panel. ### 3.5 HiCache (Hierarchical KV Caching) For long multi-turn sessions, turn on **HiCache** in the command panel to keep evicted prefixes in host memory (L2). To add an L3 store such as Mooncake, pick it in the **Hierarchical KV Cache** card of the [Playground above](#playground). See the HiCache note in [Configuration Tips](#2-configuration-tips) for sizing. ### 3.6 PD Disaggregation Step 5 Preview supports prefill/decode disaggregation over Mooncake, including the MTP draft KV cache. Pick the **Prefill role** and **Decode role** in the **PD Disaggregation** card of the [Playground above](#playground) to generate both commands and the router command. # Step3-VL-10B Source: https://docs.sglang.io/cookbook/autoregressive/StepFun/Step3-VL-10B ## 1. Model Introduction [Step3-VL-10B](https://huggingface.co/stepfun-ai/Step3-VL-10B) is a lightweight open-source multimodal model developed by StepFun, designed to redefine the trade-off between compact efficiency and frontier-level multimodal intelligence. Despite its compact 10B parameter footprint, Step3-VL-10B excels in visual perception, complex reasoning, and human-centric alignment. Key highlights of Step3-VL-10B include: * **STEM Reasoning**: Achieves 94.43% on AIME 2025 and 75.95% on MathVision (with PaCoRe), demonstrating exceptional complex reasoning capabilities that outperform models 10×–20× larger. * **Visual Perception**: Records 92.05% on MMBench and 80.11% on MMMU, establishing strong general visual understanding and multimodal reasoning. * **GUI & OCR**: Delivers state-of-the-art performance on ScreenSpot-V2 (92.61%), ScreenSpot-Pro (51.55%), and OCRBench (86.75%), optimized for agentic and document understanding tasks. * **Spatial Understanding**: Demonstrates emergent spatial awareness with 66.79% on BLINK and 57.21% on All-Angles-Bench, establishing strong potential for embodied intelligence applications. For more details, please refer to the [Step3-VL-10B model card on Hugging Face](https://huggingface.co/stepfun-ai/Step3-VL-10B). ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration Step3-VL-10B is a compact 10B dense model that can run on a single GPU. Recommended starting configurations vary depending on hardware. **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and quantization method. SGLang supports serving Step3-VL-10B on NVIDIA B200, H200, H100, and AMD MI355X, MI325X, MI300X GPUs. Run this Command:

### 3.2 Configuration Tips

* **Single GPU Deployment**: Step3-VL-10B fits comfortably on a single GPU with BF16 precision, no tensor parallelism required.
* **Memory Management**: Set lower `--context-length` to conserve memory if needed. A value of `32768` is sufficient for most scenarios.
* **FP8 Quantization**: Use FP8 quantization to further reduce memory usage while maintaining quality.

## 4. Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)
* [SGLang OpenAI Vision API Guide](../../../docs/basic_usage/openai_api_vision)

### 4.2 Advanced Usage

#### 4.2.1 Multi-Modal Inputs

Step3-VL-10B supports image inputs. Here's a basic example with image input:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://ofasys-multimodal-wlcb-3-toshanghai.oss-accelerate.aliyuncs.com/wpf272043/keepme/image/receipt.png"
                }
            },
            {
                "type": "text",
                "text": "Read all the text in the image."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="stepfun-ai/Step3-VL-10B",
    messages=messages,
    max_tokens=2048,
    extra_body={"top_k": -1}
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example output:**

```text Output theme={null}
Response costs: 5.89s
Generated text: Auntie Anne's

CINNAMON SUGAR
1 × 17,000               17,000

SUB TOTAL                    17,000

GRAND TOTAL                 17,000

CASH IDR                    20,000

CHANGE DUE                 3,000
```

**Multi-Image Input Example:**

Step3-VL-10B can process multiple images in a single request for comparison or analysis:

```python Example theme={null}
import time
from openai import OpenAI

client = OpenAI(
    api_key="EMPTY",
    base_url="http://localhost:30000/v1",
    timeout=3600
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://www.civitatis.com/f/china/hong-kong/guia/taxi.jpg"
                }
            },
            {
                "type": "image_url",
                "image_url": {
                    "url": "https://cdn.cheapoguides.com/wp-content/uploads/sites/7/2025/05/GettyImages-509614603-1280x600.jpg"
                }
            },
            {
                "type": "text",
                "text": "Compare these two images and describe the differences in 100 words or less."
            }
        ]
    }
]

start = time.time()
response = client.chat.completions.create(
    model="stepfun-ai/Step3-VL-10B",
    messages=messages,
    max_tokens=2048,
    extra_body={"top_k": -1}
)
print(f"Response costs: {time.time() - start:.2f}s")
print(f"Generated text: {response.choices[0].message.content}")
```

**Example Output:**

```text Output theme={null}
Response costs: 3.24s
Generated text: First image: Single red Hong Kong taxi close - up, clear license plate (RX 5004), “4 SEATS” sticker, urban street with shops behind. Second image: Aerial view of many taxis (red, green) on a highway with a viaduct, some hoods open, dense arrangement. Differences: Scale (single vs many), perspective (close - up vs aerial), context (street shops vs highway), and taxi conditions (normal vs some open hoods).
```

#### 4.2.2 Reasoning Parser

Step3-VL-10B supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections:

```shell Command theme={null}
python -m sglang.launch_server \
  --model stepfun-ai/Step3-VL-10B \
  --reasoning-parser deepseek-r1 \
  --host 0.0.0.0 \
  --port 30000 \
  --trust-remote-code
```

**Streaming with Thinking Process:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="stepfun-ai/Step3-VL-10B",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True,
    extra_body={"top_k": -1}
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Example Output:**

```text Output theme={null}
=============== Thinking =================
Okay, let's see. The problem is asking for 15% of 240. Hmm, I need to remember how to calculate percentages. So, percentage means "per hundred," right? So, 15% is the same as 15 per 100, or 15/100. To find a percentage of a number, I think you convert the percentage to a decimal and then multiply it by the number. Let me check that.

First, 15% as a decimal. To convert a percentage to a decimal, you divide by 100. So 15 divided by 100 is 0.15. Yeah, that's right. So 15% is 0.15 in decimal form. Then, to find 15% of 24
0, I need to multiply 0.15 by 240. Let me do that calculation.

Let me write it out: 0.15 * 240. Let's compute that. Maybe break it down. 0.1 is 10%, and 0.05 is 5%, so 10% of 240 is 24, and 5% of 240 is 12. Then 10% + 5% is 15%, so 24 + 12 is 36. Oh,
 that's a good way to check. So 15% is 10% plus 5%, which adds up to 36. Let me verify with the decimal method. 0.15 * 240. Let's multiply 240 by 0.1 first: 24. Then 240 by 0.05: 12. Adding them gives 36. Yep, that matches. Alternatively, 240 * 15 = 3600, and then divide by 100 (since it's per hundred), so 3600 / 100 = 36. That's another way. So 15% of 240 is 36. Let me make sure I didn't make a mistake. Let's check with another method. 10% of 240 is 24, 20% would be 48, so 15% is halfway between 10% and 20%, which is (24 + 48)/2 = 36. Yep, that works too
. So all methods point to 36. I think that's the answer.

=============== Content =================

To solve the problem "What is 15% of 240?" step by step:

---

### **Step 1: Understand the concept of percentage**
A percentage represents a portion of a whole. Specifically, "percent" means "per hundred." So, 15% means **15 out of 100**, or **15/100**.

---

### **Step 2: Convert the percentage to a decimal**
To use percentages in calculations, convert them to decimals by dividing by 100:
$$
15\% = \frac{15}{100} = 0.15
$$

---

### **Step 3: Multiply the decimal by the given number**
Now, multiply 0.15 (the decimal form of 15%) by 240:
$$
0.15 \times 240 = 36
$$

---

### **Alternative Verification Methods**

#### **Method A: Break into parts**
- 10% of 240 = $ 0.10 \times 240 = 24 $
- 5% of 240 = $ 0.05 \times 240 = 12 $
- Add them: $ 24 + 12 = 36 $

#### **Method B: Use direct multiplication**
- $ 15\% \text{ of } 240 = \frac{15}{100} \times 240 = \frac{3600}{100} = 36 $

#### **Method C: Estimate using known percentages**
- 20% of 240 = $ 0.20 \times 240 = 48 $
- 10% of 240 = $ 0.10 \times 240 = 24 $
- 15% is halfway between 10% and 20%: $ \frac{24 + 48}{2} = 36 $

---

### **Final Answer**
$$
\boxed{36}
$$
```

**Note:** The reasoning parser captures the model's step-by-step thinking process, allowing you to see how the model arrives at its conclusions.

#### 4.2.3 Tool Calling

Step3-VL-10B supports tool calling capabilities. Enable the tool call parser:

```shell Command theme={null}
python -m sglang.launch_server \
  --model stepfun-ai/Step3-VL-10B \
  --reasoning-parser deepseek-r1 \
  --tool-call-parser hermes \
  --host 0.0.0.0 \
  --port 30000 \
  --trust-remote-code
```

**Python Example (with Thinking Process):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Define available tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city name"
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

# Make request with streaming to see thinking process
response = client.chat.completions.create(
    model="stepfun-ai/Step3-VL-10B",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=0.7,
    stream=True,
    extra_body={"top_k": -1}
)

# Process streaming response
thinking_started = False
has_thinking = False
tool_calls_accumulator = {}

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Accumulate tool calls
        if hasattr(delta, 'tool_calls') and delta.tool_calls:
            # Close thinking section if needed
            if has_thinking and thinking_started:
                print("\n=============== Content =================\n", flush=True)
                thinking_started = False

            for tool_call in delta.tool_calls:
                index = tool_call.index
                if index not in tool_calls_accumulator:
                    tool_calls_accumulator[index] = {
                        'name': None,
                        'arguments': ''
                    }

                if tool_call.function:
                    if tool_call.function.name:
                        tool_calls_accumulator[index]['name'] = tool_call.function.name
                    if tool_call.function.arguments:
                        tool_calls_accumulator[index]['arguments'] += tool_call.function.arguments

        # Print content
        if delta.content:
            print(delta.content, end="", flush=True)

# Print accumulated tool calls
for index, tool_call in sorted(tool_calls_accumulator.items()):
    print(f"Tool Call: {tool_call['name']}")
    print(f"   Arguments: {tool_call['arguments']}")

print()
```

**Example Output:**

```text Output theme={null}
=============== Thinking =================
The user is asking about the weather in Beijing. I have a function called "get_weather" that can provide weather information for a location. Let me check the parameters:

- location: required (string) - "Beijing"
- unit: optional (string, enum: ["celsius", "fahrenheit"]) - not specified by the user, so I won't include it

I should call the function with location="Beijing".



=============== Content =================

Tool Call: get_weather
   Arguments: {"location": "Beijing"}
```

**Handling Tool Call Results:**

```python Example theme={null}
# After getting the tool call, execute the function
def get_weather(location, unit="celsius"):
    # Your actual weather API call here
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# Send tool result back to the model
messages = [
    {"role": "user", "content": "What's the weather in Beijing?"},
    {
        "role": "assistant",
        "content": None,
        "tool_calls": [{
            "id": "call_123",
            "type": "function",
            "function": {
                "name": "get_weather",
                "arguments": '{"location": "Beijing", "unit": "celsius"}'
            }
        }]
    },
    {
        "role": "tool",
        "tool_call_id": "call_123",
        "content": get_weather("Beijing", "celsius")
    }
]

final_response = client.chat.completions.create(
    model="stepfun-ai/Step3-VL-10B",
    messages=messages,
    temperature=0.7,
    extra_body={"top_k": -1}
)

print(final_response.choices[0].message.content)
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA B200 GPU (1x)
* Model: stepfun-ai/Step3-VL-10B
* Tensor Parallelism: 1
* sglang version: 0.5.8+

We use SGLang's built-in benchmarking tool to conduct performance evaluation with random images.

#### 5.1.1 Latency-Sensitive Benchmark

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model stepfun-ai/Step3-VL-10B \
  --host 0.0.0.0 \
  --port 30000 \
  --trust-remote-code
```

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model stepfun-ai/Step3-VL-10B \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  30.85
Total input tokens:                      14120
Total input text tokens:                 720
Total input vision tokens:               13400
Total generated tokens:                  4220
Total generated tokens (retokenized):    4217
Request throughput (req/s):              0.32
Input token throughput (tok/s):          457.71
Output token throughput (tok/s):         136.79
Peak output token throughput (tok/s):    240.00
Peak concurrent requests:                2
Total token throughput (tok/s):          594.50
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   3083.40
Median E2E Latency (ms):                 2747.00
P90 E2E Latency (ms):                    4574.50
P99 E2E Latency (ms):                    5462.49
---------------Time to First Token----------------
Mean TTFT (ms):                          1327.69
Median TTFT (ms):                        1341.01
P99 TTFT (ms):                           1486.11
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          4.16
Median TPOT (ms):                        4.17
P99 TPOT (ms):                           4.18
---------------Inter-Token Latency----------------
Mean ITL (ms):                           4.17
Median ITL (ms):                         4.18
P95 ITL (ms):                            4.30
P99 ITL (ms):                            4.38
Max ITL (ms):                            8.24
==================================================
```

#### 5.1.2 Throughput-Sensitive Benchmark

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model stepfun-ai/Step3-VL-10B \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

* Result:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  976.52
Total input tokens:                      1416949
Total input text tokens:                 76949
Total input vision tokens:               1340000
Total generated tokens:                  510855
Total generated tokens (retokenized):    510526
Request throughput (req/s):              1.02
Input token throughput (tok/s):          1451.02
Output token throughput (tok/s):         523.14
Peak output token throughput (tok/s):    20429.00
Peak concurrent requests:                103
Total token throughput (tok/s):          1974.16
Concurrency:                             99.81
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   97463.22
Median E2E Latency (ms):                 91872.75
P90 E2E Latency (ms):                    118553.42
P99 E2E Latency (ms):                    198445.56
---------------Time to First Token----------------
Mean TTFT (ms):                          94379.07
Median TTFT (ms):                        87163.09
P99 TTFT (ms):                           194871.41
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          5.89
Median TPOT (ms):                        5.72
P99 TPOT (ms):                           23.58
---------------Inter-Token Latency----------------
Mean ITL (ms):                           6.05
Median ITL (ms):                         0.13
P95 ITL (ms):                            0.56
P99 ITL (ms):                            3.99
Max ITL (ms):                            97551.06
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 MMMU Benchmark

You can evaluate the model's accuracy using the MMMU dataset:

* Model Deployment Command:

```shell Command theme={null}
python -m sglang.launch_server \
  --model stepfun-ai/Step3-VL-10B \
  --host 0.0.0.0 \
  --port 30000 \
  --trust-remote-code
```

* Benchmark Command:

```shell Command theme={null}
python3 benchmark/mmmu/bench_sglang.py \
    --port 30000 \
    --concurrency 64
```

* Result:

```text Output theme={null}
Benchmark time: 934.6179109360091
answers saved to: ./answer_sglang.json
Evaluating...
answers saved to: ./answer_sglang.json
{'Accounting': {'acc': 0.667, 'num': 30},
 'Agriculture': {'acc': 0.367, 'num': 30},
 'Architecture_and_Engineering': {'acc': 0.4, 'num': 30},
 'Art': {'acc': 0.467, 'num': 30},
 'Art_Theory': {'acc': 0.5, 'num': 30},
 'Basic_Medical_Science': {'acc': 0.367, 'num': 30},
 'Biology': {'acc': 0.3, 'num': 30},
 'Chemistry': {'acc': 0.467, 'num': 30},
 'Clinical_Medicine': {'acc': 0.567, 'num': 30},
 'Computer_Science': {'acc': 0.467, 'num': 30},
 'Design': {'acc': 0.567, 'num': 30},
 'Diagnostics_and_Laboratory_Medicine': {'acc': 0.3, 'num': 30},
 'Economics': {'acc': 0.6, 'num': 30},
 'Electronics': {'acc': 0.567, 'num': 30},
 'Energy_and_Power': {'acc': 0.633, 'num': 30},
 'Finance': {'acc': 0.733, 'num': 30},
 'Geography': {'acc': 0.333, 'num': 30},
 'History': {'acc': 0.533, 'num': 30},
 'Literature': {'acc': 0.533, 'num': 30},
 'Manage': {'acc': 0.6, 'num': 30},
 'Marketing': {'acc': 0.767, 'num': 30},
 'Materials': {'acc': 0.6, 'num': 30},
 'Math': {'acc': 0.7, 'num': 30},
 'Mechanical_Engineering': {'acc': 0.333, 'num': 30},
 'Music': {'acc': 0.4, 'num': 30},
 'Overall': {'acc': 0.523, 'num': 900},
 'Overall-Art and Design': {'acc': 0.483, 'num': 120},
 'Overall-Business': {'acc': 0.673, 'num': 150},
 'Overall-Health and Medicine': {'acc': 0.513, 'num': 150},
 'Overall-Humanities and Social Science': {'acc': 0.492, 'num': 120},
 'Overall-Science': {'acc': 0.5, 'num': 150},
 'Overall-Tech and Engineering': {'acc': 0.481, 'num': 210},
 'Pharmacy': {'acc': 0.6, 'num': 30},
 'Physics': {'acc': 0.7, 'num': 30},
 'Psychology': {'acc': 0.467, 'num': 30},
 'Public_Health': {'acc': 0.733, 'num': 30},
 'Sociology': {'acc': 0.433, 'num': 30}}
eval out saved to ./val_sglang.json
Overall accuracy: 0.523
```


# Step-3.5-Flash
Source: https://docs.sglang.io/cookbook/autoregressive/StepFun/Step3.5



## 1. Model Introduction

[Step-3.5-Flash](https://huggingface.co/stepfun-ai/Step-3.5-Flash) is StepFun's production-grade reasoning engine built to decouple elite intelligence from heavy compute, and cuts attention cost for low-latency, cost-effective long-context inference—purpose-built for autonomous agents in real-world workflows. The model is available in multiple quantization formats optimized for different hardware platforms.

This generation delivers comprehensive upgrades across the board:

* **Hybrid Attention Architecture**:  Interleaves Sliding Window Attention (SWA) and Global Attention (GA) with a 3:1 ratio and an aggressive 128-token window. This hybrid approach ensures consistent performance across massive datasets or long codebases while significantly reducing the computational overhead typical of standard long-context models.
* **Sparse Mixture-of-Experts**: Only 11B active parameters out of 196B parameters.
* **Multi-Layer Multi-Token Prediction (MTP)**: Equipped with a  3-way Multi-Token Prediction (MTP-3). This allows for complex, multi-step reasoning chains with immediate responsiveness.

## 2.SGLang Installation

Step-3.5-Flash is currently available in SGLang via Docker image install.

### Docker (NVIDIA)

```bash Command theme={null}
# Pull the docker image
docker pull lmsysorg/sglang:latest

# Launch the container
docker run -it --gpus all \
  --shm-size=32g \
  --ipc=host \
  --network=host \
  lmsysorg/sglang:latest bash
```

### Docker (AMD ROCm)

```bash Command theme={null}
# For MI300X/MI325X
docker pull lmsysorg/sglang:v0.5.9-rocm700-mi30x

# For MI350X/MI355X
docker pull lmsysorg/sglang:v0.5.9-rocm700-mi35x

docker run -it \
  --device=/dev/kfd --device=/dev/dri \
  --shm-size=32g \
  --ipc=host \
  --network=host \
  --group-add video --cap-add=SYS_PTRACE \
  --security-opt seccomp=unconfined \
  lmsysorg/sglang:v0.5.9-rocm700-mi30x bash  # or mi35x for MI350X/MI355X
```

## 3.Model Deployment

This section provides deployment configurations optimized for different hardware platforms and use cases.

### 3.1 Basic Configuration

The Step-3.5-Flash series comes in only one sizes. Recommended starting configurations vary depending on hardware.

**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, model size, quantization method, and thinking capabilities.

Run this Command:


### 3.2 Configuration Tips

* **Memory**: Requires GPUs with high VRAM capacity. Supported platforms: H200 (4×, TP=4), MI300X/MI325X/MI350X/MI355X (4×, TP=4 EP=4).
* **AMD Docker Image**: Use `lmsysorg/sglang:v0.5.9-rocm700-mi30x` for MI300X/MI325X and `lmsysorg/sglang:v0.5.9-rocm700-mi35x` for MI350X/MI355X.
* **AMD Expert Parallelism Required**: On AMD GPUs, always use `--ep 4` with `--tp 4`. Both BF16 and FP8 models require expert parallelism. Without EP, the MoE intermediate dimension is split across GPUs (N=320), which triggers an AITER CK GEMM incompatibility. With EP=4, each GPU handles 72 full experts (N=1280), which works correctly with cuda graph enabled.
* **AITER JIT Compilation**: First inference on AMD may take 30-40 seconds for AITER kernel JIT compilation. Subsequent requests use cached kernels.

## 4.Model Invocation

### 4.1 Basic Usage

For basic API usage and request examples, please refer to:

* [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request)

### 4.2 Advanced Usage

#### 4.2.1 Reasoning Parser

Step-3.5-Flash only supports reasoning mode. Enable the reasoning parser during deployment to separate the thinking and content sections:

```shell Command theme={null}
sglang serve \
  --model-path stepfun-ai/Step-3.5-Flash \
  --tp 4 \
  --ep 4 \
  --reasoning-parser step3p5
```

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# Enable streaming to see the thinking process in real-time
response = client.chat.completions.create(
    model="stepfun-ai/Step-3.5-Flash",
    messages=[
        {"role": "user", "content": "Solve this problem step by step: What is 15% of 240?"}
    ],
    temperature=0.7,
    max_tokens=2048,
    stream=True
)

# Process the stream
has_thinking = False
has_answer = False
thinking_started = False

for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        delta = chunk.choices[0].delta

        # Print thinking process
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
            if not thinking_started:
                print("=============== Thinking =================", flush=True)
                thinking_started = True
            has_thinking = True
            print(delta.reasoning_content, end="", flush=True)

        # Print answer content
        if delta.content:
            # Close thinking section and add content header
            if has_thinking and not has_answer:
                print("\n=============== Content =================", flush=True)
                has_answer = True
            print(delta.content, end="", flush=True)

print()
```

**Output Example:**

```text Output theme={null}
=============== Thinking =================
We are asked: "What is 15% of 240?" We need to solve step by step.

Step 1: Understand that "15% of 240" means we need to calculate 15 percent of 240. In mathematical terms, it is (15/100) * 240.

Step 2: Simplify the calculation. We can compute 15% of 240 by first finding 10% of 240 and then 5% of 240, and adding them. Alternatively, we can multiply directly.

Method 1:
10% of 240 = 240 * 0.10 = 24.
5% is half of 10%, so 5% of 240 = 24 / 2 = 12.
Then 15% = 10% + 5% = 24 + 12 = 36.

Method 2: Direct multiplication: 15% = 15/100 = 0.15, so 0.15 * 240 = 36.

We can also compute fractionally: (15/100)*240 = (15*240)/100. 15*240 = 3600, divided by 100 gives 36.

Thus, the answer is 36.

We'll present the solution step by step.

=============== Content =================

To find 15% of 240, follow these steps:

1. **Convert the percentage to a decimal**:
   \( 15\% = \frac{15}{100} = 0.15 \)

2. **Multiply by the number**:
   \( 0.15 \times 240 = 36 \)

Alternatively, break it down:
- \( 10\% \text{ of } 240 = 240 \times 0.10 = 24 \)
- \( 5\% \text{ of } 240 = \frac{24}{2} = 12 \) (since 5% is half of 10%)
- \( 15\% = 10\% + 5\% = 24 + 12 = 36 \)

**Answer:** 36
```

#### 4.2.2 Tool Calling

Step-3.5 supports tool calling capabilities. Enable the tool call parser:

**Python Example:**

Start sglang server:

```shell Command theme={null}
sglang serve \
  --model-path stepfun-ai/Step-3.5-Flash \
  --tp 4 \
  --ep 4 \
  --reasoning-parser step3p5 \
  --tool-call-parser step3p5
```

```python Example theme={null}
from openai import OpenAI
import json

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

# 1. define tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "The city name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit"}
                },
                "required": ["location"]
            }
        }
    }
]

# 2. tool run
def get_weather(location, unit="celsius"):
    return f"The weather in {location} is 22°{unit[0].upper()} and sunny."

# 3. send first request
print("--- Sending first request ---")
response = client.chat.completions.create(
    model="stepfun-ai/Step-3.5-Flash",
    messages=[
        {"role": "user", "content": "What's the weather in Beijing?"}
    ],
    tools=tools,
    temperature=1.0,
    stream=False
)

message = response.choices[0].message

# 4. Handle Reasoning Content
reasoning = getattr(message, 'reasoning_content', None)
if reasoning:
    print("=============== Thinking =================")
    print(reasoning)
    print("==========================================")

# 5. Handle Tool Calls
if message.tool_calls:
    print("\n🔧 Tool Calls detected:")
    history_messages = [
        {"role": "user", "content": "What's the weather in Beijing?"},
        message
    ]

    for tool_call in message.tool_calls:
        print(f"   Tool: {tool_call.function.name}")
        print(f"   Args: {tool_call.function.arguments}")

        args = json.loads(tool_call.function.arguments)
        tool_result = get_weather(args.get("location"), args.get("unit", "celsius"))

        history_messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": tool_result
        })

    print("\n--- Sending tool results ---")
    final_response = client.chat.completions.create(
        model="stepfun-ai/Step-3.5-Flash",
        messages=history_messages,
        temperature=1.0,
        stream=False
    )

    print("=============== Final Content =================")
    print(final_response.choices[0].message.content)

else:
    if message.content:
        print("=============== Content =================")
        print(message.content)
```

**Output Example:**

```text Output theme={null}
--- Sending first request ---
=============== Thinking =================
The user is asking for the weather in Beijing. I should use the get_weather function with location="Beijing". The unit parameter is optional and the user didn't specify a preference, so I'll leave it out (the default should be fine).

==========================================

🔧 Tool Calls detected:
   Tool: get_weather
   Args: {"location": "Beijing"}

--- Sending tool results ---
=============== Final Content =================
The weather in Beijing is 22°C and sunny.
```

**Note:**

* The reasoning parser shows how the model decides to use a tool
* Tool calls are clearly marked with the function name and arguments
* You can then execute the function and send the result back to continue the conversation

## 5. Benchmark

### 5.1 Speed Benchmark

**Test Environment:**

* Hardware: NVIDIA H200 GPU (4x)
* Model: Step-3.5-Flash
* Tensor Parallelism: 4
* Expert Parallelism: 4
* sglang version: 0.5.8

We use SGLang's built-in benchmarking tool to conduct performance evaluation on the [ShareGPT\_Vicuna\_unfiltered](https://huggingface.co/datasets/anon8231489123/ShareGPT_Vicuna_unfiltered) dataset. This dataset contains real conversation data and can better reflect performance in actual use scenarios.

#### 5.1.1 Standard Scenario Benchmark

* Model Deployment Command:

```shell Command theme={null}
sglang serve \
  --model-path stepfun-ai/Step-3.5-Flash \
  --tp 4 \
  --ep 4
```

##### 5.1.1.1 Low Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model stepfun-ai/Step-3.5-Flash \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 10 \
  --max-concurrency 1
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  35.30
Total input tokens:                      6091
Total input text tokens:                 6091
Total generated tokens:                  4220
Total generated tokens (retokenized):    4212
Request throughput (req/s):              0.28
Input token throughput (tok/s):          172.57
Output token throughput (tok/s):         119.56
Peak output token throughput (tok/s):    124.00
Peak concurrent requests:                2
Total token throughput (tok/s):          292.14
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   3527.94
Median E2E Latency (ms):                 2884.72
P90 E2E Latency (ms):                    6350.38
P99 E2E Latency (ms):                    7858.53
---------------Time to First Token----------------
Mean TTFT (ms):                          107.53
Median TTFT (ms):                        80.93
P99 TTFT (ms):                           269.52
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          8.12
Median TPOT (ms):                        8.13
P99 TPOT (ms):                           8.14
---------------Inter-Token Latency----------------
Mean ITL (ms):                           8.12
Median ITL (ms):                         8.11
P95 ITL (ms):                            8.61
P99 ITL (ms):                            8.91
Max ITL (ms):                            20.77
==================================================
```

##### 5.1.1.2 Medium Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model stepfun-ai/Step-3.5-Flash \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 80 \
  --max-concurrency 16
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 16
Successful requests:                     80
Benchmark duration (s):                  54.06
Total input tokens:                      39588
Total input text tokens:                 39588
Total generated tokens:                  40805
Total generated tokens (retokenized):    40479
Request throughput (req/s):              1.48
Input token throughput (tok/s):          732.33
Output token throughput (tok/s):         754.84
Peak output token throughput (tok/s):    928.00
Peak concurrent requests:                21
Total token throughput (tok/s):          1487.17
Concurrency:                             14.06
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   9501.23
Median E2E Latency (ms):                 10010.71
P90 E2E Latency (ms):                    15655.09
P99 E2E Latency (ms):                    18803.63
---------------Time to First Token----------------
Mean TTFT (ms):                          198.34
Median TTFT (ms):                        89.50
P99 TTFT (ms):                           984.66
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          18.97
Median TPOT (ms):                        18.80
P99 TPOT (ms):                           35.67
---------------Inter-Token Latency----------------
Mean ITL (ms):                           18.27
Median ITL (ms):                         17.48
P95 ITL (ms):                            18.44
P99 ITL (ms):                            62.47
Max ITL (ms):                            460.85
==================================================
```

##### 5.1.1.3 High Concurrency

* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model stepfun-ai/Step-3.5-Flash \
  --dataset-name random \
  --random-input-len 1000 \
  --random-output-len 1000 \
  --num-prompts 500 \
  --max-concurrency 100
```

* Test Results:

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     500
Benchmark duration (s):                  125.88
Total input tokens:                      249331
Total input text tokens:                 249331
Total generated tokens:                  252662
Total generated tokens (retokenized):    251323
Request throughput (req/s):              3.97
Input token throughput (tok/s):          1980.77
Output token throughput (tok/s):         2007.23
Peak output token throughput (tok/s):    2500.00
Peak concurrent requests:                109
Total token throughput (tok/s):          3987.99
Concurrency:                             92.25
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   23223.31
Median E2E Latency (ms):                 22631.90
P90 E2E Latency (ms):                    42269.38
P99 E2E Latency (ms):                    47637.53
---------------Time to First Token----------------
Mean TTFT (ms):                          372.13
Median TTFT (ms):                        127.26
P99 TTFT (ms):                           1880.42
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          46.06
Median TPOT (ms):                        47.61
P99 TPOT (ms):                           51.34
---------------Inter-Token Latency----------------
Mean ITL (ms):                           45.31
Median ITL (ms):                         39.86
P95 ITL (ms):                            72.49
P99 ITL (ms):                            117.05
Max ITL (ms):                            1359.81
==================================================
```

### 5.2 Accuracy Benchmark

#### 5.2.1 GSM8K Benchmark

* **Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --num-examples 200
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

* **Results**:

  * Step-3.5-Flash
    ```
    Accuracy: 0.885
    Invalid: 0.005
    Latency: 9.986 s
    Output throughput: 1972.911 token/s
    ```


# Hy3 preview
Source: https://docs.sglang.io/cookbook/autoregressive/Tencent/Hunyuan3-Preview



## 1. Model Introduction

Hy3 preview is Tencent's preview of its third-generation flagship MoE language model, featuring hybrid thinking, native tool calling, long-context reasoning, and Multi-Token Prediction (MTP) for low-latency serving.

**Key Features:**

* **MoE Architecture**: 192 routed experts + 1 shared expert, 8 experts activated per token. \~276B total parameters with \~20B active, delivering dense-model quality at MoE inference cost.
* **Hybrid Thinking**: Reasoning modes (`high`, `medium`, `low`, `none`) controllable via OpenAI-standard `reasoning_effort`, allowing the same weights to trade off latency and depth of reasoning.
* **Native Tool Calling**: Trained on structured `` / `` / `` grammar. Pairs with SGLang's `hunyuan` tool-call parser for streaming OpenAI-compatible function-calling output.
* **Long Context**: 256K token context window (262,144 positions) for repository-scale code and document reasoning.
* **Multi-Token Prediction (MTP)**: Ships with a built-in MTP draft module enabling speculative decoding out of the box.

**Available Models:**

* [tencent/Hy3-preview](https://huggingface.co/tencent/Hy3-preview) — BF16 instruct
* [tencent/Hy3-preview-Base](https://huggingface.co/tencent/Hy3-preview-Base) — BF16 base

**Recommended Generation Parameters:**

Parameter Value
`temperature` 0.7
`top_p` 0.9
`reasoning_effort` `high` / `medium` / `low` (thinking) or `none` (instant)
**License:** TODO — verify on HuggingFace model card. ## 2. SGLang Installation SGLang offers multiple installation methods. You can choose the most suitable installation method based on your hardware platform and requirements. Please refer to the [official SGLang installation guide](../../../docs/get-started/install) for installation instructions. **Docker Images by Hardware Platform:**
Hardware Platform Docker Image
NVIDIA H200 / B200 / B300 / GB300 `lmsysorg/sglang:latest`
`lmsysorg/sglang:latest` bundles the HYV3 model code, the `hunyuan` tool-call / reasoning parsers, and the MTP draft-module runtime. For SGLang CPU installation, please refer to the [CPU version installation guide](../../../docs/hardware-platforms/cpu_server#installation). ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration **Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform, quantization, and feature capabilities. Run this Command:

### 3.2 Configuration Tips

**Key Parameters:**

Parameter Description Recommended Value
`--tool-call-parser` Tool call parser for function-calling support `hunyuan`
`--reasoning-parser` Reasoning parser for hybrid thinking modes `hunyuan`
`--trust-remote-code` Required for Hunyuan model loading Always enabled
`--mem-fraction-static` Static memory fraction (KV + activations) `0.9`
`--tp` Tensor parallelism size `2` / `4` / `8` depending on hardware
`--attention-backend` Attention backend (Blackwell only) `trtllm_mha`
`--speculative-algorithm` Speculative decoding via the bundled MTP draft `EAGLE` + `--speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`
**Hardware Requirements: NVIDIA BF16 (`Hy3-preview`, \~552GB weights)** * **H200 (141GB) / B200 (180GB)**: TP=8 (minimum for BF16 to fit single-node). * **B300 (275GB) / GB300**: TP=4. * **A100 / H100 (80GB)**: not supported single-node — BF16 requires multi-node TP=16+ on 80GB-class GPUs. **Blackwell (B200 / B300 / GB300):** Auto-selected attention backend can mis-route for HYV3 on Blackwell. Always pass `--attention-backend trtllm_mha` explicitly on Blackwell hardware (the config generator above enforces this). **Multi-Token Prediction (MTP):** The `Hy3-preview` release bundles an MTP draft module. SGLang runs it via its EAGLE speculative-decoding path — the draft module auto-loads from the same `--model-path`. Enable with the standard MTP flags: ```bash Command theme={null} sglang serve \ --model-path tencent/Hy3-preview \ --tp 8 \ --speculative-algorithm EAGLE \ --speculative-num-steps 3 \ --speculative-eagle-topk 1 \ --speculative-num-draft-tokens 4 \ --reasoning-parser hunyuan \ --tool-call-parser hunyuan \ --trust-remote-code \ --mem-fraction-static 0.85 ``` Toggle the "Speculative Decoding (MTP)" option in the generator above to add these flags automatically. Tune `num-steps` / `num-draft-tokens` based on acceptance rate in your workload. **Xeon CPU service configuration:** Please refer to the `Notes` part in the serving engine launching section in [the SGLang CPU server document](../../../docs/hardware-platforms/cpu_server#launch-of-the-serving-engine) to better understand how to configure the arguments, especially for TP (tensor parallel) and NUMA binding settings. ## 4. Model Invocation ### 4.1 Basic Usage For basic API usage and request examples, please refer to: * [SGLang Basic Usage Guide](../../../docs/basic_usage/send_request) **Deployment Command (H200 × 8, BF16 default):** ```bash Command theme={null} sglang serve \ --model-path tencent/Hy3-preview \ --tp 8 \ --reasoning-parser hunyuan \ --tool-call-parser hunyuan \ --trust-remote-code \ --mem-fraction-static 0.9 ``` **Testing Deployment:** After startup, you can test the SGLang OpenAI-compatible API with the following command: ```bash Command theme={null} curl http://localhost:30000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "model": "tencent/Hy3-preview", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ] }' ``` **Simple Completion Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI( base_url="http://localhost:30000/v1", api_key="EMPTY" ) response = client.chat.completions.create( model="tencent/Hy3-preview", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Who won the world series in 2020?"} ], max_tokens=1024 ) print("Reasoning:", response.choices[0].message.reasoning_content) print("Content: ", response.choices[0].message.content) ``` **Output Example:** ```text Output theme={null} Reasoning: None Content: The Los Angeles Dodgers won the 2020 World Series. They defeated the Tampa Bay Rays in six games (4-2). This was the Dodgers' first World Series championship since 1988. The series was notable for being played in a neutral-site bubble at Globe Life Field in Arlington, Texas, due to the COVID-19 pandemic. ``` When `reasoning_effort` is not set, the server defaults to instant mode (no thinking, `reasoning_content=None`). To opt into thinking, pass `reasoning_effort="high" / "medium" / "low"` on the request — see the Hybrid Thinking section below. ### 4.2 Advanced Usage #### 4.2.1 Reasoning Parser (Hybrid Thinking) Hy3-preview is a hybrid-thinking model. Control the thinking budget via the OpenAI-standard `reasoning_effort`: * `high` / `medium` / `low` — increasing amounts of chain-of-thought in `reasoning_content` * `none` — skip thinking entirely (instant responses, content-only) Enable the reasoning parser during deployment so that the thinking section (`...`) is separated into `reasoning_content`: ```bash Command theme={null} sglang serve \ --model-path tencent/Hy3-preview \ --tp 8 \ --reasoning-parser hunyuan \ --trust-remote-code \ --mem-fraction-static 0.9 ``` **Thinking Mode — High Effort:** ```python Example theme={null} from openai import OpenAI client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") response = client.chat.completions.create( model="tencent/Hy3-preview", messages=[{"role": "user", "content": "Solve step by step: What is 15% of 240?"}], reasoning_effort="high", max_tokens=2048, ) msg = response.choices[0].message print("=============== Thinking =================") print(msg.reasoning_content) print("=============== Content =================") print(msg.content) ``` **Output Example:** ```text Output theme={null} =============== Thinking ================= We need to solve: "What is 15% of 240?" Step by step. So we need to compute 15% of 240. The process: 15% means 15 per hundred, i.e., 15/100 = 0.15. Multiply 0.15 by 240. Or we can do: 10% of 240 = 24, 5% is half of 10% = 12, so sum = 36. Or do multiplication: 15/100 * 240 = (15*240)/100 = (3600)/100 = 36. So answer is 36. We need to produce step-by-step explanation. The instruction: "Solve step by step: What is 15% of 240?" So we should provide a clear solution with steps. The final answer: 36. Also maybe include units? No units. We'll output the solution in a clear manner. =============== Content ================= To find 15% of 240, follow these steps: 1. **Understand that percent means "per hundred."** So, 15% = 15/100 or 0.15. 2. **Multiply the number (240) by the percentage in decimal form.** 0.15 × 240. Alternatively, you can use fractions: (15/100) × 240. 3. **Perform the multiplication.** 0.15 × 240 = 36. Or: (15 × 240) / 100 = 3600 / 100 = 36. 4. **Check using an alternative method:** - 10% of 240 = 24. - 5% of 240 = half of 10% = 12. - 15% = 10% + 5% = 24 + 12 = 36. Thus, **15% of 240 is 36**. ``` **Instant Mode — No Thinking:** ```python Example theme={null} response = client.chat.completions.create( model="tencent/Hy3-preview", messages=[{"role": "user", "content": "Give me a one-line summary of relativity."}], reasoning_effort="none", max_tokens=256, ) print("Content:", response.choices[0].message.content) ``` **Output Example:** ```text Output theme={null} Content: Relativity is Einstein's theory that space, time, mass, and gravity are interconnected and relative, not fixed, fundamentally changing our understanding of the universe. ``` #### 4.2.2 Tool Calling Hy3-preview supports streaming OpenAI-compatible tool calls. Enable both parsers together — the reasoning parser strips thinking tokens before the tool-call parser runs: ```bash Command theme={null} sglang serve \ --model-path tencent/Hy3-preview \ --tp 8 \ --reasoning-parser hunyuan \ --tool-call-parser hunyuan \ --trust-remote-code \ --mem-fraction-static 0.9 ``` **Non-Streaming Example:** ```python Example theme={null} from openai import OpenAI client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a city.", "parameters": { "type": "object", "properties": { "city": {"type": "string"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, }, "required": ["city"], }, }, } ] response = client.chat.completions.create( model="tencent/Hy3-preview", messages=[{"role": "user", "content": "What's the weather in Beijing? Use fahrenheit."}], tools=tools, ) msg = response.choices[0].message print("Reasoning:", msg.reasoning_content) print("Content: ", msg.content) for tc in msg.tool_calls or []: print(f"Tool Call: {tc.function.name}") print(f" Arguments: {tc.function.arguments}") ``` **Output Example:** ```text Output theme={null} Reasoning: None Content: I'll get the current weather for Beijing in Fahrenheit for you. Tool Call: get_weather Arguments: {"city": "Beijing", "unit": "fahrenheit"} ``` **Streaming Example (incremental argument deltas):** Hy3-preview's `hunyuan` tool-call parser emits tool names first, then argument JSON in incremental fragments — matching the OpenAI streaming contract: ```python Example theme={null} from openai import OpenAI client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") stream = client.chat.completions.create( model="tencent/Hy3-preview", messages=[{"role": "user", "content": "What's the weather in Beijing? Use fahrenheit."}], tools=tools, stream=True, ) tool_buffer = {} for chunk in stream: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="", flush=True) for tc in delta.tool_calls or []: buf = tool_buffer.setdefault(tc.index, {"name": "", "args": ""}) if tc.function and tc.function.name: buf["name"] += tc.function.name if tc.function and tc.function.arguments: buf["args"] += tc.function.arguments for idx, buf in tool_buffer.items(): print(f"\nTool[{idx}] {buf['name']}({buf['args']})") ``` **Output Example:** ```text Output theme={null} I'll check the current weather in Beijing for you using Fahrenheit. Tool[0] get_weather({"city": "Beijing", "unit": "fahrenheit"}) ``` ## 5. Benchmark ### 5.1 Accuracy Benchmark **Test Environment:** * Hardware: 8× NVIDIA H200 (141GB) * Docker Image: `lmsysorg/sglang:hy3-preview` * Model: `tencent/Hy3-preview` (BF16) * Tensor Parallelism: 8 * SGLang version: latest `main` #### 5.1.1 GSM8K * Benchmark Method: GSM8K on 200 questions using sgl-eval * Benchmark Command: ```bash Command theme={null} sgl-eval run gsm8k \ --base-url http://127.0.0.1:30000/v1 \ --num-examples 200 \ --num-threads 64 ``` The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result. * Test Results: ```text Output theme={null} TODO — replace with real GSM8K accuracy after benchmark run on Hy3-preview (BF16). ``` #### 5.1.2 MMLU * Benchmark Method: zero-shot Chat API evaluation via sgl-eval, all 57 subjects * Benchmark Command: ```bash Command theme={null} sgl-eval run mmlu \ --base-url http://127.0.0.1:30000/v1 \ --num-threads 64 --max-tokens 2048 ``` * Test Results: ```text Output theme={null} TODO — replace with real MMLU accuracy after benchmark run on Hy3-preview (BF16). ``` #### 5.1.3 Tool-Call Accuracy (MiniMax-Provider-Verifier) * Benchmark Tool: [MiniMax-Provider-Verifier](https://github.com/MiniMax-AI/MiniMax-Provider-Verifier) * Metric: function-call schema validity, argument match, and end-to-end response correctness * Test Results: ```text Output theme={null} TODO — replace with real tool-call accuracy after benchmark run on Hy3-preview (BF16). ``` ### 5.2 Speed Benchmark #### 5.2.1 Low Concurrency * Benchmark Command: ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model tencent/Hy3-preview \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 10 \ --max-concurrency 1 ``` * Test Results: ```text Output theme={null} TODO — replace with real low-concurrency output on Hy3-preview (BF16). ``` #### 5.2.2 High Concurrency * Benchmark Command: ```bash Command theme={null} python3 -m sglang.bench_serving \ --backend sglang \ --model tencent/Hy3-preview \ --dataset-name random \ --random-input-len 1000 \ --random-output-len 1000 \ --num-prompts 500 \ --max-concurrency 100 ``` * Test Results: ```text Output theme={null} TODO — replace with real high-concurrency output on Hy3-preview (BF16). ``` # Hy3 Source: https://docs.sglang.io/cookbook/autoregressive/Tencent/Hy3 Deploy Tencent Hy3 with SGLang — verified launch commands and tuning for the BF16 Mixture-of-Experts model with hybrid thinking, native tool calling, 256K context, and MTP speculative decoding. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). The two paths below match the **Python / Docker** toggle in the command panel. > > **Python (pip / uv)** > > ```bash theme={null} > pip install -U uv > uv venv --python 3.12 && source .venv/bin/activate > > # Install from source (main carries the suffix-aware `hunyuan` parser + the > # HYV3 model code). Once a tagged release picks it up, > # `uv pip install --prerelease=allow sglang` is enough. > git clone https://github.com/sgl-project/sglang.git > cd sglang > uv pip install --prerelease=allow -e python > ``` > > Run the **Python** output of the command panel below in that environment. > > **Docker** > > ```bash Command theme={null} > # The image bundles the HYV3 model code and the suffix-aware `hunyuan` parser. > docker pull lmsysorg/sglang:dev > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker), substituting the inner `sglang serve ...` with what the command generator below produces. > > > [!NOTE] > > > > The `dev` image bundles the HYV3 model code, the suffix-aware `hunyuan` reasoning/tool-call parsers, and the MTP draft-module runtime. The same parsers serve both the preview (suffix-less) and the shipping (suffixed) Hy3 tokenizer — no per-model hard-coding. Pick your hardware + recipe to generate the launch command. * **Low-Latency** — fastest reply for a single user. Pick for chat. * **Balanced** — good speed with several users at once. Use for typical multi-user serving. **Panel controls** (top of the command box):
  • **Python / Docker** — bare `sglang serve …` for an existing SGLang env, or a `docker run … sglang serve …` wrap against the per-hardware image from the [Install SGLang](#install) panel above.
  • **⧉ Copy** — copies the current command (with whichever framing is active) to your clipboard.
  • **\$ cURL** — a sample request against `localhost:30000` to confirm the server is up.
  • **⚙ Env** — edits the placeholders (`HOST_IP`, `PORT`, `HF_TOKEN`, `NODE_RANK`, `NODE0_IP`) the command and cURL share. Persists in localStorage across cookbooks.
  • **Verified / Not Verified** badge — green when the `(hw, variant, quant, strategy, nodes)` combo has been run end-to-end on real hardware; yellow when auto-derived from a neighbor and not yet re-checked.
## Playground The Playground lets you turn on additional knobs on top of whichever Deploy cell is currently selected. The base is read live from your Deploy selection — only your overrides change. The knobs come in two flavors: * **Built-in SGLang features** — parallelism overrides (TP / DP-Attention), MoE backend + EP, reasoning / tool-call parsers, speculative-decoding presets, prefill/decode disaggregation, and HiCache tiers. * **Hy3 specific** — `--tool-call-parser auto` / `--reasoning-parser auto` (auto-detect Hy3's suffix-aware `hunyuan` parsers from the chat template; resolve the real special tokens from the tokenizer vocab at runtime). Lines highlighted **green** are added by your overrides; lines with **red strikethrough** were in the verified base but stripped by an override. When no override differs from the base cell, the playground inherits the base's **Verified** badge; any actual change flips it to **Not Verified** until the new configuration is run end-to-end and submitted back. **Panel controls** reuse **Python / Docker** · **⧉ Copy** · **\$ cURL** · **⚙ Env** from the Deploy panel, plus one extra:
  • **Submit ↗** — opens a pre-filled GitHub issue so you can land your override combo as a new verified cookbook cell. Shown only while the badge says **Not Verified**; click it once you've actually run the command on your hardware and confirmed it works.
## 1. Model Introduction **Hy3** is Tencent's third-generation flagship Mixture-of-Experts language model, featuring hybrid thinking, native tool calling, long-context reasoning, and Multi-Token Prediction (MTP) for low-latency serving. **Key Features:** * **MoE Architecture**: 192 routed experts + 1 shared expert, top-8 activated per token. 295B total parameters with 21B active (+3.8B MTP layer), delivering dense-model quality at MoE inference cost. * **Hybrid Thinking**: Reasoning modes (`high`, `low`, `no_think`) controllable via OpenAI-standard `reasoning_effort`, allowing the same weights to trade off latency and depth of reasoning. * **Native Tool Calling**: Trained on a structured grammar. Pairs with SGLang's `hunyuan` tool-call parser for streaming OpenAI-compatible function-calling output. * **Long Context**: 256K token context window (262,144 positions) for repository-scale code and document reasoning. * **Multi-Token Prediction (MTP)**: Ships with a built-in MTP draft module enabling speculative decoding out of the box. **Available Model:** * [tencent/Hy3](https://huggingface.co/tencent/Hy3) — BF16 instruct * [tencent/Hy3-FP8](https://huggingface.co/tencent/Hy3-FP8) — FP8 **Recommended Generation Parameters:**
Parameter Value
`temperature` 0.9
`top_p` 1.0
`reasoning_effort` `high` / `low` (thinking) or `no_think` (instant)
**Special tokens.** The shipping Hy3 tokenizer appends a shared suffix to every special token (e.g. `` instead of the bare ``). SGLang's `hunyuan` parsers resolve the real token strings from the tokenizer vocab at runtime ([PR #29920](https://github.com/sgl-project/sglang/pull/29920)), so the same recipe serves both the preview (suffix-less) and the shipping (suffixed) tokenizer — no per-model hard-coding. This is why `--reasoning-parser hunyuan` / `--tool-call-parser hunyuan` work out of the box on the shipping model. ## 2. Configuration Tips **Hardware requirements (BF16, \~590GB weights):**
GPU VRAM TP Notes
H200 141GB 8 minimum single-node for BF16
B200 192GB 4 BF16 590GB → 148GB/GPU
B300 / GB300 288GB 4 BF16 590GB → 148GB/GPU; ample KV headroom
GB200 192GB 4 single-node 4×192GB = 768GB fits BF16 590GB
**Blackwell attention backend.** On SM100/SM103 (B200 / B300 / GB200 / GB300), SGLang auto-selects the `trtllm_mha` attention backend for HYV3's MHA architecture (no flag needed) — the launch commands above omit it for that reason. Override only if you have a specific kernel reason. **MTP (Multi-Token Prediction, EAGLE).** * `low-latency`: steps=3, draft-tokens=4 → largest win at bs=1. * `balanced`: MTP disabled — keep the prefill batch moderate so chunked-prefill stays efficient. **`reasoning_effort` vs `thinking`.** The Hy3 chat template is driven by `reasoning_effort` (`high` / `low` / `no_think`), NOT by the `thinking` flag that some other families use. The default is `no_think` (instant). To opt into thinking, pass `reasoning_effort="high"` on the request (the OpenAI-standard field; sglang forwards it to the template). `reasoning_effort: max` is rejected by sglang — use `high`. For eval, sgl-eval's `--thinking` flag translates to `reasoning_effort="high"` for Hy3, so the benchmark commands below use it as-is. ## 3. Advanced Usage ### 3.1 Reasoning (Hybrid Thinking) Hy3 is a hybrid-thinking model. Control the thinking budget via `reasoning_effort`: * `high` / `low` — increasing amounts of chain-of-thought in `reasoning_content` * `no_think` — skip thinking entirely (instant responses, content-only) Enable the reasoning parser during deployment so the thinking section is separated into `reasoning_content`: > **Deploy with reasoning parser** > > ```bash Command theme={null} > sglang serve \ > --model-path tencent/Hy3 \ > --tp 8 \ > --reasoning-parser auto \ > --tool-call-parser auto > ``` > **Example: thinking (reasoning\_effort=high)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="tencent/Hy3", > messages=[{"role": "user", "content": "Solve step by step: What is 15% of 240?"}], > reasoning_effort="high", > max_tokens=2048, > ) > > msg = response.choices[0].message > print("=============== Thinking =================") > print(msg.reasoning_content) > print("=============== Content =================") > print(msg.content) > ``` > > ```text Output theme={null} > =============== Thinking ================= > We need to solve: "What is 15% of 240?" Step by step. 15% means 15/100 = 0.15. Multiply 0.15 by 240. > 10% of 240 = 24, 5% is half of 10% = 12, so sum = 36. So answer is 36. > =============== Content ================= > To find 15% of 240, follow these steps: > > 1. 15% = 15/100 or 0.15. > 2. Multiply 240 by 0.15: 0.15 × 240 = 36. > 3. Check: 10% of 240 = 24, 5% = 12, 15% = 36. > > Thus, 15% of 240 is 36. > ``` > **Example: instant mode (reasoning\_effort=no\_think)** > > ```python Example theme={null} > response = client.chat.completions.create( > model="tencent/Hy3", > messages=[{"role": "user", "content": "Give me a one-line summary of relativity."}], > reasoning_effort="no_think", > max_tokens=256, > ) > > print("Content:", response.choices[0].message.content) > ``` > > ```text Output theme={null} > Content: Relativity is Einstein's theory that space, time, mass, and gravity are interconnected and relative, not fixed, fundamentally changing our understanding of the universe. > ``` ### 3.2 Tool Calling Hy3 supports streaming OpenAI-compatible tool calls. Enable both parsers together — the reasoning parser strips any thinking tokens before the tool-call parser runs: > **Deploy with tool-call parser** > > ```bash Command theme={null} > sglang serve \ > --model-path tencent/Hy3 \ > --tp 8 \ > --reasoning-parser auto \ > --tool-call-parser auto > ``` > **Example: non-streaming tool call** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city.", > "parameters": { > "type": "object", > "properties": { > "city": {"type": "string"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["city"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="tencent/Hy3", > messages=[{"role": "user", "content": "What's the weather in Beijing? Use fahrenheit."}], > tools=tools, > ) > > msg = response.choices[0].message > print("Reasoning:", msg.reasoning_content) > print("Content: ", msg.content) > for tc in msg.tool_calls or []: > print(f"Tool Call: {tc.function.name}") > print(f" Arguments: {tc.function.arguments}") > ``` > > ```text Output theme={null} > Reasoning: None > Content: I'll get the current weather for Beijing in Fahrenheit for you. > Tool Call: get_weather > Arguments: {"city": "Beijing", "unit": "fahrenheit"} > ``` > **Example: streaming tool call (incremental argument deltas)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > stream = client.chat.completions.create( > model="tencent/Hy3", > messages=[{"role": "user", "content": "What's the weather in Beijing? Use fahrenheit."}], > tools=tools, > stream=True, > ) > > tool_buffer = {} > for chunk in stream: > delta = chunk.choices[0].delta > if delta.content: > print(delta.content, end="", flush=True) > for tc in delta.tool_calls or []: > buf = tool_buffer.setdefault(tc.index, {"name": "", "args": ""}) > if tc.function and tc.function.name: > buf["name"] += tc.function.name > if tc.function and tc.function.arguments: > buf["args"] += tc.function.arguments > > for idx, buf in tool_buffer.items(): > print(f"\nTool[{idx}] {buf['name']}({buf['args']})") > ``` > > ```text Output theme={null} > I'll check the current weather in Beijing for you using Fahrenheit. > Tool[0] get_weather({"city": "Beijing", "unit": "fahrenheit"}) > ``` # Hy4 preview Source: https://docs.sglang.io/cookbook/autoregressive/Tencent/Hy4-Preview Deploy Tencent Hy4 preview with SGLang — launch recipes for the 770B-parameter Mixture-of-Experts model with MLA, DeepSeek Sparse Attention (DSA), and MTP speculative decoding, in BF16 on H200/B200/B300/GB300 and MXFP8 on Blackwell GPUs. ## Deployment > **Install SGLang** > > For all methods and hardware platforms, see the [official SGLang installation guide](/docs/get-started/install). The Docker path below matches the **Docker** framing in the command panel. > > **Docker** > > ```bash Command theme={null} > docker pull lmsysorg/sglang:hy4-preview > ``` > > > [!NOTE] > > > > The `hy4-preview` image bundles the HYV4 model code, the suffix-aware `hunyuan` reasoning/tool-call parsers, and the NEXTN MTP runtime. Switch to `:latest` once a tagged release picks them up. > > For how to launch the image, see [Install → Method 3: Using Docker](/docs/get-started/install#method-3-using-docker), substituting the inner `sglang serve ...` with what the command generator below produces. Pick your hardware + recipe to generate the launch command. The two serving strategies map to whether the MTP (NextN) draft layer is on: * **Low-Latency** — MTP speculative decoding on (steps=3, draft-tokens=4). Fastest reply for a single user; pick for chat. * **High-Throughput** — MTP off. At saturation the draft+verify overhead outweighs the speedup; best for batch jobs. **Panel controls** (top of the command box):
  • **Python / Docker** — bare `sglang serve …` for an existing SGLang env, or a `docker run … sglang serve …` wrap against the per-hardware image from the [Install SGLang](#install) panel above.
  • **⧉ Copy** — copies the current command (with whichever framing is active) to your clipboard.
  • **\$ cURL** — a sample request against `localhost:30000` to confirm the server is up.
  • **⚙ Env** — edits the placeholders (`HOST_IP`, `PORT`, `HF_TOKEN`, `NODE_RANK`, `NODE0_IP`) the command and cURL share. Persists in localStorage across cookbooks.
  • **Badge** — single-node recipes show green **Verified** (run end-to-end on real hardware); the 2-node BF16 recipes show **In Progress** and flip to **Verified** as their multi-node verification lands.
## Playground The Playground lets you turn on additional knobs on top of whichever Deploy cell is currently selected. The base is read live from your Deploy selection — only your overrides change. The knobs come in two flavors: * **Built-in SGLang features** — parallelism overrides (TP / DP-Attention), the MoE a2a backend (DeepEP, which sets EP = TP), reasoning / tool-call parsers, speculative-decoding presets, prefill/decode disaggregation, and HiCache tiers. * **Hy4 specific** — `--reasoning-parser auto` / `--tool-call-parser auto` resolve to the suffix-aware Hunyuan parsers and read the real structural-token strings from the tokenizer vocab at runtime. Lines highlighted **green** are added by your overrides; lines with **red strikethrough** were in the base recipe but stripped by an override. Parallelism combinations beyond the listed recipes (DP-Attention, DeepEP, other TP degrees) are experimentation territory — any override flips the badge to **Not Verified** until the configuration is run end-to-end and submitted back. **Panel controls** reuse **Python / Docker** · **⧉ Copy** · **\$ cURL** · **⚙ Env** from the Deploy panel, plus one extra:
  • **Submit ↗** — opens a pre-filled GitHub issue so you can land your override combo as a new verified cookbook cell. Shown only while the badge says **Not Verified**; click it once you've actually run the command on your hardware and confirmed it works.
## 1. Model Introduction **Hy4 preview** is Tencent's next-generation flagship Mixture-of-Experts language model: 770B total parameters with 49B active per token, pairing a DeepSeek-style MLA + sparse-attention stack with Hunyuan's own residual control, MoE routing, and attention gating. It is a **text-only** model (vocab 120,832; the endpoint rejects image input by design), released under **Apache-2.0**. **Key architecture:** * **MoE**: 78 layers — layer 0 is a dense MLP, the remaining 77 are sparse MoE with 256 routed experts + 1 shared expert, top-8 sigmoid-scored routing (routed scaling 2.827), expert intermediate size 2048, and bounded SwiGLU (clamp 10.0). * **MLA + DSA on every layer**: Multi-head Latent Attention (`q_lora_rank` 2048, `kv_lora_rank` 512, 192 nope + 64 rope head dims, `v_head_dim` 256) under DeepSeek Sparse Attention — indexer top-k 2048 with 32 index heads, indexers alternating full/shared (one full indexer every 4 layers), and an FP8 index cache. * **iHC residual control**: Hunyuan's own inter-layer residual gating (`enable_ihc`, `hc_mult` 4) with pre- and post-residual gate groups. Semantically distinct from DeepSeek-V4's mHC (no combination step, no Sinkhorn) — the implementations are not interchangeable. * **Gated MLA + attention sink**: element-wise attention output gating evaluated in fp32, plus a learnable per-head attention sink propagated through all attention backends. * **MTP (NextN)**: one built-in multi-token-prediction draft layer (`model.mtp_layers.0`, 10B parameters with \~0.7B active, present in both checkpoints) enabling speculative decoding out of the box. * **Long context**: 1M max positions (RoPE theta 1e7). Size `--context-length` to your KV budget — the sizing table in §2 suggests 262,144 (131,072 on H200). **Available models:** * [tencent/Hy4-preview](https://huggingface.co/tencent/Hy4-preview) — BF16 (\~1.5TB weights) * [tencent/Hy4-preview-FP8](https://huggingface.co/tencent/Hy4-preview-FP8) — MXFP8 (ModelOpt recipe, UE8M0 group-32 weight scales, dynamic activations; \~760GB weights) **Recommended generation:** `temperature=0.9`, `top_p=1.0` (informational — SGLang applies the checkpoint's `generation_config.json` defaults; don't hardcode sampling parameters in client code). Thinking depth is controlled per request via `reasoning_effort` (defaults to `high`; `no_think` for direct responses — see §3.1). **Resources:** [HuggingFace](https://huggingface.co/tencent/Hy4-preview) · [GitHub](https://github.com/Tencent-Hunyuan/Hy4-preview). **Special tokens.** The Hy4 preview tokenizer's structural tokens are suffix-bearing (``, ``, ``, ``, ``). SGLang's Hunyuan reasoning/tool-call parsers resolve the real token strings from the tokenizer vocab at runtime, so `--reasoning-parser auto --tool-call-parser auto` work out of the box. ## 2. Configuration Tips **Hardware sizing.** BF16 weights are \~1.5TB and MXFP8 \~760GB; the MLA KV cache (compressed `kv_lora` 512 + rope 64, plus the DSA FP8 indexer cache, ≈95KB/token) is replicated per TP rank, so the per-rank pool left after weights sets the context ceiling:
GPU VRAM MXFP8 (\~760GB) BF16 (\~1.5TB)
H200 141GB Not supported — the MXFP8 kernel path requires SM100 (Blackwell) TP16, 2×8 nodes · 131K context
B200 192GB TP8, single node · 262K context TP16, 2×8 nodes · 262K context (8×192GB ≈ the weights alone)
B300 288GB TP4, single node · 262K context (\~190GB/rank) TP8, single 8-GPU node · 262K context
GB300 288GB TP4, single node · 262K context TP8, 2×4 nodes · 262K context (GB300 hosts carry 4 GPUs)
On H200 (BF16, TP16 → \~95GB of weights per rank) the per-rank pool holds roughly 260K tokens of KV — set `--context-length 131072` there (the model default is 1M positions, far beyond the pool); the 192GB+ parts comfortably support 262144. **DSA attention backend.** Every layer runs DeepSeek Sparse Attention; SGLang auto-selects the DSA backend for HYV4 (`--attention-backend dsa` with `flashmla_sparse` prefill/decode and an FP8 indexer cache over a bf16 KV pool), so the recipes don't pass attention flags. Override only with a kernel-specific reason. **MXFP8 kernel stack.** The MXFP8 checkpoint self-describes via its ModelOpt `hf_quant_config` (dynamic activations, UE8M0 group-32 weight scales) — no `--quantization` flag needed; the recipes pin `--moe-runner-backend deep_gemm --fp8-gemm-backend deep_gemm`, the validated HYV4 MXFP8 path (the runtime also defaults both to `deep_gemm` for HYV4 when the flags are left unset). The MXFP8 kernel path requires SM100+ (Blackwell); H200 (SM90) cannot serve the MXFP8 checkpoint — use BF16 there. **CUDA graph decode vs eager.** Decode CUDA-graph capture is on by default; long-duration soak validation of the graph path on Hy4 is still in progress. If you hit instability under long mixed agentic workloads, pass `--disable-cuda-graph` to fall back to eager decode (a restart recovers cleanly either way). **MTP (NextN) speculative decoding.** Both checkpoints ship one draft layer; the preset is `--speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-num-draft-tokens 4` (top-k 1). Speculative decoding reserves 4 draft-token slots per request, so the effective request budget is `prompt_tokens + max_tokens + 4 ≤ context length` — requests at the exact context boundary are rejected with the reservation accounted for. **Fail-fast guardrails.** The model rejects pipeline parallelism and `--enable-prefill-cp` before allocation. The recipes run pure TP; DP-Attention, DeepEP (which sets EP = TP at runtime), and other TP degrees are Playground experimentation territory. **Multi-node BF16.** The BF16 weights don't fit a single H200/B200/GB300 host, so those cells are 2-node TP recipes — run the generated command on every node (the panel injects `--nnodes 2 --node-rank --dist-init-addr`) and keep the weights on storage shared across ranks. **Text-only.** Image input is rejected with HTTP 400 by design — don't route vision traffic to this endpoint. **Large prefills under concurrency.** First-prefill latency on very large prompts can exceed 30 s under high concurrency; use a client timeout of 300 s (and moderate concurrency) for long-context agentic workloads instead of the common 30 s default. ## 3. Advanced Usage ### 3.1 Reasoning (`reasoning_effort`) Hy4 preview is a hybrid-thinking model: reasoning defaults to `high` (deep chain-of-thought — suits math, coding, and agentic tasks). The top-level OpenAI `reasoning_effort` field accepts the standard tiers (e.g. `high`); for direct responses, pass the model-specific `no_think` through `extra_body={"chat_template_kwargs": {"reasoning_effort": "no_think"}}`. The Deploy recipes enable the reasoning parser (`--reasoning-parser auto`) so thinking is separated into `reasoning_content` and the final answer into `content`: > **Example: thinking (reasoning\_effort=high) (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="tencent/Hy4-preview-FP8", > messages=[{"role": "user", "content": "Solve step by step: What is 15% of 240?"}], > reasoning_effort="high", > max_tokens=2048, > ) > > msg = response.choices[0].message > print("=============== Thinking =================") > print(msg.reasoning_content) > print("=============== Content =================") > print(msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Pending update — will be captured verbatim from a live Hy4 preview server. > ``` > **Example: instant mode (reasoning\_effort=no\_think) (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > response = client.chat.completions.create( > model="tencent/Hy4-preview-FP8", > messages=[{"role": "user", "content": "Give me a one-line summary of relativity."}], > extra_body={"chat_template_kwargs": {"reasoning_effort": "no_think"}}, > max_tokens=256, > ) > > print("Content:", response.choices[0].message.content) > ``` > **Example Output** > > ```text Output theme={null} > Pending update — will be captured verbatim from a live Hy4 preview server. > ``` ### 3.2 Tool Calling Hy4 preview emits tool calls through suffixed structural tokens with an `arg_key` / `arg_value` argument format; SGLang's Hunyuan tool-call parser reassembles them into OpenAI-compatible `message.tool_calls` with schema-aware type coercion, for both streaming and non-streaming requests. The Deploy recipes enable both parsers together (`--reasoning-parser auto --tool-call-parser auto`) — the reasoning parser strips thinking tokens before the tool-call parser runs. > [!NOTE] > > Tool-call output is parsed, not grammar-constrained: `tool_choice: "required"` / named-function forcing is not enforced with structural-tag guided decoding on the current implementation. > **Example: non-streaming tool call (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a city.", > "parameters": { > "type": "object", > "properties": { > "city": {"type": "string"}, > "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, > }, > "required": ["city"], > }, > }, > } > ] > > response = client.chat.completions.create( > model="tencent/Hy4-preview-FP8", > messages=[{"role": "user", "content": "What's the weather in Beijing? Use fahrenheit."}], > tools=tools, > ) > > msg = response.choices[0].message > print("Reasoning:", msg.reasoning_content) > print("Content: ", msg.content) > for tc in msg.tool_calls or []: > print(f"Tool Call: {tc.function.name}") > print(f" Arguments: {tc.function.arguments}") > ``` > **Example Output** > > ```text Output theme={null} > Pending update — will be captured verbatim from a live Hy4 preview server. > ``` # Inkling Source: https://docs.sglang.io/cookbook/autoregressive/ThinkingMachines/Inkling Deploy Inkling with SGLang — verified launch commands, tuning, and multimodal / reasoning / tool-calling usage for Thinking Machines' 975B Mixture-of-Experts model with 1M-token context. ## Deployment > **Install SGLang** > > For all install methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). > > **Python (pip / uv)** > > Inkling has merged to `main` but isn't in a `pip` release yet — install from source: > > ```bash Command theme={null} > pip install --upgrade pip > pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' > ``` > > Then run the **Python** output of the command panel below. > > **Docker** > > > [!NOTE] > > > > The Inkling images are being published to [`lmsysorg/sglang`](https://hub.docker.com/r/lmsysorg/sglang/tags) — watch the tag list for status. > > There are two multi-arch (amd64 / arm64) CUDA builds plus a ROCm build; pick the CUDA build by your CUDA version, not your GPU: > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-inkling-dspark # CUDA 13 > docker pull lmsysorg/sglang:dev-cu12-inkling-dspark # CUDA 12 (final build; lane retired) > docker pull lmsysorg/sglang-rocm:dev-rocm720-mi35x-inkling-dspark # AMD MI350X / MI355X > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your hardware to generate the launch command. Each platform ships a **Balanced** recipe plus **MTP** and **DSpark** (speculative decoding) tiers and a **Long Context (MXFP8 KV)** tier where validated; the **LoRA** variant serves adapters on top of the frozen base model. Set `MAX_LORAS` to the number of distinct adapters you serve (1 is fastest for single-adapter serving). **Panel controls** (top of the command box):
  • **⧉ Copy** — copies the current command to your clipboard.
  • **\$ cURL** — a sample request against `localhost:30000` to confirm the server is up.
  • **⚙ Env** — edits the placeholders (`HOST_IP`, `PORT`, `NODE_RANK`, `NODE0_IP`) the command and cURL share.
  • **Verified / Not Verified** badge — green when the `(hw, variant, quant, strategy, nodes)` combo has been run end-to-end on real hardware; yellow when auto-derived from a neighbor and not yet re-checked.
## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations that have been signed off; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. The base is read live from your Deploy selection — only your overrides change. Lines highlighted **green** are added by your overrides; lines with **red strikethrough** were in the verified base but stripped by an override. Any change flips the badge to **Not Verified** until the new configuration is run end-to-end. ## 1. Model Introduction **Inkling** is a Mixture-of-Experts model from Thinking Machines — **975B** total parameters, **41B** active per token, with a **1M-token** context window and **open weights** (BF16 and NVFP4 checkpoints below). It handles text, image, and audio inputs natively, and exposes a **variable reasoning-effort** control to trade latency and cost against answer quality. This page covers serving Inkling on SGLang, including its **MTP** speculative-decoding path and long-context prefix caching (unified radix cache + HiCache). **Resources:** HuggingFace — [Inkling](https://huggingface.co/thinkingmachines/Inkling) (BF16) · [Inkling-NVFP4](https://huggingface.co/thinkingmachines/Inkling-NVFP4). ## 2. Configuration Tips **Multimodal.** The recipes pass `--enable-multimodal` so the server accepts image and audio inputs alongside text — drop it for text-only serving. **Memory pool ratios.** `--swa-full-tokens-ratio` and `--mamba-full-memory-ratio` (both default `0.1`) size the SWA and Mamba/sconv state pools; tune them to your workload's usage. **MTP needs `--enable-multi-layer-eagle`.** The MTP recipe drives Inkling's multi-layer draft head; without this flag the standard EAGLE worker runs against it and outputs garbage. **Reasoning effort.** Pass `reasoning_effort` as one of the named levels below; requests that omit it default to `high`, and `max` is the strongest. Each level maps to an internal effort value (max at `0.99`):
reasoning\_effort value
`none`0.0
`minimal`0.1
`low`0.2
`medium`0.7
`high`0.9
`xhigh`0.99
`max`0.99
## 3. Advanced Usage ### 3.1 Reasoning Enable the `inkling` reasoning parser (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to separate thinking from the final answer into `reasoning_content` vs `content`. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-NVFP4", > messages=[{"role": "user", "content": "What is 17 times 24?"}], > extra_body={"chat_template_kwargs": {"thinking": True}}, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user is asking for the product of 17 and 24. Let me calculate that. > > 17 × 24 > > I can break this down: > 17 × 20 = 340 > 17 × 4 = 68 > 340 + 68 = 408 > > Alternatively: > 24 × 10 = 240 > 24 × 7 = 168 > 240 + 168 = 408 > > So the answer is 408. > Answer: 17 times 24 is **408**. > > Here's a quick breakdown: > - 17 × 20 = 340 > - 17 × 4 = 68 > - 340 + 68 = **408** > ``` ### 3.2 Tool Calling Enable the `inkling` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": {"location": {"type": "string", "description": "The city name"}}, > "required": ["location"], > }, > }, > } > ] > > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-NVFP4", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Content:", msg.content) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user is asking for the weather in Beijing. I have a tool called `get_weather` that can get the current weather for a location. Let me call it with "Beijing" as the location. > Content: > Tool calls: [ChatCompletionMessageFunctionToolCall(id='call_98f772f3a0044f45b80c5ba5', function=Function(arguments='{"location": "Beijing"}', name='get_weather'), type='function', index=0)] > ``` ### 3.3 Multimodal Input (Image + Audio) Inkling is multimodal: a single user message can mix **text**, **images**, and **audio**. Pass each media item as its own content part — `image_url` for images, `audio_url` for audio — with the `url` set to either an HTTP(S) link or a base64 `data:` URI. Audio can also be sent as OpenAI's `input_audio` part, carrying the base64 bytes in `data` alongside a `format` of `wav` or `mp3`. The server must be started with `--enable-multimodal` (already included in every recipe above). > **Image + Audio Example (Python)** > > ```python Example theme={null} > import base64 > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > with open("image.png", "rb") as f: > image_b64 = base64.b64encode(f.read()).decode() > with open("audio.wav", "rb") as f: > audio_b64 = base64.b64encode(f.read()).decode() > > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-NVFP4", > messages=[ > { > "role": "user", > "content": [ > {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}}, > {"type": "audio_url", "audio_url": {"url": f"data:audio/wav;base64,{audio_b64}"}}, > {"type": "text", "text": "Describe the image, then transcribe the audio."}, > ], > } > ], > max_tokens=1024, > ) > print(resp.choices[0].message.content) > ``` > [!NOTE] > > Images and audio can be sent as public HTTP(S) URLs instead of base64 — e.g. `{"type": "image_url", "image_url": {"url": "https://.../photo.jpg"}}`. Use one content part per media item; mix as many as the context budget allows. ### 3.4 LoRA (Serving Adapters) The **LoRA** deploy variant serves adapters on top of the frozen base model. Its launch command adds `--enable-lora --lora-paths lora0={{ADAPTER_PATH}} --max-loras-per-batch {{MAX_LORAS}}` — each adapter is registered under the **name** to the left of `=` (here `lora0`). Adapters can also be added/removed at runtime via the `POST /load_lora_adapter` endpoint. To serve several adapters, pass multiple `--lora-paths name=path` at launch and reference each by its name. Pick the adapter per request by that name — either in the `model` field with `base-model:adapter` syntax (recommended), or explicitly via `lora_path` in `extra_body`: > **LoRA Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > # Option A (recommended): ":" in the model field > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-NVFP4:lora0", > messages=[{"role": "user", "content": "Summarize the changelog."}], > ) > > # Option B: explicit lora_path via extra_body > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-NVFP4", > messages=[{"role": "user", "content": "Summarize the changelog."}], > extra_body={"lora_path": "lora0"}, > ) > > print(resp.choices[0].message.content) > ``` > [!NOTE] > > One adapter per request — omit the `:adapter` suffix (and `lora_path`) to hit the base model. Different requests **in the same batch** may use different adapters; the number of *distinct* adapters co-resident in a batch is capped by `--max-loras-per-batch` (the `MAX_LORAS` field, default `1`). If both `model:adapter` and `lora_path` are supplied, the `model` suffix takes precedence. ### 3.5 HiCache (Hierarchical KV Caching) Inkling serves on SGLang's **unified radix cache**: the historically separate full-attention, SWA, and Mamba/sconv caches are combined into one radix tree with typed components, and native HiCache offloads cold prefix pages across tiers (GPU HBM → host DRAM → disk / remote). This expands effective prefix-cache capacity for multi-turn and long-context workloads. To enable HiCache, open the **HiCache** card in the [Playground above](#playground) and flip **Enable**, then pick a storage backend (`file` / `mooncake` / `nixl`) for the L3 tier. The Write policy defaults to `write_through`. ### 3.6 Long Context (MXFP8 KV) The **Long Context** deploy strategy adds `--kv-cache-dtype mxfp8` on top of the Balanced recipe. KV entries are stored as block-scaled MXFP8 instead of BF16, so the SWA + Mamba/sconv memory pool holds roughly 2x as many tokens on the same GPU. Use it when you're context-bound or concurrency-bound. **Blackwell only.** MXFP8 KV cache requires Blackwell (B200 / B300 / GB200 / GB300), it's not offered on Hopper (H200). The tradeoff is not just a \~5% decode latency penalty from the extra quantize/dequantize work versus BF16 KV — storing KV in MXFP8 also introduces some accuracy loss at long context lengths. Treat it as a capacity lever, not a speed one — stay on **Balanced** if you have headroom in the memory pool and just want lower latency or maximum output quality. To try it, select the **Long Context** strategy in the Deploy panel above for any NVFP4 cell; the panel regenerates the launch command with `--kv-cache-dtype mxfp8` inserted. Verified end-to-end on B200, B300, and GB300. ### 3.7 DSpark (Speculative Decoding) The **DSpark** deploy strategy is the second speculative-decoding path for Inkling. Unlike **MTP**, which drives Inkling's own multi-layer draft head, DSpark runs a **separate draft checkpoint** — `RadixArk/Inkling-DSpark-Preview` — served unquantized alongside the NVFP4 target. DSpark support ships in the images listed in §1 (`dev-inkling-dspark` for CUDA 13, `dev-cu12-inkling-dspark` for CUDA 12 — a final build, since that lane is retired), so no separate build is needed. Verified end-to-end on B200 (TP=8, NVFP4). # Inkling-Small Source: https://docs.sglang.io/cookbook/autoregressive/ThinkingMachines/Inkling-Small Deploy Inkling-Small with SGLang — launch commands, tuning, and multimodal / reasoning / tool-calling usage for Thinking Machines' Inkling-Small Mixture-of-Experts model. ## Deployment > **Install SGLang** > > For all install methods and hardware platforms, see the [official SGLang installation guide](../../../docs/get-started/install). > > **Python (pip / uv)** > > Inkling-Small has merged to `main` but isn't in a `pip` release yet — install from source: > > ```bash Command theme={null} > pip install --upgrade pip > pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' > ``` > > Then run the **Python** output of the command panel below. > > **Docker** > > > [!NOTE] > > > > The Inkling-Small images are being published to [`lmsysorg/sglang`](https://hub.docker.com/r/lmsysorg/sglang/tags) — watch the tag list for status. > > There are two multi-arch (amd64 / arm64) CUDA builds plus a ROCm build; pick the CUDA build by your CUDA version, not your GPU. DGX Spark (GB10) uses a dedicated arm64 CUDA 13 image: > > ```bash Command theme={null} > docker pull lmsysorg/sglang:dev-inkling-dspark # CUDA 13 > docker pull lmsysorg/sglang:dev-cu12-inkling-dspark # CUDA 12 (final build; lane retired) > docker pull lmsysorg/sglang:dev-inkling-small-dgx-spark # DGX Spark (GB10 / SM121) > docker pull lmsysorg/sglang-rocm:dev-rocm720-mi35x-inkling-dspark # AMD MI350X / MI355X > ``` > > For how to launch the image, see [Install → Method 3: Using Docker](../../../docs/get-started/install#method-3-using-docker). Substitute the inner `sglang serve ...` with what the command generator below produces. Pick your hardware to generate the launch command. Each platform ships a **Balanced** recipe plus **MTP** and **DSpark** (speculative decoding) tiers and a **Long Context (MXFP8 KV)** tier where validated; the **LoRA** variant serves adapters on top of the frozen base model. Set `MAX_LORAS` to the number of distinct adapters you serve (1 is fastest for single-adapter serving). **Panel controls** (top of the command box):
  • **⧉ Copy** — copies the current command to your clipboard.
  • **\$ cURL** — a sample request against `localhost:30000` to confirm the server is up.
  • **⚙ Env** — edits the placeholders (`HOST_IP`, `PORT`, `NODE_RANK`, `NODE0_IP`) the command and cURL share.
  • **Verified / Not Verified** badge — green when the `(hw, variant, quant, strategy, nodes)` combo has been run end-to-end on real hardware; yellow when auto-derived from a neighbor and not yet re-checked.
## Playground The Playground is where you experiment with **SGLang features beyond the verified matrix**. The Deploy panel above only emits combinations that have been signed off; the Playground lets you turn on additional knobs on top of whichever cell the Deploy panel is currently showing. The base is read live from your Deploy selection — only your overrides change. Lines highlighted **green** are added by your overrides; lines with **red strikethrough** were in the verified base but stripped by an override. Any change flips the badge to **Not Verified** until the new configuration is run end-to-end. ## 1. Model Introduction **Inkling-Small** is a Mixture-of-Experts model from Thinking Machines with **open weights** (BF16 and NVFP4 checkpoints below), in the same architecture family as Inkling. It handles text, image, and audio inputs natively, and exposes a **variable reasoning-effort** control to trade latency and cost against answer quality. This page covers serving Inkling-Small on SGLang, including its **MTP** speculative-decoding path and long-context prefix caching (unified radix cache + HiCache). **Resources:** HuggingFace — [Inkling-Small](https://huggingface.co/thinkingmachines/Inkling-Small) (BF16) · [Inkling-Small-NVFP4](https://huggingface.co/thinkingmachines/Inkling-Small-NVFP4). ## 2. Configuration Tips **Multimodal.** The recipes pass `--enable-multimodal` so the server accepts image and audio inputs alongside text — drop it for text-only serving. **DGX Spark (2× GB10).** The verified cell runs NVFP4 with TP=2 across two Sparks over ConnectX-7 (1 GPU per node). Use the `dev-inkling-small-dgx-spark` image, Triton attention + Marlin FP4/MoE, and `--disable-prefill-cuda-graph`. The Docker command already carries the ConnectX-7 flags `--ulimit memlock=-1:-1 --cap-add IPC_LOCK --device /dev/infiniband`. **Memory pool ratios.** `--swa-full-tokens-ratio` and `--mamba-full-memory-ratio` (both default `0.1`) size the SWA and Mamba/sconv state pools; tune them to your workload's usage. **MTP needs `--enable-multi-layer-eagle`.** The MTP recipe drives Inkling-Small's multi-layer draft head; without this flag the standard EAGLE worker runs against it and outputs garbage. **Reasoning effort.** Pass `reasoning_effort` as one of the named levels below; requests that omit it default to `high`, and `max` is the strongest. Each level maps to an internal effort value (max at `0.99`):
reasoning\_effort value
`none`0.0
`minimal`0.1
`low`0.2
`medium`0.7
`high`0.9
`xhigh`0.99
`max`0.99
## 3. Advanced Usage ### 3.1 Reasoning Enable the `inkling` reasoning parser (toggle **Reasoning Parser** in the **Parsers** card of the [Playground above](#playground)) to separate thinking from the final answer into `reasoning_content` vs `content`. > **Reasoning Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-Small-NVFP4", > messages=[{"role": "user", "content": "What is 17 times 24?"}], > extra_body={"chat_template_kwargs": {"thinking": True}}, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Answer:", msg.content) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user is asking for the product of 17 and 24. Let me calculate that. > > 17 × 24 > > I can break this down: > 17 × 20 = 340 > 17 × 4 = 68 > 340 + 68 = 408 > > Alternatively: > 24 × 10 = 240 > 24 × 7 = 168 > 240 + 168 = 408 > > So the answer is 408. > Answer: 17 times 24 is **408**. > > Here's a quick breakdown: > - 17 × 20 = 340 > - 17 × 4 = 68 > - 340 + 68 = **408** > ``` ### 3.2 Tool Calling Enable the `inkling` tool-call parser (toggle **Tool Call Parser** in the **Parsers** card of the [Playground above](#playground)) to surface structured tool calls via `message.tool_calls`. > **Tool Calling Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > tools = [ > { > "type": "function", > "function": { > "name": "get_weather", > "description": "Get the current weather for a location", > "parameters": { > "type": "object", > "properties": {"location": {"type": "string", "description": "The city name"}}, > "required": ["location"], > }, > }, > } > ] > > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-Small-NVFP4", > messages=[{"role": "user", "content": "What's the weather in Beijing?"}], > tools=tools, > ) > msg = resp.choices[0].message > print("Reasoning:", getattr(msg, "reasoning_content", None)) > print("Content:", msg.content) > print("Tool calls:", msg.tool_calls) > ``` > **Example Output** > > ```text Output theme={null} > Reasoning: The user is asking for the weather in Beijing. I have a tool called `get_weather` that can get the current weather for a location. Let me call it with "Beijing" as the location. > Content: > Tool calls: [ChatCompletionMessageFunctionToolCall(id='call_98f772f3a0044f45b80c5ba5', function=Function(arguments='{"location": "Beijing"}', name='get_weather'), type='function', index=0)] > ``` ### 3.3 Multimodal Input (Image + Audio) Inkling-Small is multimodal: a single user message can mix **text**, **images**, and **audio**. Pass each media item as its own content part — `image_url` for images, `audio_url` for audio — with the `url` set to either an HTTP(S) link or a base64 `data:` URI. Audio can also be sent as OpenAI's `input_audio` part, carrying the base64 bytes in `data` alongside a `format` of `wav` or `mp3`. The server must be started with `--enable-multimodal` (already included in every recipe above). > **Image + Audio Example (Python)** > > ```python Example theme={null} > import base64 > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > with open("image.png", "rb") as f: > image_b64 = base64.b64encode(f.read()).decode() > with open("audio.wav", "rb") as f: > audio_b64 = base64.b64encode(f.read()).decode() > > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-Small-NVFP4", > messages=[ > { > "role": "user", > "content": [ > {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_b64}"}}, > {"type": "audio_url", "audio_url": {"url": f"data:audio/wav;base64,{audio_b64}"}}, > {"type": "text", "text": "Describe the image, then transcribe the audio."}, > ], > } > ], > max_tokens=1024, > ) > print(resp.choices[0].message.content) > ``` > [!NOTE] > > Images and audio can be sent as public HTTP(S) URLs instead of base64 — e.g. `{"type": "image_url", "image_url": {"url": "https://.../photo.jpg"}}`. Use one content part per media item; mix as many as the context budget allows. ### 3.4 LoRA (Serving Adapters) The **LoRA** deploy variant serves adapters on top of the frozen base model. Its launch command adds `--enable-lora --lora-paths lora0={{ADAPTER_PATH}} --max-loras-per-batch {{MAX_LORAS}}` — each adapter is registered under the **name** to the left of `=` (here `lora0`). Adapters can also be added/removed at runtime via the `POST /load_lora_adapter` endpoint. To serve several adapters, pass multiple `--lora-paths name=path` at launch and reference each by its name. Pick the adapter per request by that name — either in the `model` field with `base-model:adapter` syntax (recommended), or explicitly via `lora_path` in `extra_body`: > **LoRA Example (Python)** > > ```python Example theme={null} > from openai import OpenAI > > client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY") > > # Option A (recommended): ":" in the model field > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-Small-NVFP4:lora0", > messages=[{"role": "user", "content": "Summarize the changelog."}], > ) > > # Option B: explicit lora_path via extra_body > resp = client.chat.completions.create( > model="thinkingmachines/Inkling-Small-NVFP4", > messages=[{"role": "user", "content": "Summarize the changelog."}], > extra_body={"lora_path": "lora0"}, > ) > > print(resp.choices[0].message.content) > ``` > [!NOTE] > > One adapter per request — omit the `:adapter` suffix (and `lora_path`) to hit the base model. Different requests **in the same batch** may use different adapters; the number of *distinct* adapters co-resident in a batch is capped by `--max-loras-per-batch` (the `MAX_LORAS` field, default `1`). If both `model:adapter` and `lora_path` are supplied, the `model` suffix takes precedence. ### 3.5 HiCache (Hierarchical KV Caching) Inkling-Small serves on SGLang's **unified radix cache**: the historically separate full-attention, SWA, and Mamba/sconv caches are combined into one radix tree with typed components, and native HiCache offloads cold prefix pages across tiers (GPU HBM → host DRAM → disk / remote). This expands effective prefix-cache capacity for multi-turn and long-context workloads. To enable HiCache, open the **HiCache** card in the [Playground above](#playground) and flip **Enable**, then pick a storage backend (`file` / `mooncake` / `nixl`) for the L3 tier. The Write policy defaults to `write_through`. ### 3.6 Long Context (MXFP8 KV) The **Long Context** deploy strategy adds `--kv-cache-dtype mxfp8` on top of the Balanced recipe. KV entries are stored as block-scaled MXFP8 instead of BF16, so the SWA + Mamba/sconv memory pool holds roughly 2x as many tokens on the same GPU. Use it when you're context-bound or concurrency-bound. **Blackwell only.** MXFP8 KV cache requires Blackwell (B200 / B300 / GB200 / GB300), it's not offered on Hopper (H200). The tradeoff is not just a \~5% decode latency penalty from the extra quantize/dequantize work versus BF16 KV — storing KV in MXFP8 also introduces some accuracy loss at long context lengths. Treat it as a capacity lever, not a speed one — stay on **Balanced** if you have headroom in the memory pool and just want lower latency or maximum output quality. To try it, select the **Long Context** strategy in the Deploy panel above for any NVFP4 cell; the panel regenerates the launch command with `--kv-cache-dtype mxfp8` inserted. Verified end-to-end on B200, B300, and GB300. ### 3.7 DSpark (Speculative Decoding) The **DSpark** deploy strategy is the second speculative-decoding path for Inkling-Small. Unlike **MTP**, which drives Inkling-Small's own multi-layer draft head, DSpark runs a **separate draft checkpoint** — `RadixArk/Inkling-Small-DSpark` — served unquantized alongside the NVFP4 target. DSpark support ships in the images listed in §1 (`dev-inkling-dspark` for CUDA 13, `dev-cu12-inkling-dspark` for CUDA 12 — a final build, since that lane is retired), so no separate build is needed. Verified end-to-end on B200 (TP=8, NVFP4). # MiMo-V2-Flash Source: https://docs.sglang.io/cookbook/autoregressive/Xiaomi/MiMo-V2-Flash ## Introduction XiaomiMiMo/MiMo-V2-Flash, with 309B total parameters and 15B activated parameters, is a new inference-centric model designed to maximize decoding efficiency created by XiaomiMiMo Team explicitly co-designed for real-world serving workloads, enabling flexible tradeoffs between throughput and latency on different hardware. This model creates a new balance between long-context modeling capability and inference efficiency. Key features include: * **Hybrid Attention Architecture**: Interleaves Sliding Window Attention (SWA) and Global Attention (GA) with a 5:1 ratio and an aggressive 128-token window. This reduces KV-cache storage by nearly 6x while maintaining long-context performance via learnable attention sink bias. * **Multi-Token Prediction (MTP)**: Equipped with a lightweight MTP module (0.33B params/block) using dense FFNs. This triples output speed during inference and will be good to accelerates rollout in RL training. * **Efficient Pre-Training**: Trained on 27T tokens using FP8 mixed precision and native 32k seq length. The context window supports up to 256k length. * **Agentic Capabilities**: Post-training utilizes Multi-Teacher On-Policy Distillation (MOPD) and large-scale agentic RL, achieving superior performance on SWE-Bench and complex reasoning tasks. ## Installation MiMo-V2-Flash is currently available in SGLang via Docker image and pip install. ### Docker ```bash Command theme={null} # Pull the docker image docker pull lmsysorg/sglang:latest # Launch the container docker run -it --gpus all \ --shm-size=32g \ --ipc=host \ --network=host \ lmsysorg/sglang:latest bash ``` ### Pip Installation ```bash Command theme={null} # On a machine with SGLang dependencies installed or inside a SGLang nightly container # Start an SGLang nightly container docker run -it --gpus all \ --shm-size=32g \ --ipc=host \ --network=host \ lmsysorg/sglang:latest bash # If you already have SGLang installed, uninstall the current SGLang version pip uninstall sglang -y # Install the PyPI Package pip install sglang==0.5.6.post2.dev8005+pr.15207.g39d5bd57a \ --extra-index-url https://sgl-project.github.io/whl/pr/ ``` ## Model Deployment Use the configuration selector below to automatically generate the appropriate deployment command. Run this Command:

MI355X (ROCm) is validated in the selector above with `--tp-size 4`, Triton attention, and `--disable-custom-all-reduce`. `--tp-size 8` hit a QKV sharding error during validation. EAGLE speculative decoding is still WIP on MI355X.

## Testing the deployment

Once the server is running, test it with a chat completion request in another terminal:

```bash Command theme={null}
curl http://localhost:30000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "XiaomiMiMo/MiMo-V2-Flash",
    "messages": [
      {"role": "user", "content": "Hello! What can you help me with?"}
    ],
    "temperature": 0.7,
    "max_tokens": 100
  }'
```

**Expected response:**

```json Config theme={null}
{
  "id": "...",
  "object": "chat.completion",
  "model": "XiaomiMiMo/MiMo-V2-Flash",
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "Hello! I can help you with..."
    }
  }]
}
```

## Troubleshooting

**DeepGEMM Timeout Error**

Occasionally DeepGEMM timeout errors occur during first launch. Simply rerun the server command in the same container - the compiled kernels are cached and subsequent launches will be fast.

**ROCm MI355X Attention Backend**

If you see an error such as `AiterAttnBackend.forward_decode() got an unexpected keyword argument 'sinks'` on MI355X, use the `MI355X` + `Performance Optimizations` command from the selector above, which switches to Triton attention and keeps `--disable-custom-all-reduce`.


# MiMo-V2.5
Source: https://docs.sglang.io/cookbook/autoregressive/Xiaomi/MiMo-V2.5



## 1. Model Introduction

[MiMo-V2.5-Pro](https://huggingface.co/XiaomiMiMo/MiMo-V2.5-Pro) and [MiMo-V2.5](https://huggingface.co/XiaomiMiMo/MiMo-V2.5) are next-generation Mixture-of-Experts models from the XiaomiMiMo Team.

Variant Total params Active (MoE) Modalities
**[MiMo-V2.5-Pro](https://huggingface.co/XiaomiMiMo/MiMo-V2.5-Pro)** **1.02T** 42B Text (multimodal planned)
**[MiMo-V2.5](https://huggingface.co/XiaomiMiMo/MiMo-V2.5)** **310B** 15B Text, Image, Video, Audio
**Key Features:** * **Hybrid Attention Architecture**: Interleaves Sliding Window Attention (SWA) and Global Attention (GA) for reduced KV cache while preserving long-context capability. * **Multi-Token Prediction (MTP)**: 3-layer MTP module accelerates decoding. Both variants support EAGLE speculative decoding with MTP weights. * **1M-Token Context**: Both variants support up to 1 million token context windows. * **Agentic Capabilities**: Post-training with large-scale agentic RL achieves strong performance on coding, reasoning, and tool-use benchmarks. * **MiMo-V2.5 Multimodal** (V2.5 only): Native omnimodal architecture with a 729M-param ViT Vision Encoder (28 layers: 24 SWA + 4 Full) and a 261M-param Audio Transformer (24 layers: 12 SWA + 12 Full); supports image, video, and audio understanding via standard OpenAI-compatible multimodal API. **License:** Apache 2.0 ## 2. SGLang Installation Refer to the [official SGLang installation guide](../../../docs/get-started/install). **Docker Image:** All variants (MiMo-V2.5 310B and MiMo-V2.5-Pro 1.02T) use `lmsysorg/sglang:latest`, which ships CUDA 13.0 and runs on both Hopper (H100 / H200) and Blackwell (B200 / GB300). **TPU (sgl-jax):** MiMo-V2.5-Pro can also be served on TPU via the JAX-based [sgl-jax](https://github.com/sgl-project/sglang-jax) runtime. The container image and `pip install` steps are listed in [§3.3 TPU Deployment](#3-3-tpu-deployment-mimo-v2-5-pro-sgl-jax). ## 3. Model Deployment ### 3.1 Basic Configuration Use the selector below to generate the deployment command for your variant and hardware. Run this Command:

### 3.2 Configuration Tips

**MiMo-V2.5-Pro (1.02T):**

* **B200**: single node, TP=8 (verified). Uses `--attention-backend fa4` + `--moe-runner-backend flashinfer_trtllm` + `--mem-fraction-static 0.8`. Set `--swa-full-tokens-ratio 0.1` to keep KV-cache footprint within 192 GB HBM.
* **GB300**: 2 nodes, TP=8 (verified). Same Blackwell stack as B200; multi-node interconnect requires `NCCL_MNNVL_ENABLE=1 NCCL_CUMEM_ENABLE=1`. Default SWA ratio is fine.
* **H100/H200**: 2 nodes × 8 GPUs (TP=16, not yet verified). Uses the Hopper stack (`fa3` + DeepEP + EAGLE multi-layer); fits with `--mem-fraction-static 0.7` and `--swa-full-tokens-ratio 0.3`. DeepEP dispatch tuning: `SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=256` avoids memory spikes during prefill.
* EAGLE speculative decoding (3 steps, topk=1) typically yields a 2–3× decode speedup. Requires `--enable-multi-layer-eagle` (both Hopper and Blackwell). See §5.4 for acceptance-rate behavior on natural text vs random prompts.

**MiMo-V2.5 (310B):**

* The checkpoint has a TP=4-interleaved fused `qkv_proj`; attention-TP per DP group **must** be 4. Use `--attn-dp-size = TP / 4`; for TP > 4 this means DP-attention is on. Total GPUs must be a multiple of 4. A bare `--tp 8` without `--attn-dp-size 2` will fail to load with `MiMoV2 fused qkv_proj checkpoint is TP=4-interleaved; got attention tp_size=8`.
* Single-node deployments: H100/H200 8× GPUs (`--tp 8 --attn-dp-size 2`), B200 4× GPUs (`--tp 4`, attention DP size 1, no DP-attn flag needed), GB300 4× GPUs (`--tp 4`, single NVL4 node). FP8 quantization.
* On Blackwell, pass `--attention-backend fa4`: MiMoV2's asymmetric KV (`head_dim` 192 / `v_head_dim` 128) fails on the SM100 default `trtllm_mha`, which requires equal K/V widths.
* On Blackwell, pass `--mm-attention-backend fa4` for the V2.5 vision encoder. The checkpoint config requests FlashAttention-3 internally, but SGLang rejects FA3 on Blackwell and expects FA4 for multimodal attention.
* On Blackwell, pass `--moe-runner-backend flashinfer_trtllm`; the default `auto` falls through to the triton fused-MoE runner, \~12% slower at bs=1 decode.
* `--enable-dp-lm-head` and `--mm-enable-dp-encoder` are required whenever `--attn-dp-size` is greater than 1, to keep LM head and encoder sharding consistent.
* EAGLE MTP uses the checkpoint's MTP weights. Enable with `--speculative-algorithm EAGLE` and `--enable-multi-layer-eagle` (both Hopper and Blackwell).
* **Multimodal**: Supports image, video, and audio understanding; see Section 4.3 for invocation examples.

**DeepEP (optional toggle, Hopper-only):**

* DeepEP replaces the default MoE all-to-all dispatch with a fused [DeepEP](https://github.com/deepseek-ai/DeepEP) backend; it lowers expert dispatch latency and memory traffic, so it pays off under **high concurrency / throughput-bound workloads** on H100/H200. Under concurrency=1 / latency-bound workloads the gain is negligible — leave it off.
* Enabling adds `--moe-a2a-backend deepep` + `--moe-dense-tp-size 1` (and `--ep ` for Pro) plus `SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=256` env to cap the dispatch buffer. Requires `pip install deep_ep` (not part of the default sglang install).
* On Blackwell (B200, GB300) the verified MoE backend is `flashinfer_trtllm`; the DeepEP toggle is a no-op there.

### 3.3 TPU Deployment (MiMo-V2.5-Pro, sgl-jax)

MiMo-V2.5-Pro can also be served on TPU via [sgl-jax](https://github.com/sgl-project/sglang-jax). The runtime is a separate JAX-based stack (`sgl_jax.launch_server`); pick **TPU v7x** or **TPU v6e** in the panel above to generate the launch command. Verified topologies:

| TPU Type | Topology | Chips/Node | Nodes | Total Chips | JAX Devices/Chip | Total JAX Devices (= `--tp-size`) |
| - | - | - | - | - | - | - |
| **v7x** | 2×2×4 | 4 | 4 | 16 | 2 | 32 |
| **v6e** | 4×4×4 | 4 | 16 | 64 | 1 | 64 |

> v7x exposes **2 logical JAX devices per chip**, so `--tp-size = 16 chips × 2 = 32`. v6e exposes 1 device per chip, so `--tp-size = 64`. Always set `--tp-size` to the total JAX device count across all nodes, not the chip count.

All nodes must sit in the same TPU slice and reach each other on the JAX init port (`20000`) and the TPU process port (`8471`).

**Step 1 — Launch the JAX TPU container on every node:**

```shell Command theme={null}
docker run -it --privileged \
  --shm-size=32g \
  --ipc=host \
  --network=host \
  -v /dev:/dev \
  us-docker.pkg.dev/cloud-tpu-images/jax-ai-image/tpu:jax0.8.1-rev1 bash
```

> The image is pinned to `jax0.8.1-rev1` to keep the JAX runtime aligned with sgl-jax's TPU extras.

**Step 2 — Clone and install sgl-jax (inside the container):**

```shell Command theme={null}
git clone https://github.com/sgl-project/sglang-jax.git
cd sglang-jax
pip install -e "python[tpu]"
```

## 4. Model Invocation

### 4.1 Basic Usage

See [Basic API Usage](../../../docs/basic_usage/send_request).

### 4.2 Reasoning Output

Both variants support hybrid thinking mode. Thinking content is separated via the reasoning parser.

**Thinking Mode (default):**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

response = client.chat.completions.create(
    model="XiaomiMiMo/MiMo-V2.5",
    messages=[
        {"role": "user", "content": "Which is larger, 9.11 or 9.9? Think carefully."}
    ]
)

print("====== Reasoning ======")
print(response.choices[0].message.reasoning_content)
print("====== Answer ======")
print(response.choices[0].message.content)
```

**Output Example (MiMo-V2.5):**

```text theme={null}
====== Reasoning ======
Comparing 9.11 and 9.9.

The integer parts are both 9. Now compare the decimal parts: 0.11 vs 0.9.

0.9 = 0.90, which is greater than 0.11.

So 9.9 > 9.11.
====== Answer ======
**9.9 is larger than 9.11.**

Here's the reasoning: When comparing decimals, line them up to the same number of decimal places:

- 9.11
- 9.90

Both have a **9** in the ones place, but in the tenths place, **9 > 1**, so 9.90 > 0.11.

**9.9 > 9.11**
```

**Thinking Off (instant mode):**

```python Example theme={null}
response = client.chat.completions.create(
    model="XiaomiMiMo/MiMo-V2.5",
    messages=[
        {"role": "user", "content": "Which is larger, 9.11 or 9.9? Think carefully."}
    ],
    extra_body={"chat_template_kwargs": {"thinking": False}}
)

print(response.choices[0].message.content)
```

**Output Example (MiMo-V2.5):**

```text theme={null}
## Comparing 9.11 and 9.9

**9.9 is larger.**

The key is to compare them place by place. It helps to write them with the same number of decimal places:

- **9.11** → 9.11
- **9.9** → 9.90

Both have **9** in the ones place, but in the tenths place: **9** (in 9.90) is greater than **1** (in 9.11).

So **9.90 > 9.11**.
```

### 4.3 Multimodal Invocation (V2.5 only)

**Image Understanding:**

```python Example theme={null}
from openai import OpenAI

client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")

response = client.chat.completions.create(
    model="XiaomiMiMo/MiMo-V2.5",
    messages=[{
        "role": "user",
        "content": [
            {"type": "image_url", "image_url": {"url": "https://raw.githubusercontent.com/sgl-project/sgl-test-files/refs/heads/main/images/man_ironing_on_back_of_suv.png"}},
            {"type": "text", "text": "Describe this image in detail."}
        ]
    }]
)

print(response.choices[0].message.content)
```

**Output Example:**

```text theme={null}
Based on the image provided, here is a detailed description:

The image captures a whimsical or surreal scene set on a busy city street, likely in New York City given the iconic yellow cabs. In the center foreground, a man is sitting on a folding chair, casually crossing his legs. He is wearing a bright yellow hoodie with a graphic on the front and blue jeans. He is intently focused on ironing a white dress shirt that rests on an ironing board set up directly on the asphalt.

Behind him, a yellow SUV taxi cab is stopped or moving slowly, angled slightly away from the camera. To his left, another yellow taxi sedan is captured in motion blur, indicating it is driving past him. The background features tall city buildings with glass windows and storefronts. There are banners hanging from streetlights, and some greenery is visible in the distance. The overall impression is one of incongruity—performing a domestic chore like ironing in the middle of a chaotic urban environment.
```

**Video Understanding:**

```python Example theme={null}
response = client.chat.completions.create(
    model="XiaomiMiMo/MiMo-V2.5",
    messages=[{
        "role": "user",
        "content": [
            {"type": "video_url", "video_url": {"url": "https://videos.pexels.com/video-files/4114797/4114797-uhd_3840_2160_25fps.mp4"}},
            {"type": "text", "text": "Summarize what happens in this video."}
        ]
    }]
)

print(response.choices[0].message.content)
```

**Output Example:**

```text theme={null}
A person wearing blue protective gloves is shown operating a microscope in a close-up shot. The individual is adjusting a knob on the side of the microscope, which moves the stage holding a glass slide, likely focusing the lens on the specimen.
```

> Video decoding requires `decord` (`pip install decord`); SGLang's MiMo-V2.5 multimodal processor uses `decord.VideoReader` for frame extraction.

**Audio Understanding:**

```python Example theme={null}
response = client.chat.completions.create(
    model="XiaomiMiMo/MiMo-V2.5",
    messages=[{
        "role": "user",
        "content": [
            {"type": "audio_url", "audio_url": {"url": "https://raw.githubusercontent.com/sgl-project/sgl-test-files/refs/heads/main/audios/Trump_WEF_2018_10s.mp3"}},
            {"type": "text", "text": "Transcribe and summarize this audio."}
        ]
    }]
)

print(response.choices[0].message.content)
```

**Output Example:**

```text theme={null}
**Transcript:**
"Thank you Klaus very much. It's a privilege to be here at this forum where leaders in business, science, art, diplomacy and world affairs have gathered for..."

**Summary:**
The speaker thanks Klaus for the introduction and expresses their honor at attending a forum. They highlight that the event has brought together high-level leaders from various sectors, including business, science, art, and diplomacy.
```

### 4.4 Tool Calling

```python Example theme={null}
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:30000/v1",
    api_key="EMPTY"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="XiaomiMiMo/MiMo-V2.5",
    messages=[{"role": "user", "content": "What's the weather in Beijing?"}],
    tools=tools
)

msg = response.choices[0].message
if msg.reasoning_content:
    print("=== Reasoning ===")
    print(msg.reasoning_content)
if msg.tool_calls:
    print("=== Tool Calls ===")
    for tc in msg.tool_calls:
        print(f"  Function: {tc.function.name}")
        print(f"  Arguments: {tc.function.arguments}")
```

**Output Example (MiMo-V2.5):**

```text theme={null}
=== Reasoning ===
The user wants to know the weather in Beijing. I have a function available called "get_weather" that can retrieve current weather for a location. Let me call that function with Beijing as the location.
=== Tool Calls ===
  Function: get_weather
  Arguments: {"location": "Beijing"}
```

## 5. Benchmark

Accuracy numbers come from `sglang.test.run_eval` (GSM8K standard 5-shot, MMMU validation split). Speed numbers come from `sglang.bench_serving` with generated random prompts; text runs use 1024 input tokens and 1024 output tokens per request, and the image run uses 2 random 720p images per request.

### 5.1 Accuracy Benchmark

#### 5.1.1 GSM8K

Standard 5-shot, `temperature=0`, `max_tokens=4096`, model defaults to thinking-on (responses contain `...` and the eval extracts the trailing number via regex). Server launch: see [Section 3](#3-model-deployment).

**Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --model XiaomiMiMo/MiMo-V2.5 \
  --num-examples 200 \
  --num-threads 8 \
  --max-tokens 4096 \
  --temperature 0.0
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

> `run_eval.py` automatically appends `/v1` to `--base-url`; pass the bare `host:port` URL (without trailing `/v1`), otherwise requests resolve to `/v1/v1/chat/completions` and 404.

* **Test Results:**
  * MiMo-V2.5-Pro (FP8, 8× B200)
    ```
    Score:             0.965  (193 / 200)
    Latency:           253.90 s
    Output throughput: 461.78 tok/s
    ```
  * MiMo-V2.5 (FP8, 8× H200)
    ```
    Score:             0.980  (196 / 200)
    Latency:           477.52 s
    Output throughput: 88.9 tok/s
    ```

#### 5.1.2 MMMU (V2.5 only)

`MMMU/MMMU` validation split (multi-discipline multimodal), `concurrency=16`, default sampling.

* **Benchmark Command:**

```shell Command theme={null}
python3 benchmark/mmmu/bench_sglang.py \
  --port 30000 \
  --model XiaomiMiMo/MiMo-V2.5 \
  --concurrency 16
```

* **Test Results:**
  * MiMo-V2.5 (FP8)
    ```
    Pending update
    ```

### 5.2 Speed Benchmark — MiMo-V2.5-Pro

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8×)
* Model: `XiaomiMiMo/MiMo-V2.5-Pro` (FP8)
* Tensor Parallelism: 8 (single-node, `--moe-runner-backend flashinfer_trtllm`, `--attention-backend fa4`, `--mem-fraction-static 0.8`, `--swa-full-tokens-ratio 0.1`)
* Recipe: Blackwell verified baseline (EAGLE off for this benchmark — see note below)
* sglang version: 0.5.11

> The numbers in §5.2 are the **no-EAGLE baseline** on `random 1024/1024`. On uniform-random token streams the MiMo-V2.5-Pro 3-layer MTP draft has very low accept-rate (\~0.13–0.27 vs \~0.75 on natural-text prompts, see §5.4) — there's no token-co-occurrence signal for the draft to model — so EAGLE here adds verify overhead without recovering enough draft tokens to be a net win on this workload. EAGLE MTP itself works on B200 + `--enable-multi-layer-eagle` (see §3 deployment command and §5.4 for an acceptance profile on natural text).

#### 5.2.1 Latency-Sensitive Benchmark

* **Model Deployment Command:** see the [command panel above](#3-model-deployment).
* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model XiaomiMiMo/MiMo-V2.5-Pro \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  27.59
Total input tokens:                      1997
Total input text tokens:                 1997
Total generated tokens:                  2798
Total generated tokens (retokenized):    2794
Request throughput (req/s):              0.36
Input token throughput (tok/s):          72.38
Output token throughput (tok/s):         101.41
Peak output token throughput (tok/s):    110.00
Peak concurrent requests:                3
Total token throughput (tok/s):          173.79
Concurrency:                             1.00
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2757.26
Median E2E Latency (ms):                 3319.10
P90 E2E Latency (ms):                    4157.47
P99 E2E Latency (ms):                    4869.32
---------------Time to First Token----------------
Mean TTFT (ms):                          162.17
Median TTFT (ms):                        68.11
P99 TTFT (ms):                           929.58
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          9.19
Median TPOT (ms):                        9.33
P99 TPOT (ms):                           9.39
---------------Inter-Token Latency----------------
Mean ITL (ms):                           9.31
Median ITL (ms):                         9.35
P95 ITL (ms):                            9.44
P99 ITL (ms):                            9.77
Max ITL (ms):                            19.80
==================================================
```

#### 5.2.2 Throughput-Sensitive Benchmark

* **Model Deployment Command:** see the [command panel above](#3-model-deployment).
* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model XiaomiMiMo/MiMo-V2.5-Pro \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  112.78
Total input tokens:                      302118
Total input text tokens:                 302118
Total generated tokens:                  195775
Total generated tokens (retokenized):    191069
Request throughput (req/s):              8.87
Input token throughput (tok/s):          2678.83
Output token throughput (tok/s):         1735.90
Peak output token throughput (tok/s):    3040.00
Peak concurrent requests:                121
Total token throughput (tok/s):          4414.73
Concurrency:                             87.80
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   9901.96
Median E2E Latency (ms):                 6525.54
P90 E2E Latency (ms):                    23567.98
P99 E2E Latency (ms):                    42109.22
---------------Time to First Token----------------
Mean TTFT (ms):                          223.69
Median TTFT (ms):                        139.45
P99 TTFT (ms):                           1082.02
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          50.63
Median TPOT (ms):                        51.66
P99 TPOT (ms):                           91.41
---------------Inter-Token Latency----------------
Mean ITL (ms):                           49.79
Median ITL (ms):                         33.69
P95 ITL (ms):                            103.37
P99 ITL (ms):                            151.34
Max ITL (ms):                            1600.00
==================================================
```

### 5.3 Speed Benchmark — MiMo-V2.5

**Test Environment:**

* Hardware: NVIDIA H200 GPU (8×)
* Model: `XiaomiMiMo/MiMo-V2.5` (FP8)
* Tensor Parallelism: 8 (DP-attention with `--attn-dp-size 2`)
* Recipe: Balanced (DP-attn + EAGLE MTP)
* sglang version: `0.0.0.dev1+g7d99af439` (`lmsysorg/sglang:dev-mimo-v2.5`)

#### 5.3.1 Latency-Sensitive Benchmark

* **Model Deployment Command:** select MiMo-V2.5, H200, and EAGLE MTP in the [command panel above](#3-model-deployment).
* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model XiaomiMiMo/MiMo-V2.5 \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  14.72
Total input tokens:                      1997
Total input text tokens:                 1997
Total generated tokens:                  2798
Total generated tokens (retokenized):    2697
Request throughput (req/s):              0.68
Input token throughput (tok/s):          135.67
Output token throughput (tok/s):         190.09
Peak output token throughput (tok/s):    245.00
Peak concurrent requests:                3
Total token throughput (tok/s):          325.77
Concurrency:                             1.00
Accept length:                           3.08
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   1469.98
Median E2E Latency (ms):                 1652.84
P90 E2E Latency (ms):                    2210.80
P99 E2E Latency (ms):                    2823.86
---------------Time to First Token----------------
Mean TTFT (ms):                          143.89
Median TTFT (ms):                        99.25
P99 TTFT (ms):                           481.01
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          4.87
Median TPOT (ms):                        4.30
P99 TPOT (ms):                           6.64
---------------Inter-Token Latency----------------
Mean ITL (ms):                           4.76
Median ITL (ms):                         3.46
P95 ITL (ms):                            13.52
P99 ITL (ms):                            13.84
Max ITL (ms):                            74.37
==================================================
```

#### 5.3.2 Throughput-Sensitive Benchmark

* **Model Deployment Command:** select MiMo-V2.5, H200, and EAGLE MTP in the [command panel above](#3-model-deployment).
* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --host 127.0.0.1 \
  --port 30000 \
  --model XiaomiMiMo/MiMo-V2.5 \
  --random-input-len 1024 \
  --random-output-len 1024 \
  --num-prompts 1000 \
  --max-concurrency 100
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang
Traffic request rate:                    inf
Max request concurrency:                 100
Successful requests:                     1000
Benchmark duration (s):                  93.41
Total input tokens:                      302118
Total input text tokens:                 302118
Total generated tokens:                  195775
Total generated tokens (retokenized):    188139
Request throughput (req/s):              10.71
Input token throughput (tok/s):          3234.48
Output token throughput (tok/s):         2095.97
Peak output token throughput (tok/s):    3019.00
Peak concurrent requests:                121
Total token throughput (tok/s):          5330.45
Concurrency:                             91.04
Accept length:                           2.95
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   8503.45
Median E2E Latency (ms):                 7491.96
P90 E2E Latency (ms):                    13706.99
P99 E2E Latency (ms):                    20474.33
---------------Time to First Token----------------
Mean TTFT (ms):                          4399.20
Median TTFT (ms):                        4333.35
P99 TTFT (ms):                           8004.81
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          58.23
Median TPOT (ms):                        21.78
P99 TPOT (ms):                           747.79
---------------Inter-Token Latency----------------
Mean ITL (ms):                           20.06
Median ITL (ms):                         15.28
P95 ITL (ms):                            48.36
P99 ITL (ms):                            96.99
Max ITL (ms):                            969.61
==================================================
```

#### 5.3.3 Multimodal (Image) Benchmark

* **Model Deployment Command:** select MiMo-V2.5, H200, and EAGLE MTP in the [command panel above](#3-model-deployment).
* Benchmark Command:

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang-oai-chat \
  --host 127.0.0.1 \
  --port 30000 \
  --model XiaomiMiMo/MiMo-V2.5 \
  --dataset-name image \
  --image-count 2 \
  --image-resolution 720p \
  --random-input-len 128 \
  --random-output-len 1024 \
  --num-prompts 10 \
  --max-concurrency 1
```

* **Test Results:**

```text Output theme={null}
============ Serving Benchmark Result ============
Backend:                                 sglang-oai-chat
Traffic request rate:                    inf
Max request concurrency:                 1
Successful requests:                     10
Benchmark duration (s):                  25.73
Total input tokens:                      661
Total input text tokens:                 631
Total input vision tokens:               30
Total generated tokens:                  4220
Total generated tokens (retokenized):    0
Request throughput (req/s):              0.39
Input token throughput (tok/s):          25.69
Output token throughput (tok/s):         164.03
Peak output token throughput (tok/s):    1.00
Peak concurrent requests:                2
Total token throughput (tok/s):          189.73
Concurrency:                             1.00
Accept length:                           2.94
----------------End-to-End Latency----------------
Mean E2E Latency (ms):                   2570.74
Median E2E Latency (ms):                 2411.92
P90 E2E Latency (ms):                    3711.62
P99 E2E Latency (ms):                    4949.74
---------------Time to First Token----------------
Mean TTFT (ms):                          0.00
Median TTFT (ms):                        0.00
P99 TTFT (ms):                           0.00
-----Time per Output Token (excl. 1st token)------
Mean TPOT (ms):                          7.31
Median TPOT (ms):                        6.17
P99 TPOT (ms):                           17.18
---------------Inter-Token Latency----------------
Mean ITL (ms):                           0.00
Median ITL (ms):                         0.00
P95 ITL (ms):                            0.00
P99 ITL (ms):                            0.00
Max ITL (ms):                            0.00
==================================================
```

### 5.4 Multi-Layer EAGLE Acceptance Profile — MiMo-V2.5-Pro

Pro's 3-layer MTP behaves very differently on natural text vs uniform-random token streams. The §5.2 benchmarks use `random 1024/1024`, which collapses accept-rate; this section measures the same server on GSM8K so the acceptance number is comparable to real workloads.

**Test Environment:**

* Hardware: NVIDIA B200 GPU (8×)
* Model: `XiaomiMiMo/MiMo-V2.5-Pro` (FP8)
* Tensor Parallelism: 8 (single-node, `--moe-runner-backend flashinfer_trtllm`, `--attention-backend fa4`, `--mem-fraction-static 0.8`, `--swa-full-tokens-ratio 0.1`)
* Recipe: 3-layer EAGLE — `--enable-multi-layer-eagle --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4` (top-1, max accept length 4)

**Benchmark Command:**

```shell Command theme={null}
sgl-eval run gsm8k \
  --base-url http://127.0.0.1:30000/v1 \
  --model XiaomiMiMo/MiMo-V2.5-Pro \
  --num-examples 200 \
  --num-threads 4
```

The command above uses sgl-eval. Historical scores from other harnesses are not directly comparable; rerun this command for a matching result.

The `accept_rate` and `accept_length` rows below are not part of `run_eval`'s own output — they were aggregated from the server-side `Decode batch ... accept rate: X accept len: Y` log lines emitted during the GSM8K run (307 batches total).

| Workload | accept\_rate | accept\_length (max = 4) |
| - | - | - |
| GSM8K (natural text) | **0.755** | **3.27** |
| `random 1024/1024` (reference) | 0.13–0.27 | \~1.x |

GSM8K Score: **0.97** (194 / 200), output throughput ≈ 635 tok/s end-to-end on this single-server run.

The accept-rate gap is intrinsic to MTP-style speculative decoding: the draft model is trained on natural-language token distributions and has no useful signal on uniform-random byte sequences. Workloads with structure (chat, code, reasoning traces) should expect the GSM8K-class number; the random-prompt baseline in §5.2 is a worst case for draft acceptance.

### 5.5 Long-Context Prefill & MTP Decode — MiMo-V2.5-Pro (Reference)

Reference numbers from the [day0 enablement PR](https://github.com/sgl-project/sglang/pull/23808), collected on a 2-node Hopper deployment with the **EP=16, DP=2, TP=16** recipe (`--moe-a2a-backend deepep`, `--attention-backend fa3`, `--enable-multi-layer-eagle`). The setup, parallelism, and benchmark methodology all differ from §5.2 (Blackwell TP=8 with `random 1024/1024`), so treat these as a separate operating point — long-context prefill scaling and the MTP decode speedup — rather than a comparison against §5.2.

**Test Environment:**

* Hardware: NVIDIA Hopper GPU (2 nodes × 8 GPUs, GPU SKU intentionally not disclosed)
* Model: `XiaomiMiMo/MiMo-V2.5-Pro` (FP8)
* Parallelism: `--tp 16 --attn-dp-size 2 --ep 16 --moe-dense-tp-size 1`
* Recipe: Hopper EP16 (DeepEP + EAGLE multi-layer MTP)

#### 5.5.1 Long-Context Prefill Throughput

Test setting: `chunked_prefill_size=32K`, `random_output_len=1`, cache flushed before every run. For input lengths ≥ 512K the workload was split into two requests routed to distinct DP ranks and the per-node throughput was read from `bench_serving` output.

* **Benchmark Command:**

```shell Command theme={null}
python3 -m sglang.bench_serving \
  --backend sglang \
  --model XiaomiMiMo/MiMo-V2.5-Pro \
  --host 0.0.0.0 \
  --port 30000 \
  --dataset-name random \
  --random-input-len  \
  --random-output-len 1 \
  --random-range-ratio 1.0 \
  --flush-cache \
  --seed 12345 \
  --num-prompts 10000
```

* **Test Results** — single-node prefill throughput, cache-miss:

| Input length | Output length | Single-node prefill throughput |
| - | - | - |
| 4K | 1 | 30.80K tok/s |
| 8K | 1 | 30.65K tok/s |
| 16K | 1 | 29.85K tok/s |
| 32K | 1 | 28.60K tok/s |
| 64K | 1 | 26.65K tok/s |
| 128K | 1 | 23.00K tok/s |
| 256K | 1 | 17.90K tok/s |
| 512K | 1 | 11.30K tok/s |
| 768K | 1 | 9.40K tok/s |
| 1M | 1 | 7.30K tok/s |

Prefill throughput stays within \~10% of peak from 4K up to 32K and degrades gracefully past 128K, confirming the hybrid SWA+GA attention works correctly at 1M context.

#### 5.5.2 Decode Throughput — MTP Speedup

Test setting: fixed **16K input / 1K output**, varying batch size per DP rank, with and without the 3-layer MTP module. `MTP accept length` is the average number of draft tokens accepted per step under EAGLE speculative decoding. **TPS** below is per-request output tokens/sec (i.e. single-user perceived speed); the rightmost column is aggregated single-node decode throughput (= TPS × batch size).

* **Test Results** — single-node decode throughput:

| BS per DP rank | MTP | MTP accept length | Per-request TPS | Single-node decode throughput |
| - | - | - | - | - |
| 64 | disabled | - | 29.3 | 1875 tok/s |
| 64 | 3-layer | 3 | 60.5 | 3873 tok/s |
| 64 | 3-layer | 4 | 79.7 | 5103 tok/s |
| 96 | disabled | - | 26.7 | 2564 tok/s |
| 96 | 3-layer | 3 | 50.4 | 4840 tok/s |
| 96 | 3-layer | 4 | 64.8 | 6225 tok/s |

**Summary — MTP on / off:**

| BS per DP rank | Without MTP | 3-layer MTP, accept=3 | 3-layer MTP, accept=4 |
| - | - | - | - |
| 64 | 1875 tok/s | 3873 tok/s (2.07×) | 5103 tok/s (2.72×) |
| 96 | 2564 tok/s | 4840 tok/s (1.89×) | 6225 tok/s (2.43×) |

The 3-layer MTP module delivers \~2× decode throughput at accept length 3 and \~2.5–2.7× at accept length 4 — the same order of magnitude as the "2–3× decode speedup" guidance in §3.2.


# MiMo-V2.6
Source: https://docs.sglang.io/cookbook/autoregressive/Xiaomi/MiMo-V2.6

Deploy MiMo-V2.6-Flash and Pro with SGLang on NVIDIA H200 and B300 GPUs, using MXFP4 MoE weights, BF16 routing, DFlash decoding, and a 1M-token context window.

## Deployment

The recipes below target **MiMo-V2.6-Flash on 4× H200 or B300** and **MiMo-V2.6-Pro on 8× H200 or B300**, each on a single node. Both use MXFP4 MoE weights, a BF16 MoE router, and DFlash speculative decoding.

> **Install SGLang with MiMo-V2.6 support**
>
> BF16 MoE routing and MXFP4 expert loading for MiMo V2.6 landed in [SGLang PR #40448](https://github.com/sgl-project/sglang/pull/40448) and are on `main`, so a recent nightly already carries them. Prepare an NVIDIA CUDA environment with FlashAttention 4, DeepGEMM, and DeepEP available. See the [installation guide](/docs/get-started/install) for platform prerequisites.
>
> **Python (source)**
>
> Install from source. The commit below is the revision these recipes were captured at; build from `main` instead if you want later fixes.
>
> ```bash Command theme={null}
> git clone https://github.com/sgl-project/sglang.git sglang-mimo-v2.6
> cd sglang-mimo-v2.6
> git checkout 983e643854f15cf9ef4370a49dfd74b6af54c3e3
> python3 -m pip install -e ./python
> ```
>
> Then run the **Python** command from the panel below. Checkpoint paths refer to directories on this host.
>
> **Docker (official image)**
>
> Pull the official nightly image, which already includes the MiMo-V2.6 support:
>
> ```bash Command theme={null}
> docker pull lmsysorg/sglang:dev
> ```

Select **Flash** or **Pro** to generate its command. Each variant has one base recipe; **Balanced** identifies that recipe and does not imply a measured throughput or latency optimum. The `/model/...` checkpoint and DFlash paths in the generated command are editable defaults, not download locations — set them to your own paths under **⚙ Env** before launching. Use the panel's cURL example to send a request to port **30000** after the server is ready.

## Playground

Experiment with reasoning and tool-call parsers, or disable speculative decoding for comparison. These overrides inherit the selected Flash or Pro recipe; they require separate validation. Parallelism and attention backends remain at the PR settings.

## 1. Model introduction

**MiMo-V2.6-Flash** is an open-source foundation model developed by Xiaomi. Its Mixture-of-Experts architecture has **309B total parameters and 15B activated per token**, with hybrid attention for computational efficiency. It supports a **1M-token context window** and **native multimodal capabilities**, and is designed for coding, visual understanding, general-purpose assistance, and research in agentic workflows, including complex tasks that require many steps.

**MiMo-V2.6-Pro** is Xiaomi's flagship foundation model, with **1.02T total parameters and 42B activated per token**, designed for demanding workloads. It also supports a **1M-token context window** and **native multimodal capabilities**, with an emphasis on coding, visual understanding, general-purpose assistance, research, and long-horizon agentic tasks.

Variant Total parameters Context window Recipe (H200 / B300)
MiMo-V2.6-Flash 309B (15B active) 1M tokens 4 GPUs, TP=EP=4
MiMo-V2.6-Pro 1.02T (42B active) 1M tokens 8 GPUs, TP=EP=8
**License:** MIT, continuing the MiMo-V2.5 licensing as confirmed by the model team. **Architecture references:** The [MiMo-V2.6-Flash-RL](https://huggingface.co/XiaomiMiMo/MiMo-V2.6-Flash-RL) and [MiMo-V2.6-Pro-RL](https://huggingface.co/XiaomiMiMo/MiMo-V2.6-Pro-RL) model cards document this generation directly — the hybrid sliding-window/global attention backbone, the omnimodal encoders, and the published evaluation scores — and each repository also ships the MiMo-V2.6 technical report. Both checkpoints declare `store_dtype: mxfp4` alongside `moe_router_dtype: bfloat16` in `config.json`, which is the expert-only MXFP4 quantization and BF16 routing these recipes depend on, and both carry the paired DFlash drafter in a `dflash/` subdirectory. ## 2. Configuration tips ### Parallelism and precision * **Flash:** `--tp 4 --ep 4`; **Pro:** `--tp 8 --ep 8`. Both keep `--dp 1 --pp-size 1`. TP and EP use the same GPU ranks; do not multiply them to determine the GPU count. * **MoE compute and communication:** Keep `--moe-runner-backend deep_gemm` on B300 and `--moe-runner-backend marlin` on H200, with `--moe-a2a-backend deepep --deepep-mode auto`, together with `--moe-dense-tp-size 1` and `--enable-dp-lm-head`, as in the PR. * **Precision:** MXFP4 describes the MoE expert weights, not the entire model. BF16 router weights are selected by the checkpoint's `moe_router_dtype`; the support commit computes router output logits in FP32. The PR relies on checkpoint quantization metadata and does not add a `--quantization` override. * **Attention:** Keep `--attention-backend fa4` and `--mm-attention-backend fa4` on both H200 and B300. The recipe also enables `--mm-enable-dp-encoder` for multimodal encoding. ### Context length and memory Both commands set `--context-length 1048576`. This is the configured per-request context limit; it does not establish that 64 simultaneous 1M-token requests fit in memory. Flash uses `--mem-fraction-static 0.6 --swa-full-tokens-ratio 0.03`; Pro uses `--mem-fraction-static 0.7 --swa-full-tokens-ratio 0.08`. The memory fraction budgets weights and KV cache, while the SWA ratio controls sliding-window versus full-attention KV allocation. Preserve these model-specific values for the base recipe. The shared prefill settings are `--chunked-prefill-size 49152 --max-prefill-tokens 65536`. Both commands cap running requests and decode CUDA-graph batch size at **64**, disable prefill CUDA graphs, and use page size **1**. `--enable-cache-report` and `--log-level-http warning` retain the PR's reporting settings. ### DFlash and caching The base recipe uses `--speculative-algorithm DFLASH --speculative-num-draft-tokens 8`. Supply the DFlash checkpoint paired with the selected target model; the draft path is independently editable and does not have to be a subdirectory of the target checkpoint. At the pinned commit, DFlash on NVIDIA GPUs requires PP=1 and rejects DP-attention. Do not set `--attn-dp-size` above 1 or copy EAGLE-specific settings from the V2.5 cookbook. ## 3. Reasoning and tool calling Both launch commands enable `--reasoning-parser mimo --tool-call-parser mimo`. The MiMo reasoning parser uses the request's `chat_template_kwargs.enable_thinking` setting: set it to `true` for reasoning or `false` for a direct answer. The command panel's cURL example enables reasoning explicitly. For OpenAI-compatible clients, read reasoning from `choices[0].message.reasoning_content`, the final answer from `choices[0].message.content`, and structured tool requests from `choices[0].message.tool_calls`. Preserve both reasoning and answer fields when inspecting responses. Use the checkpoint's generation defaults unless your application needs explicit sampling settings. Runtime throughput, latency, accuracy, and example responses for V2.6 will be added when measurements from these checkpoints are available. # Overview Source: https://docs.sglang.io/cookbook/autoregressive/intro Practical guides for deploying and using large language models and vision language models with SGLang. > **[Reflection](/cookbook/autoregressive/Reflection/Beam-1_0)** > **[IQuestLab](/cookbook/autoregressive/IQuestLab/IQuest-Q1)** > **[IFM](/cookbook/autoregressive/IFM/K2-Horizon)** > **[Kimi (Moonshot AI)](/cookbook/autoregressive/Moonshotai/Kimi-K3)** > **[Thinking Machines](/cookbook/autoregressive/ThinkingMachines/Inkling)** > **[GigaChat](/cookbook/autoregressive/GigaChat/GigaChat3.5)** > **[GLM](/cookbook/autoregressive/GLM/GLM-5.3-Flash)** > **[Qwen](/cookbook/autoregressive/Qwen/Qwen3.8-Flash-Next)** > **[DeepSeek](/cookbook/autoregressive/DeepSeek/DeepSeek-V4_1)** > **[DeepReinforce](/cookbook/autoregressive/DeepReinforce/Ornith-1.5)** > **[Meta](/cookbook/autoregressive/Meta/MuseSparkOpen)** > **[Meituan](/cookbook/autoregressive/Meituan/LongCat-2.0)** > **[Google](/cookbook/autoregressive/Google/Gemma4)** > **[IBM](/cookbook/autoregressive/IBM/Granite-4.2)** > **[LiquidAI](/cookbook/autoregressive/LiquidAI/LFM2.5)** > **[OpenAI](/cookbook/autoregressive/OpenAI/GPT-OSS)** > **[MiniMax](/cookbook/autoregressive/MiniMax/MiniMax-M3.1)** > **[NVIDIA](/cookbook/autoregressive/NVIDIA/Nemotron3.5-Super)** > **[Baidu](/cookbook/autoregressive/Baidu/PaddleOCR-VL)** > **[Ernie](/cookbook/autoregressive/Ernie/Ernie4.5)** > **[StepFun](/cookbook/autoregressive/StepFun/Step-5-Preview)** > **[InclusionAI](/cookbook/autoregressive/InclusionAI/Ling-3.1-flash)** > **[InternLM](/cookbook/autoregressive/InternLM/Intern-S2-Mobius)** > **[InternVL](/cookbook/autoregressive/InternVL/InternVL3.5)** > **[OpenBMB](/cookbook/autoregressive/OpenBMB/MiniCPM-V-4_7)** > **[Jina AI](/cookbook/autoregressive/Jina/Jina-reranker-m0)** > **[Mistral](/cookbook/autoregressive/Mistral/Ministral-3)** > **[Xiaomi](/cookbook/autoregressive/Xiaomi/MiMo-V2.6)** > **[FlashLabs](/cookbook/autoregressive/FlashLabs/Chroma1.0)** > **[Tencent](/cookbook/autoregressive/Tencent/Hy4-Preview)** > **[Recursive](/cookbook/autoregressive/Recursive/Flint)** > **[Poolside](/cookbook/autoregressive/Poolside/Laguna-S-2.1)** > **[Perplexity](/cookbook/autoregressive/Perplexity/PPLX-Decider-v1.1-27B)** > **[Cloudflare](/cookbook/autoregressive/Cloudflare/clef)** > **[Kev](/cookbook/autoregressive/Kev/kev)** # Autoregressive Model Benchmark Documentation Source: https://docs.sglang.io/cookbook/base/benchmarks/autoregressive_model_benchmark `sglang.bench_serving` is a command-line tool designed to benchmark the online serving throughput and latency of Large Language Models (LLMs) and Vision Language Models(VLMs). It supports various backends (`SGLang`, `vLLM`, etc.) and offers flexible configurations for request rates, dataset types, and profiling. ## 1. Quick Start ### Basic Usage (Random Data) Run a benchmark using randomly generated prompts with a local SGLang server. ```bash Command theme={null} python -m sglang.bench_serving --backend sglang --port 30000 --dataset-name random --num-prompts 100 ``` ### Real-World Data (ShareGPT) Run a benchmark using the ShareGPT dataset with a specific request rate. ```shell Command theme={null} python -m sglang.bench_serving \ --backend sglang \ --dataset-name sharegpt \ --dataset-path ./ShareGPT_V3_unfiltered_cleaned_split.json \ --num-prompts 1000 \ --request-rate 10 ``` ## 2. Parameter Reference ### 2.1 Backend & Server Configuration These parameters define the target server and the inference engine being used.
Parameter Description
`--backend` **Required.** Specifies the backend engine. Options: `sglang`, `sglang-native`, `sglang-oai`, `sglang-oai-chat`, `vllm`, `vllm-chat`, `lmdeploy`, `lmdeploy-chat`, `trt`, `gserver`, `truss`.
`--base-url` The API base URL (if not using specific host/port flags).
`--host` Server hostname. Default: `0.0.0.0`.
`--port` Server port. If not set, it defaults to the specific backend's standard port.
`--model` Model name or path. If unset, it queries `/v1/models` for configuration.
`--served-model-name` The model name used in the API request body. Defaults to the value of `--model`.
`--tokenizer` Path or name of the tokenizer. Defaults to the model configuration.
### 2.2 Dataset Configuration Controls the source of the prompts used for benchmarking.
Parameter Description
`--dataset-name` The type of dataset. Options: `sharegpt`, `custom`, `random`, `random-ids`, `generated-shared-prefix`, `mmmu`, `image`, `mooncake`.
`--dataset-path` File path to the dataset (e.g., local JSON file for ShareGPT).
`--num-prompts` Total number of prompts to process. Default: `1000`.
`--seed` Random seed for reproducibility.
`--tokenize-prompt` Uses integer IDs instead of strings for inputs. Useful for precise length control.
### 2.3 Input/Output Length Control Parameters to control the shape of requests (context length and generation length). #### For Random/Image Datasets: * `--random-input-len`: Number of input tokens per request. * `--random-output-len`: Number of output tokens per request. * `--random-range-ratio`: Range ratio for sampling input/output lengths. #### For ShareGPT Dataset: * `--sharegpt-output-len`: Overrides the output length defined in the dataset for each request. * `--sharegpt-context-len`: Max context length. Requests exceeding this are dropped. #### General Request Modifiers: * `--extra-request-body`: Appends a JSON object to the request payload (e.g., \{"key": "value"}). Useful for passing sampling parameters. * `--prompt-suffix`: A string suffix appended to all user prompts. * `--disable-ignore-eos`: If set, the model will stop generation upon hitting the EOS token (benchmarks usually ignore EOS to force max generation length). * `--apply-chat-template`: Applies the model's chat template to the input. ### 2.4 Traffic & Concurrency Controls how fast requests are sent to the server.
Parameter Description
`--request-rate` Requests per second (RPS). If `inf` (default), all requests are sent immediately (burst). Otherwise, arrival times follow a Poisson process.
`--max-concurrency` The maximum number of active requests allowed at once. Even if `request-rate` is high, the client will hold back requests if this limit is reached.
`--warmup-requests` Number of requests to run before the actual measurement begins to warm up the server.
`--flush-cache` Flushes the server cache before starting the benchmark.
### 2.5 Output & Logging
Parameter Description
`--output-file` Path to save the results in JSONL format.
`--output-details` Includes detailed metrics in the output.
`--print-requests` Prints requests to stdout as they are sent (useful for debugging).
`--disable-tqdm` Hides the progress bar.
`--disable-stream` Disables streaming mode (waits for full response).
`--return-logprob` Requests logprobs from the server.
`--tag` An arbitrary string tag added to the output file for identification.
### 2.6 Advanced #### 2.6.1 Image / Multi-modal Only applicable when --dataset-name is set to image. * `--image-count`: Number of images per request. * `--image-resolution`: Resolution (e.g., 1080p, 4k, or custom 1080x1920). * `--image-format`: jpeg or png. * `--image-content`: random (noise) or blank. #### 2.6.2 LoRA Benchmarking Used to simulate multi-LoRA serving scenarios. * `--lora-name`: A list of LoRA adapter names (e.g., `--lora-name` adapter1 adapter2). * `--lora-request-distribution`: How requests are assigned to adapters: * `uniform`: Equal probability. * `distinct`: New adapter for every request. * `skewed`: Follows a Zipf distribution (simulating hot/cold adapters). * `--lora-zipf-alpha`: The alpha parameter for the Zipf distribution (if `skewed` is used). #### 2.6.3 Profiling Tools for deep performance analysis. * `--profile`: Enables Torch Profiler (Requires `SGLANG_TORCH_PROFILER_DIR` env var on server). * `--plot-throughput`: Generates throughput/concurrency plots (requires `termplotlib` and `gnuplot`). * `--profile-activities`: Activities to profile (CPU, GPU, CUDA\_PROFILER). * `--profile-num-steps`: Number of steps to profile. * `--profile-by-stage` / `--profile-stages`: Profile specific processing stages. #### 2.6.4 PD Disaggregation For benchmarking Prefill-Decode (PD) separated architectures. * `--pd-separated`: Enable PD disaggregation benchmarking. * `--profile-prefill-url`: URL(s) of prefill workers for profiling. * `--profile-decode-url`: URL(s) of decode workers for profiling. Note: In PD mode, `prefill` and `decode` must be profiled separately. ### 2.7 Specialized Datasets #### 2.7.1 Generated Shared Prefix (GSP): Designed to test system prompt caching/prefix sharing performance. * `--gsp-num-groups`: Number of unique system prompts. * `--gsp-prompts-per-group`: How many user questions share the same system prompt. * `--gsp-system-prompt-len`: Length of the shared prefix. * `--gsp-fast-prepare`: Skips some statistics calculation for faster startup. #### 2.7.2 Mooncake Designed for trace replay. * `--mooncake-slowdown-factor`: Slows down the trace replay (e.g., 2.0 = 2x slower). * `--mooncake-num-rounds`: Number of conversation rounds (supports multi-turn). * `--use-trace-timestamps`: Schedules requests based on timestamps found in the trace file. ## 3. Metrics After running the benchmark, the tool generally reports: * `E2E` (End-to-End Latency): The total time from sending the request to receiving the final token. * `TTFT` (Time To First Token): The time between sending the request and seeing the first word appear. This represents the Prefill time (processing the image and text prompt). * `TPOT` (Time per Output Token): The average time it takes to generate one token (excluding the first one). This is calculated per request. * `ITL` (Inter-Token Latency): The time gap between two distinct streaming packets. While TPOT is an average, ITL measures the "jitter" or smoothness of the stream. # Diffusion Models Benchmark Documentation Source: https://docs.sglang.io/cookbook/base/benchmarks/diffusion_model_benchmark `sglang.multimodal_gen.benchmarks.bench_serving` is a command-line tool designed to benchmark the online serving throughput and latency of diffusion models. It selects the image or video API from the requested task and offers flexible configurations for request rates, dataset types, and profiling. ## 1. Quick Start ### 1.1 Benchmarking in Low Concurrency Run a benchmark on a local server (port 30000) generating 1 videos/images from the `vbench` dataset. ```bash Command theme={null} # For text to video: such as Wan2.2-T2V-A14B-Diffusers python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task text-to-video --num-prompts 1 --max-concurrency 1 # For image to video: such as Wan2.2-I2V-A14B-Diffusers python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task image-to-video --num-prompts 1 --max-concurrency 1 # For image-text to video: such as Wan2.2-TI2V-5B-Diffusers python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task image-to-video --num-prompts 1 --max-concurrency 1 # For text to image: such as Qwen-Image python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task text-to-image --num-prompts 1 --max-concurrency 1 # For image-text to image: such as Qwen-Image-Edit python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task image-to-image --num-prompts 1 --max-concurrency 1 ``` ### 1.2 Benchmarking in High Concurrency Run a benchmark on a local server (port 30000) generating 20 videos/images from the `vbench` dataset. ```bash Command theme={null} # For text to video: such as Wan2.2-T2V-A14B-Diffusers python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task text-to-video --num-prompts 20 --max-concurrency 20 # For image to video: such as Wan2.2-I2V-A14B-Diffusers python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task image-to-video --num-prompts 20 --max-concurrency 20 # For image-text to video: such as Wan2.2-TI2V-5B-Diffusers python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task image-to-video --num-prompts 20 --max-concurrency 20 # For text to image: such as Qwen-Image python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task text-to-image --num-prompts 20 --max-concurrency 20 # For image-text to image: such as Qwen-Image-Edit python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task image-to-image --num-prompts 20 --max-concurrency 20 ``` ## 2. Parameter Reference ### 2.1 Connection Settings
Argument Default Description
`--base-url` `None` Base URL of the server (e.g., `http://localhost:30000`). If specified, this overrides `--host` and `--port`.
`--host` `None` The server host (e.g., `127.0.0.1`).
`--port` `None` The server port.
`--model` `None` Model name or path.
### 2.2 Workload & Task Configuration
Argument Choices Description
`--task` `text-to-video`, `image-to-video`, `text-to-image`, `image-to-image`, `video-to-video` Defines the generation task when it cannot be inferred from the model metadata.
`--dataset` `vbench`, `random` The source of prompts/inputs.
`--dataset-path` `None` (Optional) Path to a local dataset file if not using built-in presets.
`--num-prompts` `None` The total number of prompts/requests to execute during the benchmark.
### 2.3 Generation Parameters
Argument Description
`--width` The target width for the generated image or video.
`--height` The target height for the generated image or video.
`--num-frames` Number of frames to generate (Specific to Video backends).
`--fps` Frames Per Second configuration (Specific to Video backends).
### 2.4 Concurrency & Load Control
Argument Description
`--request-rate` The number of requests initiated per second. If set to `inf`, all requests are sent immediately (burst). If set to a number, request arrival times follow a Poisson process.
`--max-concurrency` The maximum number of requests allowed to execute simultaneously. This simulates a semaphore or upstream limit. Even if `request-rate` is high, the actual processing rate is capped by this value.
### 2.5 Logging & Output
Argument Description
`--output-file` Path to save the benchmark metrics (JSON format).
`--disable-tqdm` If set, disables the progress bar in the console.
## 3. Metrics * `Request Throughput` (req/s), Output Throughput (tok/s) * `Latency Mean` (ms): Time to Per Step * `Peak Memory Max` (ms): Max Memory Usage during running # Server Arguments Source: https://docs.sglang.io/cookbook/base/reference/server_arguments This guide explains the parallelism configuration fields used in SGLang model configurations and how they map to SGLang server command-line arguments. ## Quick Reference
Config Field SGLang CLI Argument Description
`tp` `--tp-size`, `--tensor-parallel-size` Tensor Parallelism - splits model across GPUs
`dp` `--dp-size`, `--data-parallel-size` Data Parallelism - runs multiple model replicas
`ep` `--ep-size`, `--expert-parallel-size`, `--ep` Expert Parallelism - distributes MoE experts
`attn_dp_size` `--attn-dp-size`, `--attention-data-parallel-size` Attention Data Parallelism - data-parallel attention groups inside the TP group, TP for FFN (hybrid)
`enable_dp_attention` `--enable-dp-attention` **Deprecated.** Use `--attn-dp-size ` instead of `--dp-size --enable-dp-attention`.
# Anima Source: https://docs.sglang.io/cookbook/diffusion/CircleStone/Anima Deploy Anima Base v1.0 with SGLang Diffusion for anime and illustration generation, using native components and single- or multi-GPU execution. ## 1. Quick start On Linux with NVIDIA CUDA, use a nightly Docker image containing this integration, or install from source, following the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation). Run the commands below inside that environment. Use the official `circlestone-labs/Anima-Base-v1.0-Diffusers` checkpoint. SGLang reads its `modular_model_index.json` directly; no checkpoint conversion or newer Diffusers runtime is required. Start with **Resident + Compiled** for repeated generation on RTX 5090, DGX Spark, or H200. Select **Eager** for shorter startup or frequent shape changes. Spark's 128 GB is unified memory shared with the CPU, not dedicated VRAM. See the [measurements and tradeoffs](#5-measured-tuning) below. ## 2. Model capabilities [Anima](https://huggingface.co/circlestone-labs/Anima) is CircleStone Labs and Comfy Org's text-to-image model for anime and illustration. It combines a Cosmos Predict2 transformer with Qwen3 text encoding, a learned T5-token conditioner, and a Qwen-Image VAE. Prompts can combine tags with natural-language descriptions. This integration targets **Base v1.0 text-to-image**. It does not claim support for the separate Aesthetic or Turbo checkpoints, single-file ComfyUI weights, or image editing. The checkpoint uses the CircleStone Labs Non-Commercial License; review the [official license](https://huggingface.co/circlestone-labs/Anima/blob/main/LICENSE.md) before deployment. ## 3. Sampling Defaults are 1024 x 1024, 30 steps, guidance scale 4, and an empty negative prompt. Width and height should be divisible by 16. `max_sequence_length` defaults to 512 and accepts 1 through 4096. The text conditioner pads short sequences to 512 tokens; these padding positions remain part of the transformer's cross-attention, matching the official implementation. For offline generation: ```bash Generate theme={null} sglang generate \ --model-path circlestone-labs/Anima-Base-v1.0-Diffusers \ --prompt "masterpiece, best quality, safe, watercolor landscape, a quiet seaside village at sunset" \ --seed 42 \ --save-output ``` Use the same seed, generator device, dimensions, scheduler settings, and precision when comparing runtimes. Latents and scheduler updates remain FP32; the transformer, text components, and VAE default to BF16. Different attention kernels can produce small floating-point differences that accumulate during denoising. ## 4. Runtime features The pipeline reuses SGLang's native Qwen3 encoder, Qwen-Image VAE, component loaders, denoising loop, and residency management. Anima's transformer and text conditioner are native modules, not wrappers around Diffusers models. For multi-GPU execution, choose TP to shard transformer weights or Ulysses/Ring to shard image tokens. The transformer has 16 heads, so `tp_size * ulysses_degree` must divide 16. CFG parallelism additionally splits conditional and unconditional denoising and requires guidance greater than 1. The total GPU count must match the selected parallel topology. CPU and layerwise offload trade memory for transfers. The additional `text_conditioner` component accepts the same residency controls as other native components. Cache-DiT and quantized attention are approximate optimizations; assess image quality for your prompts before enabling them. See [performance optimization](/docs/sglang-diffusion/performance-optimization) for the shared controls. H200 functional checks cover TP, Ulysses, Ring, CFG parallelism, encoder folding, parallel tiled VAE decode, layerwise offload, FlashAttention, Torch SDPA, SageAttention, Cache-DiT, and breakable CUDA graphs. These checks are not a quality guarantee for approximate optimizations. Combined TP and SP, multi-node execution, non-NVIDIA devices, and third-party LoRAs remain unverified. Breakable CUDA graphs reuse the conditioner's actual sequence length, without additional text-bucket padding. Requests with uncaptured shapes fall back to eager execution. Standard short prompts use the same 512-token conditioning shape. ## 5. Measured tuning For repeated requests, compilation was faster than eager execution on all three tested platforms. The picker keeps eager available because initial compilation and recompilation for new shapes can take minutes and use additional CPU memory. No CPU offload, quantized attention, or Cache-DiT is enabled in the recommended recipes. The following are warm, sequential HTTP request medians: 1024 x 1024, 30 steps, CFG 4, one image, CPU generator, and PNG/base64 output. Startup is excluded. | GPU | Recommended recipe | Original eager | Recommended | Peak allocated | | - | - | - | - | - | | RTX 5090, 32 GB | cuDNN SDPA + compile, tiled VAE | 6.99 s | 6.10 s | 5.7 GiB | | DGX Spark, 128 GB unified | Torch SDPA + compile, tiled VAE | 26.03 s | 17.41 s | 5.6 GiB | | H200, 141 GB | FlashAttention + compile, untiled VAE | 3.22 s | 2.22 s | 10.2 GiB | Measurements used five timed requests after warmup, PyTorch 2.13.0+cu130, and the native Anima implementation at `214c9a48bb1` (Spark used `7f3f903f039`, with identical runtime code). Results are workload-specific, not throughput-at-saturation measurements. The original eager baseline uses Torch SDPA on 5090/Spark and FlashAttention on H200, with VAE tiling enabled. Peak allocated memory excludes the CUDA context, reserved pool, and compilation CPU memory; it is not total device usage. On **two NVLink-connected H200s**, Auto selects CFG parallelism instead of TP: the compiled, untiled recipe measured **1.28 s**. Untiled decoding trades about 4-5 GiB more allocated memory for lower latency and is verified at 1024 x 1024, one output. The tiled recipes additionally passed repeated 512 x 512 and 1536 x 1536 requests, plus two outputs at 1024 x 1024. Use **Tiled** for that verified scope. At 512 x 512, two-GPU CFG eager was faster than compiled; more GPUs or compilation are not universally better. The recommended recipes change floating-point kernels and, on H200, VAE tiling. They are **not pixel-identical to eager**: across three fixed prompt/seed pairs, the single-GPU recipes above measured PSNR 21.95-35.44 dB and SSIM 0.851-0.969 against their same-device eager outputs. These measure output differences, not perceptual quality guarantees. Use eager with the same backend and tiling settings when reproducing an eager reference. Breakable CUDA graphs were near parity at 1024 x 1024 while consuming about 1.2 GiB more allocated GPU memory for a single captured shape. They are not the default. Cache-DiT can accelerate further, but changes the denoising computation; validate it separately against your quality requirements. # Cosmos3 Source: https://docs.sglang.io/cookbook/diffusion/Cosmos/Cosmos3 Serve NVIDIA Cosmos3 image, video, sound, and action generation with SGLang Diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. Choose a [generation or policy request](#4-openai-compatible-requests) matching the checkpoint; the Request tab queries model metadata. > **Installation and prerequisites** > > Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation). Docker is recommended for Linux GPU deployments; run the commands below inside the container or your installed Python environment. > > Cosmos3 guardrails are enabled by default when the package is available: > > ```bash Command theme={null} > pip install "cosmos-guardrail==0.3.1" > ``` > > `cosmos-guardrail` downloads gated NVIDIA guardrail weights, so pass a Hugging Face token if your environment needs one. If the package is not installed, SGLang skips Cosmos3 guardrails and logs a warning. To disable Cosmos3 guardrails for local experiments, set `SGLANG_DISABLE_COSMOS3_GUARDRAILS=1` before starting the server. > > There may be problems loading the Cosmos-1.0-Guardrail weights on Ascend NPU. If the *\_pickle.UnpicklingError* error occurs during startup, you should change `weight_only=True` to `weights_only=False` parameter in *cosmos\_guardrail/cosmos\_utils.py*: > > ``` > #!/usr/bin/env bash > COSMOS_GUARDRAIL_DIR="$(dirname "$(python -c 'import cosmos_guardrail; print(cosmos_guardrail.__file__)')")" > sed -i 's/weights_only=True/weights_only=False/g' "$COSMOS_GUARDRAIL_DIR/cosmos_utils.py" > ``` ## 2. Model capabilities [NVIDIA Cosmos3](https://huggingface.co/collections/nvidia/cosmos3) is an omnimodal world-model family spanning text/image/video generation, optional synchronized sound, and robot action prediction. Its main advantage is breadth: the same native SGLang pipeline can serve media-generation checkpoints and the DROID policy checkpoint without routing through an LLM sampler. Choose Nano for the broadest modality coverage and lower deployment cost, Super for the larger 64B image/video model, and a specialized checkpoint when only T2I or I2V is needed. Sound and action are checkpoint-specific heads, so they are not available from every Cosmos3 repository. | Model | Status | Notes | | - | - | - | | `nvidia/Cosmos3-Nano` | Supported | T2I, T2V, I2V, V2V, joint sound, and action | | `nvidia/Cosmos3-Super` | Supported | T2I, T2V, I2V, and V2V; use multi-GPU for the 64B checkpoint | | `nvidia/Cosmos3-Super-Text2Image` | Supported | T2I-specialized checkpoint | | `nvidia/Cosmos3-Super-Image2Video` | Supported | I2V-specialized checkpoint | | `nvidia/Cosmos3-Nano-Policy-DROID` | Supported | DROID policy action generation | | `nvidia/Cosmos3-Edge` | Supported | 4B dense model for T2I, T2V, I2V, V2V, and action generation | | `nvidia/Cosmos3-Edge-Policy-DROID` | Supported | 4B DROID policy action generation | | `nvidia/Cosmos3-Super-Text2Image-4Step` | Supported | 64B T2I checkpoint distilled to a fixed 4-step schedule | | `nvidia/Cosmos3-Super-Image2Video-4Step` | Supported | 64B I2V checkpoint distilled to a fixed 4-step schedule | Sound and action generation require the corresponding checkpoint heads. The pipeline reads the transformer and scheduler configs at startup, so Edge and distilled checkpoints do not require architecture-specific server flags. Non-distilled checkpoints use the flow-native `FlowUniPCMultistepScheduler`; distilled checkpoints use the fixed sigma schedule stored in the checkpoint. The default `flow_shift` is `3.0` for T2I, `10.0` for non-Edge video and all action modes, and `3.0` for Edge video modes. Distilled checkpoints bake the schedule into their sigmas and do not use a request-level `flow_shift`. ## 3. Serve Cosmos3 For Intel Xeon CPU deployment, use `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu` with the selected Cosmos3 checkpoint. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu sglang serve --model-path nvidia/Cosmos3-Nano --port 30010 ``` Serve `Cosmos3-Nano` directly from the Hugging Face model ID: ```bash Command theme={null} sglang serve \ --model-path nvidia/Cosmos3-Nano \ --num-gpus 1 ``` With `--performance-mode auto`, Cosmos3 Nano keeps its DiT and VAE resident when every selected GPU has at least 90 GiB available at startup. Other Cosmos3 checkpoints use a 120 GiB threshold. Below the applicable threshold, auto mode retains the conservative DiT component-offload policy. Cosmos3 runs one DiT per pipeline, so component offload above the threshold only pays to copy the weights out to host memory and back on every request. Serve `Cosmos3-Super` across multiple GPUs as shown below so each rank holds a shard of the weights. For `Cosmos3-Super`, split the model across multiple GPUs: ```bash Command theme={null} sglang serve \ --model-path nvidia/Cosmos3-Super \ --num-gpus 4 ``` The server also accepts the specialized `nvidia/Cosmos3-Super-Text2Image` and `nvidia/Cosmos3-Super-Image2Video` checkpoint IDs. ### Edge checkpoints `Cosmos3-Edge` is a 4B dense model and can be served on one GPU: ```bash Command theme={null} sglang serve \ --model-path nvidia/Cosmos3-Edge \ --num-gpus 1 ``` Edge is trained for 256p and 480p generation. Its default video configuration is `832x480` with `guidance_scale=5.0`; its default image configuration is `640x640` with `guidance_scale=7.0`. Supported sizes are `832x480`, `480x832`, `640x480`, `480x640`, `480x480`, `640x640`, `448x256`, `256x448`, and `256x256`. Serve the Edge DROID policy checkpoint with the same single-GPU configuration, replacing the model path with `nvidia/Cosmos3-Edge-Policy-DROID`. ### Distilled checkpoints The distilled Super checkpoints are 64B models. Use multiple GPUs unless the complete model and request workload fit on one GPU: ```bash Command theme={null} sglang serve \ --model-path nvidia/Cosmos3-Super-Text2Image-4Step \ --num-gpus 4 ``` For distilled I2V, replace the model path with `nvidia/Cosmos3-Super-Image2Video-4Step`. SGLang detects both checkpoints from `scheduler/scheduler_config.json`, uses the checkpoint's fixed four-step sigma schedule, and forces `guidance_scale=1.0`. Do not tune `num_inference_steps` or `flow_shift` for these checkpoints. ### Simulation and multiview checkpoints These checkpoints use native pipelines with checkpoint-specific conditioning: | Checkpoint | Inputs | Rollout | | - | - | - | | `nvidia/Cosmos3-Nano-Sim-Bimanual` | Image, prompt, camera or robot actions | Causal chunks with committed KV history | | `nvidia/Cosmos3-Nano-Sim-Transfer` | Control video and prompt | Causal control-video transfer | | `nvidia/Cosmos3-Nano-Transfer-Auto` | Per-camera WSM clips and captions; optional LiDAR | Bidirectional multiview generation | | `nvidia/Cosmos3-Nano-Sim-Auto` | Per-camera WSM clips and captions; optional LiDAR | Causal multiview generation | For example, start the Bimanual server: ```bash theme={null} sglang serve --model-path nvidia/Cosmos3-Nano-Sim-Bimanual ``` Submit image-conditioned video requests through `/v1/videos`. Supply `action` rows according to the checkpoint's embodiment contract, selected by `domain_name` or `domain_id`. Native contracts accept raw rows with `action_normalization="contract"`; unified contracts require normalized 59-dimensional rows and default to `action_normalization="none"`. Without actions, Bimanual uses null-action conditioning. These pipelines predict video from actions, not actions from video; use the policy checkpoints above for action prediction. For realtime Bimanual sessions, add `--pipeline-class-name CosmosDreamsRealtimePipeline` and use [`/v1/realtime_video`](/docs/sglang-diffusion/realtime_models). Each tick consumes one action block and preserves causal KV history. Transfer-Auto and Sim-Auto take a `multiview` object with `views`, each containing `camera_key`, `control_path`, optional `vision_path`, and optional `prompt`. Joint checkpoints also accept `lidar`; set `lidar.decode=true` to return decoded range maps and previews. Outputs pack all frames of each camera consecutively, in request camera order. LiDAR uses built-in compiled FlexAttention by default. The optional NATTEN path requires a wheel matching your PyTorch/CUDA versions and `SGLANG_DIFFUSION_COSMOS3_LIDAR_USE_NATTEN=1`; it is not installed by default. Bimanual and Sim-Transfer support TP, but not SP or CFG parallelism. Transfer-Auto supports Ulysses without TP or Ring; Sim-Auto supports TP and Ulysses subject to the checkpoint's query/KV head divisibility, but not Ring or CFG parallelism. Causal pipelines use the exported fixed-step schedule and require guidance `1.0`. Use `--component-residency` for memory-constrained deployments. Joint checkpoints register `lidar_encoder` and `lidar_decoder` separately from the camera `vae`. Bimanual overlaps causal VAE decode only when the VAE is resident; offloaded VAEs use the final serial decode stage. History-window reduction and frustum retrieval change the attention context and are not lossless acceleration settings. ## 4. OpenAI-Compatible Requests ### Text to image Cosmos3 text-to-image uses `/v1/images/generations`. The default Cosmos3 image response is `b64_json`, matching vLLM-Omni's examples. ```bash Command theme={null} curl -sS -X POST http://127.0.0.1:30010/v1/images/generations \ -H "Content-Type: application/json" \ -d '{ "prompt": "A warehouse robot folds a blue cloth on a clean workbench.", "size": "1280x720", "n": 1, "num_inference_steps": 35, "guidance_scale": 6.0, "flow_shift": 3.0, "seed": 0, "extra_body": { "use_resolution_template": false, "guardrails": true } }' ``` With a server running `nvidia/Cosmos3-Super-Text2Image-4Step`, omit the scheduler controls and use `guidance_scale=1.0`: ```bash Command theme={null} curl -sS -X POST http://127.0.0.1:30010/v1/images/generations \ -H "Content-Type: application/json" \ -d '{ "prompt": "A warehouse robot folds a blue cloth on a clean workbench.", "size": "640x640", "n": 1, "guidance_scale": 1.0, "seed": 0, "extra_body": { "use_resolution_template": false, "guardrails": true } }' ``` ### Text to video with sound Use `/v1/videos` to create an asynchronous job, then poll the job and download the completed MP4. Set `generate_sound=true` to generate and mux a stereo 48 kHz audio track; omit it for a silent video. ```bash Command theme={null} job_id=$(curl -sS -X POST http://127.0.0.1:30010/v1/videos \ --form-string "prompt=A small warehouse robot moves a blue box across a clean floor." \ --form-string "negative_prompt=blurry, distorted, low quality" \ --form-string "size=1280x720" \ --form-string "num_frames=81" \ --form-string "fps=24" \ --form-string "num_inference_steps=35" \ --form-string "guidance_scale=4.0" \ --form-string "flow_shift=10.0" \ --form-string "generate_sound=true" \ --form-string "seed=42" \ --form-string 'extra_params={"guardrails":true,"use_resolution_template":false,"use_duration_template":false}' \ | python -c 'import json, sys; print(json.load(sys.stdin)["id"])') while true; do status=$(curl -sS "http://127.0.0.1:30010/v1/videos/${job_id}" \ | python -c 'import json, sys; print(json.load(sys.stdin)["status"])') [ "$status" = "completed" ] && break [ "$status" = "failed" ] && exit 1 sleep 1 done curl -sS -L "http://127.0.0.1:30010/v1/videos/${job_id}/content" \ -o cosmos3_t2v.mp4 ``` ### Image to video This mirrors the official `nvidia/Cosmos3-Nano` Hugging Face image-to-video example: ```python Python theme={null} import json import time from pathlib import Path import requests from huggingface_hub import snapshot_download base_url = "http://127.0.0.1:30010" model_dir = Path(snapshot_download("nvidia/Cosmos3-Nano")) asset_dir = model_dir / "assets" prompt = json.dumps(json.loads((asset_dir / "example_i2v_prompt.json").read_text())) negative_prompt = json.dumps( json.loads((asset_dir / "negative_prompt.json").read_text()) ) data = { "prompt": prompt, "negative_prompt": negative_prompt, "size": "1280x720", "num_frames": "189", "fps": "24", "num_inference_steps": "35", "guidance_scale": "6.0", "max_sequence_length": "4096", "flow_shift": "10.0", "seed": "1111", "extra_params": json.dumps( { "use_resolution_template": False, "use_duration_template": False, "guardrails": True, } ), } with (asset_dir / "example_i2v_input.jpg").open("rb") as image: response = requests.post( f"{base_url}/v1/videos", data=data, files={"input_reference": ("example_i2v_input.jpg", image, "image/jpeg")}, timeout=60, ) response.raise_for_status() video_id = response.json()["id"] while True: job = requests.get(f"{base_url}/v1/videos/{video_id}", timeout=30).json() if job["status"] == "completed": break if job["status"] == "failed": raise RuntimeError(job.get("error") or "Video generation failed") time.sleep(1) response = requests.get(f"{base_url}/v1/videos/{video_id}/content", timeout=300) response.raise_for_status() Path("cosmos3_i2v.mp4").write_bytes(response.content) ``` For the distilled I2V checkpoint, use the same API with a server running `nvidia/Cosmos3-Super-Image2Video-4Step`. The recommended request is 480p and does not specify scheduler controls: ```bash Command theme={null} job_id=$(curl -sS -X POST http://127.0.0.1:30010/v1/videos \ --form-string "prompt=A warehouse robot carefully places a blue box on a shelf." \ --form "input_reference=@first_frame.png;type=image/png" \ --form-string "size=832x480" \ --form-string "num_frames=189" \ --form-string "fps=24" \ --form-string "guidance_scale=1.0" \ --form-string "seed=42" \ --form-string 'extra_params={"guardrails":true,"use_resolution_template":false,"use_duration_template":false}' \ | python -c 'import json, sys; print(json.load(sys.stdin)["id"])') ``` Poll and download this job with the same status and content endpoints used by the T2V example. ### Video to video Upload a source video with `video_reference`. Cosmos3 keeps latent frames `[0, 1]` by default and generates the remaining frames. Use `condition_frame_indexes` to select different latent frames, and `condition_video_keep` to take conditioning frames from the start or end of the source. ```bash Command theme={null} job_id=$(curl -sS -X POST http://127.0.0.1:30010/v1/videos \ --form-string "prompt=A robotic arm pours liquid into a glass on a white tabletop." \ --form "video_reference=@robot_pouring.mp4;type=video/mp4" \ --form-string "size=1280x704" \ --form-string "num_frames=45" \ --form-string "fps=24" \ --form-string "num_inference_steps=35" \ --form-string "guidance_scale=6.0" \ --form-string 'condition_frame_indexes=[0,1]' \ --form-string "condition_video_keep=first" \ | python -c 'import json, sys; print(json.load(sys.stdin)["id"])') ``` Poll and download this job with the same status and content endpoints used by the T2V example. ### Action generation For DROID policy generation, start a single-GPU server with either the Nano or Edge policy checkpoint. Cosmos3 action generation does not currently support CFG or sequence parallelism. ```bash Command theme={null} sglang serve \ --model-path nvidia/Cosmos3-Nano-Policy-DROID \ --num-gpus 1 ``` Use `nvidia/Cosmos3-Edge-Policy-DROID` in the same command to serve the smaller 4B policy checkpoint. `policy` and `inverse_dynamics` return actions, so their canonical API is the synchronous `/v1/actions/generations` endpoint. The following request predicts a 16-step action chunk from one observation image. `action_horizon=16` maps to the model's `num_frames=17` convention. ```python Python theme={null} import base64 from pathlib import Path import requests image_b64 = base64.b64encode(Path("observation.png").read_bytes()).decode() response = requests.post( "http://127.0.0.1:30010/v1/actions/generations", json={ "input": { "task": "Put the pot to the left of the purple item.", "observation": { "image": {"b64_json": image_b64}, }, }, "parameters": { "action_mode": "policy", "action_horizon": 16, "domain_name": "droid_lerobot", "height": 480, "width": 832, "fps": 5, "num_inference_steps": 30, "guidance_scale": 1.0, "seed": 42, }, }, timeout=300, ) response.raise_for_status() action = response.json()["data"][0]["action"] print(action["shape"], action["values"]) ``` Use `GET /v1/actions/metadata` to inspect the action modes, default horizon, padded action dimension, and accepted observation modalities. Msgpack requests and the `/v1/actions/realtime` websocket use the same action envelope. To batch policy observations inside one request, opt in with a bounded batch size: ```bash Command theme={null} sglang serve \ --model-path nvidia/Cosmos3-Nano-Policy-DROID \ --num-gpus 1 \ --batching-max-size 4 ``` Send one image per observation as a list or `[B, H, W, C]` uint8 array in `input.input_reference`, and either one prompt per image or one scalar prompt to broadcast across the batch. Batched prompts must currently tokenize to the same length because Cosmos3 GEN cross-attention does not mask padded text K/V. All items in one request share the domain, resolution, action horizon, and denoise settings. The standard action envelope returns one `data[i]` item per input, each with action shape `[H, D]`. For a compact msgpack response containing one `[B, H, D]` array, set `runtime.response_format="raw"` and read the top-level `actions` field. For JSON, `input_reference` can be a list of base64 image payloads. For msgpack, it can be a packed uint8 numpy array directly: ```json JSON theme={null} { "input": { "prompt": ["pick up the block", "close the drawer"], "input_reference": [ {"b64_json": ""}, {"b64_json": ""} ] }, "parameters": { "action_mode": "policy", "domain_name": "droid_lerobot" } } ``` The batch size cannot exceed `--batching-max-size`; this keeps one request from bypassing the server's configured memory limit. Batching applies to `action_mode="policy"` only. A request seed controls the random stream for the whole batch, so a batched result is deterministic for that request but is not expected to be bit-exact with separately seeded B=1 requests. `inverse_dynamics` also uses `/v1/actions/generations`; set `action_mode="inverse_dynamics"` and pass an observation video URL or server-local path as `input.observation.video`. Select the embodiment head with `domain_name` or `domain_id`; set `raw_action_dim` explicitly when it cannot be inferred from the domain name. `forward_dynamics` is intentionally different: it consumes an action array and predicts video, so it remains on `/v1/videos`. Action-producing modes submitted to `/v1/videos` return HTTP 400 with the canonical action endpoint in the error message. ## 5. Cosmos3 Parameters Cosmos3 supports the standard SGLang video and image fields such as `size`, `num_frames`, `fps`, `num_inference_steps`, `guidance_scale`, `negative_prompt`, and `seed`. For distilled checkpoints, SGLang replaces `num_inference_steps` with the checkpoint's fixed four-step schedule and forces `guidance_scale=1.0`; negative-prompt CFG and request-level `flow_shift` do not apply. Top-level Cosmos3 request fields: * `max_sequence_length`: maximum text token length used by the Cosmos3 tokenizer. * `flow_shift`: per-request scheduler shift for non-distilled checkpoints. If omitted, SGLang uses `--flow-shift`, then the mode default (`3.0` for T2I, `10.0` for non-Edge video and all action modes, or `3.0` for Edge video). * `guidance_interval`: optional `[start, end]` noise interval for CFG. Non-distilled T2I defaults to `[400, 1000]`; video modes guide at every step. Cosmos3 omnimodal fields are accepted as extra JSON fields or multipart form fields: * `generate_sound`: generate a sound track whose duration follows `num_frames / fps`. * `sound_duration`: explicit sound duration in seconds; takes precedence over the derived duration. * `condition_frame_indexes`: V2V latent-frame indexes to keep from the source video; defaults to `[0, 1]`. * `condition_video_keep`: use the `first` or `last` source frames for V2V conditioning. * `action_mode`: `policy`, `forward_dynamics`, or `inverse_dynamics`. * `domain_name` / `domain_id`: select the action embodiment head. * `raw_action_dim`: number of active action dimensions; inferred for known domain names. * `action`: action array with shape `[T, D]`, required by `forward_dynamics`. * `action_fps`: action-token frame rate for temporal mRoPE; defaults to the video FPS. * `action_view_point`: viewpoint used in the structured action caption. * `action_normalization`: dataset normalization mode, such as `quantile`, `meanstd`, or `minmax`. Pass model-specific controls through `extra_body` with the OpenAI Python SDK. Raw JSON may keep them at the top level; multipart video requests should put them in the `extra_params` JSON object. The legacy image `extra_args` container remains accepted for compatibility, but new clients should use `extra_body`: * `use_duration_template`: whether to append SGLang's generated duration suffix to video prompts. * `use_resolution_template`: accepted for vLLM-Omni request compatibility. * `use_system_prompt`: whether to add the Cosmos3 system prompt to the chat template. * `guardrails` or `use_guardrails`: per-request guardrail toggle when the server started with guardrails enabled. ## 6. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Video`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # ERNIE-Image Source: https://docs.sglang.io/cookbook/diffusion/Ernie-Image/Ernie-Image Deploy ERNIE-Image and ERNIE-Image-Turbo with SGLang Diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. ## 2. Model capabilities [ERNIE-Image](https://huggingface.co/baidu/ERNIE-Image) is Baidu's text-to-image family with separate standard and Turbo checkpoints. The standard model is the quality-oriented path; Turbo is the lower-latency choice, and both load through SGLang's native `ErnieImagePipeline`. This integration currently targets text-only image generation rather than image editing or reference conditioning. Choose it for a straightforward single-GPU T2I deployment; use a dedicated editing model when preserving source-image structure is part of the task. | Model | Hugging Face model ID | Notes | | - | - | - | | ERNIE-Image | `baidu/ERNIE-Image` | Regular text-to-image checkpoint | | ERNIE-Image-Turbo | `baidu/ERNIE-Image-Turbo` | Turbo text-to-image checkpoint | ## 3. Serve the model The commands below target a single supported NVIDIA CUDA or AMD ROCm GPU. Start with `--performance-mode auto`; use `speed` only when the full pipeline fits comfortably on the selected GPU(s), and use `memory` when you need lower peak GPU memory. Serve ERNIE-Image: ```bash Command theme={null} sglang serve \ --model-path baidu/ERNIE-Image \ --num-gpus 1 \ --performance-mode auto \ --port 30010 ``` Serve ERNIE-Image-Turbo: ```bash Command theme={null} sglang serve \ --model-path baidu/ERNIE-Image-Turbo \ --num-gpus 1 \ --performance-mode auto \ --port 30010 ``` Intel Xeon CPU deployment is supported by prefixing the server command with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu` and omitting GPU-only flags. Serve ERNIE-Image: ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu sglang serve --model-path baidu/ERNIE-Image --port 30010 ``` Serve ERNIE-Image-Turbo: ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu sglang serve --model-path baidu/ERNIE-Image-Turbo --port 30010 ``` ## 4. Generate an image Use the OpenAI-compatible image generation API after the server starts: ```python Python theme={null} import base64 from openai import OpenAI client = OpenAI(api_key="EMPTY", base_url="http://127.0.0.1:30010/v1") response = client.images.generate( model="baidu/ERNIE-Image-Turbo", prompt="A cinematic photo of a quiet lakeside cabin at sunrise", n=1, response_format="b64_json", ) image_bytes = base64.b64decode(response.data[0].b64_json) with open("ernie_image.png", "wb") as f: f.write(image_bytes) ``` ## 5. Configuration tips * ERNIE-Image is a text-to-image pipeline; do not pass `--image-path`. * `--performance-mode auto` keeps conservative defaults while preserving explicit user flags. * If the checkpoint includes a PE component, SGLang loads it automatically with the native Ministral3 runtime. Use `--layerwise-offload-components pe` when the local PE decoder needs to trade latency for lower GPU memory usage. * Treat FSDP, SP/Ulysses/Ring, and TP as explicit benchmark knobs. Measure the target resolution, step count, and GPU type before making them production defaults. ## 6. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Image`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # FLUX Source: https://docs.sglang.io/cookbook/diffusion/FLUX/FLUX Deploy FLUX diffusion models with SGLang - 12B/32B rectified flow transformers for high-quality text-to-image generation. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. ## 2. Model capabilities [FLUX](https://blackforestlabs.ai/) is Black Forest Labs' rectified-flow image model family. [FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) is the smaller 12B text-to-image checkpoint; [FLUX.2-dev](https://huggingface.co/black-forest-labs/FLUX.2-dev) is a 32B model that adds instruction-based editing plus single- and multi-reference composition. FLUX is a strong default when prompt adherence, polished image quality, or reference consistency matters. The tradeoff is deployment weight: FLUX.2 needs substantially more memory than FLUX.1, and the dev checkpoints use the FLUX non-commercial license, so review the model license before production use. | Checkpoint | Best fit | Main limitation | | - | - | - | | `black-forest-labs/FLUX.1-dev` | High-quality text-to-image with the lighter FLUX deployment | No native multi-reference editing path | | `black-forest-labs/FLUX.2-dev` | Text-to-image, editing, and reference-guided composition in one model | 32B model with a larger memory footprint | ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration FLUX models are optimized for high-quality image generation. The recommended launch configurations vary by hardware and model version. Use the [command builder](#1-quick-start) above. ### 3.2 Configuration Tips See [Performance Optimization](/docs/sglang-diffusion/performance-optimization) for acceleration features and their runtime requirements. * `--vae-path`: Path to a custom VAE model or HuggingFace model ID (e.g., fal/FLUX.2-Tiny-AutoEncoder). If not specified, the VAE will be loaded from the main model path. * `--num-gpus`: Number of GPUs to use * `--tp-size`: Tensor parallelism size (only for the encoder; should not be larger than 1 if text encoder offload is enabled, as layer-wise offload plus prefetch is faster) * `--sp-degree`: Sequence parallelism size (typically should match the number of GPUs) * `--ulysses-degree`: The degree of DeepSpeed-Ulysses-style SP in USP * `--ring-degree`: The degree of ring attention-style SP in USP ### 3.3 Breakable CUDA graph for FLUX.1-dev For repeated `quality=lossless` requests, FLUX.1-dev supports breakable CUDA graph (BCG) execution with the native backend. BCG captures DiT segments during startup and replays them for the warmed resolutions. It can reduce recurring host launch overhead without enabling `torch.compile`. The following configuration was validated on two NVIDIA H200 GPUs with BF16 weights, PyTorch 2.13, and CUDA 13.0. Set `HF_TOKEN` to a Hugging Face token with access to the checkpoint before downloading it. ```bash theme={null} CUDA_VISIBLE_DEVICES=0,1 sglang generate \ --model-path black-forest-labs/FLUX.1-dev \ --backend sglang \ --num-gpus 2 --tp-size 2 \ --component-residency dit=resident \ --enable-torch-compile false \ --enable-breakable-cuda-graph \ --warmup-resolutions 1024x1024 \ --quality exact \ --width 1024 --height 1024 \ --num-inference-steps 50 --guidance-scale 3.5 --seed 42 \ --prompt "A futuristic cyberpunk city at night, neon lights reflecting on wet streets" ``` Confirm `[Diffusion BCG] captured` in the log, then compare warmed request latency with eager execution on the same GPUs. Capture time and graph memory are additional startup costs. Add other served resolutions to `--warmup-resolutions`; a request with an uncaptured signature falls back to eager. FLUX.1-dev uses a fixed 512-token T5 conditioning sequence, so changing `--bcg-text-buckets` does not create additional prompt-length graphs. Its request-gated DiT fusions at `quality=high` and `lossless` cannot be combined with BCG: the runtime rejects those requests because the captured graph uses the lossless branches. FLUX.2 and quantized transformer overrides require separate validation. ## 4. API Usage For complete API documentation, please refer to the [official API usage guide](/docs/sglang-diffusion/api/openai_api). ### 4.1 Generate an Image ```python Example theme={null} import base64 from openai import OpenAI client = OpenAI(api_key="EMPTY", base_url="http://localhost:3000/v1") response = client.images.generate( model="black-forest-labs/FLUX.1-dev", prompt="A cat holding a sign that says hello world", size="1024x1024", n=1, response_format="b64_json", ) # Save the generated image image_bytes = base64.b64decode(response.data[0].b64_json) with open("output.png", "wb") as f: f.write(image_bytes) ``` ### 4.2 Advanced Usage #### 4.2.1 Cache-DiT Acceleration SGLang integrates [Cache-DiT](https://github.com/vipshop/cache-dit), a caching acceleration engine for Diffusion Transformers (DiT), to achieve up to 7.4x inference speedup with minimal quality loss. You can set `SGLANG_CACHE_DIT_ENABLED=True` to enable it. For more details, please refer to the SGLang Cache-DiT [documentation](/docs/sglang-diffusion/cache_dit). **Basic Usage** ```bash Command theme={null} SGLANG_CACHE_DIT_ENABLED=true sglang serve --model-path black-forest-labs/FLUX.1-dev ``` **Advanced Usage** * DBCache Parameters: DBCache controls block-level caching behavior:
Parameter Env Variable Default Description
Fn `SGLANG_CACHE_DIT_FN` 1 Number of first blocks to always compute
Bn `SGLANG_CACHE_DIT_BN` 0 Number of last blocks to always compute
W `SGLANG_CACHE_DIT_WARMUP` 4 Warmup steps before caching starts
R `SGLANG_CACHE_DIT_RDT` 0.24 Residual difference threshold
MC `SGLANG_CACHE_DIT_MC` 3 Maximum continuous cached steps
* TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion:
Parameter Env Variable Default Description
Enable `SGLANG_CACHE_DIT_TAYLORSEER` false Enable TaylorSeer calibrator
Order `SGLANG_CACHE_DIT_TS_ORDER` 1 Taylor expansion order (1 or 2)
Combined Configuration Example: ```bash Command theme={null} SGLANG_CACHE_DIT_ENABLED=true \ SGLANG_CACHE_DIT_FN=2 \ SGLANG_CACHE_DIT_BN=1 \ SGLANG_CACHE_DIT_WARMUP=4 \ SGLANG_CACHE_DIT_RDT=0.4 \ SGLANG_CACHE_DIT_MC=4 \ SGLANG_CACHE_DIT_TAYLORSEER=true \ SGLANG_CACHE_DIT_TS_ORDER=2 \ sglang serve --model-path black-forest-labs/FLUX.1-dev ``` #### 4.2.2 CPU Offload * `--dit-cpu-offload`: Use CPU offload for DiT inference. Enable if run out of memory. * `--text-encoder-cpu-offload`: Use CPU offload for text encoder inference. * `--vae-cpu-offload`: Use CPU offload for VAE. * `--pin-cpu-memory`: Pin memory for CPU offload. Only added as a temp workaround if it throws "CUDA error: invalid argument". #### 4.2.3 Known LoRA examples Use `--lora-path` at startup or the [LoRA management API](/docs/sglang-diffusion/api/openai_api#lora-management) to load an adapter. Known FLUX examples include: * [`dvyio/flux-lora-simple-illustration`](https://huggingface.co/dvyio/flux-lora-simple-illustration) * [`XLabs-AI/flux-furry-lora`](https://huggingface.co/XLabs-AI/flux-furry-lora) * [`XLabs-AI/flux-RealismLora`](https://huggingface.co/XLabs-AI/flux-RealismLora) #### 4.2.4 Negative prompts (true CFG) FLUX.1-dev is guidance-distilled: its guidance embedding comes from the server's `--embedded-cfg-scale` (3.5 for FLUX.1), and the requests above run one DiT forward per step. A negative prompt turns on classifier-free guidance, which adds an unconditional forward per step: * `--true-cfg-scale` sets the CFG weight, as in diffusers `FluxPipeline`. * Without `--true-cfg-scale`, the negative prompt uses `--guidance-scale` as the CFG weight. ```bash theme={null} sglang generate \ --model-path black-forest-labs/FLUX.1-dev \ --prompt "A red bicycle leaning against a stone wall beside a quiet lake at sunset" \ --negative-prompt "blurry, distorted, low quality" \ --true-cfg-scale 2.0 \ --width 1024 --height 1024 --num-inference-steps 50 --seed 42 ``` Keep the weight moderate. On top of the distilled guidance, CFG over-exposes FLUX.1-dev in diffusers as well as in SGLang: at 1024x1024 and 28 steps, about 45% of pixels clip to 0 or 255 at a weight of 4, and 8-15% at 1.5-2. ## 5. Benchmark ### 5.1 Speedup Benchmark #### 5.1.1 Generate a image Test Environment: * Hardware: NVIDIA B200 GPU (1x) * Model: black-forest-labs/FLUX.1-dev * sglang diffusion version: 0.5.6.post2 **NVIDIA B200** **Server Command**: ```shell Command theme={null} sglang serve --model-path black-forest-labs/FLUX.1-dev --port 30000 ``` **Benchmark Command**: ```shell Command theme={null} python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task text-to-image --num-prompts 1 --max-concurrency 1 ``` **Result**: ```text Output theme={null} ================= Serving Benchmark Result ================= Model: black-forest-labs/FLUX.1-dev Dataset: vbench Task: text-to-image -------------------------------------------------- Benchmark duration (s): 50.97 Request rate: inf Max request concurrency: 1 Successful requests: 1/1 -------------------------------------------------- Request throughput (req/s): 0.02 Latency Mean (s): 50.9681 Latency Median (s): 50.9681 Latency P99 (s): 50.9681 -------------------------------------------------- Peak Memory Max (MB): 27905.19 Peak Memory Mean (MB): 27905.19 Peak Memory Median (MB): 27905.19 ============================================================ ``` **Ascend A3 Series** **Server Command**: ```shell Command theme={null} #One A3 Series card has 2 npu chips sglang serve --tp-size 2 --sp-degree 1 --model-path black-forest-labs/FLUX.1-dev --num-gpus 2 ``` **Benchmark Command**: ```shell Command theme={null} python -m sglang.multimodal_gen.benchmarks.bench_serving --dataset vbench --task text-to-image --num-prompts 1 --max-concurrency 1 ``` **Result**: ```text Output theme={null} ================= Serving Benchmark Result ================= Task: text-to-image Model: black-forest-labs/FLUX.1-dev Dataset: vbench -------------------------------------------------- Benchmark duration (s): 16.30 Request rate: inf Max request concurrency: 1 Successful requests: 1/1 Completed outputs: 1 Outputs per prompt: 1 -------------------------------------------------- Request throughput (req/s): 0.06 Output throughput (outputs/s): 0.06 Latency Mean (s): 16.30 Latency Median (s): 16.30 Latency P90 (s): 16.30 Latency P95 (s): 16.30 Latency P99 (s): 16.30 -------------------------------------------------- Peak Memory Max (MB): 19972.00 Peak Memory Mean (MB): 19972.00 Peak Memory Median (MB): 19972.00 ------------------------------------------------------------ ``` #### 5.1.2 Generate images with high concurrency **NVIDIA B200** **Server Command** : ```shell Command theme={null} sglang serve --model-path black-forest-labs/FLUX.1-dev --port 30000 ``` **Benchmark Command** : ```shell Command theme={null} python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --dataset vbench --task text-to-image --num-prompts 20 --max-concurrency 20 ``` **Result** : ```text Output theme={null} ================= Serving Benchmark Result ================= Model: black-forest-labs/FLUX.1-dev Dataset: vbench Task: text-to-image -------------------------------------------------- Benchmark duration (s): 111.79 Request rate: inf Max request concurrency: 20 Successful requests: 20/20 -------------------------------------------------- Request throughput (req/s): 0.18 Latency Mean (s): 67.0646 Latency Median (s): 66.9691 Latency P99 (s): 110.8949 -------------------------------------------------- Peak Memory Max (MB): 27917.19 Peak Memory Mean (MB): 27916.59 Peak Memory Median (MB): 27917.19 ============================================================ ``` **Ascend A3 Series** **Server Command** : ```shell Command theme={null} #One A3 Series card has 2 npu chips sglang serve --tp-size 2 --sp-degree 1 --model-path black-forest-labs/FLUX.1-dev --num-gpus 2 ``` **Benchmark Command** : ```shell Command theme={null} python -m sglang.multimodal_gen.benchmarks.bench_serving --dataset vbench --task text-to-image --num-prompts 20 --max-concurrency 20 ``` **Result** : ```text Output theme={null} ================= Serving Benchmark Result ================= Task: text-to-image Model: black-forest-labs/FLUX.1-dev Dataset: vbench -------------------------------------------------- Benchmark duration (s): 300.85 Request rate: inf Max request concurrency: 20 Successful requests: 18/20 Completed outputs: 18 Outputs per prompt: 1 -------------------------------------------------- Request throughput (req/s): 0.06 Output throughput (outputs/s): 0.06 Latency Mean (s): 155.16 Latency Median (s): 155.11 Latency P90 (s): 266.30 Latency P95 (s): 280.15 Latency P99 (s): 291.23 -------------------------------------------------- Peak Memory Max (MB): 19972.00 Peak Memory Mean (MB): 19972.00 Peak Memory Median (MB): 19972.00 ------------------------------------------------------------ ``` ## 6. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Image`. **Integrated mode** — ComfyUI's own sampler, CLIP, and VAE drive the loop while SGLang replaces the model forward. Load the checkpoint with `SGLDiffusion UNET Loader` and set `model_type` to `flux` on the `SGLDiffusion Options` node. A reference workflow is included at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion/workflows/flux_sgld_sp.json`. # FLUX.3 Source: https://docs.sglang.io/cookbook/diffusion/FLUX/FLUX.3 Serve FLUX.3 Image Klein text-to-image generation and image editing with SGLang Diffusion. ## 1. Quick start Use a [SGLang Diffusion Docker environment](/docs/sglang-diffusion/installation). Until a released image contains this integration, install SGLang from `main` inside it: ```bash theme={null} pip install 'sglang[diffusion] @ git+https://github.com/sgl-project/sglang.git#subdirectory=python' ``` > [!NOTE] > > The picker selects `black-forest-labs/flux-3-image-klein-base` or > `black-forest-labs/flux-3-image-klein`, each a self-contained repository. Access > to the selected checkpoint is required. Keep `--model-path` at its repository > root; `--model-variant` selects only the quantized DiT. Both release BF16 > checkpoints have single-GPU generation checks; see the validation boundaries > below. Unverified hardware or resource shapes remain selectable but are not > measured recommendations. The picker defaults to resident weights for its 1 MP, batch-1 workload. Its recommended execution uses BCG only where a matched E2E comparison showed a material gain: currently single-GB300 distilled NVFP4 T2I. Other combinations start eager; this graph recipe covers the 80-token text bucket. Changing precision never happens automatically. Recommendations are best among the tested settings, not an exhaustive optimum. > [!WARNING] > > FLUX.3 Image Klein is released under the > [FLUX Kommunity License v1.0](https://huggingface.co/black-forest-labs/flux-3-image-klein/blob/main/LICENSE.md): > non-commercial use, plus commercial output generation for Qualifying Users with > less than US\$5M in gross annualized revenue, subject to its terms. The > Qwen3-VL-4B-Instruct text encoder is Apache-2.0. Review the license before > production or commercial use. For platform-specific installation, see the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation). ## 2. Model capabilities [FLUX.3 Image Klein](https://huggingface.co/collections/black-forest-labs/flux-3-image-klein) is Black Forest Labs' 5.6B open-weights model for text-to-image generation and image editing. It takes a prompt and up to 10 reference images and returns one image; text-to-image, single-reference edits and multi-reference compositions run through the same DiT, with Qwen3-VL-4B-Instruct as the text encoder. The 5.6B count covers the image transformer only. Prompts can place elements with bounding boxes on a 0 to 1000 grid, then recolor, move, replace or remove them; boxes guide placement and scale rather than masking pixels. The model also renders text inside images. One SGLang server serves text-to-image and editing, chosen per request. This image pipeline does not serve the separate FLUX.3 Action robot policy. | Checkpoint | Training | Steps | Guidance | Built for | | - | - | - | - | - | | [Klein](https://huggingface.co/black-forest-labs/flux-3-image-klein) | step-distilled flow map | 16 | none | generation and editing, self-hosting; the checkpoint behind the BFL API | | [Klein Base](https://huggingface.co/black-forest-labs/flux-3-image-klein-base) | undistilled | 50 | 3.5 | fine-tuning, LoRA training, research | Each repository ships its BF16 DiT with FP8 (`fp8r`) and NVFP4 variants, together with the text encoder and image autoencoder. Quantization and caching are separate fidelity/latency tradeoffs, not lossless substitutes for the selected checkpoint. | Task | Endpoint | Conditioning | | - | - | - | | Text to image | `POST /v1/images/generations` | Text prompt | | Image to image | `POST /v1/images/edits` | Text prompt and 1 to 10 `image` uploads | Start the server: ```bash theme={null} sglang serve \ --model-path black-forest-labs/flux-3-image-klein-base \ --host 0.0.0.0 \ --port 30010 ``` Sampling is set per request (`num_inference_steps`, `guidance_scale`, `size`, `seed`, `n`); unset fields take the checkpoint's defaults from its `config.json`. SGLang expands `n` into independently seeded requests and can pack compatible requests into one DiT forward. References are prepared as in the [BFL reference pipeline](https://github.com/black-forest-labs/flux-3-image-klein). A single reference is fitted under 4 MP, reflect-padded to the 16-pixel grid and, when you set no output size, sets the output size; the padding is cropped from the result. With several references each is fitted under 1 MP and centre-cropped, and the output takes the first one's size. ### Prompting The caption controls composition; reference images anchor content but do not lock structure. * Write full scene captions covering framing, subject, background and lighting. A short prompt gives generic output, and a one-line edit instruction ("make it blue") reframes the shot. The [prompt upsampler](#7-prompt-upsampler) expands a short request into a full caption. * For edits, describe the target image as a complete caption of the reference with the edit folded in. * For layout, append a JSON list of elements to the caption. Each box is `[top, left, bottom, right]` on a 0 to 1000 grid, and the caption tags each element as ``. To edit by box, refer to the n-th reference as `` and give each element `from`, `src_bbox` and `tgt_bbox`; a `null` target removes it. See BFL's [bounding box guide](https://docs.bfl.ai/flux_3/flux3_image_bounding_boxes) for the full format. ## 3. Checkpoints and precision | Repository | `--model-variant` | Sampling | | - | - | - | | `black-forest-labs/flux-3-image-klein-base` | Omit / `fp8r` / `nvfp4` | Base CFG; defaults from the selected configuration | | `black-forest-labs/flux-3-image-klein` | Omit / `fp8r` / `nvfp4` | Step-distilled flow map; no CFG | Both repositories use `flux-3-image-klein` in configuration and safetensors metadata. This shared identifier does not determine the sampling mode. The release repositories do not need the pre-release `sd-*` variant names. The distilled model is a step-distilled flow-map DiT: each step jumps straight to the next time of the schedule, so it samples without CFG. SGLang tells a flow map from its weights. It rejects `--enable-cfg-parallel`, a request `guidance_scale` other than 1, and a non-empty `negative_prompt`. Tensor parallelism, Ulysses SP and breakable CUDA graphs work as for the base model. The Base model defaults to CFG 3.5 against an empty negative prompt. Both variants reuse the package's text encoder and VAE. Keep the checkpoint revision, precision, attention backend, guidance and sampling parameters fixed when comparing outputs. Explicit `guidance_scale=1` uses scale 1, not the package default; `true_cfg_scale`, when provided, takes precedence over `guidance_scale`. ### Quantized checkpoints Each repo ships quantized DiTs under `variants/`: select one with `--model-variant fp8r` or `--model-variant nvfp4` and keep `--model-path` pointing at the repo root. Text encoder and VAE precision follow their own package settings; quantizing the DiT does not quantize them. The quantization comes from the variant's `hf_quant_config.json`, so do not also pass `--quantization`. ```bash theme={null} sglang serve \ --model-path black-forest-labs/flux-3-image-klein-base \ --model-variant fp8r \ --host 0.0.0.0 \ --port 30010 ``` **FP8R** stores rowwise-FP8 weights. On Blackwell (SM10x) the FP8 projections run FlashInfer PrimsTS GEMMs with fused QK-norm/RoPE and SwiGLU epilogues (FlashInfer >= 0.7.1); set `SGLANG_ENABLE_FLUX3_PRIMS_TS_AUTOTUNE=1` to autotune them during warmup. Other GPUs use the generic rowwise-FP8 GEMM. **NVFP4** stores FP4 (E2M1) weights with FP8 block scales and needs a Blackwell GPU and a compatible GEMM implementation. SM10x and consumer SM120 use different kernel paths; a B200 recipe does not establish RTX 5090 performance. Both quantization modes can change output quality and need workload-specific comparison against BF16. These flags remain separately configurable; see the validation boundaries below before combining quantization with other optimizations. ### Breakable CUDA graphs BCG reserves additional device memory and captures specific request shapes. The picker generates `--warmup-resolutions 1024x1024` and matching `--warmup-sampling-params` for the selected quality. For editing it also sets `flux3_mode="i2i"` and a server-local reference path: mount a 1024x1024 image there before starting the server. This path can differ from the client's upload path. Longer prompt token buckets, other reference dimensions/counts, batches or quality settings may run eager instead; check for a serving-signature miss in the server log. Changing the picker workload also changes its graph warmup command. Restart with that command to capture the new workload. Keep eager for variable-shape traffic, or explicitly validate every shape you intend to capture. ### LoRA adapters Use the standard LoRA API with native DiT keys, optionally prefixed by `dit.` or `transformer.`. BF16 dynamic and merged adapters have a synthetic rank-4 generation check, including repeatability and exact restoration after unloading; this does not validate every community adapter. For quantized deployments requiring LoRA, pass `--lora-path` at startup to select the generic quantized layout. Attaching LoRA after PrimsTS weight preparation is rejected before replacing any layers. FP8R and NVFP4 startup adapters also have synthetic rank-4 generation checks on GB300, including repeatability and exact restoration after unloading. These do not establish compatibility with arbitrary quantized community adapters. ## 4. Multi-GPU and memory FLUX.3 shares its DiT with FLUX.3 Action, so the image pipeline supports tensor parallelism, Ulysses sequence parallelism, CFG parallelism, layerwise offload and breakable CUDA graphs. The picker covers RTX 5090, RTX PRO 6000, H100/H200, and B200/B300/GB200/GB300 with one to eight GPUs on one node. TP times Ulysses degree must equal the GPU count and evenly partition the 24 attention heads. Ring is not admitted by this image recipe. For example, two-GPU TP uses `--num-gpus 2 --tp-size 2`; two-GPU Ulysses uses `--num-gpus 2 --tp-size 1 --ulysses-degree 2`. Base also permits CFG parallelism; distilled checkpoints have no CFG branch to parallelize. More GPUs do not guarantee lower latency, particularly over PCIe. Ulysses inherits all-to-all streaming through the shared attention layer. Leave its pipeline-group policy automatic; short sequences need not benefit. TP-only deployments do not use this path. Encoding-while-decoding overlaps video-frame decoding with video-file encoding, so it does not apply to this still-image pipeline. > [!NOTE] > > Under sequence parallelism every rank holds the full DiT, so combining it with > layerwise offload streams the whole model to each GPU every step. TP also > partitions weights, so it is the lower-memory starting point when offloading > on several GPUs. Preserve headroom for the longest prompt, references and output > size you intend to serve; a successful small request is not a capacity guarantee. For FP32 VAE attention above 1 MP, `quality="lossless"` can use dense-layout, full-context memory-efficient SDPA; `quality="exact"` retains the original path. It does not prune attention or reduce precision, but reduction order can change pixels. In a Base BF16 test with a 2048x2048 reference and 1024x1024 output, GB300 peak allocated memory fell from 54.3 to 29.5 GiB; latency was effectively unchanged. GB300/H200 image SSIM was 0.9951-0.9992 against the exact path across four samples. This is allocated memory, not total device usage: a 32 GB card still needs offload or quantization headroom for that reference size. ### Disaggregated serving You can deploy the prompt encoder, reference-image VAE encoder, DiT, and VAE decoder as separate worker pools behind the same image API. Both T2I and i2i are supported. Use the [split encoding deployment guide](/docs/sglang-diffusion/disaggregation#flux3-split-encoding) for the four-role commands, or keep the existing three-role topology with a combined encoder. This separates resources and scaling; it adds transfer hops and does not imply lower single-request latency. T2I skips the image encoder; editing keeps reference padding/crop semantics. Each pool can have a different number of workers. Keep the package variant and numerical settings consistent across workers; the guide includes the required transfer dependency, network ports, and same-node validation scope. ## 5. Cache-DiT [Cache-DiT](/docs/sglang-diffusion/cache_dit) skips the 28 single-stream blocks on steps where their input barely changes and reuses the cached residual. Turn it on for every request with `SGLANG_CACHE_DIT_ENABLED=true` on `sglang serve`, or per request with `"enable_cache_dit": true`. A request can also tune it, for example `"cache_dit_params": {"residual_diff_threshold": 0.12, "enable_taylorseer": true}`. For image editing, send `-F "enable_cache_dit=true"` and a JSON-encoded `cache_dit_params` form field; generation uses JSON request fields. Cache-DiT is approximate and may change composition; measure quality and latency on representative prompts rather than treating its threshold as a fidelity guarantee. It combines with FP8R and NVFP4, tensor parallelism, CFG parallelism and layerwise offload. It is skipped, with a warning, under Ulysses sequence parallelism and breakable CUDA graphs, and for a request whose CFG pair has to run as two forwards to fit in device memory. ## 6. Request examples **Text to image** ```bash theme={null} curl -sS -X POST http://localhost:30010/v1/images/generations \ -H 'Content-Type: application/json' \ -d '{"prompt": "A red fox standing in fresh snow", "size": "1024x1024", "seed": 0, "response_format": "b64_json"}' \ -o flux3_t2i.json ``` **Image to image** ```bash theme={null} curl -sS -X POST http://localhost:30010/v1/images/edits \ -F "image=@/data/flux3/reference.png" \ -F "prompt=Render the reference as a winter wildlife photograph" \ -F "seed=0" \ -F "response_format=b64_json" \ -o flux3_i2i.json ``` **Offline generation** ```bash theme={null} sglang generate \ --model-path black-forest-labs/flux-3-image-klein-base \ --height 1024 --width 1024 \ --num-inference-steps 50 \ --guidance-scale 3.5 \ --prompt "A red fox standing in fresh snow" ``` Pass `--image-path` (one or more images) to edit references instead. ## 7. Prompt upsampler [black-forest-labs/flux-3-image-klein-pup](https://huggingface.co/black-forest-labs/flux-3-image-klein-pup) is a Qwen3.5-9B vision-language fine-tune that expands a short prompt into the detailed caption FLUX.3 works best with. The BFL reference code runs it in front of the image model by default. It is a standard `Qwen3_5ForConditionalGeneration` checkpoint, so it is served as a regular LLM, separately from the image pipeline. The system prompt (`system_prompts.json` in the repository) selects the mode; `t2i` is the text-to-image upsampler. Download the package and start the upsampler on its own port: ```bash theme={null} PUP_PATH="" hf download black-forest-labs/flux-3-image-klein-pup --local-dir ${PUP_PATH} CUDA_VISIBLE_DEVICES=1 sglang serve ${PUP_PATH} \ --model-type llm \ --served-model-name flux-3-image-klein-pup \ --host 0.0.0.0 --port 8001 \ --context-length 16384 \ --mem-fraction-static 0.90 \ --reasoning-parser qwen3 ``` Upsample a text prompt through the OpenAI-compatible chat endpoint. The `t2i` system prompt is read from the downloaded package; thinking is disabled and decoding follows the model card (greedy, presence penalty 1.5): ```bash theme={null} jq -n --slurpfile p ${PUP_PATH}/system_prompts.json '{ model: "flux-3-image-klein-pup", messages: [ {role: "system", content: $p[0].t2i}, {role: "user", content: "A man walking with his dog, afternoon sun"} ], max_tokens: 3584, temperature: 0, presence_penalty: 1.5, chat_template_kwargs: {enable_thinking: false} }' | curl -s http://0.0.0.0:8001/v1/chat/completions \ -H 'Content-Type: application/json' -d @- \ | jq -r '.choices[0].message.content' ``` You can then pass the returned caption as the `--prompt` of a `t2i` request to the Flux3 pipeline. To have the image server call the upsampler itself, point it at this endpoint with the built-in `flux3-klein-pup` protocol. It reads `system_prompts.json` from the upsampler package (`protocol_source`, a local directory or the Hugging Face repo, which is the default) and follows BFL's reference code: the `t2i` prompt for generations, the `i2i` prompt with the references first (resized as the reference code does) for edits, greedy decoding with presence penalty 1.5 for `t2i` and 0 for `i2i`, and thinking disabled. ```bash theme={null} cat > flux3_pup.json <<'JSON' { "base_url": "http://127.0.0.1:8001/v1", "model": "flux-3-image-klein-pup", "protocol": "flux3-klein-pup", "protocol_source": "" } JSON sglang serve --model-path black-forest-labs/flux-3-image-klein-base \ --prompt-enhancer-config flux3_pup.json --port 30010 ``` A request opts in with `enhance_prompt`; it is off by default, so a full caption is sent as typed: ```bash theme={null} curl -sS -X POST http://localhost:30010/v1/images/generations \ -H 'Content-Type: application/json' \ -d '{"prompt": "A man walking with his dog, afternoon sun", "enhance_prompt": true, "size": "1024x1024", "response_format": "b64_json"}' ``` Greedy decoding is not by itself reproducible here: the caption changes with the upsampler's prefix cache and batch. Start the upsampler with `--enable-deterministic-inference --disable-radix-cache` when the same request must give the same caption. The layout prompts (`t2i_bbox`, `i2i_bbox`) are not wired in yet; write the box table into the prompt yourself as described in [Model capabilities](#2-model-capabilities). ## 8. Dynamic batching Enable a small batching window to collect concurrent requests: ```bash Serve concurrent requests theme={null} sglang serve --model-path black-forest-labs/flux-3-image-klein-base \ --batching-max-size 2 --batching-delay-ms 5 ``` The existing scheduler groups requests with matching sampling/runtime settings. Each keeps its own prompt, seed and reference images. Text encoding groups unique prompts by token-length bucket; DiT attention remains isolated per packed sample, including each CFG branch. VAE decoding groups outputs by canvas size before restoring request order and each reference crop. Larger batches need more activation memory and may increase individual request latency. Start with batch 2, compare throughput and tail latency under your actual QPS, and keep batch 1 for low-latency or low-VRAM workloads. Batching does not imply bitwise equality with separate forwards: GEMM and attention reduction choices can change with shape. Check output fidelity with fixed prompts and seeds. ### Pre-release batching measurements These measurements used pre-release weights, not the release repositories above. They do not establish release-checkpoint performance. The following are warmed HTTP measurements on one GB300 (about 277 GiB device memory), Base BF16, Torch SDPA, eager execution and all components resident. Each row compares two different prompt/seed requests served serially with the same two requests served together. Times include local HTTP transfer and JPEG output; medians cover three rounds after warming both shapes and reference encoding. Software: PyTorch 2.14.1+cu130, Transformers 5.19.0. Checkpoint revision: `5de4fe32f17aee3dbc34375a94935f09206dba2c`. | Workload | Serial pair | Batch-2 pair | Throughput ratio | | - | - | - | - | | T2I, 512x512, 8 steps | 0.649 s | 0.324 s | 2.00x | | I2I, 512x512, 8 steps | 0.737 s | 0.546 s | 1.35x | | T2I, 1024x1024, 50 steps | 6.248 s | 6.050 s | 1.03x | | I2I, 1024x1024, 50 steps | 13.171 s | 12.996 s | 1.01x | Eight steps exercise batching, not the recommended Base image-quality setting. The standard 50-step workload shows little batching benefit; FlashAttention gives a similarly small gain in this setup. Batch 1 remains the default. Do not extrapolate the small-request speedup to full-resolution generation or other GPUs. For these 50-step requests, batch-1 versus batch-2 JPEG outputs had SSIM 0.9920-0.9977. A separate four-image PNG comparison at 512x512/8 steps had SSIM 0.9885-0.9955; JPEG can amplify small rounding differences. These are observed samples, not a universal quality guarantee. Identical single requests before and after batching matched exactly. Preserve additional memory headroom for batching rather than assuming a batch-1 recipe fits on a 32 GB card at batch 2. ## 9. Validation boundaries The release BF16 and FP8R checkpoints have single-GB300/H200 generation checks; NVFP4 has GB300 and RTX 5090 checks. RTX 5090 also has Base BF16 and both checkpoints' FP8R and Cache-DiT checks. Single-GPU measurements use eager execution, all components resident, batch 1, 1024x1024 T2I and I2I, two prompts/seeds and repeated requests. Base uses 50 steps and distilled uses 16. Repeated requests matched pixel-for-pixel within each tested configuration. This does not establish official-reference parity or validate every combination of hardware, parallelism, batching and optional features in the picker. ### Multi-GPU measurements Base BF16, 50 steps, CFG 3.5, batch 1 and `quality="exact"`. These are warmed localhost HTTP medians through PNG decoding, excluding loading and warmup; two prompts/seeds and two timed rounds per prompt. Software: PyTorch 2.14.1+cu130, Transformers 5.19.0, FlashInfer 0.7.1. Both runs use checkpoint `d8acde427a698bdb98b5c1c941c60fa4c97e9f28`. The H200 run uses FA3 and NVLink; the RTX 4090 run uses Torch SDPA over PCIe without CUDA peer access. | GPUs | Topology | T2I 1024x1024 | I2I, 1 MP reference/output | | - | - | - | - | | 2x H200 | TP2 | 4.27 s | Not measured | | 2x H200 | Ulysses 2, streaming auto | 4.68 s | Not measured | | 4x RTX 4090 | TP4 | 16.97 s | 32.61 s | | 4x RTX 4090 | TP2 x Ulysses 2 | 16.28 s | 32.63 s | The picker keeps TP as its multi-GPU starting point, not a guarantee that TP always wins. A hybrid topology can help on PCIe; validate it on your own interconnect. H100, B200 and other unmeasured resource shapes are extrapolated starting points and are not labelled verified. On the same two H200s, Ulysses streaming reduced 2048x2048 T2I from 24.00 to 22.87 s and editing a 2048x2048 reference into a 1024x1024 output from 31.01 to 29.54 s. Streamed and non-streamed outputs matched pixel-for-pixel in these samples, with no quantization or caching. At 1024x1024, automatic dispatch selected no streaming groups and gave no speedup. TP and SP themselves are not bit-identical: sample SSIM was 0.9890-0.9985. None of these comparisons establishes which path is closer to an official reference. ### Single-GPU measurements Warmed local HTTP medians, including PNG encoding and response transfer, from two rounds per prompt. PyTorch 2.14.1+cu130, Transformers 5.19.0, FP32 VAE, `quality="exact"`; FlashAttention on GB300/H200 and Torch SDPA on RTX 5090. The Base checkpoint revision is `d8acde427a698bdb98b5c1c941c60fa4c97e9f28`. SSIM compares each quantized result with BF16 on the same GPU, prompt, seed and reference, and reports the lowest value across two samples, not a quality bound. | GPU | Base DiT | T2I | I2I | Minimum SSIM, T2I / I2I | | - | - | - | - | - | | GB300, 277 GiB | BF16 | 3.21 s | 6.31 s | Reference | | GB300, 277 GiB | FP8R | 2.18 s | 4.49 s | 0.958 / 0.981 | | GB300, 277 GiB | NVFP4 | 2.14 s | 4.31 s | 0.919 / 0.958 | | H200, 140 GiB | BF16 | 7.09 s | 14.52 s | Reference | | H200, 140 GiB | FP8R | 5.15 s | 11.24 s | 0.955 / 0.984 | | RTX 5090, 32 GB | BF16 | 20.39 s | 43.4 s | Reference | For the distilled checkpoint, quantization's T2I benefit was small on GB300; do not assume Base's speedup transfers to a 16-step workload. Cache-DiT at threshold 0.12 reduced Base I2I from 6.31 to 3.08 s on GB300, with sample SSIM 0.9786-0.9975. It remains opt-in and approximate. ### Eager versus CUDA graphs Matched ABBA comparisons use `quality="lossless"`, resident weights, batch 1, 1024x1024 output/reference, and the same software versions above with stable FlashInfer 0.7.1. Base uses 50 steps/CFG 3.5; distilled uses 16 steps/no CFG. Times are warmed localhost HTTP medians through JPEG decoding: two prompts/seeds and four timed samples per arm, excluding loading and graph capture. These JPEG timings are not directly comparable with the earlier PNG table. | GPU | Checkpoint | Workload | Eager | BCG | Recommended | | - | - | - | - | - | - | | GB300 | Distilled NVFP4, FA4 | T2I | 0.563 s | 0.436 s | BCG | | GB300 | Distilled NVFP4, FA4 | I2I | 0.882 s | 0.886 s | Eager | | GB300 | Base BF16, FA4 | T2I | 3.103 s | 3.130 s | Eager | | GB300 | Base BF16, FA4 | I2I | 6.236 s | 6.733 s | Eager | | H200 | Base BF16, FA3 | T2I | 6.845 s | 6.916 s | Eager | | H200 | Base BF16, FA3 | I2I | 14.183 s | 15.252 s | Eager | | 2x H200, TP2 | Base BF16, FA3 | T2I | 4.000 s | 4.199 s | Eager | | RTX 5090 | Distilled NVFP4, SDPA | T2I | 1.676 s | 1.678 s | Eager | | RTX 5090 | Distilled NVFP4, SDPA | I2I | 4.092 s | 4.104 s | Eager | | RTX 5090 | Base NVFP4, SDPA | T2I | 9.449 s | 9.583 s | Eager | GB300 distilled NVFP4 T2I improves by 22.5% with FA4 + BCG. Peak allocated memory increases from 16.63 to 17.46 GiB; peak reserved rises from 18.75 to 19.96 GiB. These are per-process allocator maxima across warmup/runtime, not loading or total-device peaks. Other workloads also need headroom; memory capacity alone is not a reason to enable graphs when they do not improve latency. All 15 fixed-backend eager/BCG workload pairs passed repeated-request checks and pixel-identical PNG comparisons across the two prompts. This is not an official-reference accuracy guarantee or evidence that quantization preserves BF16 output. GB300 measurements use Base revision `17333191c36bae1b61b0a247e33ba284f1df07fa` and distilled `875076bf83d4364b68dccdbf8307f4f01475f68d`; H200/5090 use `d8acde427a698bdb98b5c1c941c60fa4c97e9f28` and `4d02a6a4dc4d5c7a0f3fa767187483b2b70f2384`. TP2 uses tensor-identical Base DiT weights with a different safetensors header. GB300 distilled NVFP4 T2I also ran at 0.424 s with SDPA + BCG (versus 0.589 s SDPA eager). It is selectable but not the default backend: SDPA versus FA4 outputs had sample SSIM 0.978-0.987 and MAD 1.74-1.75/255. Neither path is established as closer to the official output. Keep the backend fixed when evaluating the graph speedup. The native DiT's packed CFG forward has focused comparison tests against the shared FLUX 3 transformer. Such component tests do not replace full-checkpoint E2E or establish parity with every upstream release. Keep unverified hardware, topologies and optional optimizations separate from measured deployment recipes. The opt-in full-checkpoint HTTP regression covers concurrent prompts, image editing, multiple outputs and a repeated single request: ```bash theme={null} SGLANG_TEST_FLUX3_IMAGE=1 pytest -q \ python/sglang/multimodal_gen/test/server/test_server_flux3_image.py ``` Set `SGLANG_TEST_FLUX3_IMAGE_MODEL` to a local package path when using an offline checkpoint. This test needs checkpoint access; it does not substitute for an official-reference golden-image comparison. ## 10. ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Image`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. FLUX.3 has no integrated KSampler executor. Use server mode; the plugin-specific FLUX.3 workflow has not been validated. # HY-Nomas Source: https://docs.sglang.io/cookbook/diffusion/HY-Nomas/HY-Nomas Serve the HY-Nomas event-conditioned video world model with SGLang-diffusion, as offline video jobs or a realtime WebSocket session. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) on Linux with NVIDIA CUDA. One `sglang serve` process answers both HTTP video jobs and realtime WebSocket sessions. On first load, SGLang downloads the official checkpoints and assembles a local pipeline; see [Weights](#weights). ## 2. Model capabilities [HY-Nomas](https://huggingface.co/tencent/Hy-Nomas) is Tencent Hunyuan's video world model. A video is described as a sequence of events: each event is a structured JSON caption with a frame count and optional camera poses. The model generates one event at a time while attending to the cached state of earlier events, so a scene can be extended or redirected without regenerating what came before. Choose it for long, steerable scene continuation, either as one offline request with all events planned up front or as a live session that receives events one by one. It generates from noise: there is no image-to-video input. Captions must follow the official event JSON schema, which the official prompt enhancer (Nomas-PE) produces from free text; SGLang does not host that enhancer. The code and weights are released under Apache-2.0. See the [GitHub repository](https://github.com/Tencent-Hunyuan/Hy-Nomas) for the event schema and training details. | Component | Implementation | | - | - | | Text encoder | Qwen2.5-VL-7B-Instruct, 1280 tokens per event | | DiT | Distilled segment-autoregressive DiT, 8 Euler steps, no CFG | | Decoder | PixelUMM pixel decoder, windowed over 10 latents with 5-latent overlap | | Camera | Optional normalized extrinsics, one matrix per latent-aligned frame | ## 3. Deployment ```bash Command theme={null} sglang serve --model-path tencent/Hy-Nomas --num-gpus 1 --port 30000 ``` For two GPUs, use Ulysses sequence parallelism. Its output matched the single-GPU output pixel for pixel: ```bash Command theme={null} sglang serve --model-path tencent/Hy-Nomas --num-gpus 2 --sp-degree 2 --port 30000 ``` Tensor parallelism (`--tp-size 2`) also runs, but its trained-weight output differs from one GPU, so prefer SP. `tp_size * sp_degree` must divide the 16 attention heads, and TP and SP can be combined. Ring attention, CFG parallelism and data parallelism are rejected. Both layouts shard only the DiT computation; the text encoder and decoder are not placed on a separate GPU. To reduce DiT memory, stream its blocks from host memory: ```bash Command theme={null} sglang serve --model-path tencent/Hy-Nomas --num-gpus 1 --dit-layerwise-offload true --port 30000 ``` ### Weights `tencent/Hy-Nomas` is resolved through a pinned [model overlay](https://huggingface.co/Niehen6174/Hy-Nomas-overlay). It downloads the official distilled, non-quantized DiT, the PixelUMM decoder and the Qwen2.5-VL text encoder. It then caches a Diffusers-style pipeline under `SGLANG_DIFFUSION_CACHE_ROOT`. Weights keep their original values and dtypes. Later starts reuse the cache, and a local directory with the same layout can be passed to `--model-path` instead. The first load needs extra disk space for the decoder export. The overlay does not include Nomas-PE, LoRA adapters, or FP8/INT8 variants. ## 4. Offline and HTTP generation A request lists its events in `segments`. Each caption is a JSON string in the official event schema; later events usually describe only what changes. This two-event request makes 240 frames at 352×640 and saves it as `request.json`: ```python Python theme={null} import json first = { "Style": "Cinematic fantasy", "perspective_view": "Third-person view", "subject_list": [{"subject_id": "fox", "display_name": "a small orange fox", "subject_attribute": "Orange fur, white chest, and a fluffy tail."}], "segments": [{ "visual_description_long": "A small orange fox stands on a stone path in a luminous forest.", "contained_actions": [{"start_time": "00:00.000", "end_time": "00:05.000", "action_description": "The fox walks slowly along the path."}], }], } second = { "segments": [{ "description_change": "Glowing blue flowers open beside the path.", "contained_actions": [{"start_time": "00:00.000", "end_time": "00:05.000", "action_description": "The fox passes the flowers and looks around."}], }], } request = { "prompt": json.dumps(first), "prompt_format": "json", "segments": [ {"frames": 120, "caption": json.dumps(first)}, {"frames": 120, "caption": json.dumps(second)}, ], "num_frames": 240, "height": 352, "width": 640, "fps": 24, "num_inference_steps": 8, "guidance_scale": 1.0, "seed": 42, } with open("request.json", "w") as f: json.dump(request, f) ``` Send it to the HTTP video API, then poll `GET /v1/videos/{id}` and download from `GET /v1/videos/{id}/content`: ```bash Command theme={null} curl -sS http://127.0.0.1:30000/v1/videos \ -H 'Content-Type: application/json' \ --data-binary @request.json ``` The same request runs without a server through the Python API: ```python Python theme={null} from sglang.multimodal_gen import DiffGenerator with DiffGenerator.from_pretrained(model_path="tencent/Hy-Nomas") as generator: result = generator.generate({**request, "save_output": True}) ``` | Field | Meaning | | - | - | | `segments` | One entry per event: `frames` and a JSON `caption`, optionally `norm_extrinsics`. Event frames must sum to `num_frames`, and `prompt` repeats the first caption. | | `prompt_format` | `json` applies the official event schema. `plain` accepts free text for smoke tests only and logs a warning. | | `norm_extrinsics` | Camera matrices that are already normalized. The server does not normalize raw poses. | | `num_inference_steps`, `guidance_scale` | The distilled checkpoint uses 8 steps and guidance 1. | | `height`, `width` | Rounded to multiples of 32 as in the official code; 720×1280 becomes 704×1280. | Event frame counts do not need to be multiples of four; the decoded video is cropped to each requested count. Sampling noise is always drawn on the CPU, so a fixed seed gives the same video through the Python API and HTTP. ## 5. Realtime session Open `ws://HOST:PORT/v1/realtime_video/generate` and exchange MessagePack maps. | Message | Direction | Content | | - | - | - | | `{"type": "init", "prompt": ..., "num_frames": ..., "size": "640x352", "num_inference_steps": 8, "condition_inputs": {"prompt_format": "json", "segments": [...]}}` | client | Starts the session. Without `segments`, `prompt` and `num_frames` form the first event. | | `{"type": "event", "kind": "segment", "event_id": n, "payload": {"caption": ..., "frames": ..., "norm_extrinsics": ...}}` | client | Queues the next event. `norm_extrinsics` covers this event only. | | `{"type": "event", "kind": "end"}` | client | No more events. The server sends the remaining frames and closes. | | `frame_batch` / `frame_batch_header` | server | Raw RGB, WebP or JPEG frames for one chunk. A chunk may contain no frames. | Each event is generated as soon as it arrives, against the session's cached history. The decoder streams in overlapping windows and sends a frame only when no later window can change it, so frames are never revised. Output therefore lags generation, and `end` releases the tail: a 120 + 120 frame session sends 84, 120 and then 36 frames. The server keeps one session at a time and rejects a second connection. Disconnecting ends the session and frees its state; there is no resume. Because a session draws noise from a persistent bank, compare its frames with another session using the same seed, not with an offline request. A minimal client sends the first event in `init`, the rest as `segment` events, then `end`, and collects raw RGB frames until the server closes the socket: ```python Python theme={null} import msgspec import numpy as np import websocket events = request["segments"] # from the request above ws = websocket.create_connection("ws://127.0.0.1:30000/v1/realtime_video/generate") ws.send_binary(msgspec.msgpack.encode({ "type": "init", "prompt": events[0]["caption"], "num_frames": events[0]["frames"], "size": "640x352", "fps": 24, "num_inference_steps": 8, "seed": 42, "realtime_output_format": "raw", "condition_inputs": {"prompt_format": "json", "segments": events[:1]}, })) for event_id, event in enumerate(events[1:], start=1): ws.send_binary(msgspec.msgpack.encode( {"type": "event", "kind": "segment", "event_id": event_id, "payload": event})) ws.send_binary(msgspec.msgpack.encode({"type": "event", "kind": "end"})) frames = [] while True: try: raw = ws.recv() except websocket.WebSocketConnectionClosedException: break if not isinstance(raw, bytes): break message = msgspec.msgpack.decode(raw) if message.get("type") == "error": raise RuntimeError(message) if message.get("type") in ("frame_batch", "frame_batch_header"): # Large batches send their payload as the next binary message. payload = message["payload"] if message["type"] == "frame_batch" else ws.recv() if message["num_frames"]: shape = (message["num_frames"], message["height"], message["width"], message["channels"]) frames.append(np.frombuffer(payload, dtype=np.uint8).reshape(shape)) video = np.concatenate(frames) # 240 frames ``` To steer from free text, run Nomas-PE as a separate service. It turns the user's text and recent frames into the next event JSON, which the client then sends as the `caption`. ### KV cache budget The session cache starts at 65,536 tokens and grows by 1.5× up to 32 GiB, or to free GPU memory minus 8 GiB, whichever is smaller. At that limit, the oldest event is evicted first, as in the official code. Setting `max_cache_segments` also limits the number of cached events. Positions keep counting across evictions. If a cache write fails after an eviction, the session must be restarted. These limits are `NomasPipelineConfig` fields (`interactive_kv_cache_initial_tokens`, `interactive_kv_cache_growth_factor`, `max_cache_gib`, `cache_free_memory_reserve_gib`, `max_cache_segments`). At 1280×704, one 10-latent event uses about 4.5 GB of K/V on one GPU; TP and SP divide this across ranks. ## 6. Limitations * No image-to-video, classifier-free guidance, or raw camera-pose normalization. * Nomas-PE is not served by SGLang. * One realtime session per server; Ring attention, KV CPU swap, INT8 KV and sliding-window history are not implemented. * TP output is not yet equivalent to single-GPU output with trained weights. * Validation was on H200 only. # Ideogram 4 Source: https://docs.sglang.io/cookbook/diffusion/Ideogram/Ideogram4 Deploy Ideogram 4 with SGLang Diffusion for high-aesthetic text-to-image generation. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. Set `HF_TOKEN` with access to the gated Ideogram repositories. Install `bitsandbytes>=0.46.1` and `accelerate>=1.1.0` for NF4 and the shared NF4 text encoder. > **Installation and prerequisites** > > * NVIDIA CUDA GPU. > * SGLang installed with diffusion dependencies. > * `bitsandbytes>=0.46.1` and `accelerate>=1.1.0` for the NF4 checkpoint and the fal variants' shared NF4 text encoder. > * `HF_TOKEN` with access to the Ideogram 4 gated repositories. ## 2. Model capabilities [Ideogram 4](https://huggingface.co/ideogram-ai/ideogram-4-nf4) is a text-to-image family focused on polished composition and typography-aware generation. SGLang supports the official NF4 and FP8 checkpoints, Comfy-Org's NVFP4 transformer, and fal's distilled Fast and Instant variants. Choose NF4 when memory is the primary constraint, FP8/NVFP4 for supported accelerator deployments, Fast for a 20-step balance, and Instant for the 8-step latency target. The public repositories are gated, and the available releases are already quantized or distilled rather than a single full-precision baseline. | Variant | Hugging Face model ID | Notes | | - | - | - | | NF4 | `ideogram-ai/ideogram-4-nf4` | Official bitsandbytes NF4 checkpoint. Use this path first for low-memory deployment. | | FP8 | `ideogram-ai/ideogram-4-fp8` | Official FP8 checkpoint. | | NVFP4 | `Comfy-Org/Ideogram-4` | Comfy-Org NVFP4 transformer weights. SGLang loads non-transformer components from `ideogram-ai/ideogram-4-fp8`. | | Fast | `fal/ideogram-v4-fast` | 20-step, CFG-distilled, FP4-targeted floating checkpoint. Defaults to `V4_FAST_20`. | | Instant | `fal/ideogram-v4-instant` | 8-step, CFG- and timestep-distilled BF16 checkpoint. Defaults to `V4_INSTANT_8`. | The fal repositories contain only the transformer component. When either model ID is passed directly to `--model-path`, SGLang loads the text encoder, tokenizer, VAE, and scheduler from the `ideogram-ai/ideogram-4-nf4-diffusers` revision referenced by fal's model cards, then runs the distilled transformer without the unconditional branch. ## 3. Serve the model NF4: ```bash Command theme={null} HF_TOKEN=$HF_TOKEN sglang serve \ --model-path ideogram-ai/ideogram-4-nf4 \ --num-gpus 1 \ --performance-mode auto \ --port 30010 ``` Intel Xeon CPU deployment is supported for the fal checkpoints with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu`; omit GPU-only flags. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu HF_TOKEN=$HF_TOKEN sglang serve --model-path ideogram-ai/ideogram-4-nf4 --port 30010 ``` FP8: ```bash Command theme={null} HF_TOKEN=$HF_TOKEN sglang serve \ --model-path ideogram-ai/ideogram-4-fp8 \ --num-gpus 1 \ --performance-mode auto \ --port 30010 ``` Intel Xeon CPU deployment is supported for the fal checkpoints with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu`; omit GPU-only flags. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu HF_TOKEN=$HF_TOKEN sglang serve --model-path ideogram-ai/ideogram-4-fp8 --port 30010 ``` Comfy-Org NVFP4: ```bash Command theme={null} HF_TOKEN=$HF_TOKEN sglang serve \ --model-path Comfy-Org/Ideogram-4 \ --num-gpus 1 \ --performance-mode auto \ --port 30010 ``` Use B200 or another Blackwell GPU for NVFP4. fal Fast: ```bash Command theme={null} HF_TOKEN=$HF_TOKEN sglang serve \ --model-path fal/ideogram-v4-fast \ --num-gpus 1 \ --performance-mode auto \ --port 30010 ``` IntelXeon CPU deployment is supported for the fal checkpoints with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu`; omit GPU-only flags. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu HF_TOKEN=$HF_TOKEN sglang serve --model-path fal/ideogram-v4-fast --port 30010 ``` fal Instant: ```bash Command theme={null} HF_TOKEN=$HF_TOKEN sglang serve \ --model-path fal/ideogram-v4-instant \ --num-gpus 1 \ --performance-mode auto \ --port 30010 ``` Intel Xeon CPU deployment is supported for the fal checkpoints with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu`; omit GPU-only flags. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu HF_TOKEN=$HF_TOKEN sglang serve --model-path fal/ideogram-v4-instant --port 30010 ``` ### Tensor and sequence parallelism Both fal variants support native DiT tensor parallelism and Ulysses sequence parallelism. The following two-GPU layouts were validated at 1024×1024 on B200 GPUs for both `fal/ideogram-v4-fast` and `fal/ideogram-v4-instant`. TP2 shards the distilled DiT weights. The shared bitsandbytes NF4 text encoder is replicated because 4-bit row-parallel quantization states cannot be safely sharded: ```bash Command theme={null} HF_TOKEN=$HF_TOKEN sglang serve \ --model-path fal/ideogram-v4-instant \ --num-gpus 2 \ --tp-size 2 \ --port 30010 ``` Ulysses/SP2 shards the image-token sequence while keeping the DiT weights replicated: ```bash Command theme={null} HF_TOKEN=$HF_TOKEN sglang serve \ --model-path fal/ideogram-v4-instant \ --num-gpus 2 \ --ulysses-degree 2 \ --port 30010 ``` Replace the model ID with `fal/ideogram-v4-fast` to use the same layouts for Fast. TP2 and Ulysses/SP2 are the validated configurations; Ring SP is not yet validated for this pipeline. Ideogram 4 has 18 attention heads, so any other TP degree must divide 18. ### Layerwise offload If the distilled DiT does not fit in GPU memory, enable transformer layerwise offload. This keeps the shared NF4 text encoder on the GPU while streaming the DiT blocks from pinned CPU memory. It reduces peak VRAM at the cost of additional latency: ```bash Command theme={null} HF_TOKEN=$HF_TOKEN sglang serve \ --model-path fal/ideogram-v4-instant \ --num-gpus 1 \ --dit-layerwise-offload \ --layerwise-offload-components transformer \ --port 30010 ``` The same option applies to Fast. Layerwise offload was validated with a real Instant generation; TP2 and Ulysses/SP2 were validated separately without offload. The released Fast weights are stored in a floating-point pre-pack form and can be loaded directly, but fal trained them with QAD for an NVFP4 execution path. SGLang does not currently quantize dense NVIDIA DiTs to NVFP4 at load time, so direct Fast inference bypasses the intended quantization path and may be visibly degraded. Treat direct floating-point Fast inference as compatibility/testing support, not the production-quality path. The released Instant checkpoint is BF16 and is the recommended local checkpoint today. ## 4. Generate an image ```python Example theme={null} import base64 from openai import OpenAI client = OpenAI(api_key="EMPTY", base_url="http://localhost:30010/v1") response = client.images.generate( model="ideogram-ai/ideogram-4-nf4", prompt="A cinematic poster of a quiet bookstore at dusk with elegant hand-lettered signage", size="1024x1024", n=1, response_format="b64_json", extra_body={"preset": "V4_QUALITY_48", "seed": 0}, ) image_bytes = base64.b64decode(response.data[0].b64_json) with open("ideogram4.png", "wb") as f: f.write(image_bytes) ``` fal's hosted endpoint expands natural-language prompts, but these local checkpoints expect Ideogram 4's structured JSON caption format. Pass a complete caption as the API `prompt`, for example: ```python Example theme={null} import json prompt = json.dumps( { "high_level_description": ( "A bold typographic poster centered on the exact words INSTANT BY FAL, " "printed in black and electric orange on warm white paper." ), "compositional_deconstruction": { "background": "Warm white textured paper with generous negative space.", "elements": [ { "type": "text", "text": "INSTANT BY FAL", "desc": "Large uppercase geometric sans-serif lettering, precisely centered.", } ], }, }, ensure_ascii=False, separators=(",", ":"), ) response = client.images.generate( model="fal/ideogram-v4-instant", prompt=prompt, size="1024x1024", n=1, response_format="b64_json", extra_body={"seed": 42}, ) ``` Base Ideogram 4 presets are `V4_DEFAULT_20`, `V4_QUALITY_48`, and `V4_TURBO_12`. The fal variants automatically select `V4_FAST_20` and `V4_INSTANT_8`, respectively. A preset controls both `num_inference_steps` and guidance, so do not set those fields directly. You can also produce captions with a separate SRT LLM using [prompt enhancement](/docs/sglang-diffusion/models_with_pe). Configure an Ideogram-specific JSON caption template and schema; the generic prose template is not appropriate for these checkpoints. This does not reproduce fal's checkpoint-specific prompt expander or establish equivalent image quality. ## 5. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Image`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # JoyAI-Echo Source: https://docs.sglang.io/cookbook/diffusion/JoyEcho/JoyEcho Run JoyAI-Echo multi-shot audio–video generation with SGLang Diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. Prepare the [pinned Echo 1.0 checkpoint](#3-1-prepare-the-echo-1-0-checkpoint) and set `JOY_ECHO_MODEL_PATH` before starting the server. ## 2. Model capabilities [JoyAI-Echo](https://huggingface.co/jdopensource/JoyAI-Echo) is an 8-step long-form audio-video model built on LTX-2. Its paired memory bank carries decoded visual context and audio latents across prompt changes, making it strongest for multi-shot, minute-scale sequences that need continuity in both picture and soundtrack. Choose JoyEcho over a standard LTX pipeline when shots must share audiovisual memory. Its distilled 832×480 path prioritizes long-form continuity and throughput rather than the higher-resolution two-stage quality modes offered by LTX-2.3. SGLang materializes the Echo 1.0 monolithic release through the built-in [JoyAI-Echo overlay](https://huggingface.co/Niehen6174/JoyAI-Echo-overlay). Prepare the pinned checkpoint below before running the examples. | Aspect | Standard LTX-2.3 | JoyEcho | | - | - | - | | Pipeline | `LTX2Pipeline` / `LTX2TwoStageHQPipeline` | `JoyEchoPipeline` (default for this model) | | Denoising | Multi-step flow matching + CFG | LTX-2 DMD distilled path (8 steps, `guidance_scale=1.0`) | | Multi-shot | Not supported | Paired audio–video memory bank across shots | | Sequence parallelism | LTX-2 SP (video/audio sharded) | Ulysses SP (`ulysses_degree=2`): single-shot and multi-shot + memory bank | | Post-processing | Optional two-stage HQ upscaling | Per-shot mp4 output | > [!WARNING] > > Review the model license on the [JoyAI-Echo Hugging Face page](https://huggingface.co/jdopensource/JoyAI-Echo) before production or commercial use. SGLang support does not grant additional model usage rights. ## 3. Model Deployment ### 3.1 Prepare the Echo 1.0 checkpoint The native overlay requires `JoyAI-Echo-release.safetensors`. The upstream repository's Echo 1.5 revision does not contain that file. Download the [Echo 1.0 revision](https://huggingface.co/jdopensource/JoyAI-Echo/tree/4187f9a53c6eff3a76c51e79bd27f70d10f7591b) into the Hugging Face cache: ```bash theme={null} JOY_ECHO_MODEL_PATH=$(python - <<'PY' from huggingface_hub import snapshot_download print(snapshot_download( repo_id="jdopensource/JoyAI-Echo", revision="4187f9a53c6eff3a76c51e79bd27f70d10f7591b", allow_patterns=["JoyAI-Echo-release.safetensors", "*.json", "*.md", "LICENSE"], )) PY ) ``` Use the returned cache path as `--model-path` and keep `--model-id jdopensource/JoyAI-Echo` when using local weights. The model ID lets BCG select JoyEcho's support policy. Initial startup also downloads and materializes the overlay and its text encoder dependencies. ### 3.2 Serve the model JoyEcho uses the default `JoyEchoPipeline` registered for `jdopensource/JoyAI-Echo`. A single high-VRAM GPU (for example H100 or H200) is enough for the common 832x480 / 121-frame / 8-step setting. ```bash theme={null} sglang serve \ --model-path "$JOY_ECHO_MODEL_PATH" \ --model-id jdopensource/JoyAI-Echo ``` Optional environment variable for long runs: ```bash theme={null} export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True ``` For multi-GPU serving, tensor parallelism (TP) and **Ulysses sequence parallelism (SP)** are supported. JoyEcho SP uses an **asymmetric layout**: video target latents are time-sharded across ranks, while audio (including memory tokens) is **replicated** on every rank so cross-attention stays temporally aligned. Multi-shot runs with `enable_memory_bank=true` are supported on SP. ```bash theme={null} sglang serve \ --model-path "$JOY_ECHO_MODEL_PATH" \ --model-id jdopensource/JoyAI-Echo \ --num-gpus 2 \ --ulysses-degree 2 ``` > [!NOTE] > > JoyEcho SP currently targets **Ulysses-only** parallelism (`ulysses_degree=2`, `ring_degree=1`). Ring SP is not validated for this pipeline. For `sglang generate`, add `--num-gpus 2 --ulysses-degree 2` to the commands in section 4. ## 4. Model Invocation ### 4.1 Default sampling | Setting | Default | | - | - | | Resolution | 832x480 | | Frames | 121 | | FPS | 25 | | Steps | 8 | | Guidance scale | 1.0 | | Seed | 12345 | ### 4.2 Single-shot text-to-video ```bash theme={null} sglang generate \ --model-path "$JOY_ECHO_MODEL_PATH" \ --model-id jdopensource/JoyAI-Echo \ --prompt "A curious raccoon walks through a sunlit forest path" \ --height 480 --width 832 --num-frames 121 --fps 25 \ --num-inference-steps 8 --seed 42 \ --save-output ``` Disable the memory bank for standalone clips with a config file: ```bash theme={null} cat > /tmp/joy_echo_single.json <<'EOF' { "prompt": "A curious raccoon walks through a sunlit forest path", "enable_memory_bank": false, "seed": 42, "height": 480, "width": 832, "num_frames": 121, "fps": 25, "num_inference_steps": 8 } EOF sglang generate --config /tmp/joy_echo_single.json \ --model-path "$JOY_ECHO_MODEL_PATH" --model-id jdopensource/JoyAI-Echo \ --save-output ``` ### 4.3 Multi-shot generation JoyEcho does **not** generate all shots in one forward pass. Each shot is one generation request. Continuity is carried by an in-process **memory bank** on the pipeline instance. Typical workflow: 1. **Shot 0** — memory bank is empty; the model generates a standalone A/V clip. 2. **After decode** — decoded video frames and packed audio latents are committed to the memory bank (up to 7 slots by default). 3. **Shot 1+** — prior-shot frames are re-encoded and prepended as a memory prefix before denoising. 4. **Per-shot seeding** — official semantics use `prompt_seed = base_seed + shot_index`. Pass multiple prompts as a list in a config file: ```bash theme={null} cat > /tmp/joy_echo_4shot.json <<'EOF' { "prompt": [ "Shot 0: A raccoon wakes up in a cozy attic.", "Shot 1: The raccoon climbs down and opens the back door.", "Shot 2: It walks through a rainy alley under neon signs.", "Shot 3: The raccoon finds a warm bakery window and stops." ], "enable_memory_bank": true, "reset_memory_bank": true, "seed": 42, "height": 480, "width": 832, "num_frames": 121, "fps": 25, "num_inference_steps": 8 } EOF sglang generate --config /tmp/joy_echo_4shot.json \ --model-path "$JOY_ECHO_MODEL_PATH" --model-id jdopensource/JoyAI-Echo \ --save-output ``` You can also pass prompts from a text file (one prompt per line) with `--prompt-path`: ```bash theme={null} sglang generate \ --model-path "$JOY_ECHO_MODEL_PATH" \ --model-id jdopensource/JoyAI-Echo \ --prompt-path /tmp/joy_echo_shots.txt \ --seed 42 \ --height 480 --width 832 --num-frames 121 --fps 25 \ --num-inference-steps 8 \ --save-output ``` ### 4.4 Memory bank controls | Parameter | Default | Meaning | | - | - | - | | `enable_memory_bank` | `true` | Read/write the paired A/V memory bank between shots. | | `reset_memory_bank` | `true` | Clear the bank and shot counter at the start of a new session (`request_id` change or first shot). | Set `enable_memory_bank=false` when you want independent shots without cross-shot continuity. ### 4.5 Measured two-H200 single-shot configuration For short independent clips, keep the text and audio/video components on GPU with `--component-residency=all=resident`. Full-stage profiles showed that this removes repeated host-to-device weight copies between component uses. The following configuration was measured on two H200s with Ulysses degree 2, TP1, PyTorch 2.11.0+cu130, 640x384, 33 frames, 8 steps and seed 42. It disables compilation and the memory bank: ```bash theme={null} cat > joy_echo_h200.json <<'EOF' {"enable_memory_bank": false} EOF CUDA_VISIBLE_DEVICES=0,1 sglang generate \ --model-path "$JOY_ECHO_MODEL_PATH" --model-id jdopensource/JoyAI-Echo \ --config joy_echo_h200.json --prompt "A curious raccoon" \ --width 640 --height 384 --num-frames 33 --num-inference-steps 8 --seed 42 \ --num-gpus 2 --ulysses-degree 2 \ --performance-mode manual --enable-torch-compile=false --quality exact \ --component-residency=all=resident --warmup-mode request \ --save-output --perf-dump-path joy_echo_h200.json.perf ``` For BCG, add `--enable-breakable-cuda-graph --warmup-resolutions 640x384 --warmup-num-frames 33`. Check for successful `[Diffusion BCG] captured` logs and absence of request signature misses. Keep the same model ID, resolution, frame count and quality as warmup. Two fresh-process saved requests per configuration, after request warmup: | Lossless mode | Auto residency E2E | All resident E2E | Reduction | Peak reserved per rank, auto → resident | | - | -: | -: | -: | -: | | Eager | 2.563 s | 2.366 s | 7.65% | 46.43 → 69.32 GiB | | BCG | 1.229 s | 1.058 s | 13.88% | 48.77–48.88 → 69.32 GiB | Loading, warmup and profiling are excluded from these timings. The paired eager profiles remove 71 pinned host-to-device copies (13.07 GB, 278.86 ms on the profiled rank), with the same 77,045 kernel launches. All eight lossless outputs have pixel-identical video frames; audio differences are comparable to baseline repeat variability. These results cover this compact single-shot workload, rather than the default 121-frame or multi-shot memory-bank workload. Use `quality=lossless` for this recipe. High-mode output did not pass the separate quality comparison, and high + BCG is rejected by the runtime. If a larger request exceeds available memory, return to auto residency or keep only selected components resident. ## 5. Practical Tips * Use `--num-inference-steps 8` and `--guidance-scale 1.0` to match the official JoyEcho DMD distilled path. * Multi-shot prompts can be passed as a `prompt` list, via `prompt_path`, or as sequential API calls on the same server instance. * The memory bank caps at **7 slots**; from shot 8 onward the oldest slots roll off. * For **2-GPU latency**, try **Ulysses SP** (`--num-gpus 2 --ulysses-degree 2`) on both single-shot and multi-shot runs. Use **TP** when you need a different sharding strategy or more than two GPUs. * Set `PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True` for long multi-shot SP sessions. * JoyEcho outputs per-shot mp4 files with synchronized audio. There is no built-in two-stage HQ upscaling path like LTX-2.3 HQ. ## 6. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Video`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # Kandinsky6 Source: https://docs.sglang.io/cookbook/diffusion/Kandinsky/Kandinsky6 Deploy Kandinsky 6.0 for joint text- and image-conditioned video and audio generation. ## 1. Quick start Use Linux with NVIDIA CUDA. This model is not yet in a released package; use a checkout containing this implementation, not an unmodified release image. Your Hugging Face account must have access to the checkpoint; authenticate with `hf auth login` or supply `HF_TOKEN` in the server environment. Install from the repo root: ```bash theme={null} uv pip install -e "python[diffusion]" --prerelease=allow ``` Start with Pro-distill and resident weights on B200, GB300, or RTX PRO 6000 (96 GB). The picker separates verified lightweight HTTP requests from full-size offline generation and unverified custom topologies. See the [installation guide](/docs/sglang-diffusion/installation) for platform setup. The request returns a video job ID, not the video bytes. Poll `GET /v1/videos/{id}` until `status` is `completed`, then download `GET /v1/videos/{id}/content` for the MP4 containing both video and audio. Treat `failed` as an error; delete the job with `DELETE /v1/videos/{id}` when finished. See [Download a completed video](#5-download-a-completed-video) for a complete polling example. ## 2. Model capabilities Kandinsky 6.0 generates video and audio jointly from a text prompt, optionally conditioned on a reference image. One DiT predicts both modalities at each denoising step. A Reason1 encoder derived from Qwen2.5-VL supplies token features, and CLIP supplies pooled text features. Both request modes use the same server; image conditioning does not require switching checkpoints. Choose Pro-distill for the 10-step path, or Pro for 50-step classifier-free guidance. The recipes cover 768 x 512, 121-frame clips at 24 fps. They use native SGLang components, without calling a third-party model pipeline. Validation compares against the initial SGLang implementation; it does not establish parity with the unpublished Kandinsky6 Diffusers implementation. | Checkpoint | Scheduler | Default steps | Default guidance | | - | - | -: | -: | | `kandinskylab/Kandinsky-6.0-Pro-distill-5s-Diffusers` | PiFlow | 10 | 1.0 | | `kandinskylab/Kandinsky-6.0-Pro-5s-Diffusers` | Flow-match Euler | 50 | 5.0 | Pro-distill only accepts guidance 1.0 and does not encode a negative prompt. The scheduler is loaded from the checkpoint. For a local directory with an unrelated name, specify `--model-id Kandinsky-6.0-Pro-distill-5s-Diffusers` to select its sampling defaults, or explicitly pass 10 steps and guidance 1.0. ## 3. Offline generation The default request produces a muxed video and audio file: ```bash theme={null} sglang generate \ --model-path kandinskylab/Kandinsky-6.0-Pro-distill-5s-Diffusers \ --performance-mode speed --attention-backend fa --warmup-mode off \ --prompt "A woman chops vegetables in a sunlit kitchen, with soft jazz playing." \ --seed 42 --save-output ``` Add `--image-path /path/to/reference.png` for image conditioning. On RTX PRO 6000, use `--attention-backend torch_sdpa` in the CLI or `attention_backend="torch_sdpa"` in Python. For two B200 GPUs, add `--num-gpus 2 --tp-size 1 --ulysses-degree 2 --ring-degree 1`. To use Pro, change the model path; its defaults select 50 steps and guidance 5.0. ### Python API ```python theme={null} from sglang.multimodal_gen import DiffGenerator generator = DiffGenerator.from_pretrained( model_path="kandinskylab/Kandinsky-6.0-Pro-distill-5s-Diffusers", num_gpus=1, performance_mode="speed", attention_backend="fa", warmup_mode="off", ) try: result = generator.generate(sampling_params_kwargs={ "prompt": "A woman chops vegetables in a sunlit kitchen, with soft jazz playing.", "seed": 42, "save_output": True, "output_path": "kandinsky6_samples", "return_file_paths_only": False, "return_frames": True, }) print(result.output_file_path) finally: generator.shutdown() ``` `result.frames` contains RGB frames and `result.audio` contains the decoded waveform. Add `image_path` to the sampling parameters for a reference image. Omit the two return-data flags when only the output file is needed. ## 4. Parallelism and memory * **Ulysses**: full-size Pro-distill generation on two B200 or four GB300 GPUs matches single-GPU output on the same hardware, including every decoded RGB frame and the audio waveform. It shards the video stream; audio and text streams remain replicated. Video K/V is gathered for audio-to-video attention. * **CFG parallel**: Pro can distribute its conditional and unconditional branches with `--num-gpus 2 --ulysses-degree 1 --enable-cfg-parallel`. This is a different topology from Ulysses. It does not accelerate Pro-distill, which has no guidance branch. * **TP and Ring**: implemented, but full-model outputs differ from the single-GPU baseline. Do not treat them as verified bitwise-equivalent modes. Ring2, Ring4, and TP2 x Ring2 complete full-size Pro-distill generation on GB300 and repeat exactly within each topology. Ring2 serving also covers image conditioning, Cache-DiT, and dynamic/merged LoRA restoration. Use `--num-gpus 2 --ulysses-degree 1 --ring-degree 2` to select Ring2; validate both video and audio quality before deployment. * **TP x SP**: four-GB300 TP2 x Ulysses2 full generation is tested. It reduces weight memory but was slower than Ulysses4 and produced different video and audio. Prefer Ulysses when memory permits; validate quality before deploying TP. * **FSDP + Ulysses**: add `--use-fsdp-inference true` to shard DiT weights without sharding linear reductions. Four-GB300 Ulysses4 generation matches resident Ulysses4 in every decoded RGB frame and the audio waveform. This is a lower-memory alternative with additional weight-gather latency, not a faster default. Request-level Cache-DiT switching is also tested with FSDP. * **Encoder parallelism**: `--encoder-parallel fold` shards Reason1 and CLIP across the DiT replica, including a Ulysses-only replica. Four-GPU generation is tested, but folding changes reductions and the generated video and audio. Keep `auto` for the baseline recipes and validate quality before forcing folding. See [Encoder parallelism](/docs/sglang-diffusion/encoder_parallel). * **Offload**: keep components resident when memory allows. Use `--cpu-offload-components transformer text_encoder vae` for whole-component offload, or `--layerwise-offload-components all` for layerwise offload. Layerwise offload includes both DiT text towers and the audio VAE's encoder, decoder, and vocoder blocks. Use component-specific residency settings to keep selected components resident. Both require host RAM and add transfers; lower device memory does not imply lower total memory or lower latency. The picker's **Server** tab exposes attention, weight placement and offload components. With DiT layerwise offload, you can also tune prefetch depth and resident layers using `--dit-offload-prefetch-size` and `--dit-layerwise-resident-layers`. Increasing either uses more VRAM; these non-default settings are unverified tuning choices, not faster recommendations. Component offload moves whole components; layerwise offload streams supported blocks. They are alternatives to FSDP in this picker, not additive presets. ### Deployment limits Use monolithic serving. Encoder/denoiser/decoder disaggregation is not supported. Breakable CUDA graphs are also not enabled for Kandinsky6: the server disables `--enable-breakable-cuda-graph`. Its variable-length text path needs additional handling to preserve the unpadded computation; same-shape graph experiments do not establish support for arbitrary requests. Keep eager execution for the recipes on this page. ### Choosing a topology Pro-distill, batch 1, 768 x 512, 121 frames, 10 steps, BF16/FA, no offload or compilation, on GB300 with 277.5 GiB per GPU: | Topology | Hot E2E (s) | Output-rank peak reserved (GiB) | Matches single-GPU RGB/audio | | - | -: | -: | - | | Single GPU | 33.95 | 80.36 | Reference | | Ulysses4 | 11.33 | 80.91 | Exact | | Ulysses4 + FSDP | 12.13 | 42.54 | Exact | | TP2 x Ulysses2 | 13.99 | 50.97 | No | | TP4 | 17.72 | 35.91 | No | Times are medians of three hot requests after one initial request, with startup warmup disabled and default conditioning caching enabled. They include MP4 saving but exclude model loading. Memory is PyTorch runtime peak reserved on the output rank, not loading peak or the maximum across all GPUs. These results do not establish output quality for TP; TP also changes the text encoder's numerical path. For this workload, FSDP reduces measured memory by 47% versus resident Ulysses4 at a 7% latency cost. Add it when weight memory is the constraint; keep ordinary Ulysses when latency is the priority. ### RTX PRO 6000 and SageAttention3 Pro-distill also runs with resident weights on one 96 GB RTX PRO 6000 Blackwell Server Edition. Use `--attention-backend torch_sdpa` on this SM120 device: the current platform resolves `fa` to SDPA, so requesting `fa` does not establish a FlashAttention benchmark. With [SageAttention3](https://github.com/thu-ml/SageAttention/tree/d1a57a546c3d395b1ffcbeecc66d81db76f3b4b5/sageattention3_blackwell) installed, `--component-attention-backends transformer=sage_attn_3` selects it only for the DiT, keeping the encoders on SDPA. The tested upstream revision requires SM120/121 and rejects B200 SM100. With PyTorch 2.14, its build required `NVCC_APPEND_FLAGS=-std=c++20`; no kernel source or hardware guard was modified. Same full-size workload and timing method as above, on one RTX PRO 6000 with driver 595.84, PyTorch 2.14.1+cu130, Transformers 5.17.0, and Diffusers 0.37.0: | DiT backend | Hot E2E (s) | Runtime peak reserved (GiB) | | - | -: | -: | | SDPA | 133.91 | 80.34 | | SageAttention3 | 105.33 | 82.05 | Sage3 reduced latency by 21.3% but changed the outputs substantially: all-frame PSNR 11.97 dB, mean SSIM 0.375, and raw-audio waveform SNR -2.21 dB versus SDPA. These are paired differences, not perceptual quality scores. Each backend was repeatable across four requests, but Sage3 is **not lossless** and is not the default recipe. Validate both video and audio before choosing it. ### VAE decode The video VAE defaults to tiled decoding, including multi-GPU execution. Its decode group is separate from the DiT's TP and CFG collectives. Explicit `--vae-config.parallel-decode-mode spatial_shard` uses whole-clip decoding with frame-causal attention computed without a quadratic whole-video mask. Whole-clip decoding still needs substantial activation memory. A 768 x 512, 121-frame run on two B200 GPUs completed with the transformer, both text encoders, and audio VAE offloaded, but reached 170.4 GiB output-rank peak reserved. This is not a lower-memory replacement for tiled decode. Tiled and whole-clip decoding use different normalization and attention contexts and are not interchangeable numerical baselines; keep tiled decoding for the validated default output. The audio VAE contains both the mel decoder and vocoder. Current checkpoints include a complete vocoder copy inside `audio_vae`, so this pipeline does not also load the redundant standalone `vocoder` component. CUDA matrix RoPE uses a fused kernel that preserves the eager FP32 rounding boundaries. CPU and autograd paths retain the eager implementation. No sampling parameter or sparse-attention approximation is introduced. The checkpoint's 128-wide Q/K normalization uses native PyTorch FP32 fusion during CUDA inference without changing the stored parameter dtype or offload policy. Other head widths retain the original normalization path. ### Cache-DiT Cache-DiT is opt-in per request through `enable_cache_dit` and `cache_dit_params` in the Python sampling parameters or the JSON `/v1/videos` body. Set `enable_cache_dit: false` to restore uncached execution without restarting. See [Cache-DiT configuration](/docs/sglang-diffusion/cache_dit) for the available knobs. The **Request** tab offers an opt-in Cache-DiT switch for both text and image conditioning. It uses the runtime cache defaults, not a quality-calibrated preset. A short request may finish before cache warmup ends and gain no speedup. The adapter caches both evolving video and audio streams together. Its dynamic decision uses the video residual, not an independent audio-quality metric. Skipping blocks is approximate and can change both outputs substantially; validate video and audio on your own prompts before enabling it. It is not part of the lossless defaults, and should not be combined with breakable CUDA graphs. ### LoRA adapters Use adapters trained for the same Kandinsky6 checkpoint architecture. The native loader accepts PEFT A/B weights with Diffusers or SGLang DiT layer names, including the `transformer.` prefix. Both video and audio branches belong to `transformer`; an adapter can change both outputs. Add `--lora-path /path/to/adapter.safetensors` to load an adapter at startup. To switch an existing server to dynamic LoRA without restarting: ```bash theme={null} curl --fail-with-body http://localhost:30000/v1/set_lora \ -H "Content-Type: application/json" \ -d '{ "lora_nickname": "kandinsky6", "lora_path": "/path/to/adapter.safetensors", "target": "transformer", "strength": 1.0, "merge_mode": "dynamic" }' ``` The adapter path must be readable by the server. `dynamic` applies the low-rank update during inference; `merge` updates the base weights before inference. These modes may differ numerically. To disable either mode and restore the base model: ```bash theme={null} curl --fail-with-body http://localhost:30000/v1/unmerge_lora_weights \ -H "Content-Type: application/json" -d '{"target": "transformer"}' ``` Adapter selection is server-wide, not isolated per request. Coordinate changes with other clients. Merging offloaded weights retains CPU snapshots of the modified layers for exact restoration; budget for this host memory. Validation uses synthetic adapters to check loading, strength changes, repeatability, and exact restoration of video and audio; it does not establish the quality of a community adapter. See the [model inventory](/docs/sglang-diffusion/compatibility_matrix) and the [super-resolution recipe](/cookbook/diffusion/Kandinsky/Kandinsky6-SR) for the separate video SR pipeline. ## 5. Download a completed video Use the `id` returned by the picker's Request command. The same endpoints serve joint generation and SR. Set the base URL to match your server port: ```python Download theme={null} import json import shutil import time import urllib.request base_url = "http://localhost:30000" video_id = "REPLACE_WITH_RETURNED_ID" deadline = time.monotonic() + 1800 while time.monotonic() < deadline: with urllib.request.urlopen(f"{base_url}/v1/videos/{video_id}", timeout=30) as response: job = json.load(response) if job["status"] == "failed": raise RuntimeError(job) if job["status"] == "completed": with urllib.request.urlopen( f"{base_url}/v1/videos/{video_id}/content", timeout=120 ) as response, open("output.mp4", "wb") as output: shutil.copyfileobj(response, output) break time.sleep(2) else: raise TimeoutError("Video generation did not finish within 30 minutes") ``` After downloading, remove the server-side job when no longer needed: ```bash Cleanup theme={null} curl --fail-with-body -X DELETE http://localhost:30000/v1/videos/REPLACE_WITH_RETURNED_ID ``` ## 6. ComfyUI There is no Kandinsky6 integrated DiT executor in the [ComfyUI plugin](/docs/sglang-diffusion/comfyui). The generic server video node has not been validated for this model's joint audio/video output. Use the HTTP or offline recipes above until that integration is verified. # Kandinsky6 SR Source: https://docs.sglang.io/cookbook/diffusion/Kandinsky/Kandinsky6-SR Deploy Kandinsky 6 video super-resolution with x2, x4 or x2.25 upscaling, source audio and explicit decode speed, memory and numerical tradeoffs. ## 1. Quick start Use Linux with NVIDIA CUDA and a checkout containing this implementation; it is not yet in a released package or unmodified release image. Authenticate an account with checkpoint access using `hf auth login`, or supply `HF_TOKEN` to the server. From the repo root: ```bash Install theme={null} uv pip install -e "python[diffusion]" --prerelease=allow ``` The picker uses the distilled two-step checkpoint. Four-GB300 whole-tile decode is the output-preserving choice measured on multi-tile clips; one GPU suffices for a functional check when it has enough memory. The picker also includes explicitly **extrapolated** Hopper and RTX 5090 starting points, not measured speed or memory guarantees. HTTP verification is scoped separately from offline measurements. See the [installation guide](/docs/sglang-diffusion/installation) for platform setup. The request uploads a local video and returns a job `id`. Poll `GET /v1/videos/{id}`, then download `GET /v1/videos/{id}/content` when completed. Use the shared [polling and download example](/cookbook/diffusion/Kandinsky/Kandinsky6#5-download-a-completed-video). For JSON requests, `video_path` refers to a file on the **server**, not the client. ## 2. Model capabilities Kandinsky 6 VSR upscales a source video without a prompt. It encodes the source with a causal KVAE, denoises overlapping tiles and blends their decoded outputs. Unlike the [generation model](/cookbook/diffusion/Kandinsky/Kandinsky6), it retains the source soundtrack rather than generating audio. Audio is converted to mono 44.1 kHz and trimmed to the processed video duration. Use `kandinskylab/Kandinsky-6.0-VSR-distilled2steps-5s-Diffusers` for x2, x4 or x2.25 upscaling of up to 121 frames. Its checkpoint-selected PiFlow scheduler uses two DiT calls per tile; changing `num_inference_steps` does not increase quality or the number of evaluations. The scheduler and transformer must come from the same Diffusers checkpoint; sampler settings are read from `scheduler/`. The native path uses dense attention, not the checkpoint's requested NABLA sparse attention, so this is not a claim of numerical parity with the sparse reference. > [!WARNING] > > The tested non-distilled `Kandinsky-6.0-VSR-5s-Diffusers` revision > `d6ddfabc62b3920b6da6487e4f444d37c591d5f4` declares a flow-Euler scheduler but > contains a 640-wide output head instead of the required 64. It is not supported > as-is. Do not change the scheduler to bypass this error; use the distilled model. ## 3. Offline usage No prompt is required. A single-GPU example: ```bash Generate theme={null} sglang generate \ --model-path kandinskylab/Kandinsky-6.0-VSR-distilled2steps-5s-Diffusers \ --video-path /path/to/input.mp4 \ --sr-resolution-scale 2 \ --num-inference-steps 2 \ --seed 42 --save-output --output-path ./sr_outputs ``` > **Python API** > > ```python Generate theme={null} > from sglang.multimodal_gen import DiffGenerator > > generator = DiffGenerator.from_pretrained( > model_path="kandinskylab/Kandinsky-6.0-VSR-distilled2steps-5s-Diffusers", > num_gpus=1, > ) > try: > result = generator.generate(sampling_params_kwargs={ > "video_path": "/path/to/input.mp4", > "sr_resolution_scale": 2, > "num_inference_steps": 2, > "seed": 42, > "output_path": "sr_outputs", > "save_output": True, > }) > print(result.output_file_path) > finally: > generator.shutdown() > ``` ### Request parameters * `sr_resolution_scale`: `2`, `4` or `2.25` (default). The x2.25 path first enlarges pixels x1.125, then processes x2 tiles. * `sr_tiles_batch_size`: default `1`. More tiles per DiT call need more activation memory. Each chunk is seeded by its first tile index, so changing this value changes the noise and output. It is **not a lossless batching optimization**. * `sr_tile_min_overlap`: default `0.2`. Changing overlap changes tile geometry and blending, not just performance. * `sr_target_resolution`: optional `hd`, `fullhd`, `2k` or `WxH`; only downscales the generated result. `sr_target_resize_mode` is `fit` (default) or `exact`. * `seed`: default `42`. Compare identical seeds, tile batching, source frames and attention policy when evaluating a decode optimization. The input must fit at least one tile. A tested landscape source is 384 x 256. The default filename is `_srx_.mp4`; override it with `--output-file-name`. ## 4. Decode speed, memory and numerics These are **VAE decode choices**, independent of DiT TP/Ulysses/Ring:
DecodeHot E2EPeak reservedOutput versus serial
Serial45.26 s47.55 GiBReference
Whole-tile parallel21.73 s47.55 GiBRGB and audio exact in this test
Spatial shard18.01 s24.37 GiBRGB differs; audio exact
Setup: four GB300 GPUs (277.5 GiB each, NV18 links), host RAM 955.7 GiB with an 860 GiB cgroup limit; BF16/FA, Ulysses4, resident weights, no compile or startup warmup. PyTorch 2.14.1+cu130, Transformers 5.17.0, Diffusers 0.37.0. Distilled checkpoint revision `3e3e10bcd23659eeeb23cac740258ee4fc14aa7d`; seed 42, tile batch 1, two steps per tile. A generated kitchen clip, 768 x 512 x 121 frames at 24 fps, was upscaled x2 to 1536 x 1024. Times are medians of three hot requests after one initial request, including MP4 saving and excluding model loading. Memory is PyTorch request peak reserved on the output rank, not loading, NVML or the maximum across ranks. Host memory is not claimed unchanged. **Whole-tile parallel** assigns complete existing tiles to ranks and preserves their temporal caches and blend order. It matched serial RGB and raw audio exactly on the tested workloads **within the same topology**. Select `--vae-config.use-parallel-tiling true`. A single tile falls back to serial. Communication can outweigh savings for small clips or slow interconnects. **Spatial shard is not bitwise lossless.** It splits each tile's height, using halo exchanges and the original temporal cache. Changed convolution shapes change rounding. In the experiment above, all-frame RGB PSNR was **57.51 dB**, minimum SSIM over the first/middle/last frames **0.99921**, mean absolute difference **0.1132/255**, and maximum difference **4/255**. Audio was exact. These measurements are not a guarantee for other videos or perceptual-quality certification. Select it only after validating the output for your workload: ```bash Spatial decode flags theme={null} --vae-config.use-parallel-decode true --vae-config.parallel-decode-mode spatial_shard ``` Both modes are opt-in runtime features. The picker selects whole-tile parallel for its multi-tile recipe; it does not change runtime defaults. If both flags are enabled, spatial sharding takes precedence. One GPU or a tile too short to split retains replicated decoding. Neither mode changes the tile geometry. ### RTX PRO 6000 over PCIe | GPUs / placement | Decode | Hot E2E | Sampled GPU peak | | - | - | - | - | | 1 / resident | Serial | 134.09 s | 48.91 GiB | | 2 / resident, Ulysses2 | Serial | 122.11 s | 48.81 GiB | | 2 / resident, Ulysses2 | Whole-tile | 83.04 s | 48.81 GiB | | 2 / resident, Ulysses2 | Spatial | 73.62 s | 37.45 GiB | | 1 / all-layerwise offload | Serial | 133.60 s | 37.43 GiB | Setup: two RTX PRO 6000 Blackwell Server Edition GPUs (96GB nominal), PCIe/SYS across CPU sockets, **no NVLink**; 499.2 GiB host RAM, no cgroup cap. Driver 595.84, the same PyTorch/Transformers/Diffusers versions and checkpoint as above, but **SDPA**, not FA. A separate generated 768 x 512 x 121-frame clip at 24 fps was upscaled x2 with seed 42, tile batch 1 and two steps per tile. Each row uses one initial request and three hot requests, no compile/startup warmup. E2E includes MP4 saving and raw-frame return, excludes model loading. GPU memory is the maximum **per-GPU NVML sample across ranks**, sampled every 0.5 seconds during requests, not the sum or PyTorch reserved memory; brief peaks may be missed. These are within-machine comparisons, not GB300-versus-RTX speed ratios. Ulysses2 alone reduced latency by only 8.9%. Whole-tile decode reduced it by 38.1% versus one GPU, with **exact RGB/audio** in this test. Spatial reached 45.1% lower latency, but RGB differed: PSNR **57.54 dB**, minimum sampled SSIM **0.99919**, maximum difference **4/255**; audio remained exact. All five configurations reproduced their own outputs across repeated requests. Layerwise offload reduced memory with essentially unchanged latency here; this does not make offload free on other workloads or slower host links. A separate **memory-budget probe**, still on RTX PRO 6000, completed the full clip twice with all-layerwise offload and a **30 GiB PyTorch allocator cap**. Sampled whole-GPU usage peaked at **31.03 GiB**, and RGB/audio matched the resident baseline exactly. The cap excludes CUDA allocations outside PyTorch; it is a test setting, not a deployment recommendation. This supports trying the 32GB recipe, but is **not a 5090 speed, memory-fit or quality measurement**. The complete HTTP regression also passed on one-GPU resident serial, Ulysses2 resident whole-tile and one-GPU layerwise serial with the allocator cap: six requests each covering JSON, uploads, x2/x4/x2.25, tile batch 2, audio/silent inputs and repeated-request equality. Arbitrary videos still need their own validation. ### Small workloads do not necessarily scale On GB300, a 384 x 256 x 33-frame source upscaled x2 (one tile, serial decode, otherwise the same BF16/FA/seed/step policy) took **1.77 s on one GPU, 1.72 s on Ulysses2 and 1.74 s on Ulysses4**. These are three-hot-request medians including saving. The roughly 2% difference is not evidence of a useful speedup; prefer one GPU for this workload. More tiles, not just more GPUs, create work that whole-tile decoding can distribute. ## 5. Memory and parallelism ### Hardware and GPU counts | Hardware | Starting point | Evidence boundary | | - | - | - | | GB300 | Resident, FA; Ulysses4 + whole-tile for multi-tile clips | Measured offline; smaller 1/2/4-GPU workloads also tested | | RTX PRO 6000 96GB | Resident, SDPA; compare 1 GPU with Ulysses2 | PCIe measurements, not a substitute for 5090 memory validation | | H100 80GB / H200 141GB | Resident, FA; start with 1 GPU, then Ulysses2/4 | Extrapolated from native CUDA support; no Hopper SR measurement | | B200 | Resident, FA; start with 1 GPU, then Ulysses2/4 | Extrapolated SR recipe; generation-model tests do not validate SR | | RTX 5090 32GB | SDPA, layerwise offload, tile batch 1; short 384 x 256 input first | Extrapolated from the RTX memory-budget probe; no 5090 execution claim | Only compare GPU counts on the **same input, scale, tile batching and backend**. For small single-tile clips, one GPU avoids communication overhead. For larger multi-tile clips, try Ulysses2/4 with whole-tile decode; extra GPUs do not divide replicated KVAE/latent-upscaler weights. Spatial decode can reduce activation memory, but changes rounding. Offload needs sufficient host RAM as well as VRAM. Do not extrapolate NVLink scaling to a PCIe system, especially across CPU sockets. Eight-GPU FA configurations are selectable as **Ulysses4 x Ring2**, not Ulysses8: 28 heads are not divisible by 8. This is an unmeasured topology, not a speedup recommendation. The current RTX SDPA path has no Ring support, so the picker rejects that combination. Start with fewer GPUs before trying an eight-GPU run. ### Placement and topology DiT Ulysses, TP, Ring and TP x SP are supported. For example, use `--num-gpus 4 --tp-size 1 --ulysses-degree 4` for Ulysses4, or `--num-gpus 4 --tp-size 2 --ulysses-degree 2` for TP2 x Ulysses2. TP times Ulysses must divide the checkpoint's 28 attention heads. **TP and Ring can change output numerics independently of decode mode**; whole-tile decode being exact does not make a TP/Ring topology change lossless. The decode group includes TP/SP ranks within each DP replica, not different requests. KVAE encoding, latent upscaling and tile scheduling remain replicated. For short two-step clips, extra GPUs can add communication without a speedup. Keep components resident when memory permits. For less GPU weight memory, use `--layerwise-offload-components all`, or select `vae latent_upscaler` instead. Temporal caches and non-block weights remain on GPU. Offload is compatible with both decode modes, but consumes host RAM and adds transfers for tiles and temporal segments. The assembled output also occupies host memory until saved. The **Server** tab also offers whole-component offload with `--cpu-offload-components`, selectable offload components, and DiT prefetch and resident-layer counts when streaming the DiT. Increasing those counts consumes additional VRAM. Partial offload recipes, non-default layer counts and FSDP (`--use-fsdp-inference true`) are **unverified options**, not measured improvements. FSDP requires multiple GPUs; SDPA cannot be combined with Ring. The default backend is FA on datacenter Blackwell/Hopper and SDPA on RTX. Hardware starting points do not automatically adapt to every uploaded video's memory demand. Request scale and tile batching do not require restarting the server. ## 6. Limits * **Input:** at most 121 frames. Sources near 24 fps retain their frames; faster videos are subsampled, slower videos retain their native rate. This can change the source timing; SR is not a bit-preserving video/audio transcode. * **Attention:** this native path is dense. Do not compare it with a NABLA sparse reference and attribute every difference to parallel decoding. The latent upscaler uses SDPA motion attention when `natten` is unavailable. * **Deployment:** monolithic only. Disaggregated roles, `torch.compile`, LoRA, direct latent inputs and KVAE-bridge chaining are not supported. * **Loading:** component config and weight mismatches fail explicitly. For a renamed local checkpoint, pass `--model-id Kandinsky-6.0-VSR-distilled2steps-5s-Diffusers` to retain SR routing. See the [compatibility matrix](/docs/sglang-diffusion/compatibility_matrix) for other model families. The opt-in server regression is `python/sglang/multimodal_gen/test/server/test_server_kandinsky6_sr.py`; it covers uploads, JSON, all three scales, source audio and repeated requests, not official pipeline parity. # Krea-2 Source: https://docs.sglang.io/cookbook/diffusion/Krea/Krea-2 Deploy Krea-2 with SGLang - fast, high-quality text-to-image generation. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. ## 2. Model capabilities [Krea-2](https://huggingface.co/krea/Krea-2-Turbo) is Krea's photorealistic text-to-image family, built as a single-stream MMDiT with a Qwen3-VL text encoder and Qwen-Image VAE. Both public variants use the same native SGLang pipeline and differ mainly in their sampling target. Choose Turbo for interactive generation: it is distilled to 8 steps with `guidance_scale=1.0`. Choose Raw when maximum fidelity matters more than latency: it uses roughly 52 steps with classifier-free guidance. Neither checkpoint is an image-editing model; use the Qwen-Image-Edit or FLUX.2 path when an input image must be preserved or transformed. | Variant | Model ID | Sampling profile | | - | - | - | | Turbo | `krea/Krea-2-Turbo` | 8 steps, no CFG; fastest path | | Raw | `krea/Krea-2-Raw` | About 52 steps with CFG; higher-fidelity path | ## 3. Model Deployment This section covers deploying Krea-2-Turbo for fast, high-quality image generation. ### 3.1 Basic Configuration Intel Xeon CPU deployment is supported with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu` and the selected Krea-2 checkpoint. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu sglang serve --model-path krea/Krea-2-Turbo ``` Krea-2-Turbo generates high-quality images in only 8 inference steps. Launch the server with: ```bash Command theme={null} sglang serve \ --model-path krea/Krea-2-Turbo \ --num-gpus 1 \ --port 30000 ``` The step count and guidance scale are **request-time** settings (see [API Usage](#4-api-usage)); Krea-2-Turbo defaults to 8 steps with `guidance_scale = 1.0`. ### 3.2 Configuration Tips See [Performance Optimization](/docs/sglang-diffusion/performance-optimization) for acceleration features and their runtime requirements. * `--num-gpus`: Number of GPUs to use. * Multi-GPU (tensor and/or sequence parallelism): see [Section 3.3](#3-3-multi-gpu-tensor-and-sequence-parallelism). ### 3.3 Multi-GPU: tensor and sequence parallelism Krea-2 supports two multi-GPU axes that can be combined; `--num-gpus` must equal `tp_size × ulysses_degree`. * **Tensor parallelism (`--tp-size N`)** shards the DiT weights across GPUs, lowering per-GPU VRAM. Krea-2's attention heads (48 query / 12 KV) and text heads (20) are divisible by a tp size of 1, 2, or 4. * **Sequence parallelism / Ulysses (`--ulysses-degree N`)** shards the image-token sequence across GPUs while keeping the text prefix replicated. It does **not** shard weights (per-GPU VRAM is unchanged), but its output is **bitwise-identical** to single-GPU. It currently requires a single prompt per request (ragged/padded multi-prompt batches under SP are not supported — use `--tp-size` for those). ```bash Command theme={null} # Tensor parallel (2 GPUs) — lowest per-GPU VRAM (DiT weights sharded) sglang serve --model-path krea/Krea-2-Turbo --num-gpus 2 --tp-size 2 --port 30000 # Sequence parallel / Ulysses (2 GPUs) — output bitwise-identical to single-GPU sglang serve --model-path krea/Krea-2-Turbo --num-gpus 2 --ulysses-degree 2 --port 30000 # Hybrid TP × SP (4 GPUs) — composes both axes sglang serve --model-path krea/Krea-2-Turbo --num-gpus 4 --tp-size 2 --ulysses-degree 2 --port 30000 ``` Measured on 2× H200 (Krea-2-Turbo, 8 steps, 1024×1024): `--tp-size 2` and `--ulysses-degree 2` each give \~1.7× denoise speedup over single-GPU; the hybrid TP=2 × SP=2 reaches \~2.8× on 4 GPUs. **Choosing:** on memory-constrained GPUs prefer `--tp-size` (it shards the \~24 GB DiT, e.g. \~38 GB → \~27 GB per GPU on 2 GPUs); on large-VRAM GPUs sequence parallelism is marginally faster and numerically exact, and the two compose for the highest throughput. ## 4. API Usage For complete API documentation, please refer to the [official API usage guide](/docs/sglang-diffusion/api/openai_api). ### 4.1 Generate an Image Generate an image with the OpenAI-compatible images API: ```python Example theme={null} import base64 from openai import OpenAI client = OpenAI(api_key="EMPTY", base_url="http://localhost:30000/v1") response = client.images.generate( model="krea/Krea-2-Turbo", prompt="a red fox sitting in fresh snow, golden hour, photorealistic", n=1, response_format="b64_json", ) # Save the generated image image_bytes = base64.b64decode(response.data[0].b64_json) with open("output.png", "wb") as f: f.write(image_bytes) ``` You can also generate a single image from the command line: ```bash Command theme={null} sglang generate --model-path krea/Krea-2-Turbo \ --prompt "a red fox sitting in fresh snow, golden hour, photorealistic" \ --num-inference-steps 8 --height 1024 --width 1024 --save-output ``` ### 4.2 Advanced Usage #### 4.2.1 Cache-DiT Acceleration SGLang integrates [Cache-DiT](https://github.com/vipshop/cache-dit), a caching acceleration engine for Diffusion Transformers (DiT), to speed up inference with minimal quality loss. Enable it by setting `SGLANG_CACHE_DIT_ENABLED=true`. For more details, see the SGLang Cache-DiT [documentation](/docs/sglang-diffusion/cache_dit). Cache-DiT works for **both** Krea-2 variants with no extra configuration: SGLang tracks each request's classifier-free-guidance mode, so Krea-2-Turbo (no CFG, `guidance_scale = 1.0`) and Krea-2-Raw (CFG, `guidance_scale ≈ 4.5`) both cache correctly and automatically. **Basic Usage** ```bash Command theme={null} SGLANG_CACHE_DIT_ENABLED=true sglang serve \ --model-path krea/Krea-2-Turbo \ --num-gpus 1 \ --port 30000 ``` Measured per-image denoise speedup with the default cache settings (NVIDIA H200, 1024x1024, seed 0): | Variant | Inference steps | Denoise (no cache → cache) | Speedup | | :- | :- | :- | :- | | Krea-2-Turbo (no CFG) | 8 | 1.27s → 0.92s | \~1.4x | | Krea-2-Raw (CFG 4.5) | 50 | 18.0s → 6.3s | \~2.9x | Caching has the most headroom on Raw's longer schedule; the 8-step distilled Turbo has only a few cacheable steps after warmup. **Advanced Usage** * DBCache Parameters: DBCache controls block-level caching behavior:
Parameter Env Variable Default Description
Fn `SGLANG_CACHE_DIT_FN` 1 Number of first blocks to always compute
Bn `SGLANG_CACHE_DIT_BN` 0 Number of last blocks to always compute
W `SGLANG_CACHE_DIT_WARMUP` 4 Warmup steps before caching starts
R `SGLANG_CACHE_DIT_RDT` 0.24 Residual difference threshold
MC `SGLANG_CACHE_DIT_MC` 3 Maximum continuous cached steps
* TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion (best suited to the longer Raw schedule; not recommended for the 8-step Turbo):
Parameter Env Variable Default Description
Enable `SGLANG_CACHE_DIT_TAYLORSEER` false Enable TaylorSeer calibrator
Order `SGLANG_CACHE_DIT_TS_ORDER` 1 Taylor expansion order (1 or 2)
Combined Configuration Example (Krea-2-Raw, default cache settings shown explicitly): ```bash Command theme={null} SGLANG_CACHE_DIT_ENABLED=true \ SGLANG_CACHE_DIT_FN=1 \ SGLANG_CACHE_DIT_BN=0 \ SGLANG_CACHE_DIT_WARMUP=4 \ SGLANG_CACHE_DIT_RDT=0.24 \ SGLANG_CACHE_DIT_MC=3 \ sglang serve --model-path krea/Krea-2-Raw ``` #### 4.2.2 Memory and Component Residency Krea-2's DiT is \~24 GB in bf16 (the bulk of the model). On memory-constrained GPUs you can keep less of it resident: * `--component-residency dit=layerwise-offload`: stream the DiT's transformer blocks layer-by-layer with async host-to-device prefetch overlap, so only a small working set stays on the GPU. This is the primary way to fit Krea-2 on a single consumer / 32 GB-class card, at a modest latency cost. Tune the memory/latency trade-off with `--dit-offload-prefetch-size` (`0.0` prefetches one layer for the lowest memory; larger values prefetch more layers -- faster but more memory). * `--component-residency dit=component-offload`: keep the complete DiT on CPU between denoising uses. This and layerwise offload are distinct modes; do not combine them for the same component. * `--component-residency text_encoder=component-offload`: offload the Qwen3-VL text encoder while it is idle during denoising. * `--component-residency vae=component-offload`: offload the VAE between uses. * `--pin-cpu-memory`: pin host memory for offload. Add only as a temporary workaround if you hit `CUDA error: invalid argument`. The legacy `--dit-layerwise-offload`, `--dit-cpu-offload`, `--text-encoder-cpu-offload`, and `--vae-cpu-offload` forms remain accepted. If both legacy DiT offload flags are enabled, layerwise offload is the effective DiT mode. On large-VRAM GPUs (e.g. H200), keep everything resident (offloads off) for the fastest latency. ## 5. Benchmark Test Environment: * Hardware: NVIDIA H200 GPU (1x) * Model: krea/Krea-2-Turbo (8 inference steps) * sglang diffusion version: 0.5.13 **Server Command** (used for both benchmarks below): ```shell Command theme={null} sglang serve --model-path krea/Krea-2-Turbo --port 30000 ``` ### 5.1 Generate an image **Benchmark Command**: ```shell Command theme={null} python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --model krea/Krea-2-Turbo --dataset vbench --task text-to-image \ --num-prompts 1 --max-concurrency 1 ``` **Result**: ```text Output theme={null} ================= Serving Benchmark Result ================= Task: text-to-image Model: krea/Krea-2-Turbo Dataset: vbench -------------------------------------------------- Benchmark duration (s): 1.56 Request rate: inf Max request concurrency: 1 Successful requests: 1/1 -------------------------------------------------- Request throughput (req/s): 0.64 Latency Mean (s): 1.5600 Latency Median (s): 1.5600 Latency P99 (s): 1.5600 -------------------------------------------------- Peak Memory Max (MB): 37466.00 Peak Memory Mean (MB): 37466.00 Peak Memory Median (MB): 37466.00 ============================================================ ``` ### 5.2 Generate images with high concurrency **Benchmark Command**: ```shell Command theme={null} python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --model krea/Krea-2-Turbo --dataset vbench --task text-to-image \ --num-prompts 20 --max-concurrency 20 ``` **Result**: ```text Output theme={null} ================= Serving Benchmark Result ================= Task: text-to-image Model: krea/Krea-2-Turbo Dataset: vbench -------------------------------------------------- Benchmark duration (s): 31.47 Request rate: inf Max request concurrency: 20 Successful requests: 20/20 -------------------------------------------------- Request throughput (req/s): 0.64 Latency Mean (s): 16.5000 Latency Median (s): 16.5200 Latency P99 (s): 31.1300 -------------------------------------------------- Peak Memory Max (MB): 37468.00 Peak Memory Mean (MB): 37466.40 Peak Memory Median (MB): 37466.00 ============================================================ ``` ## 6. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Image`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # LTX2 & LTX2.3 Source: https://docs.sglang.io/cookbook/diffusion/LTX/LTX2 & LTX2.3 Run LTX-2 and LTX-2.3 video generation pipelines with SGLang Diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. ## 2. Model capabilities [LTX-2](https://huggingface.co/Lightricks/LTX-2) and [LTX-2.3](https://huggingface.co/Lightricks/LTX-2.3) are Lightricks video models for text-to-video and image-conditioned generation. Their defining deployment choice is the pipeline: one-stage minimizes latency, standard two-stage refines quality, and LTX-2.3 adds a 1920×1088 HQ path. Choose LTX when one model family must span fast generation, higher-quality refinement, and LoRA adaptation. Two-stage quality costs substantially more memory and startup work because both DiTs and the spatial upsampler participate; use the one-stage path when latency or capacity matters more than final detail. Use `Lightricks/LTX-2` or `Lightricks/LTX-2.3` as `--model-path`. SGLang loads the two-stage upsampler and distilled components from the selected snapshot. > [!WARNING] > > **License notice:** LTX-2 and LTX-2.3 are released under the LTX-2 Community License Agreement, not Apache 2.0. The license includes commercial-use restrictions for some entities. Review the [official Lightricks license](https://huggingface.co/Lightricks/LTX-2.3/blob/main/LICENSE) before production or commercial use; SGLang support does not grant additional model usage rights. ## 3. Model Deployment This section provides deployment configurations optimized for different LTX pipelines and hardware targets. ### 3.1 Basic Configuration The LTX series supports one-stage and two-stage pipelines. LTX-2.3 also supports the HQ two-stage pipeline. The recommended launch configuration depends on whether the target GPU can keep both two-stage DiTs resident. Use the [command builder](#1-quick-start) above. ### 3.2 Configuration Tips Choose the pipeline class based on the quality and latency target: | Use case | Pipeline class | Notes | | - | - | - | | One-stage generation | `LTX2Pipeline` | Fastest LTX native path. Supports T2V and TI2V. | | Two-stage generation | `LTX2TwoStagePipeline` | Uses a base stage and a refinement stage. Supported by LTX-2 and LTX-2.3. | | Two-stage High Quality (HQ) generation | `LTX2TwoStageHQPipeline` | LTX-2.3 HQ path; defaults to 1920x1088 unless you override `--width` and `--height`. | Feature compatibility: | Pipeline class | T2V | TI2V (`--image-path`) | LoRA (`--lora-path`) | Notes | | - | - | - | - | - | | `LTX2Pipeline` | Yes | Yes | Yes | One-stage path. Cannot be combined with HQ because HQ is a separate two-stage pipeline class. | | `LTX2TwoStagePipeline` | Yes | Yes | Yes | Standard two-stage path for LTX-2 and LTX-2.3. | | `LTX2TwoStageHQPipeline` | Yes | Yes | Yes | High Quality two-stage path for LTX-2.3. Use this instead of `LTX2Pipeline`; it is not a one-stage mode flag. | For two-stage pipelines, `--ltx2-two-stage-device-mode` controls transformer residency: | Mode | When to use it | | - | - | | `resident` | Best latency on high-VRAM GPUs because both DiTs can stay resident. | | `original` | Closest to the original two-stage switching semantics. | Other deployment flags: * `--lora-path`: Preload a community LoRA adapter. * `--lora-weight-name`: Select the exact safetensors file when the LoRA repository contains multiple weight files. > [!NOTE] > > For LTX-2 and LTX-2.3 two-stage serving without a user LoRA, `resident` is the fastest high-VRAM path: stage 2 runs a second DiT with the distilled LoRA merged in, and it is the default on GPUs with at least 130 GiB. When you pass `--lora-path`, SGLang still applies the user LoRA during the two-stage switch, so use `resident` on H200-class GPUs for enough VRAM, but do not expect the same premerged-stage2 benefit as the no-user-LoRA path. ### 3.3 Fast multi-GPU presets For latency-oriented LTX serving, prefer CFG parallel over sequence parallelism. CFG parallel splits guidance branches across GPUs, while SP/Ulysses is mainly a memory/long-sequence tool for LTX. | Target | Recommended server flags | Notes | | - | - | - | | LTX-2.3, 1 high-VRAM GPU | `--ltx2-two-stage-device-mode resident` | Fastest two-stage setup when both DiTs fit. | | LTX-2.3, 1 standard GPU | `--ltx2-two-stage-device-mode original` | Lower VRAM than `resident`; use this when H100-class memory is tight. | | LTX-2, 2 GPUs | `--num-gpus 2 --enable-cfg-parallel` | Fastest verified 2-GPU setup; keep `--dit-layerwise-offload` disabled unless memory is tight. | | LTX-2.3, 2 GPUs | `--num-gpus 2 --enable-cfg-parallel --ltx2-two-stage-device-mode resident` | Fastest common 2-GPU setup. | | LTX-2.3, 4 GPUs | `--num-gpus 4 --tp-size 2 --enable-cfg-parallel --ltx2-two-stage-device-mode resident` | Fastest common 4-GPU layout: TP2 inside each CFG branch. | | Official comparison | `--ltx2-two-stage-device-mode original` | Use this only when matching the original LTX-2.3 stage-switch semantics matters. | Use `--enable-cfg-parallel` for degree-2 CFG parallel. Use `--cfg-parallel-size` only when you explicitly need a different CFG branch count. If `resident` exceeds available VRAM, keep the same parallelism preset and switch only the device mode to `original`. On high-VRAM GPUs, add `--text-encoder-cpu-offload false` if text encoding latency matters and you have enough memory. On GPUs with at least 130 GiB (H200, B200, B300), `LTX2TwoStagePipeline` serving turns on breakable CUDA graphs by default when the DiTs stay resident (LTX-2.3: `resident` mode). Warmup captures the default 768x512, 121-frame request; other resolutions or frame counts run eager, so pass `--warmup-resolutions` and `--warmup-num-frames` for the shape you serve (the OpenAI video API defaults to 4 seconds, which LTX rounds to 89 frames). Pass `--enable-breakable-cuda-graph false` to run eager. #### 3.3.1 Two GPUs ```bash theme={null} sglang serve \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2TwoStagePipeline \ --num-gpus 2 \ --enable-cfg-parallel \ --ltx2-two-stage-device-mode resident ``` #### 3.3.2 Four GPUs ```bash theme={null} sglang serve \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2TwoStagePipeline \ --num-gpus 4 \ --tp-size 2 \ --enable-cfg-parallel \ --ltx2-two-stage-device-mode resident ``` ## 4. Model Invocation ### 4.1 Basic Usage The examples below spell out the current SGLang sampling defaults for reproducibility: | Model path | Default output | Default frames | Default steps | | - | - | - | - | | `Lightricks/LTX-2` | 768x512 | 121 | 40 | | `Lightricks/LTX-2.3` | 768x512 | 121 | 30 | | `Lightricks/LTX-2.3` with `LTX2TwoStageHQPipeline` | 1920x1088 | 121 | 15 | #### 4.1.1 LTX-2 one-stage text-to-video ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2 \ --pipeline-class-name LTX2Pipeline \ --prompt "A quiet coastal town at sunrise, fishing boats moving slowly through golden mist, cinematic camera movement" \ --save-output ``` #### 4.1.2 LTX-2.3 one-stage text-to-video ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2Pipeline \ --prompt "A quiet coastal town at sunrise, fishing boats moving slowly through golden mist, cinematic camera movement" \ --save-output ``` #### 4.1.3 LTX-2 two-stage text-to-video ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2 \ --pipeline-class-name LTX2TwoStagePipeline \ --prompt "A handheld shot follows a red tram crossing a rainy city square at night, reflections on the pavement, cinematic lighting" \ --save-output ``` #### 4.1.4 LTX-2.3 two-stage text-to-video ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2TwoStagePipeline \ --prompt "A handheld shot follows a red tram crossing a rainy city square at night, reflections on the pavement, cinematic lighting" \ --save-output ``` #### 4.1.5 LTX-2.3 HQ text-to-video ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2TwoStageHQPipeline \ --prompt "A wide cinematic shot of alpine clouds rolling over a mountain ridge, soft morning light, slow aerial camera movement" \ --save-output ``` #### 4.1.6 Image-to-video with one reference image Pass one image to `--image-path` for image-conditioned generation: ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2TwoStagePipeline \ --image-path ./inputs/start.png \ --prompt "The camera slowly pushes forward as the subject turns toward warm window light, subtle natural motion, cinematic" \ --save-output ``` #### 4.1.7 First-to-last-frame transition with two reference images Pass two images to `--image-path` for transition-style TI2V. The first image is used as the starting condition and the second image is used as the ending condition. ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2TwoStagePipeline \ --image-path ./inputs/start.png ./inputs/end.png \ --prompt "A smooth cinematic transition from the first scene into the final scene, dynamic camera motion, motion blur, zhuanchang" \ --save-output ``` ### 4.2 Advanced Usage #### 4.2.1 Use community LoRAs Use `--lora-path` to load a LoRA adapter. If the Hugging Face repo contains multiple safetensors files, use `--lora-weight-name` to select the exact file. `--lora-scale` maps to the standard LoRA merge scale and defaults to `1.0`. The following example uses [`valiantcat/LTX-2.3-Transition-LORA`](https://huggingface.co/valiantcat/LTX-2.3-Transition-LORA): ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2TwoStagePipeline \ --lora-path valiantcat/LTX-2.3-Transition-LORA \ --lora-weight-name ltx2.3-transition.safetensors \ --prompt "A low-angle tracking shot moves through a foggy forest road. The camera rises above the treetops and transitions into a clear view of a snowy mountain peak under bright sunlight, zhuanchang" \ --save-output ``` You can combine the Transition LoRA with two reference images: ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.3 \ --pipeline-class-name LTX2TwoStagePipeline \ --image-path ./inputs/start.png ./inputs/end.png \ --lora-path valiantcat/LTX-2.3-Transition-LORA \ --lora-weight-name ltx2.3-transition.safetensors \ --prompt "A fast cinematic transition from the first image to the second image, whip-pan motion, atmospheric lighting, zhuanchang" \ --save-output ``` > [!NOTE] > > Some community LoRAs only include weights for transformer blocks. In that case, SGLang logs a concise coverage summary and leaves unmatched LoRA-capable layers on the base model weights. This is expected when the adapter format intentionally omits those layers. ## 5. Practical Tips * Use `--pipeline-class-name LTX2TwoStagePipeline` as the default LTX two-stage quality path. * Use `--pipeline-class-name LTX2TwoStageHQPipeline` when you want the HQ path and have enough VRAM for larger outputs. * Use `--ltx2-two-stage-device-mode resident` on high-VRAM GPUs if latency matters more than memory usage. * Use `--ltx2-two-stage-device-mode original` when comparing against official two-stage behavior. * Keep `--width` and `--height` aligned with the target model resolution; for LTX models, these are output video dimensions. ## 6. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Video`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # LTX2.5 Source: https://docs.sglang.io/cookbook/diffusion/LTX/LTX2.5 Run LTX-2.5 video + audio generation with SGLang Diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. > **Installation and prerequisites** > > Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation). Docker is recommended for Linux GPU deployments; run the commands below inside the container or your installed Python environment. > > NATTEN is an optional extra, worth installing only if you plan to use the > [diffusion decoder](#4-6-diffusion-decoder) — see that section for why. To use diffusion decoding, load **Diffusion decoder weights** in Server, then select **Diffusion** in Request. Duration and decoder selection are request-time choices; loading the optional decoder requires a server restart. ## 2. Model capabilities [LTX-2.5](https://huggingface.co/Lightricks/LTX-2.5) is an open world model from Lightricks, built for local execution and fine-tuning. Its established use is generating synchronized, high-fidelity video and audio from text, image and video inputs. It is a 22B DiT paired with a Gemma-4-12B text encoder, separate video and audio VAEs, and a vocoder that outputs 48 kHz stereo. Video and audio are denoised jointly in one pass rather than dubbed afterwards, so they stay in sync. Use **`Lightricks/LTX-2.5-Diffusers`** as `--model-path`. > [!WARNING] > > **License notice:** LTX-2.5 is released under the LTX-2.x Community License > Agreement, not Apache 2.0. The license includes commercial-use restrictions for > some entities. Review the [official Lightricks license](https://github.com/Lightricks/LTX-2/blob/main/LICENSE.md) > before production or commercial use; SGLang support does not grant additional > model usage rights. ### 2.1 New in LTX-2.5 Two capabilities have no equivalent in LTX-2 / LTX-2.3: > **[Auto-duration](#4-3-auto-duration)** > > A duration head predicts how long the shot the caption implies should run, > and picks the frame count for you. Pass `--auto-duration` instead of > `--num-frames`. > **[Diffusion decoder](#4-6-diffusion-decoder)** > > A diffusion model replaces the convolutional VAE decoder for the > latent-to-pixel step. Enable with `--use-diffusion-decoder`. Both are optional and off by default. ### 2.2 Components | Path | Component | Used by | | - | - | - | | `transformer/` | Distilled DiT (the default) | always | | `transformer_full/` | Full / SFT DiT | `--model-variant dev` | | `vae/` | Convolutional video VAE | encode always; decode by default | | `diffusion_decoder/` | Diffusion video decoder, decoder-only | `--use-diffusion-decoder` | | `latent_upsampler/` | Spatial x2 latent upsampler | `LTX2TwoStagePipeline` | | `duration_head/` | Predicts clip length from the caption | `--auto-duration` | | `audio_vae/`, `vocoder/`, `connectors/`, `text_encoder/`, `tokenizer/`, `scheduler/` | Shared | always | Encoding always uses `vae/`, and both decoders consume the same latents, so the decoder choice does not change anything upstream of it. ## 3. Model Deployment ### 3.1 Basic Configuration ```bash theme={null} sglang serve \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline ``` On a single high-VRAM GPU no extra flags are needed. Use the [command builder](#1-quick-start) above. ### 3.2 Configuration Tips Choose the pipeline class based on the quality and latency target: | Use case | Pipeline class | Notes | | - | - | - | | One-stage generation | `LTX2Pipeline` | Fastest path. Supports T2V and TI2V, auto-duration and the diffusion decoder. | | Two-stage generation | `LTX2TwoStagePipeline` | Half-resolution base stage, x2 latent upsample, then a short refinement. Pass the **final** resolution. | There is no HQ pipeline class for LTX-2.5, and no `--distilled-lora-path` for either weights variant: LTX-2.5 distils the weights themselves rather than merging a LoRA per stage, so `--ltx2-two-stage-device-mode` (which governs that swap) does not apply either. Every feature on this page — text-to-video, image conditioning, auto-duration, the diffusion decoder, and either weights variant — works with both pipeline classes. Selecting weights: * `--model-variant dev` serves the full / SFT DiT from `transformer_full/`; the default is the distilled one. See [section 4.5](#4-5-the-dev-transformer). On GPUs with at least 130 GiB, `LTX2TwoStagePipeline` serving turns on breakable CUDA graphs by default, as for LTX-2 / LTX-2.3. Graphs are captured per shape at warmup, so pass the shape you serve (for example `--warmup-resolutions 1920x1088 --warmup-num-frames 121`); other shapes run eager. Pass `--enable-breakable-cuda-graph false` to run eager throughout. ### 3.3 Multi-GPU presets | Target | Recommended server flags | Notes | | - | - | - | | 1 high-VRAM GPU | *(no extra flags)* | 960×544 fits comfortably on an H200. | | 1 tight-VRAM GPU | `--quantization fp8` | Halves the DiT and cuts peak memory \~18 GB at unchanged speed. See [section 3.4](#3-4-fp8-quantization). | | 1 very tight GPU | `--dit-layerwise-offload` | Cuts peak memory by roughly 10 GB, at about 4x the wall clock. | | 1 32 GB GPU (e.g. RTX 5090) | `--layerwise-offload-components dit text_encoder` | Streams the DiT and the 22 GB Gemma-4 encoder layer by layer and keeps the rest resident. 960×544 / 121 frames / 8 steps: 15.2 s at 17 GB peak, vs 17.0 s at 31 GB with `--cpu-offload-components text_encoder ...`. Pins \~55 GB of host memory per GPU. | | 2 GPUs, long sequences | `--num-gpus 2 --ulysses-degree 2` | Sequence parallel; the memory/long-sequence tool. | | 2 32 GB GPUs | `--num-gpus 2 --ulysses-degree 2 --layerwise-offload-components dit text_encoder --vae-tiling false --vae-sp false --dit-layerwise-resident-layers 12` | Untiled VAE decode splits the frame height across the ranks (2.2 s to 1.1 s); 12 resident DiT layers cut the per-step host stream. RTX 5090 960×544 / 121 frames: 16.9 s at 26 GB peak per GPU, vs 21.8 s. Pins \~55 GB of host memory per GPU. | | 2 GPUs, large DiT | `--num-gpus 2 --tp-size 2` | Tensor parallel across attention heads. | | 2 GPUs, dev weights | `--num-gpus 2 --enable-cfg-parallel` | Splits the guided and unguided branches across GPUs. Measured 1.77x on denoising (15.1s to 8.5s, 960×544 / 57 frames / 30 steps). | | 2 GPUs, diffusion decoder | `--num-gpus 2 --ulysses-degree 2` | The decoder's tiles are split across the ranks by default. See [section 4.6.1](#4-6-1-memory-and-multi-gpu). | > [!WARNING] > > **CFG parallelism does not apply on the default (distilled) path.** That DiT > runs unguided, so there is no negative branch to split across GPUs and > `--enable-cfg-parallel` buys nothing — the CFG-parallel presets on the > LTX-2 / LTX-2.3 page do not carry over. It *is* worth using with > `--model-variant dev`, which runs with guidance. ### 3.4 fp8 quantization `--quantization fp8` quantizes the DiT's linear layers as it loads them, so it needs no pre-quantized checkpoint: ```bash theme={null} sglang serve \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --quantization fp8 ``` At 960×544 / 49 frames the transformer loads in 18.11 GB against 35.37 GB for bf16, and the run peaks at 53.5 GB against 71.1 GB. Denoising time is unchanged: the distilled 8-step path at this size is bound by memory traffic rather than matmul throughput, so fp8 buys headroom rather than speed. Expect a different sample for a given seed. Quantization nudges the denoising trajectory and diffusion amplifies that, so the result differs from bf16 without being worse. ## 4. Model Invocation ### 4.1 Text-to-video with audio ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --prompt "A cinematic shot of a red fox walking through a snowy forest at dawn, the camera tracking alongside, snow crunching underfoot." \ --save-output ``` Defaults: 960×544, 121 frames, 24 fps. Video and audio are generated jointly and muxed into one MP4. The default DiT is distilled and runs off a fixed 8-sigma schedule rather than a step count, so `--num-inference-steps` and `--guidance-scale` have no effect here. Use [`--model-variant dev`](#4-5-the-dev-transformer) when you want control over either. ### 4.2 Image-to-video ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --image-path ./inputs/start.png \ --prompt "The camera pushes forward as the subject turns toward the light." \ --save-output ``` The conditioning image is re-compressed to match the compression the model was trained against — CRF 18 for LTX-2.5, where LTX-2 / 2.3 use 33. SGLang picks the right one from the checkpoint, so nothing needs to be passed. ### 4.3 Auto-duration LTX-2.5 ships a duration head — a small module that reads the encoded caption and regresses the natural length of the shot it describes. Use it when the prompt implies a duration ("a quick glance" vs "a slow pan across the valley") and you would rather not guess a frame count: ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --prompt "A red fox walking through a snowy forest at dawn." \ --auto-duration \ --save-output ``` The prediction is clamped to `--auto-duration-min-seconds` / `--auto-duration-max-seconds` (default 1–20 s) and snapped to the VAE's temporal grid, so the result is always a valid frame count. It overrides `--num-frames`. For an online server, pass the same LTX-2.5-only controls through `extra_body`: ```python Python theme={null} from openai import OpenAI client = OpenAI(api_key="EMPTY", base_url="http://localhost:30010/v1") video = client.videos.create( model="Lightricks/LTX-2.5-Diffusers", prompt="A red fox walking through a snowy forest at dawn.", extra_body={ "auto_duration": True, "auto_duration_min_seconds": 2.0, "auto_duration_max_seconds": 8.0, }, ) ``` ### 4.4 Two-stage (higher quality) Stage 1 runs at half the requested resolution, the latents are upsampled 2x, and a short sigma tail refines at full resolution. Pass the **final** size: ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2TwoStagePipeline \ --prompt "A cinematic shot of a red fox walking through a snowy forest at dawn." \ --height 1088 --width 1920 \ --save-output ``` Resolution must be divisible by 64. Unlike LTX-2.3, no `--distilled-lora-path` is needed: the LTX-2.5 transformer is already distilled. ### 4.5 The dev transformer LTX-2.5 ships two DiTs. `model_index.json` points at the distilled one; the full / SFT weights live in `transformer_full/` and are deliberately left out of the index. Select them with `--model-variant dev`: ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --model-variant dev \ --prompt "A cinematic shot of a red fox walking through a snowy forest at dawn." \ --num-inference-steps 30 --guidance-scale 3.0 \ --save-output ``` The dev variant is not distilled, so SGLang automatically drops the pinned distilled sigma schedule and re-enables the dynamic shifting that `scheduler/` turns off for the distilled DiT. Unlike the distilled path it *is* driven by a step count and *does* want CFG, so pass `--num-inference-steps` and `--guidance-scale` yourself. Note that `from_pretrained` only fetches what `model_index.json` lists, so a partial snapshot download will not include `transformer_full/` (another 38 GB). ### 4.6 Diffusion decoder LTX-2.5 adds a diffusion-based video decoder as an alternative to the convolutional VAE decoder. Rather than deconvolving the latent it denoises pixels conditioned on a context volume built from it, which recovers detail a convolutional decoder tends to smooth away: ```bash theme={null} sglang generate \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --prompt "A red fox walking through a snowy forest at dawn." \ --use-diffusion-decoder \ --save-output ``` It is a diffusion model in its own right and decodes more slowly than the VAE decoder, so it is off by default — matching upstream, where `LTX2Pipeline` also decodes with the VAE. The offline `generate` command loads the optional decoder automatically when `--use-diffusion-decoder` is present. For an online server, opt into loading the decoder at startup, then select it per request with `use_diffusion_decoder: true`: ```bash theme={null} sglang serve \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --load-diffusion-decoder ``` ```python Python theme={null} video = client.videos.create( model="Lightricks/LTX-2.5-Diffusers", prompt="A red fox walking through a snowy forest at dawn.", extra_body={"use_diffusion_decoder": True}, ) ``` This keeps the default server footprint unchanged while still allowing VAE and diffusion-decoder requests to share one server. When GPU memory is constrained, `--cpu-offload-components diffusion_decoder` keeps the optional decoder on CPU between uses. > [!TIP] > > **Install NATTEN for this decoder.** Its stages run 3D neighborhood attention, > and SGLang uses NATTEN's fused `na3d` kernel for it when the package is present. > NATTEN is *not* a dependency of `sglang[diffusion]`: without it the decoder > falls back to a compiled FlexAttention block mask. The two agree to bf16 > rounding, but the fallback is roughly **5x slower** on the decoder's largest > attention grid, and has to build the mask on top of that. > > NATTEN ships prebuilt wheels pinned to a specific torch and CUDA build, so > install the one matching your environment rather than a bare version — check > your combination at [natten.org](https://natten.org). For torch 2.11 / CUDA > 13.0, for example: > > ```bash theme={null} > uv pip install natten==0.21.6+torch2110cu130 -f https://whl.natten.org/ > ``` > > Nothing else changes if you skip it: the decoder still produces the same video, > just slower. #### 4.6.1 Memory and multi-GPU Two flags govern how the decode is executed. Both default to on, so the numbers below are what you already get — they matter when you want to turn one off. `--diffusion-decoder-tiling` runs the decoder's two expensive stages over overlapping tiles instead of the whole volume. It is a **memory** control, not a speed one: it costs wall clock and buys headroom. `--diffusion-decoder-parallel-tiling` splits those tiles across the decode-parallel ranks -- the TP, SP, PP and CFG ranks of one replica, since the decoder is replicated over all of them. Without it every one of those ranks decodes every tile and keeps its own identical copy. It only applies on the tiled path, so it does nothing when tiling is off, and nothing at a single rank. Decoding stage on 2xH200 at 960×544, Ulysses degree 2. "Peak" is the whole process, not the decode alone: | Frames | Tiling | Parallel tiling | Decode | Peak | | - | - | - | - | - | | 121 | off | *(n/a)* | **3.38s** | 103.2 GB | | 121 | on | off | 5.68s | 78.2 GB | | 121 | on | on | 4.08s | 79.3 GB | | 49 | off | *(n/a)* | **1.93s** | 84.0 GB | | 49 | on | off | 2.79s | 78.2 GB | | 49 | on | on | 2.12s | 78.2 GB | Reading that: * **Untiled is the fastest option** whenever it fits. Tiling exists for the \~25 GB it saves at 121 frames, which is the difference between fitting on an 80 GB card and not. * **Parallel tiling recovers most of tiling's cost** — 1.39x at 121 frames, 1.32x at 49 — but does not beat an untiled decode. It also adds about 1 GB for the gather buffers. * The gain grows with tile count, so it is larger at higher resolution: at 1920×1088 / 49 frames the decode goes from 12.32s to 7.86s, **1.57x**. Output is bitwise identical however many ranks the tiles are split over: every rank draws the whole grid's noise in the same order, and only the decode is shared out. Turning *tiling* on or off does change the result slightly near tile borders, so pick one and stay with it if you need reproducible frames: ```bash theme={null} # Fastest, if the untiled decode fits in VRAM sglang serve \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --load-diffusion-decoder \ --diffusion-decoder-tiling false # Memory-bound: keep tiling, and split the tiles over both GPUs sglang serve \ --model-path Lightricks/LTX-2.5-Diffusers \ --pipeline-class-name LTX2Pipeline \ --load-diffusion-decoder \ --num-gpus 2 --ulysses-degree 2 ``` # LingBot Video MoE Source: https://docs.sglang.io/cookbook/diffusion/LingBot-Video/LingBot-Video-MoE Serve the native LingBot Video MoE 30B-A3B text-to-video model with SGLang Diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. ## 2. Model capabilities [LingBot Video MoE 30B-A3B](https://huggingface.co/robbyant/lingbot-video-moe-30b-a3b) is a text-to-video mixture-of-experts model served through a native SGLang Diffusion pipeline. Its main advantage is the MoE economics: 30B total parameters with 3B active per token, so a plain `sglang serve` invocation covers the released 480×480, 81-frame profile without parallelism flags. Prompting is the distinctive part of this checkpoint: it expects a structured JSON caption rather than an unexpanded natural-language prompt, passed as the request's `prompt` string. A compact 17-frame, 12-step smoke-test profile is available for quick validation next to the released 40-step profile. The public checkpoint served by the pipeline: | Model ID | Task | Default output | | - | - | - | | `robbyant/lingbot-video-moe-30b-a3b` | Text to video | 480x480, 81 frames at 16 FPS | The checkpoint expects a structured JSON caption rather than an unexpanded natural-language prompt. The JSON is passed as the request's `prompt` string; it is not an `extra_params` object. ## 3. Serve LingBot Video MoE Start the server with the Hugging Face model ID: ```bash Command theme={null} sglang serve \ --model-path robbyant/lingbot-video-moe-30b-a3b \ --port 30010 ``` ## 4. Generate a video The following request uses the compact 17-frame, 12-step smoke-test profile. Use the model defaults of 81 frames and 40 steps for the released generation profile. ```python Python theme={null} import json import time from pathlib import Path import requests base_url = "http://127.0.0.1:30010" prompt = json.dumps( { "comprehensive_description": { "scene_content_description": ( "A small silver robot arm on a white table slowly reaches " "toward a red cube. The background is a softly lit laboratory wall." ), "camera_movement_description": ( "The camera is static at eye level in a medium shot." ), }, "camera_info": { "color": "Neutral", "frame_size": "Medium", "shot_type_angle": "Eye level", "lens_size": "Medium", "composition": "Center", "lighting": "Soft light", "lighting_type": "Artificial light", }, "world_knowledge": [], "prominent_elements": [ { "name": "robot arm", "description": "A small silver robot arm with a two-finger gripper.", "actions": [ { "timestamp": "[0.0s - 1.0s]", "action": "reaches toward the red cube", } ], "location": "center of the frame", "relative_size": "dominant", "shape_and_color": "articulated silver metal arm", "texture": "brushed metal", "appearance_details": "two-finger gripper and visible joints", "relationship": "reaching toward the red cube on the table", "orientation": "upright, base on the table", "pose": "reaching", } ], }, separators=(",", ":"), ) response = requests.post( f"{base_url}/v1/videos", json={ "model": "robbyant/lingbot-video-moe-30b-a3b", "prompt": prompt, "size": "640x384", "num_frames": 17, "fps": 16, "num_inference_steps": 12, "guidance_scale": 6.0, "flow_shift": 3.0, "seed": 0, }, timeout=60, ) response.raise_for_status() video_id = response.json()["id"] while True: job = requests.get(f"{base_url}/v1/videos/{video_id}", timeout=30).json() if job["status"] == "completed": break if job["status"] == "failed": raise RuntimeError(job.get("error") or "Video generation failed") time.sleep(1) video = requests.get( f"{base_url}/v1/videos/{video_id}/content", timeout=300, ) video.raise_for_status() Path("lingbot_video_moe.mp4").write_bytes(video.content) ``` ## 5. Request constraints * `num_frames` must be `1` or `4n+1`; examples include 17 and 81. * Width and height must both be multiples of 16. * The native defaults are `guidance_scale=6.0`, `flow_shift=3.0`, `num_inference_steps=40`, and `fps=16`. * Keep the prompt as serialized JSON. Raw free text is outside the checkpoint's expected caption format. # LingBot World Source: https://docs.sglang.io/cookbook/diffusion/LingBot-World/LingBot-World Serve LingBot World realtime camera-controlled video world models with SGLang-diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. Use the [Realtime WebUI](#3-realtime-webui) to start a camera-controlled session. The Request tab checks model metadata; video generation uses WebSocket, not an HTTP POST. ## 2. Model capabilities [LingBot World](https://huggingface.co/robbyant/lingbot-world-fast-diffusers) is a realtime camera-controlled video world model. It keeps a live causal session, applies prompt and camera events between chunks, reuses DiT/VAE state, and streams decoded frames instead of finishing a bounded clip before returning. Choose it for interactive exploration and continuous control, not one-shot cinematic generation. The causal window makes long sessions practical but gives up the global bidirectional context available to offline Wan or LTX pipelines; session state and cache policy are therefore part of the serving contract. ## 3. Deployment ```bash Command theme={null} sglang serve \ --model-path robbyant/lingbot-world-fast-diffusers \ --pipeline-class-name LingBotWorldCausalDMDPipeline \ --num-gpus 4 \ --ulysses-degree 4 \ --dit-cpu-offload false \ --text-encoder-cpu-offload false ``` Intel Xeon CPU deployment is supported with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu`; omit GPU-only parallel and offload flags. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu sglang serve --model-path robbyant/lingbot-world-fast-diffusers --pipeline-class-name LingBotWorldCausalDMDPipeline ``` ### Optional KV-Cache Compression Long-running sessions can enable lossy int4 PRQ compression for completed causal KV-cache chunks by installing `quant-videogen` as described in the quantization guide and adding `--kv-cache-quant int4` to the server command. The current and most recent completed chunks remain in BF16. See [Causal KV-Cache Quantization](/docs/sglang-diffusion/quantization#causal-kv-cache-quantization) for the algorithm, tuning options, measured memory-latency tradeoff, and support limits. ## 4. Realtime WebUI The lightweight local WebUI is useful for validating latency, frame transport, and camera control behavior. ```bash Command theme={null} python -m http.server 18080 -d python/sglang/multimodal_gen/apps/realtime_webui ``` Open `http://127.0.0.1:18080` and use: ```text Example theme={null} ws://127.0.0.1:30000/v1/realtime_video/generate ``` ## 5. HTTP and WebSocket API LingBot World uses the realtime video WebSocket endpoint. The server keeps one live session, generates one chunk at a time, and accepts runtime control events while generation is running. ### Endpoints | API | Method | Purpose | Notes | | - | - | - | - | | `/v1/models` | `GET` | Query the served model id before opening a session. | The WebUI uses this to fill the model field when the server exposes model metadata. | | `/v1/realtime_video/generate` | `WebSocket` | Create one realtime LingBot session and stream generated video chunks. | The first client message must be an `init` message encoded with MessagePack. | ### `init` message Send this MessagePack map immediately after the WebSocket opens. | Parameter | Type | Required | Meaning | | - | - | - | - | | `type` | string | Yes | Must be `"init"`. | | `model` | string | No | Model id. Leave empty to use the served model. | | `prompt` | string | Yes | Text prompt for the initial scene and motion style. | | `first_frame` | bytes or string | Yes | Initial reference image. Send bytes from the WebUI/client, or a server-readable image path/string. | | `size` | string | Yes | Generation size as `WIDTHxHEIGHT`, for example `832x480`. | | `fps` | number | Yes | Target playback FPS for the generated stream. | | `num_frames` | integer | Yes | Frames per generated chunk. LingBot uses chunked causal generation, so this controls per-chunk latency and queue size. | | `seed` | integer | No | Random seed for deterministic sampling. | | `num_inference_steps` | integer | No | Denoising steps per chunk. LingBot defaults to `4` when omitted. | | `guidance_scale` | number | No | Classifier-free guidance scale. Realtime LingBot commonly uses `1`. | | `negative_prompt` | string | No | Negative prompt passed to the diffusion pipeline. | | `quality` | `"exact"`, `"lossless"`, `"high"` | No | `lossless` keeps FP32 VAE decode. `lossless` keeps FP32 decode and enables only any eligible request-gated kernel fusions. `high` includes those fusions and uses the validated BF16 decode path for lower per-chunk latency. | | `max_chunks` | integer | No | Stop after this many chunks. Omit for a continuous session. | | `realtime_causal_sink_size` | integer | No | Number of sink frames/tokens retained in the causal attention window. | | `realtime_causal_kv_cache_num_frames` | integer | No | Number of recent frames retained in the causal KV cache window. | | `realtime_output_format` | `"webp"`, `"jpeg"`, `"raw"` | No | Preview/output transport. `webp` and `jpeg` send encoded preview frames; `raw` (the default when omitted) sends lossless raw RGB. | | `output_compression` | integer | No | Preview quality for `webp` or `jpeg`, from `1` to `100`. | | `enable_upscaling` | boolean | No | Enable server-side super resolution after frame decode. | | `upscaling_scale` | integer | No | Super-resolution scale. Current default is `4` when upscaling is enabled. | | `upscaling_model_path` | string | No | Optional Real-ESRGAN model path. | | `enable_frame_interpolation` | boolean | No | Enable frame interpolation. Keep this disabled when measuring true generated FPS. | | `frame_interpolation_exp` | integer | No | Interpolation multiplier exponent. `1` means 2x frames. | | `frame_interpolation_scale` | number | No | RIFE internal scale for interpolation. | | `frame_interpolation_model_path` | string | No | Optional RIFE model path. | | `condition_inputs.camera_actions` | `list[list[string]]` | No | Initial scripted camera actions, one action list per frame. | ### Runtime `event` messages After `init`, send MessagePack event maps to update the live session. | Parameter | Type | Required | Meaning | | - | - | - | - | | `type` | string | Yes | Must be `"event"`. | | `kind` | `"prompt"` or `"camera_actions"` | Yes | Runtime event kind. | | `payload` | string or object/list | Yes | For `prompt`, a non-empty string. For `camera_actions`, either scripted `list[list[string]]` or state-mode payload. | | `event_id` | integer | No | Client sequence id. The server echoes it in chunk/frame metadata after the event is sampled. | `camera_actions` supports two payload modes: | Mode | Payload shape | Meaning | | - | - | - | | Script | `list[list[string]]` | A fixed sequence of per-frame actions consumed by upcoming chunks. | | State | `{ "mode": "state", "transitions": [{"actions": [...], "client_ts_ms": ...}] }` | Live control state transitions from keyboard or UI controls. | Supported LingBot action tokens include `w`, `a`, `s`, `d` for camera movement and `i`, `j`, `k`, `l` for look controls. ### Server messages | Message | Payload | Meaning | | - | - | - | | `frame_batch` | MessagePack map with `payload` bytes | One batch of frames. The map includes `chunk_index`, `num_frames`, `content_type`, `encoding`, `width`, `height`, and frame-batch metadata. | | `chunk_stats` | MessagePack map | Per-chunk timing and transport metrics, including `scheduler_forward_ms`, `raw_payload_build_ms`, `chunk_total_ms`, `num_frames`, and `ws_payload_bytes`. | | `error` | MessagePack map | Server-side validation or generation error. | ### Minimal client sketch ```python Python theme={null} import msgspec.msgpack import websocket ws = websocket.create_connection("ws://127.0.0.1:30000/v1/realtime_video/generate") ws.send_binary(msgspec.msgpack.encode({ "type": "init", "prompt": "A quiet rainy London alley, stable camera motion.", "first_frame": open("reference.jpg", "rb").read(), "size": "832x480", "fps": 25, "num_frames": 9, "num_inference_steps": 4, "guidance_scale": 1, "realtime_output_format": "webp", "output_compression": 95, })) ws.send_binary(msgspec.msgpack.encode({ "type": "event", "kind": "camera_actions", "event_id": 1, "payload": {"mode": "state", "transitions": [{"actions": ["w"], "client_ts_ms": 0}]}, })) ``` ## 6. Consistency LingBot World uses raw-frame websocket GT plus per-chunk latency guards for consistency checks. ## 7. Notes * Use the realtime endpoint for interactive sessions: `/v1/realtime_video/generate`. * Prefer WebP preview transport for interactive testing; use raw-frame transport for consistency checks. * Long-running sessions should be validated with raw-frame consistency before changing causal cache, condition sampling, or VAE decode behavior. ## 8. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Video`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # LingBot World 2.0 Source: https://docs.sglang.io/cookbook/diffusion/LingBot-World/LingBot-World-2.0 Serve LingBot World 2.0 realtime camera-controlled video world models with SGLang-diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. Use the [Realtime WebUI](#3-realtime-webui) to start a camera-controlled session. The Request tab checks model metadata; video generation uses WebSocket, not an HTTP POST. ## 2. Model capabilities [LingBot World 2.0](https://huggingface.co/robbyant/lingbot-world-v2-14b-causal-fast-diffusers) is the 14B realtime camera-controlled world model in the LingBot family. It generates continuously from a live causal session, accepts control updates between chunks, and reuses DiT and VAE state for incremental frame delivery. Choose 2.0 when the larger model and interactive KV-window path justify an 8-GPU deployment. Like the earlier LingBot release, it prioritizes responsive control and bounded causal state over the full-clip global context of offline video diffusion. ## 3. Deployment ```bash Command theme={null} export SGLANG_LINGBOT_LAZY_VAE_ENCODE_BLACK_FRAMES=60 export SGLANG_LINGBOT_ENABLE_INTERACTIVE_KV_WINDOW=true sglang serve \ --model-path robbyant/lingbot-world-v2-14b-causal-fast-diffusers \ --pipeline-class-name LingBotWorldCausalDMDPipeline \ --num-gpus 8 \ --ulysses-degree 8 \ --dit-cpu-offload false \ --text-encoder-cpu-offload false \ --vae-config.use-parallel-decode true \ --vae-config.parallel-decode-mode spatial \ --enable-torch-compile false ``` Intel Xeon CPU deployment is supported with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu`; omit GPU-only parallel and offload flags. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu sglang serve --model-path robbyant/lingbot-world-v2-14b-causal-fast-diffusers --pipeline-class-name LingBotWorldCausalDMDPipeline ``` ### Optional KV-Cache Compression Long-running sessions can enable lossy int4 PRQ compression for completed causal KV-cache chunks by installing `quant-videogen` as described in the quantization guide and adding `--kv-cache-quant int4` to the server command. The current and most recent completed chunks remain in BF16. See [Causal KV-Cache Quantization](/docs/sglang-diffusion/quantization#causal-kv-cache-quantization) for the algorithm, tuning options, measured memory-latency tradeoff, and support limits. ## 4. Realtime WebUI The lightweight local WebUI is useful for validating latency, frame transport, and camera control behavior. ```bash Command theme={null} python -m http.server 18080 -d python/sglang/multimodal_gen/apps/realtime_webui ``` Open `http://127.0.0.1:18080` and use: ```text Example theme={null} ws://127.0.0.1:30000/v1/realtime_video/generate ``` ## 5. HTTP and WebSocket API LingBot World 2.0 uses the realtime video WebSocket endpoint. The server keeps one live session, generates one chunk at a time, and accepts runtime control events while generation is running. ### Endpoints | API | Method | Purpose | Notes | | - | - | - | - | | `/v1/models` | `GET` | Query the served model id before opening a session. | The WebUI uses this to fill the model field when the server exposes model metadata. | | `/v1/realtime_video/generate` | `WebSocket` | Create one realtime LingBot session and stream generated video chunks. | The first client message must be an `init` message encoded with MessagePack. | ### `init` message Send this MessagePack map immediately after the WebSocket opens. | Parameter | Type | Required | Meaning | | - | - | - | - | | `type` | string | Yes | Must be `"init"`. | | `model` | string | No | Model id. Leave empty to use the served model. | | `prompt` | string | Yes | Text prompt for the initial scene and motion style. | | `first_frame` | bytes or string | Yes | Initial reference image. Send bytes from the WebUI/client, or a server-readable image path/string. | | `size` | string | Yes | Generation size as `WIDTHxHEIGHT`, for example `832x480`. | | `fps` | number | Yes | Target playback FPS for the generated stream. | | `num_frames` | integer | Yes | Frames per generated chunk. LingBot uses chunked causal generation, so this controls per-chunk latency and queue size. | | `seed` | integer | No | Random seed for deterministic sampling. | | `num_inference_steps` | integer | No | Denoising steps per chunk. LingBot defaults to `4` when omitted. | | `guidance_scale` | number | No | Classifier-free guidance scale. Realtime LingBot commonly uses `1`. | | `negative_prompt` | string | No | Negative prompt passed to the diffusion pipeline. | | `quality` | `"exact"`, `"lossless"`, `"high"` | No | `lossless` keeps FP32 VAE decode. `lossless` keeps FP32 decode and enables only any eligible request-gated kernel fusions. `high` includes those fusions and uses the validated BF16 decode path for lower per-chunk latency. | | `max_chunks` | integer | No | Stop after this many chunks. Omit for a continuous session. | | `realtime_causal_sink_size` | integer | No | Number of sink frames/tokens retained in the causal attention window. | | `realtime_causal_kv_cache_num_frames` | integer | No | Number of recent frames retained in the causal KV cache window. | | `realtime_output_format` | `"webp"`, `"jpeg"`, `"raw"` | No | Preview/output transport. `webp` and `jpeg` send encoded preview frames; `raw` (the default when omitted) sends lossless raw RGB. | | `output_compression` | integer | No | Preview quality for `webp` or `jpeg`, from `1` to `100`. | | `enable_upscaling` | boolean | No | Enable server-side super resolution after frame decode. | | `upscaling_scale` | integer | No | Super-resolution scale. Current default is `4` when upscaling is enabled. | | `upscaling_model_path` | string | No | Optional Real-ESRGAN model path. | | `enable_frame_interpolation` | boolean | No | Enable frame interpolation. Keep this disabled when measuring true generated FPS. | | `frame_interpolation_exp` | integer | No | Interpolation multiplier exponent. `1` means 2x frames. | | `frame_interpolation_scale` | number | No | RIFE internal scale for interpolation. | | `frame_interpolation_model_path` | string | No | Optional RIFE model path. | | `condition_inputs.camera_actions` | `list[list[string]]` | No | Initial scripted camera actions, one action list per frame. | ### Runtime `event` messages After `init`, send MessagePack event maps to update the live session. | Parameter | Type | Required | Meaning | | - | - | - | - | | `type` | string | Yes | Must be `"event"`. | | `kind` | `"prompt"`, `"camera_actions"`, or `"composite_input"` | Yes | Runtime event kind. | | `payload` | string, object, or list | Yes | For `prompt`, a non-empty string. For `camera_actions`, either scripted `list[list[string]]` or state-mode payload. For `composite_input`, a map containing `input_types` plus each named input. | | `event_id` | integer | No | Client sequence id. The server echoes it in chunk/frame metadata after the event is sampled. | `camera_actions` supports two payload modes: | Mode | Payload shape | Meaning | | - | - | - | | Script | `list[list[string]]` | A fixed sequence of per-frame actions consumed by upcoming chunks. | | State | `{ "mode": "state", "transitions": [{"actions": [...], "client_ts_ms": ...}] }` | Live control state transitions from keyboard or UI controls. | Supported LingBot action tokens include `w`, `a`, `s`, `d` for camera movement and `i`, `j`, `k`, `l` for look controls. Use `composite_input` when multiple runtime inputs should be sampled together, such as updating the prompt and camera controls in one event. ### Server messages | Message | Payload | Meaning | | - | - | - | | `frame_batch` | MessagePack map with `payload` bytes | One batch of frames. The map includes `chunk_index`, `num_frames`, `content_type`, `encoding`, `width`, `height`, and frame-batch metadata. | | `chunk_stats` | MessagePack map | Per-chunk timing and transport metrics, including `scheduler_forward_ms`, `raw_payload_build_ms`, `chunk_total_ms`, `num_frames`, and `ws_payload_bytes`. | | `error` | MessagePack map | Server-side validation or generation error. | ### Minimal client sketch ```python Python theme={null} import msgspec.msgpack import websocket ws = websocket.create_connection("ws://127.0.0.1:30000/v1/realtime_video/generate") ws.send_binary(msgspec.msgpack.encode({ "type": "init", "prompt": "A quiet rainy London alley, stable camera motion.", "first_frame": open("reference.jpg", "rb").read(), "size": "832x480", "fps": 25, "num_frames": 9, "num_inference_steps": 4, "guidance_scale": 1, "realtime_output_format": "webp", "output_compression": 95, })) ws.send_binary(msgspec.msgpack.encode({ "type": "event", "kind": "camera_actions", "event_id": 1, "payload": {"mode": "state", "transitions": [{"actions": ["w"], "client_ts_ms": 0}]}, })) ws.send_binary(msgspec.msgpack.encode({ "type": "event", "kind": "prompt", "event_id": 2, "payload": "A quiet snowy Tokyo alley, stable camera motion.", })) ws.send_binary(msgspec.msgpack.encode({ "type": "event", "kind": "composite_input", "event_id": 3, "payload": { "input_types": ["prompt", "camera_actions"], "prompt": "A quiet neon Shanghai alley, stable forward camera motion.", "camera_actions": [["w"], ["w"], []], }, })) ``` ## 6. Consistency LingBot World 2.0 uses raw-frame websocket GT plus per-chunk latency guards for consistency checks. ## 7. Notes * Use the realtime endpoint for interactive sessions: `/v1/realtime_video/generate`. * Prefer WebP preview transport for interactive testing; use raw-frame transport for consistency checks. * Long-running sessions should be validated with raw-frame consistency before changing causal cache, condition sampling, or VAE decode behavior. ## 8. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Video`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # LongCat-Image Source: https://docs.sglang.io/cookbook/diffusion/LongCat/LongCat-Image Deploy LongCat-Image with SGLang Diffusion and its native in-process Qwen2.5-VL prompt rewriter. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. ## 2. Model capabilities [LongCat-Image](https://huggingface.co/meituan-longcat/LongCat-Image) is a text-to-image model from Meituan. SGLang runs its Qwen2.5-VL prompt rewriter in process with the native SGLang runtime before text encoding and denoising. The native pipeline keeps prompt rewriting and diffusion behind one OpenAI-compatible image endpoint. Rewriting is enabled by default for stronger prompt expansion, but each request can disable it when lower latency matters more than the rewritten prompt. ## 3. Serve the model ```bash Command theme={null} sglang serve \ --model-path meituan-longcat/LongCat-Image \ --performance-mode auto \ --port 30010 ``` Prompt rewriting is enabled by default for LongCat-Image. It adds an autoregressive Qwen2.5-VL pass before diffusion; set `enable_prompt_rewrite=false` on a request when lower latency is more important than rewritten prompt quality. ## 4. Generate an image ```python Python theme={null} import base64 from openai import OpenAI client = OpenAI(api_key="EMPTY", base_url="http://127.0.0.1:30010/v1") response = client.images.generate( model="meituan-longcat/LongCat-Image", prompt="A quiet bookshop on a rainy evening, warm light in the windows", n=1, response_format="b64_json", ) image_bytes = base64.b64decode(response.data[0].b64_json) with open("longcat_image.png", "wb") as f: f.write(image_bytes) ``` To skip prompt rewriting with the OpenAI client, pass the model-specific request field through `extra_body`: ```python Python theme={null} response = client.images.generate( model="meituan-longcat/LongCat-Image", prompt="A quiet bookshop on a rainy evening", extra_body={"enable_prompt_rewrite": False}, ) ``` ## 5. Memory placement Use the unified component-residency selector when the complete pipeline does not fit on the accelerator. For example, keep the repeatedly used DiT resident while moving auxiliary components to CPU between stages: ```bash Command theme={null} sglang serve \ --model-path meituan-longcat/LongCat-Image \ --component-residency dit=resident text_encoder=component-offload vae=component-offload \ --pin-cpu-memory \ --port 30010 ``` See [Component Residency](/docs/sglang-diffusion/api/cli#component-residency) for mode semantics and compatibility with the existing CPU-offload flags. # LongLive 2.0 Source: https://docs.sglang.io/cookbook/diffusion/LongLive/LongLive-2.0 Serve LongLive 2.0 distilled text-to-video and image-to-video models with SGLang-diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. ## 2. Model capabilities [LongLive 2.0](https://nvlabs.github.io/LongLive/LongLive2/) is NVIDIA's 4-step text/image-to-video model distilled from Wan2.2-TI2V-5B. Its main strength is extending few-step causal generation across prompt changes, so a single request can produce multi-shot sequences without paying a full diffusion schedule for every shot. Choose it for low-step long or multi-shot generation rather than maximum one-shot fidelity. The SGLang path uses a Diffusers conversion of the official weights, and scene continuity still depends on prompt-block and sink settings; validate transitions on the target storyboard. The model weights use the NVIDIA Open Model License. See the [paper](https://arxiv.org/abs/2605.18739) and [GitHub repository](https://github.com/NVlabs/LongLive) for training details. ## 3. Deployment ```bash Command theme={null} sglang serve --model-path Rabinovich/LongLive-2.0-5B-Diffusers ``` In `auto` mode, GPUs with at least 60 GiB available keep the DiT, text encoder, and VAE resident. This uses about 44 GiB on H200 for the 832x480 preset and avoids moving encoder and decoder layers from host memory on every request. Smaller GPUs retain the layerwise-offload defaults. If the GPU runs out of memory, move the text encoder, VAE, and DiT to CPU between stages: ```bash Command theme={null} sglang serve \ --model-path Rabinovich/LongLive-2.0-5B-Diffusers \ --dit-cpu-offload \ --text-encoder-cpu-offload \ --vae-cpu-offload ``` `Rabinovich/LongLive-2.0-5B-Diffusers` is the Diffusers-format conversion of the official `Efficient-Large-Model/LongLive-2.0-5B` weights. Intel Xeon CPU deployment is supported with `SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu` and the selected LongLive checkpoint. ```bash Command theme={null} SGLANG_DIFFUSION_PLATFORM_OVERRIDE=cpu sglang serve --model-path Rabinovich/LongLive-2.0-5B-Diffusers ``` ## 4. Generation ### 4.1 Single prompt Generate one clip without starting a server: ```bash Command theme={null} sglang generate \ --model-path Rabinovich/LongLive-2.0-5B-Diffusers \ --prompt "A quiet street at dusk" \ --num-frames 61 \ --save-output \ --output-path outputs ``` 61 frames is 16 latent frames, which is two causal blocks of 8. ### 4.2 Multi-shot long video Multi-shot prompts are sampling parameters, so pass them through the Python API: ```python Python theme={null} from sglang import DiffGenerator gen = DiffGenerator.from_pretrained("Rabinovich/LongLive-2.0-5B-Diffusers") result = gen.generate(sampling_params_kwargs={ "shot_prompts": [ "A husky walks down a sunlit hallway.", "The husky turns and looks at the camera.", "Two dogs play together on a carpet.", ], "chunks_per_shot": 4, "num_frames": 381, # 3 shots x 4 chunks x 8 = 96 latent frames -> 381 frames "scene_cut_prefix": "The scene transitions. ", "multi_shot_sink": True, "multi_shot_rope_offset": 8.0, "save_output": True, "output_path": "outputs", }) ``` Each shot runs for `chunks_per_shot` causal blocks before the next prompt is used. The multi-shot defaults mirror the original LongLive prompt-block settings. ### 4.3 Key parameters These are SGLang request parameters. Original LongLive configs use latent-frame `num_output_frames`; SGLang exposes output-video `num_frames`. * `num_frames`: 61 in the examples. This maps to 16 latent frames, while the original release config defaults to 128 latent frames. * `num_inference_steps`: 4, matching original `sampling_steps`. * `guidance_scale`: 1.0, matching the original inference config. * `height` / `width`: 704 / 1280 by default, matching original latent H/W 44 / 80 with 16x spatial compression. * `shot_prompts`, `chunks_per_shot`, `scene_cut_prefix`, `multi_shot_sink`, and `multi_shot_rope_offset`: SGLang request fields for the original prompt-block and multi-shot behavior. ### 4.4 Image-to-video Pass a first frame with `--image-path` to condition the clip on an image: ```bash Command theme={null} sglang generate \ --model-path Rabinovich/LongLive-2.0-5B-Diffusers \ --prompt "A quiet street at dusk" \ --image-path first_frame.png \ --num-frames 61 \ --save-output \ --output-path outputs ``` The image is used as the first-frame condition. ## 5. Notes * `num_frames` must map to a whole number of causal blocks. The latent frame count is `(num_frames - 1) / 4 + 1` and must be divisible by 8. For example, 61, 125, and 189 frames give 16, 32, and 48 latent frames. * SGLang supports T2V sizes 1280x704, 704x1280, 832x480, and 480x832. * I2V request images follow the Wan TI2V preprocessing path in SGLang. This is different from the original LongLive dataset resize path. * For multi-shot runs, set `num_frames` to match `len(shot_prompts) * chunks_per_shot * 8` latent frames, that is `num_frames = (len(shot_prompts) * chunks_per_shot * 8 - 1) * 4 + 1`. ## 6. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Video`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # MOVA Source: https://docs.sglang.io/cookbook/diffusion/MOVA/MOVA Deploy MOVA with SGLang - simultaneous video and audio generation with asymmetric dual-tower architecture, precise lip-sync, and environment-aware sound effects. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation) for your GPU platform. Set the output directory before starting the server: ```bash theme={null} export SG_OUTPUT_DIR=/root/output_mova mkdir -p "$SG_OUTPUT_DIR" ``` ## 2. Model capabilities [MOVA](https://github.com/OpenMOSS/MOVA) generates video and audio together with an asymmetric dual-tower model connected by bidirectional cross-attention. Its strongest use cases are speaking subjects, visible sound-producing events, and scenes where ambient audio must track the picture rather than be synthesized by a later cascade. The public 360p and 720p checkpoints both generate up to 8 seconds. Choose 360p for the lighter deployment and 720p for output resolution; MOVA is less suitable when the task needs long-form continuity or the richer image/video/audio reference conditioning provided by H3. | Checkpoint | Best fit | Output limit | | - | - | - | | `OpenMOSS-Team/MOVA-360p` | Faster, lower-memory joint audiovisual generation | Up to 8 seconds at 360p | | `OpenMOSS-Team/MOVA-720p` | Higher-resolution lip-sync and environment audio | Up to 8 seconds at 720p | ## 3. Model Deployment This section provides deployment configurations optimized for different hardware platforms and use cases. ### 3.1 Basic Configuration MOVA supports both online serving and CLI generation modes. The recommended launch configurations vary by hardware and resolution. Use the [command builder](#1-quick-start) above. ### 3.2 Configuration Tips See [Performance Optimization](/docs/sglang-diffusion/performance-optimization) for acceleration features and their runtime requirements. * `--num-gpus`: Number of GPUs to use * `--tp`: Tensor parallelism size (should not be larger than 1 if text encoder offload is enabled, as layer-wise offload plus prefetch is faster) * `--ring-degree`: The degree of ring attention-style SP in USP * `--ulysses-degree`: The degree of DeepSpeed-Ulysses-style SP in USP * `--adjust-frames`: Whether to adjust frames automatically (set to `false` for MOVA) * `--enable-torch-compile`: Enable torch.compile for faster inference ## 4. API Usage For complete API documentation, please refer to the [official API usage guide](/docs/sglang-diffusion/api/openai_api). ### 4.1 CLI Generation (sglang generate) ```bash Command theme={null} sglang generate \ --model-path OpenMOSS-Team/MOVA-720p \ --prompt "A man in a blue blazer and glasses speaks in a formal indoor setting, \ framed by wooden furniture and a filled bookshelf. \ Quiet room acoustics underscore his measured tone as he delivers his remarks. \ At one point, he says, \"I would also believe that this advance in AI recently wasn't unexpected.\"" \ --image-path "" \ --adjust-frames false \ --num-gpus 8 \ --ring-degree 2 \ --ulysses-degree 4 \ --num-frames 193 \ --fps 24 \ --seed 67 \ --num-inference-steps 25 \ --enable-torch-compile \ --save-output ``` ### 4.2 Generate a Video ```bash Command theme={null} curl -X POST "http://0.0.0.0:30002/v1/videos" \ -F "prompt=A man in a blue blazer and glasses speaks in a formal indoor setting, framed by wooden furniture and a filled bookshelf. Quiet room acoustics underscore his measured tone as he delivers his remarks. At one point, he says, \"I would also believe that this advance in AI recently wasn't unexpected.\"" \ -F "input_reference=@" \ -F "size=640x352" \ -F "num_frames=193" \ -F "fps=24" \ -F "seed=67" \ -F "guidance_scale=5.0" \ -F "num_inference_steps=25" \ -o create_video.json ``` ### 4.3 Advanced Usage #### 4.3.1 Cache-DiT Acceleration SGLang integrates [Cache-DiT](https://github.com/vipshop/cache-dit), a caching acceleration engine for Diffusion Transformers (DiT), to achieve up to 7.4x inference speedup with minimal quality loss. You can set `SGLANG_CACHE_DIT_ENABLED=True` to enable it. For more details, please refer to the SGLang Cache-DiT [documentation](/docs/sglang-diffusion/cache_dit). **Basic Usage** ```bash Command theme={null} SGLANG_CACHE_DIT_ENABLED=true sglang serve --model-path OpenMOSS-Team/MOVA-720p ``` **Advanced Usage** * DBCache Parameters: DBCache controls block-level caching behavior:
Parameter Env Variable Default Description
Fn `SGLANG_CACHE_DIT_FN` 1 Number of first blocks to always compute
Bn `SGLANG_CACHE_DIT_BN` 0 Number of last blocks to always compute
W `SGLANG_CACHE_DIT_WARMUP` 4 Warmup steps before caching starts
R `SGLANG_CACHE_DIT_RDT` 0.24 Residual difference threshold
MC `SGLANG_CACHE_DIT_MC` 3 Maximum continuous cached steps
* TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion:
Parameter Env Variable Default Description
Enable `SGLANG_CACHE_DIT_TAYLORSEER` false Enable TaylorSeer calibrator
Order `SGLANG_CACHE_DIT_TS_ORDER` 1 Taylor expansion order (1 or 2)
Combined Configuration Example: ```bash Command theme={null} SGLANG_CACHE_DIT_ENABLED=true \ SGLANG_CACHE_DIT_FN=2 \ SGLANG_CACHE_DIT_BN=1 \ SGLANG_CACHE_DIT_WARMUP=4 \ SGLANG_CACHE_DIT_RDT=0.4 \ SGLANG_CACHE_DIT_MC=4 \ SGLANG_CACHE_DIT_TAYLORSEER=true \ SGLANG_CACHE_DIT_TS_ORDER=2 \ sglang serve --model-path OpenMOSS-Team/MOVA-720p ``` #### 4.3.2 CPU Offload * `--dit-cpu-offload`: Use CPU offload for DiT inference. Enable if run out of memory. * `--text-encoder-cpu-offload`: Use CPU offload for text encoder inference. * `--vae-cpu-offload`: Use CPU offload for VAE. * `--pin-cpu-memory`: Pin memory for CPU offload. Only added as a temp workaround if it throws "CUDA error: invalid argument". ## 5. Benchmark ### 5.1 Speedup Benchmark #### 5.1.1 Generate a video Test Environment: * Hardware: NVIDIA H200 x 8 * git revision: 443b1a8 * Model: OpenMOSS-Team/MOVA-720p **Server Command**: ```bash Command theme={null} sglang serve --model-path OpenMOSS-Team/MOVA-720p --port 30002 \ --adjust-frames false --num-gpus 8 --ring-degree 2 --ulysses-degree 4 \ --tp 1 --enable-torch-compile ``` **Benchmark Command**: ```bash Command theme={null} python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --task image-to-video --dataset vbench --num-prompts 1 --max-concurrency 1 \ --port 30002 ``` **Result**: ```text Output theme={null} ================= Serving Benchmark Result ================= Task: image-to-video Model: OpenMOSS-Team/MOVA-720p Dataset: vbench -------------------------------------------------- Benchmark duration (s): 590.76 Request rate: inf Max request concurrency: 1 Successful requests: 1/1 -------------------------------------------------- Request throughput (req/s): 0.00 Latency Mean (s): 590.7549 Latency Median (s): 590.7549 Latency P99 (s): 590.7549 -------------------------------------------------- Peak Memory Max (MB): 74996.00 Peak Memory Mean (MB): 74996.00 Peak Memory Median (MB): 74996.00 ============================================================ ``` #### 5.1.2 Generate videos with high concurrency **Server Command**: ```bash Command theme={null} sglang serve --model-path OpenMOSS-Team/MOVA-720p --port 30002 \ --adjust-frames false --num-gpus 8 --ring-degree 2 --ulysses-degree 4 \ --tp 1 --enable-torch-compile ``` **Benchmark Command**: ```bash Command theme={null} python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ --task image-to-video --dataset vbench --num-prompts 20 --max-concurrency 20 \ --port 30002 ``` ## 6. Run in ComfyUI Run this model from ComfyUI with the [SGLDiffusion plugin](https://github.com/sgl-project/sglang/tree/main/python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion), which ships in the SGLang repository at `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion`. **Server mode** — SGLang runs the pipeline and ComfyUI sends the request. Start a server as shown above, point the `SGLDiffusion Server Model` node at it, then generate with `SGLDiffusion Generate Video`. **Integrated mode** — not available for this model , which has no executor in the plugin . Use server mode. # MiniMax-H3 Source: https://docs.sglang.io/cookbook/diffusion/MiniMax/MiniMax-H3 Run native MiniMax-H3 video-and-audio generation with SGLang Diffusion. ## 1. Quick start Follow the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation), then choose a verified recipe below. Docker is recommended where the picker offers it. Setup changes the deployment; Server and Request expose orthogonal startup and sampling choices. > [!NOTE] > > The generated Server command already includes the recommended encoder policy. > Change a Server option only for a deliberate trade-off; Request options do not > reload the model. The Docker form uses the image's bundled diffusion dependencies without reinstalling them at startup. For conditioned requests, set **Host media directory** under **Variables**; the builder mounts it read-only at `/data/minimax-h3`. AMD and Grace Blackwell currently offer the Python form; the other NVIDIA recipes also offer Docker. To use ModelScope through the same normal `sglang serve` path, prefix the copied command with `SGLANG_USE_MODELSCOPE=true` and replace the model path with `MiniMax/MiniMax-H3`. Keep the selected variant and topology flags unchanged. For platform-specific installation details, see the [SGLang Diffusion installation guide](/docs/sglang-diffusion/installation). ## 2. Model capabilities [MiniMax-H3](https://huggingface.co/MiniMaxAI/MiniMax-H3) is a native joint video-and-audio model for text-to-video-and-audio, first/last-frame control, and multimodal reference conditioning. Its main strength is producing the picture and stereo soundtrack together, so speech, music, ambient sound, and visible events can stay aligned without a separate audio-generation pass. Choose H3 when synchronized audiovisual output or reference-driven generation matters more than a lightweight deployment. The released recipe targets a 768-pixel short edge at 24 fps for 4–15 seconds, and its capabilities are split across two checkpoint partitions; serving every mode therefore requires separate FL2VA and Ref2VA deployments. | Task | `task` value | Conditioning | | - | - | - | | Text to video and audio | `t2va` | Text prompt only | | First/last frame to video and audio | `fl2va` | First frame, last frame, or both | | Reference to video and audio | `ref2va` | Image, video, and audio references, optionally combined with first/last keyframes | Video-to-video (V2V) is a supported `ref2va` use case, not a fourth task value. Run the `Ref2VA` partition and provide a video reference in `conditions`. A hybrid `ref2va` request may also include the same ordered first/last keyframes accepted by `fl2va`, but it must still contain at least one reference condition. Use the selected Hub's root model ID: `MiniMaxAI/MiniMax-H3` on Hugging Face or `MiniMax/MiniMax-H3` on ModelScope. Select the checkpoint variant with `--model-variant`: `fl2va` serves both `t2va` and `fl2va`, while `ref2va` serves reference-conditioned requests. SGLang owns the checkpoint-directory mapping; do not point `--model-path` at a manually downloaded subdirectory. The same FL2VA / Ref2VA split applies in [ComfyUI integrated mode](#comfyui-integrated-mode). > [!WARNING] > > Review the license and usage terms in the MiniMax-H3 model card before production or commercial use. SGLang support does not grant additional model usage rights. ## 3. Deployment details The builder accepts legal custom GPU counts and topologies, marking them **Unverified** until the exact recipe has completed end-to-end validation. Static H3 head or partition violations disable Copy before they reach `sglang serve`. ### Grace Blackwell Select **GB300** or **GB200** in the builder. The default is one Linux ARM64 host with four GPUs, Ulysses4, and resident weights. This follows the [four-GPU compute-tray layout](https://docs.nvidia.com/dgx/dgxgb200-user-guide/hardware.html); an NVL72 rack is not a single 72-GPU process host. For two four-GPU hosts, set **Nodes = 2** and **GPUs / node = 4**. The builder emits Ulysses4 inside each host, Ring2 across hosts, and replicated encoders. Set the same reachable **Head address** on both hosts and use node ranks 0 and 1. Run the generated command once per host, with the same SGLang revision and dependencies. Let `sglang serve` resolve and download the selected weights. GB200 is a **derived, unverified recipe**, not a measured GB300-equivalent performance claim. Keep the native precision and platform-default attention for the baseline; the B200/B300 quantization measurements and H200 Cache-DiT quality audit do not establish coverage on Grace Blackwell. GB300 end-to-end coverage currently includes single-host FL2VA text-to-video with audio, native precision, eager execution, and `quality="exact"`. Ref2VA and multi-host commands remain **Unverified**. See the [GB300 measurements](#gb300-single-host) for the tested workload. ### Checkpoint and adapter formats Start with the command emitted by the builder. Every row below is an overlay on the same native SGLang pipeline; component repositories contribute their own config and weights, while weight files retain the base component config. Storage layout and inference behavior are separate contracts: for example, a PEFT file may be either a normal style adapter or a timestep-distilled Turbo adapter. | Scope | Format or variant | Add to the base command | Contract | | - | - | - | - | | Full model | Official mixed BF16/FP32, CFG-distilled | `--model-variant fl2va` or `--model-variant ref2va` | Lossless reference and consistency GT path. CFG distillation removes the negative branch; it is not the few-step timestep distillation used by Turbo releases. | | DiT | Official Diffusers component layout | `--component-paths.transformer MiniMaxAI/MiniMax-H3/transformer` (`fl2va`) or `.../transformer_ref` (`ref2va`) | Loads the official component through the native SGLang graph; no Diffusers runtime fallback. | | DiT | [AdaLN-pruned Diffusers component](https://huggingface.co/multimodalart/MiniMax-H3-Pruned) | `--component-paths.transformer multimodalart/MiniMax-H3-Pruned/transformer` or `.../transformer_ref` | Approximate curve-AdaLN architecture; its config and basis metadata are loaded natively. | | DiT | [Full or AdaLN-pruned](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/diffusion_models), or [LoRA-merged/remixed](https://huggingface.co/FX-FeiHou/MiniMax-H3-Remix) BF16 safetensors | `--component-weights-paths.transformer OWNER/REPO/path/FILE.safetensors` | Weight-only override for a native full/pruned H3 layout. Match the FL2VA/Ref2VA partition; pruned, merged, or dtype-converted exports are approximate, and any author-specific sampler remains a separate requirement. | | DiT | FL/Ref hybrid fine-tunes, including [Singularity v1.3](https://huggingface.co/WarmBloodAban/Minimax-h3_Singularity) (full or pruned INT8) | Replace `--model-variant` with `hybrid`; add `--component-weights-paths.transformer OWNER/REPO/FILE.safetensors` | Explicit merged-weight deployment serving `t2va`, `fl2va`, and `ref2va` on one native pipeline. Quantization and pruning are detected from the file; INT8 requires `comfy-kitchen`. See [Singularity](#singularity-hybrid-weights). | | DiT | Comfy FP8 or self-describing MXFP8 safetensors | `--component-weights-paths.transformer OWNER/REPO/path/FILE.safetensors` | Per-layer metadata selects static/dynamic FP8 or MXFP8 automatically. | | DiT | ConvRot INT8, W4A8, W4A4, or mixed W4A4+INT8 safetensors ([INT8](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/diffusion_models), [W4A8](https://huggingface.co/Winnougan/MiniMax-H3-INT4_Convrot_ComfyUI), [W4A4](https://huggingface.co/Merserk/MiniMax-H3-INT4-ConvRot)) | `--component-weights-paths.transformer OWNER/REPO/path/FILE.safetensors` | Auto-detected. INT8 layers run on SGLang's JIT-compiled ConvRot ops on CC 9.0, 10.0, 12.0 and 12.1 and on `comfy-kitchen` elsewhere; W4A8 and W4A4 layers require `comfy-kitchen`. TP must preserve each file's ConvRot group boundaries. | | DiT | [NVFP4, optionally mixed with INT8 or FP8](https://huggingface.co/Abiray/Minimax-H3-nvfp4-INT4-INT8-Convrot) | `--component-weights-paths.transformer OWNER/REPO/path/FILE.safetensors` | Auto-detected; NVFP4 execution requires NVIDIA compute capability 10.0+. | | DiT | [AutoRound W4A16 component](https://huggingface.co/Ar4ikov/MiniMax-H3-transformer-W4A16-RTN) | `--component-paths.transformer Ar4ikov/MiniMax-H3-transformer-W4A16-RTN` | Self-describing Diffusers component; SGLang reuses the SRT GPTQ/Marlin backend. The linked export is FL2VA. | | DiT | GGUF, full or AdaLN-pruned ([full](https://huggingface.co/leejet/MiniMax-H3-GGUF), [pruned](https://huggingface.co/unsloth/MiniMax-H3-GGUF)) | `--component-weights-paths.transformer OWNER/REPO/FILE.gguf` | CUDA capacity path; aligned TP and layerwise offload are supported, FSDP and LoRA are not. | | Text encoder | Architecture-compatible Qwen3-VL BF16 finetune ([Heretic example](https://huggingface.co/llmfan46/Qwen3-VL-32B-Instruct-ultra-uncensored-heretic)) | `--component-paths.text_encoder OWNER/REPO` | Reuses the native H3 extractor, including its vision tower and layer-50 hidden-state selection. Finetuning changes conditioning, not the sampling schedule. | | Text encoder | [Serialized FP8 component](https://huggingface.co/Qwen/Qwen3-VL-32B-Instruct-FP8) | `--component-paths.text_encoder Qwen/Qwen3-VL-32B-Instruct-FP8` | Only eligible language-model linears use FP8; embeddings, norms, and the vision tower keep their declared precision. | | Text encoder | ConvRot INT8, W4A8, or W4A4 safetensors ([INT8](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/text_encoders), [Heretic INT8](https://huggingface.co/ethanfel/Qwen3-VL-32B-Ultra-Heretic-H3-ComfyUI-INT8-ConvRot), [W4A8](https://huggingface.co/Winnougan/MiniMax-H3-INT4_Convrot_ComfyUI), [W4A4](https://huggingface.co/Merserk/MiniMax-H3-INT4-ConvRot)) | `--component-weights-paths.text_encoder OWNER/REPO/path/FILE.safetensors` | Auto-detected. INT8 layers run on SGLang's JIT-compiled ConvRot ops on CC 9.0, 10.0, 12.0 and 12.1 and on `comfy-kitchen` elsewhere; W4A8 and W4A4 layers require `comfy-kitchen`. INT8/W4A8 files may include a scalar-scale INT8 embedding, which requires `comfy-kitchen`. Unmarked tensors retain their declared precision. | | Text encoder | Comfy NVFP4 with dynamic activation quantization ([Heretic example](https://huggingface.co/sakamakismile/Qwen3-VL-32B-Heretic-MiniMax-H3-NVFP4)) | `--component-weights-paths.text_encoder OWNER/REPO/path/FILE.safetensors` | Requires `comfy-kitchen` and NVIDIA compute capability 10.0+. Per-layer metadata selects native NVFP4 matmul; scalar/row-wise INT8 embeddings remain packed. | | Text encoder | [NVFP4-AWQ](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/text_encoders) or [Quanto qint8](https://huggingface.co/DeepBeepMeep/MiniMax-H3/tree/main/Qwen3-VL-32B-Instruct) safetensors | `--component-weights-paths.text_encoder OWNER/REPO/path/FILE.safetensors` | Memory-oriented formats: compressed storage is restored, then each active matrix uses BF16/FP16 compute. | | Text encoder | [GGUF Qwen3-VL](https://huggingface.co/DeepBeepMeep/MiniMax-H3/tree/main/Qwen3-VL-32B-Instruct) | `--component-weights-paths.text_encoder OWNER/REPO/FILE.gguf` | CUDA capacity path with encoder TP/layerwise support; encoder FSDP is not supported. | | Text encoder | [Compact Qwen3-VL 4B/8B + ClipProj](https://huggingface.co/NicoLab28/ClipProj-MiniMax-H3) | `--component-paths.text_encoder ENCODER_REPO --component-paths.conditioning_projection PROJECTION.safetensors` | Approximate conditioning replacement. A separate weight-only override may quantize the selected small encoder. | | DiT or adapter | Timestep-distilled Turbo, as merged weights or LoRA ([Larry](https://huggingface.co/larryvrh/MiniMax-H3-Turbo-Lora), [LightX2V](https://huggingface.co/lightx2v/Minimax-h3-Turbo), [merged Ref2VA INT8 example](https://huggingface.co/PulpCut/MiniMax-H3-Ref2VA-Turbo-INT8-ConvRot)) | Use `--component-weights-paths.transformer ...` for merged weights, or `--lora-path OWNER/REPO --lora-weight-name FILE --lora-merge-mode auto` for LoRA | Few-step semantic variant. Pin the exact FL2VA/Ref2VA file and its NFE/sigma schedule, scale, and alpha; storage-format detection does not infer sampling behavior. See [LoRA recipes](#5-lora-recipes). | | Adapter | Style, subject, or behavior LoRA ([example](https://huggingface.co/fal/MiniMax-H3-Realism-People-LoRA)) | `--lora-path OWNER/REPO [--lora-weight-name FILE] --lora-merge-mode auto` | Native fused and Diffusers/PEFT layouts are normalized at load time. Keep the base schedule unless the author specifies another one, and preserve any trigger phrase, scale, and alpha metadata. | The rows compose rather than enumerate every cross-product. A Turbo-merged INT8 ConvRot checkpoint, for example, must satisfy both the Turbo sampling contract and the ConvRot storage/backend contract. H3's Qwen3-VL text encoder also handles image understanding; there is no separate `image_encoder` component. Select the conditioning checkpoint, not an optional generation-tail file for prompt rewriting. The `uncensored` or `Heretic` label describes a weight modification, not a separate loader or a guarantee of output quality. For H3, the registered component names are `transformer`, `text_encoder`, `video_vae`, and `audio_vae`. The shorter `--transformer-weights-path` and `--text-encoder-path` aliases remain supported. `conditioning_projection` is an H3 text-encoder sidecar key, not a standalone model component. Plain video/audio VAE safetensors can use `--component-weights-paths.video_vae` or `--component-weights-paths.audio_vae`, but SGLang does not currently advertise a native quantized H3 VAE format. Pre-quantized files are self-describing: do not combine those rows with `--quantization` or `--component-quantizations.*`. Only byte-identical official full weights—whether loaded from the original model, Diffusers component, or a weight-only layout—belong to the consistency GT. Pruned, quantized, compact-encoder, and LoRA routes are outside that baseline and the audited `quality="high"` contract. Packed and per-layer mixed formats reject FSDP unless their row says otherwise; see [Quantization](/docs/sglang-diffusion/quantization) for backend-wide constraints. LoRA tensors alone do not make an execution-coupled release portable. Sparse- attention/SLA adapters and causal-streaming adapters such as RAVEN also require their matching attention or streaming pipeline; they are not standard H3 LoRA overlays in SGLang. Likewise, a remixed checkpoint that prescribes a custom sampler is only covered when that sampler contract can be reproduced—the fact that its safetensors layout loads is not sufficient. For a four-card H200 host, keep the full BF16/FP32 model resident by default. The model fits without FSDP, so this path avoids the per-block parameter all-gathers of the memory-oriented FSDP profile: ```bash 4×H200 resident theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-H3 \ --model-variant fl2va \ --num-gpus 4 \ --ulysses-degree 4 \ --encoder-parallel auto \ --performance-mode speed \ --port 30010 ``` Pure Ulysses4 is also the faster measured topology on H200, not just a capacity default. The 4×H100 TP2 + Ulysses2 recipe below fits on 141 GB H200 cards, but it replaces the Ulysses all-to-all exchange with two per-block tensor-parallel all-reduces and measured slower end-to-end, at about 30 GB lower peak memory per GPU. See the **H200 topology comparison** in the Benchmarks section for the measured numbers; treat TP2 + Ulysses2 on H200 as a deliberate memory trade, not a latency default. For 4×H100 80 GB, balance the large packed activation with resident weight sharding. TP2 + Ulysses2 was the fastest measured lossless topology while the Qwen encoder still folds across all four GPUs: ```bash 4×H100 fastest theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-H3 \ --model-variant fl2va \ --num-gpus 4 \ --tp-size 2 \ --ulysses-degree 2 \ --encoder-parallel auto \ --performance-mode speed \ --port 30010 ``` Pure Ulysses4 could not keep the full pipeline resident on 80 GB H100s. Use `--tp-size 4 --ulysses-degree 1` when lower resident memory matters more than the last few percent of latency. FSDP remains a verified capacity option, but its per-block weight all-gathers do not make it the H100 speed default: ```bash 4×H100 FSDP capacity theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-H3 \ --model-variant fl2va \ --num-gpus 4 \ --ulysses-degree 4 \ --encoder-parallel auto \ --performance-mode speed \ --use-fsdp-inference true \ --port 30010 ``` For a two-card RTX 5090 host, use TP2 and keep 20 DiT blocks resident. Layerwise placement is lossless: it changes parameter placement and transfer scheduling, not the BF16/FP32 denoising or VAE math. This is the fastest measured 32 GB operating point: ```bash 2×RTX 5090 fastest lossless theme={null} sglang serve \ --model-path MiniMaxAI/MiniMax-H3 \ --model-variant fl2va \ --num-gpus 2 \ --tp-size 2 \ --ulysses-degree 1 \ --encoder-parallel auto \ --performance-mode memory \ --layerwise-offload-components dit,text_encoder,vae \ --dit-offload-prefetch-size 1 \ --dit-layerwise-resident-layers 20 \ --enable-torch-compile false \ --port 30010 ``` The DiT residency and prefetch knobs apply only to the repeatedly executed DiT blocks. The text encoder and the video VAE decoder blocks use one-layer prefetch with zero resident layers. The video VAE encoder stays resident because its indexed down blocks cannot host executable layerwise hooks; the roughly 577 MiB audio VAE also stays resident because offloading it only adds transfer overhead. This exact recipe was validated on 2× RTX 5090 (32 GB each) and a 377 GiB host; use a 384 GiB-class machine. The latency and memory comparison is collected in the benchmark section below. For a single 24 GB consumer card (RTX 4090), stream the DiT and text encoder and quantize DiT linear layers online with `convrot_int8`. Keep `vae` out of `--layerwise-offload-components`: putting the VAE decoder in layerwise offload re-streams about 9 GiB on each of 167 decode tiles. Default attention stays `fa` (exact). Approximate backends are opt-in; see [Attention Backends](/docs/sglang-diffusion/attention_backends#sage-then-sol-hybrid). On the RTX 4090 (CC 8.9) `convrot_int8` runs on `comfy-kitchen`, so install it first (`pip install comfy-kitchen`); on CC 9.0, 10.0, 12.0 and 12.1 it uses SGLang's JIT-compiled ConvRot ops instead (built once per machine on first use). ```bash 1×RTX 4090 24GB theme={null} sglang generate \ --model-path MiniMaxAI/MiniMax-H3 \ --model-variant fl2va \ --quantization convrot_int8 \ --attention-backend fa \ --performance-mode memory \ --layerwise-offload-components dit,text_encoder \ --dit-offload-prefetch-size 1 \ --dit-layerwise-resident-layers 0 \ --enable-torch-compile false \ --prompt "A cat walking on a sunny beach, gentle waves." \ --save-output ``` The same flags work on `sglang serve`. Drop `--quantization` for the BF16 baseline; everything else stays identical. GPU peak stays about 18 GB either way because streaming offload is set by the offload buffers and VAE decode, not the weight dtype. To skip DiT steps on 4090 while keeping `fa`, add Spectrum to the generate command above. Do not combine it with `quality="high"` or Cache-DiT. On this card, 50-step BF16+FA (**1008.6 s**) drops to **285.3 s (3.53×)** with exact attention, up to **219.0 s (4.61×)** with Sage→Sol hybrid + Spectrum. See the 4090 table in Benchmarks. ```bash theme={null} --enable-spectrum \ --spectrum-warmup-steps 11 \ --spectrum-window-size 5 \ --spectrum-flex-window 1.0 ``` The first launch resolves every selected source through the normal Hub path. If a repository requires authentication, export a Hugging Face token in the server environment; no manual pre-download is required. For MiniMax-H3, `--performance-mode speed` deliberately keeps the DiT eager. The current `torch.compile` path changes the model's numerical output, so no recommended lossless preset enables it implicitly. An explicit `--enable-torch-compile true` remains available for controlled experiments, but do not use it to generate consistency ground truth. ### ComfyUI integrated mode The [ComfyUI plugin](/docs/sglang-diffusion/comfyui) can run H3 as a per-step DiT backend. ComfyUI keeps CLIP, VAE, and the sampler loop. SGLang loads only the transformer under `--comfyui-mode`. Copy `python/sglang/multimodal_gen/apps/ComfyUI_SGLDiffusion` into ComfyUI `custom_nodes/`. Load a shipped graph and set `SGLDOptions.model_type` to `minimax_h3`: | Graph | Task | DiT filename | | - | - | - | | `minimax_h3_t2v_sgld.json` | T2V / I2VA / FL2VA | `minimax_h3_fl2va_*.safetensors` | | `minimax_h3_r2v_sgld.json` | Reference-to-video | `minimax_h3_ref2va_*.safetensors` | | `minimax_h3_t2v_sgld_upscaler.json` | Low-res then 3D ×2 | `fl2va` DiT | Pruned BF16 / FP8 files from [Comfy-Org/MiniMax-H3](https://huggingface.co/Comfy-Org/MiniMax-H3/tree/main/diffusion_models) are the usual loader inputs. GGUF goes in `SGLDOptions.transformer_weights_path`. On a 24 GB card put the 32B CLIP on CPU and enable DiT layerwise offload; use `convrot_int8` or GGUF rather than the full unpruned BF16 DiT. ### Singularity hybrid weights [Singularity](https://huggingface.co/WarmBloodAban/Minimax-h3_Singularity) is an FL/Ref fusion fine-tune, not a complete pipeline repository. Keep the official model ID for the encoders and VAEs, and select one exact transformer file: ```bash 2×B300 hybrid checkpoint theme={null} pip install comfy-kitchen WEIGHTS=WarmBloodAban/Minimax-h3_Singularity/Minimax-h3_Singularity_ref2va_Pruned_v1.3_int8.safetensors sglang serve --model-path MiniMaxAI/MiniMax-H3 \ --model-variant hybrid \ --component-weights-paths.transformer "$WEIGHTS" \ --num-gpus 2 --ulysses-degree 2 --performance-mode speed \ --port 30000 ``` For the full INT8 checkpoint, replace the filename with `Minimax-h3_Singularity_ref2va_v1.3_int8.safetensors`. SGLang downloads the selected file automatically. Do not add an online quantization override. `hybrid` requires an explicit weight override; it does not convert the official Ref2VA weights into a multimode model. Request `task` and `conditions` retain their [usual meanings](#4-generate-video-and-audio), including `conditions: []` for `t2va` and keyframes for `fl2va`. Start with `quality: "lossless"` and the standard 50-point schedule. Here `exact` disables additional request-time approximations; it does not undo INT8 quantization, pruning, or fine-tuning. The author's recommended Ref2V Turbo LoRA is a separate optional adapter, not an automatically inferred 4-step schedule. Reference fidelity can differ from the official model; see the [author's guidance](https://huggingface.co/WarmBloodAban/Minimax-h3_Singularity/discussions/1) before applying the [LoRA sampling contract](#5-lora-recipes). ### Advanced: precomputed AdaLN cache The [model card](https://huggingface.co/MiniMaxAI/MiniMax-H3) notes that about 13B H3 parameters are AdaLN branches whose outputs can be precomputed for inference. The public base checkpoint contains the original branches, not a ready-to-use cache. SGLang therefore keeps the standard path as the default. > [!WARNING] > > This is an experimental deployment path. It is intentionally disabled unless > you provide an explicitly generated cache; end-to-end numerical and peak-memory > validation remains required before using it in production. When an inference-only deployment has a fixed sampling schedule, build a cache from the already materialized transformer directory on CUDA, then pass it to the usual `sglang serve` command. This does not alter the denoising formula: the cache stores the BF16 outputs of the original AdaLN linears. ```bash Command theme={null} python -m sglang.multimodal_gen.tools.build_minimax_h3_adaln_cache \ --transformer-path "$TRANSFORMER_PATH" \ --model-variant fl2va \ --mode t2va \ --num-inference-steps 50 \ --flow-shift 12 \ --audio-flow-shift 3 \ --output /models/minimax-h3-fl2va-adaln-50step.safetensors sglang serve \ --model-path MiniMaxAI/MiniMax-H3 \ --model-variant fl2va \ --minimax-h3-adaln-cache-path /models/minimax-h3-fl2va-adaln-50step.safetensors \ --num-gpus 4 \ --tp-size 2 \ --ulysses-degree 2 \ --port 30010 ``` `$TRANSFORMER_PATH` is the `FL2VA/transformer` or `Ref2VA/transformer` directory in the normal SGLang/Hugging Face snapshot; the builder never downloads a second copy. A cache only covers the scheduler settings used to create it, including its mode, step count, flow shifts, and condition noise values. SGLang rejects a request outside that coverage instead of silently changing conditioning. Cache mode supports the matching unquantized checkpoint only. ### Advanced: online AdaLN rebuild with a host cache `--minimax-h3-adaln-online true` needs no prebuilt artifact: the server drops the 24.2 GiB of `adaln_proj` weights from the GPU and computes each request's AdaLN outputs from the checkpoint on demand, bit-exact with the resident-weight path. Because a rebuild pass streams the whole 24.2 GiB, the first request of every new `(task shape, num_inference_steps, flow_shift, audio_flow_shift)` combination pays several seconds; after that the plans are served from a 64-slot GPU slab (LRU per plan) backed by a pinned host cache (`--minimax-h3-adaln-host-cache-gb`, LRU per schedule, default 8 GB per rank), so mixed-schedule serving does not re-read the checkpoint. Plan sets that exceed the host budget are simply recomputed on their next occurrence. Expert escape hatches live in environment variables: `SGLANG_DIFFUSION_MINIMAX_H3_ADALN_GPU_PLANS` resizes the GPU slab (needed only beyond 65 inference steps) and `SGLANG_DIFFUSION_MINIMAX_H3_ADALN_FP32` computes the one-time projections in fp32 (experimental; not bit-comparable to resident weights, validate end-to-end before production). LoRA adapters that modify `adaln_proj` are rejected in both cache modes rather than silently ignored. Both cache modes hold values derived from `adaln_proj`, so a runtime weight update is only accepted when the cache can follow it: online mode takes a disk update whose target directory carries native `adaln_proj` safetensors, and rejects everything else (tensor updates, and directories without those tensors) before a single weight is written. A sidecar is built offline and cannot be regenerated in the server, so weight updates are rejected outright; rebuild the sidecar against the new weights and restart. ### Serve MiniMax-H3 on Ascend NPUs For Ascend NPU, follow the [NPU installation guide](/docs/hardware-platforms/ascend-npus/getting-started/installation) before starting the server. The Ascend commands below explicitly enable the Cache-DiT configuration used for the reported performance measurements. Remove these `SGLANG_CACHE_DIT_*` variables to use lossless denoising. See the **Ascend NPU topology comparison** in the Benchmarks section for the measured eight- and four-NPU latency. The measured latency configuration also passes `--dit-cpu-offload false` to keep the transformer resident on the NPUs. Omit this flag when lower device memory usage is more important than avoiding CPU-to-NPU transfer latency. For an eight-NPU host, the validated topology is TP2 + SP4 with Laser Attention. Use Ascend Flash Attention by replacing `laser_attn` with `fa`. ```bash 8-NPU theme={null} SGLANG_CACHE_DIT_ENABLED=true \ SGLANG_CACHE_DIT_FN=2 \ SGLANG_CACHE_DIT_BN=1 \ SGLANG_CACHE_DIT_WARMUP=4 \ SGLANG_CACHE_DIT_RDT=0.4 \ SGLANG_CACHE_DIT_MC=4 \ SGLANG_CACHE_DIT_TAYLORSEER=true \ SGLANG_CACHE_DIT_TS_ORDER=2 \ HCCL_BUFFSIZE=256 sglang serve \ --model-path MiniMaxAI/MiniMax-H3 \ --model-type diffusion \ --model-variant fl2va \ --dit-cpu-offload false \ --num-gpus 8 \ --tp-size 2 \ --sp-degree 4 \ --attention-backend laser_attn \ --port 30088 \ --component-residency text_encoder=layerwise-offload ``` For a four-NPU host, use TP2 + SP2: ```bash 4-NPU theme={null} SGLANG_CACHE_DIT_ENABLED=true \ SGLANG_CACHE_DIT_FN=2 \ SGLANG_CACHE_DIT_BN=1 \ SGLANG_CACHE_DIT_WARMUP=4 \ SGLANG_CACHE_DIT_RDT=0.4 \ SGLANG_CACHE_DIT_MC=4 \ SGLANG_CACHE_DIT_TAYLORSEER=true \ SGLANG_CACHE_DIT_TS_ORDER=2 \ HCCL_BUFFSIZE=256 sglang serve \ --model-path MiniMaxAI/MiniMax-H3 \ --model-type diffusion \ --model-variant fl2va \ --dit-cpu-offload false \ --num-gpus 4 \ --tp-size 2 \ --sp-degree 2 \ --attention-backend laser_attn \ --port 30088 \ --component-residency text_encoder=layerwise-offload ``` ## 4. Generate video and audio `num_inference_steps: N` executes **N denoising updates** over N+1 sigma points, including the terminal zero. Reference implementations that count sigma points need N+1 to reproduce this schedule. Older SGLang versions ran N-1 updates for the same request; use N-1 here to preserve their sampling trajectory. Changing the step count changes the trajectory, not just latency. MiniMax-H3 uses the asynchronous OpenAI-compatible video endpoint. Choose a generation mode below, submit a job, poll its status, and then download the completed MP4. **T2VA** MiniMax-H3 supports output durations from 4 through 15 seconds, inclusive. The following request keeps the verified 5-second profile at a 768-pixel short edge. MiniMax-H3 resolves the aligned output canvas and frame count from `target`. ```bash Command theme={null} video_id=$( curl -sS -X POST http://127.0.0.1:30010/v1/videos \ -H "Content-Type: application/json" \ -d '{ "model": "MiniMaxAI/MiniMax-H3", "prompt": "At night, while their owner sleeps in a bedroom, three cats march in loudly playing tiny brass instruments, then abruptly file out.", "seconds": 5, "task": "t2va", "conditions": [], "target": { "short_edge": 768, "aspect_ratio": "16:9", "duration_seconds": 5.0 }, "num_outputs_per_prompt": 1, "num_inference_steps": 50, "flow_shift": 12.0, "audio_flow_shift": 3.0, "seed": 1101 }' | jq -r '.id' ) while true; do status=$(curl -sS "http://127.0.0.1:30010/v1/videos/${video_id}" | jq -r '.status') [ "$status" = "completed" ] && break [ "$status" = "failed" ] && exit 1 sleep 1 done curl -sS -L "http://127.0.0.1:30010/v1/videos/${video_id}/content" \ -o minimax-h3-t2va.mp4 ``` The output contract is an MP4 containing H.264 video at 24 fps and one AAC stereo audio stream at 32 kHz. **FL2VA** For `fl2va`, provide one or two image conditions with role `keyframe`. The supported frame-index sets are `[0]`, `[-1]`, and `[0, -1]`. The following request uses one server-local first frame. Use `frame_index: -1` for a last frame, or include both entries for first-and-last conditioning. Choose FL2VA when the supplied image should be the actual first or last frame of the generated clip. Use image-based Ref2VA instead when the image should guide identity, style, or composition without being preserved as an endpoint; Ref2VA may recompose or crop the reference. ```bash Command theme={null} curl -sS -X POST http://127.0.0.1:30010/v1/videos \ -H "Content-Type: application/json" \ -d '{ "model": "MiniMaxAI/MiniMax-H3", "prompt": "The supplied frame continues with calm, natural motion and synchronized ambient sound.", "seconds": 5, "task": "fl2va", "conditions": [ { "type": "image", "uri": "file:///data/minimax-h3/first-frame.png", "role": "keyframe", "frame_index": 0 } ], "target": { "short_edge": 768, "aspect_ratio": "auto", "duration_seconds": 5.0 }, "num_outputs_per_prompt": 1, "num_inference_steps": 50, "flow_shift": 12.0, "audio_flow_shift": 3.0, "seed": 2101 }' ``` **V2V** V2V uses the reference-conditioning weights. Launch the server with `--model-variant ref2va`, keep the request `task` set to `ref2va`, and provide a video reference in `conditions`. There is no separate `v2v` task value. Use `type: "video"` when the input may be silent. If the file has a soundtrack, H3 also uses it as an audio reference. Use `type: "video_audio"` only when both streams are required; that form rejects an input without audio. The prompt tag for the visual stream is `