diff --git a/.gitignore b/.gitignore index a8aa903e2..8ac442295 100644 --- a/.gitignore +++ b/.gitignore @@ -192,6 +192,7 @@ work_dirs/ *.csv !logo.png +!docs_new/images/*.png # Prerequisites *.d diff --git a/docs_new/.github/workflows/sync-lmsys-sglang-blogs.yml b/docs_new/.github/workflows/sync-lmsys-sglang-blogs.yml new file mode 100644 index 000000000..f555baf10 --- /dev/null +++ b/docs_new/.github/workflows/sync-lmsys-sglang-blogs.yml @@ -0,0 +1,39 @@ +name: Sync LMSYS SGLang blogs + +on: + workflow_dispatch: + schedule: + - cron: "0 */12 * * *" + +permissions: + contents: write + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Sync blog cards + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: python scripts/update_lmsys_sglang_blogs.py + + - name: Commit and push changes + run: | + if git diff --quiet; then + echo "No changes to commit." + exit 0 + fi + + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + git add index.mdx src/generated/lmsys_sglang_blogs.json + git commit -m "docs: sync LMSYS SGLang blog cards" + git push diff --git a/docs_new/.gitignore b/docs_new/.gitignore new file mode 100644 index 000000000..126ca6550 --- /dev/null +++ b/docs_new/.gitignore @@ -0,0 +1,30 @@ +# Node +node_modules/ +.env +.DS_Store +.cache/ +dist/ +.next/ +*.log + +# OS +Thumbs.db +Desktop.ini + +# VSCode +.vscode/ + +# Mintlify +.mintlify/ + +# Python (if any) +__pycache__/ +*.pyc + +# Misc +*.swp +*.swo + +.agents +.claude +skills-lock.json diff --git a/docs_new/.mintignore b/docs_new/.mintignore new file mode 100644 index 000000000..9922f06dc --- /dev/null +++ b/docs_new/.mintignore @@ -0,0 +1,7 @@ +# Mintlify automatically ignores these files and directories: +# .git, .github, .claude, .agents, .idea, node_modules, +# README.md, LICENSE.md, CHANGELOG.md, CONTRIBUTING.md + +# Draft content +drafts/ +*.draft.mdx diff --git a/docs_new/AGENTS.md b/docs_new/AGENTS.md new file mode 100644 index 000000000..dd60e68fb --- /dev/null +++ b/docs_new/AGENTS.md @@ -0,0 +1,381 @@ +--- +name: sglang-docs-mintlify +description: Build and maintain the SGLang documentation site and integrated cookbook using Mintlify. Use when + creating docs pages, configuring navigation, adding components, or setting up + API references. +license: Apache-2.0 +compatibility: Requires Node.js for CLI. Works with any Git-based workflow. +metadata: + author: SGLang Team + version: "1.0" + mintlify-proj: mintlify +--- + +# SGLang Mintlify documentation guide for agents + +## Non-negotiables + +- **Do not guess flags, defaults, or behavior.** + If you’re documenting CLI args, env vars, APIs, or performance behavior, verify against: + - the upstream codebase (`sgl-project/sglang`) + - the current public docs (`docs.sglang.io`) until the migration is complete + - or an authoritative vendor doc when platform-specific (ROCm, CANN/Ascend, Intel XPU). +- **Prefer fixing the docs-site version of an internal link** instead of copying links from older docs. +- **Keep examples copy/pasteable.** Use placeholders consistently (e.g., `MODEL_PATH`, `HF_TOKEN`, `HOST`, `PORT`). + +## Source of truth hierarchy + +1. **This repo** + - `docs.json` for site structure + navigation + - existing MDX pages for voice + conventions +2. **Canonical current docs** + - `docs.sglang.io` (Sphinx site) is currently the reference structure and content baseline. +3. **Implementation** + - `sgl-project/sglang` for anything that can change with releases (flags, env vars, defaults, supported models). +4. **Cookbook** + - `cookbook.sglang.io` / `sgl-project/sgl-cookbook` for recipe patterns and model-specific operational guidance. + +## Writing standards (SGLang-specific) + +### Voice and structure + +* Second person (“you”), active voice. +* Prefer **short, scannable sections** with clear outcomes. +* Headings in **sentence case**. +* Put prerequisites before commands. + +### Technical accuracy patterns + +For pages that include commands/configs, always specify: + +* **Platform** (NVIDIA CUDA / AMD ROCm / Intel XPU / Ascend NPU / CPU) +* **OS** (if relevant) and **version constraints** +* **Model identifier** format (e.g., Hugging Face repo id) and where it goes (`--model-path`, `--model`, etc.) +* **Parallelism knobs** used in the example (`--tp`, `--dp`, node count, etc.) +* Any required secrets/tokens (`HF_TOKEN`) and where they are used. + +# Mintlify best practices + +**Always consult [mintlify.com/docs](https://mintlify.com/docs) for components, configuration, and latest features.** + +If you are not already connected to the Mintlify MCP server, [https://mintlify.com/docs/mcp](https://mintlify.com/docs/mcp), add it so that you can search more efficiently. + +**Always** favor searching the current Mintlify documentation over whatever is in your training data about Mintlify. + +Mintlify is a documentation platform that transforms MDX files into documentation sites. Configure site-wide settings in the `docs.json` file, write content in MDX with YAML frontmatter, and favor built-in components over custom components. + +Full schema at [mintlify.com/docs.json](https://mintlify.com/docs.json). + +## Before you write + +### Understand the project + +Read `docs.json` in the project root. This file defines the entire site: navigation structure, theme, colors, links, API and specs. + +Understanding the project tells you: + +* What pages exist and how they're organized +* What navigation groups are used (and their naming conventions) +* How the site navigation is structured +* What theme and configuration the site uses + +### Check for existing content + +Search the docs before creating new pages. You may need to: + +* Update an existing page instead of creating a new one +* Add a section to an existing page +* Link to existing content rather than duplicating + +### Read surrounding content + +Before writing, read 2-3 similar pages to understand the site's voice, structure, formatting conventions, and level of detail. + +### Understand Mintlify components + +Review the Mintlify [components](https://www.mintlify.com/docs/components) to select and use any relevant components for the documentation request that you are working on. + +## Quick reference + +### CLI commands + +* `npm i -g mint` - Install the Mintlify CLI +* `mint dev` - Local preview at localhost:3000 +* `mint broken-links` - Check internal links +* `mint a11y` - Check for accessibility issues in content +* `mint rename` - Rename/move files and update references +* `mint validate` - Validate documentation builds + +### Required files + +* `docs.json` - Site configuration (navigation, theme, integrations, etc.). See [global settings](https://www.mintlify.com/docs/organize/settings) for all options. +* `*.mdx` files - Documentation pages with YAML frontmatter + +### Example file structure + +``` +project/ +├── docs.json # Site configuration +├── introduction.mdx +├── quickstart.mdx +├── guides/ +│ └── example.mdx +├── openapi.yml # API specification +├── images/ # Static assets +│ └── example.png +└── snippets/ # Reusable components + └── component.jsx +``` + +## Page frontmatter + +Every page requires `title` in its frontmatter. Include `description` for SEO and navigation. + +```yaml theme={null} +--- +title: "Clear, descriptive title" +description: "Concise summary for SEO and navigation." +--- +``` + +Optional frontmatter fields: + +* `sidebarTitle`: Short title for sidebar navigation. +* `icon`: Lucide or Font Awesome icon name, URL, or file path. +* `tag`: Label next to the page title in the sidebar (for example, "NEW"). +* `mode`: Page layout mode (`default`, `wide`, `custom`). +* `keywords`: Array of terms related to the page content for local search and SEO. +* Any custom YAML fields for use with personalization or conditional content. + +## File conventions + +* Match existing naming patterns in the directory +* If there are no existing files or inconsistent file naming patterns, use kebab-case: `getting-started.mdx`, `api-reference.mdx` +* Use root-relative paths without file extensions for internal links: `/getting-started/quickstart` +* Do not use relative paths (`../`) or absolute URLs for internal pages +* When you create a new page, add it to `docs.json` navigation or it won't appear in the sidebar + +## Organize content + +When a user asks about anything related to site-wide configurations, start by understanding the [global settings](https://www.mintlify.com/docs/organize/settings). See if a setting in the `docs.json` file can be updated to achieve what the user wants. + +### Navigation + +The `navigation` property in `docs.json` controls site structure. Choose one primary pattern at the root level, then nest others within it. + +**Choose your primary pattern:** + +| Pattern | When to use | +| ------------- | ---------------------------------------------------------------------------------------------- | +| **Groups** | Default. Single audience, straightforward hierarchy | +| **Tabs** | Distinct sections with different audiences (Guides vs API Reference) or content types | +| **Anchors** | Want persistent section links at sidebar top. Good for separating docs from external resources | +| **Dropdowns** | Multiple doc sections users switch between, but not distinct enough for tabs | +| **Products** | Multi-product company with separate documentation per product | +| **Versions** | Maintaining docs for multiple API/product versions simultaneously | +| **Languages** | Localized content | + +**Within your primary pattern:** + +* **Groups** - Organize related pages. Can nest groups within groups, but keep hierarchy shallow +* **Menus** - Add dropdown navigation within tabs for quick jumps to specific pages +* **`expanded: false`** - Collapse nested groups by default. Use for reference sections users browse selectively +* **`openapi`** - Auto-generate pages from OpenAPI spec. Add at group/tab level to inherit + +**Common combinations:** + +* Tabs containing groups (most common for docs with API reference) +* Products containing tabs (multi-product SaaS) +* Versions containing tabs (versioned API docs) +* Anchors containing groups (simple docs with external resource links) + +### Links and paths + +* **Internal links:** Root-relative, no extension: `/getting-started/quickstart` +* **Images:** Store in `/images`, reference as `/images/example.png` +* **External links:** Use full URLs, they open in new tabs automatically + +## Customize docs sites + +**What to customize where:** + +* **Brand colors, fonts, logo** → `docs.json`. See [global settings](https://www.mintlify.com/docs/organize/settings) +* **Component styling, layout tweaks** → `custom.css` at project root +* **Dark mode** → Enabled by default. Only disable with `"appearance": "light"` in `docs.json` if brand requires it + +Start with `docs.json`. Only add `custom.css` when you need styling that config doesn't support. + +## Write content + +### Components + +The [components overview](https://mintlify.com/docs/components) organizes all components by purpose: structure content, draw attention, show/hide content, document APIs, link to pages, and add visual context. Start there to find the right component. + +**Common decision points:** + +| Need | Use | +| -------------------------- | ----------------------- | +| Hide optional details | `` | +| Long code examples | `` | +| User chooses one option | `` | +| Linked navigation cards | `` in `` | +| Sequential instructions | `` | +| Code in multiple languages | `` | +| API parameters | `` | +| API response fields | `` | + +**Callouts by severity:** + +* `` - Supplementary info, safe to skip +* `` - Helpful context such as permissions +* `` - Recommendations or best practices +* `` - Potentially destructive actions +* `` - Success confirmation + +### Reusable content + +**When to use snippets:** + +* Exact content appears on more than one page +* Complex components you want to maintain in one place +* Shared content across teams/repos + +**When NOT to use snippets:** + +* Slight variations needed per page (leads to complex props) + +Import snippets with `import { Component } from "/path/to/snippet-name.jsx"`. + +## Writing standards + +### Voice and structure + +* Second-person voice ("you") +* Active voice, direct language +* Sentence case for headings ("Getting started", not "Getting Started") +* Sentence case for code block titles ("Expandable example", not "Expandable Example") +* Lead with context: explain what something is before how to use it +* Prerequisites at the start of procedural content + +### What to avoid + +**Never use:** + +* Marketing language ("powerful", "seamless", "robust", "cutting-edge") +* Filler phrases ("it's important to note", "in order to") +* Excessive conjunctions ("moreover", "furthermore", "additionally") +* Editorializing ("obviously", "simply", "just", "easily") + +**Watch for AI-typical patterns:** + +* Overly formal or stilted phrasing +* Unnecessary repetition of concepts +* Generic introductions that don't add value +* Concluding summaries that restate what was just said + +### Formatting + +* All code blocks must have language tags +* All images and media must have descriptive alt text +* Use bold and italics only when they serve the reader's understanding--never use text styling just for decoration +* No decorative formatting or emoji + +### Code examples + +* Keep examples simple and practical +* Use realistic values (not "foo" or "bar") +* One clear example is better than multiple variations +* Test that code works before including it + +## Deploy + +Mintlify deploys automatically when changes are pushed to the connected Git repository. + +**What agents can configure:** + +* **Redirects** → Add to `docs.json` with `"redirects": [{"source": "/old", "destination": "/new"}]` +* **SEO indexing** → Control with `"seo": {"indexing": "all"}` to include hidden pages in search + +**Requires dashboard setup (human task):** + +* Custom domains and subdomains +* Preview deployment settings +* DNS configuration + +For `/docs` subpath hosting with Vercel or Cloudflare, agents can help configure rewrite rules. See [/docs subpath](https://mintlify.com/docs/deploy/vercel). + +## Workflow + +### 1. Understand the task + +Identify what needs to be documented, which pages are affected, and what the reader should accomplish afterward. If any of these are unclear, ask. + +### 2. Research + +* Read `docs.json` to understand the site structure +* Search existing docs for related content +* Read similar pages to match the site's style + +### 3. Plan + +* Synthesize what the reader should accomplish after reading the docs and the current content +* Propose any updates or new content +* Verify that your proposed changes will help readers be successful + +### 4. Write + +* Start with the most important information +* Keep sections focused and scannable +* Use components appropriately (don't overuse them) +* Mark anything uncertain with a TODO comment: + +```mdx theme={null} +{/* TODO: Verify the default timeout value */} +``` + +### 5. Update navigation + +If you created a new page, add it to the appropriate group in `docs.json`. + +### 6. Verify + +Before submitting: + +* [ ] Frontmatter includes title and description +* [ ] All code blocks have language tags +* [ ] Internal links use root-relative paths without file extensions +* [ ] New pages are added to `docs.json` navigation +* [ ] Content matches the style of surrounding pages +* [ ] No marketing language or filler phrases +* [ ] TODOs are clearly marked for anything uncertain +* [ ] Run `mint broken-links` to check links +* [ ] Run `mint validate` to find any errors + +## Edge cases + +### Migrations + +If a user asks about migrating to Mintlify, ask if they are using ReadMe or Docusaurus. If they are, use the [@mintlify/scraping](https://www.npmjs.com/package/@mintlify/scraping) CLI to migrate content. If they are using a different platform to host their documentation, help them manually convert their content to MDX pages using Mintlify components. + +### Hidden pages + +Any page that is not included in the `docs.json` navigation is hidden. Use hidden pages for content that should be accessible by URL or indexed for the assistant or search, but not discoverable through the sidebar navigation. + +### Exclude pages + +The `.mintignore` file is used to exclude files from a documentation repository from being processed. + +## Common gotchas + +1. **Component imports** - JSX components need explicit import, MDX components don't +2. **Frontmatter required** - Every MDX file needs `title` at minimum +3. **Code block language** - Always specify language identifier +4. **Never use `mint.json`** - `mint.json` is deprecated. Only ever use `docs.json` + +## Resources + +* [Documentation](https://mintlify.com/docs) +* [https://github.com/sgl-project/sglang](https://github.com/sgl-project/sglang) +* [Configuration schema](https://mintlify.com/docs.json) +* [Feature requests](https://github.com/orgs/mintlify/discussions/categories/feature-requests) +* [Bugs and feedback](https://github.com/orgs/mintlify/discussions/categories/bugs-feedback) diff --git a/docs_new/CONTRIBUTING.md b/docs_new/CONTRIBUTING.md new file mode 100644 index 000000000..fc42a9b2d --- /dev/null +++ b/docs_new/CONTRIBUTING.md @@ -0,0 +1,34 @@ +> **Customize this file**: Tailor this template to your project by noting specific contribution types you're looking for, adding a Code of Conduct, or adjusting the writing guidelines to match your style. + +# Contribute to the documentation + +Thank you for your interest in contributing to our documentation! This guide will help you get started. + +## How to contribute + +### Option 1: Edit directly on GitHub + +1. Navigate to the page you want to edit +2. Click the "Edit this file" button (the pencil icon) +3. Make your changes and submit a pull request + +### Option 2: Local development + +1. Fork and clone this repository +2. Install the Mintlify CLI: `npm i -g mint` +3. Create a branch for your changes +4. Make changes +5. Run `mint dev` +6. Preview your changes at `http://localhost:3000` +7. Commit your changes and submit a pull request + +For more details on local development, see our [development guide](development.mdx). + +## Writing guidelines + +- **Use active voice**: "Run the command" not "The command should be run" +- **Address the reader directly**: Use "you" instead of "the user" +- **Keep sentences concise**: Aim for one idea per sentence +- **Lead with the goal**: Start instructions with what the user wants to accomplish +- **Use consistent terminology**: Don't alternate between synonyms for the same concept +- **Include examples**: Show, don't just tell diff --git a/docs_new/LICENSE b/docs_new/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/docs_new/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/docs_new/README.md b/docs_new/README.md new file mode 100644 index 000000000..a71cdaea0 --- /dev/null +++ b/docs_new/README.md @@ -0,0 +1,126 @@ +# SGLang Documentation + +The official documentation and cookbook for [SGLang](https://github.com/sgl-project/sglang) — a high-performance serving framework for large language models and vision-language models. + +- **Docs**: Getting started guides, installation, and reference +- **Cookbook**: Battle-tested recipes for deploying specific models (Qwen, DeepSeek, Llama, GLM, etc.) on various hardware + + +## Project structure + +``` +. +├── docs.json # Site configuration (navigation, theme, metadata) +├── index.mdx # Homepage +├── docs/ # Documentation pages +│ └── get-started/ +│ └── install.mdx # Installation guide +└── cookbook/ # Model deployment recipes + ├── intro.mdx # Cookbook overview and recipe index + └── autoregressive/ # Autoregressive model recipes + └── Qwen/ + └── Qwen3.5.mdx +``` + +Pages are `.mdx` files with YAML frontmatter. Navigation is defined in `docs.json`. + +## Local development + +### Prerequisites + +- Node.js >= 20 + +### Setup + +```bash +# Install the CLI +npm i -g mint + +# Start the dev server (with hot reload) +mint dev +``` + +Preview at `http://localhost:3000`. + +### Useful commands + +```bash +mint dev # Start local preview server +mint broken-links # Check for broken links +mint update # Update the CLI +``` + +## Contributing + +We welcome contributions! Whether you want to add a recipe for a new model, improve existing docs, or fix a typo — PRs are appreciated. + +### Quick edit (GitHub) + +1. Navigate to the file you want to edit on GitHub +2. Click the pencil icon to edit +3. Submit a pull request + +### Local development workflow + +```bash +# 1. Fork and clone the repo +git clone https://github.com//sgl-docs.git +cd sgl-docs + +# 2. Create a branch +git checkout -b my-changes + +# 3. Start the dev server and make your changes +mint dev + +# 4. Verify links aren't broken +mint broken-links + +# 5. Commit and push +git add +git commit -m "docs: describe your change" +git push origin my-changes + +# 6. Open a pull request on GitHub +``` + +### Adding a new cookbook recipe + +1. Create a new `.mdx` file under `cookbook/` following the existing directory structure (e.g., `cookbook/llm//.mdx` or `cookbook/vlm//.mdx`) +2. Use an existing recipe like `cookbook/llm/Qwen/Qwen3.5.mdx` as a template +3. Add your page to the navigation in `docs.json` +4. Each recipe should include: + - Model introduction and key specs + - Installation / environment setup + - Deployment configuration (with hardware recommendations) + - Usage examples (basic + advanced) + - Benchmarks (if available) + +### Writing guidelines + +- Use active voice: "Run the command" not "The command should be run" +- Address the reader as "you" +- Keep sentences concise — one idea per sentence +- Lead with the goal, then the steps +- Use consistent terminology +- Include concrete examples and code snippets + +## Acknowledgements + +Thank you to all the authors who contributed to the original documentation in [`sglang/docs/`](https://github.com/sgl-project/sglang/tree/main/docs) and the original cookbook in [`sgl-cookbook`](https://github.com/sgl-project/sgl-cookbook). The migration to the new Mintlify-based documentation was led by the following [ACM_VIT](https://github.com/ACM-VIT) students: + +[@Adhyan Jain](https://github.com/Adhyan-Jain), [@Maitri-shah29](https://github.com/Maitri-shah29), [@architnigam](https://github.com/architnigam), [@Nakul-Sinha](https://github.com/Nakul-Sinha), [@divyamagrawal06](https://github.com/divyamagrawal06), [@A-Taman](https://github.com/A-Taman), [@nimeshas](https://github.com/nimeshas), [@IshhanKheria](https://github.com/IshhanKheria), [@Krishang-Zinzuwadia](https://github.com/Krishang-Zinzuwadia), [@pokymono](https://github.com/pokymono), [@Ishitajoshii](https://github.com/Ishitajoshii), [@AdityaVKochar](https://github.com/AdityaVKochar) + +Advised by [@adarshxs](https://github.com/adarshxs) (ACM_VIT) and [@wisclmy0611](https://github.com/wisclmy0611), [@Richardczl98](https://github.com/Richardczl98) (LMSYS). + +## Community + +- [GitHub](https://github.com/sgl-project/sglang) +- [Slack](https://slack.sglang.io/) +- [Discord](https://discord.gg/4ugb2t6YY2) +- [X / Twitter](https://x.com/lmsysorg) +- [LinkedIn](https://www.linkedin.com/company/sgl-project/) + +## License + +Apache License 2.0 — see the [LICENSE](LICENSE) for details. diff --git a/docs_new/cards/Autoregressive-benchmark-card.png b/docs_new/cards/Autoregressive-benchmark-card.png new file mode 100644 index 000000000..fee0558b5 Binary files /dev/null and b/docs_new/cards/Autoregressive-benchmark-card.png differ diff --git a/docs_new/cards/Autoregressive-card.png b/docs_new/cards/Autoregressive-card.png new file mode 100644 index 000000000..da4c367c3 Binary files /dev/null and b/docs_new/cards/Autoregressive-card.png differ diff --git a/docs_new/cards/Classification-card.png b/docs_new/cards/Classification-card.png new file mode 100644 index 000000000..a26b9180a Binary files /dev/null and b/docs_new/cards/Classification-card.png differ diff --git a/docs_new/cards/Diffusion-benchmark-card.png b/docs_new/cards/Diffusion-benchmark-card.png new file mode 100644 index 000000000..7799bbd2a Binary files /dev/null and b/docs_new/cards/Diffusion-benchmark-card.png differ diff --git a/docs_new/cards/Diffusion-card.png b/docs_new/cards/Diffusion-card.png new file mode 100644 index 000000000..708171b43 Binary files /dev/null and b/docs_new/cards/Diffusion-card.png differ diff --git a/docs_new/cards/Embedding-card.png b/docs_new/cards/Embedding-card.png new file mode 100644 index 000000000..7a53d213f Binary files /dev/null and b/docs_new/cards/Embedding-card.png differ diff --git a/docs_new/cards/LLM-card.png b/docs_new/cards/LLM-card.png new file mode 100644 index 000000000..36fa41267 Binary files /dev/null and b/docs_new/cards/LLM-card.png differ diff --git a/docs_new/cards/Omni-card.png b/docs_new/cards/Omni-card.png new file mode 100644 index 000000000..203158c85 Binary files /dev/null and b/docs_new/cards/Omni-card.png differ diff --git a/docs_new/cards/Rerank-card.png b/docs_new/cards/Rerank-card.png new file mode 100644 index 000000000..2000b30d5 Binary files /dev/null and b/docs_new/cards/Rerank-card.png differ diff --git a/docs_new/cards/Reward-card.png b/docs_new/cards/Reward-card.png new file mode 100644 index 000000000..11fbe240e Binary files /dev/null and b/docs_new/cards/Reward-card.png differ diff --git a/docs_new/cards/VLM-card.png b/docs_new/cards/VLM-card.png new file mode 100644 index 000000000..d0e8c059d Binary files /dev/null and b/docs_new/cards/VLM-card.png differ diff --git a/docs_new/cards/dLLM-card.png b/docs_new/cards/dLLM-card.png new file mode 100644 index 000000000..1bd217f09 Binary files /dev/null and b/docs_new/cards/dLLM-card.png differ diff --git a/docs_new/cards/logos/deepseek.png b/docs_new/cards/logos/deepseek.png new file mode 100644 index 000000000..b553b5627 Binary files /dev/null and b/docs_new/cards/logos/deepseek.png differ diff --git a/docs_new/cards/logos/ernie.png b/docs_new/cards/logos/ernie.png new file mode 100644 index 000000000..ac1a0bd55 Binary files /dev/null and b/docs_new/cards/logos/ernie.png differ diff --git a/docs_new/cards/logos/fishaudio.png b/docs_new/cards/logos/fishaudio.png new file mode 100644 index 000000000..a3c951c95 Binary files /dev/null and b/docs_new/cards/logos/fishaudio.png differ diff --git a/docs_new/cards/logos/flashlabs.png b/docs_new/cards/logos/flashlabs.png new file mode 100644 index 000000000..0c1581988 Binary files /dev/null and b/docs_new/cards/logos/flashlabs.png differ diff --git a/docs_new/cards/logos/flux.png b/docs_new/cards/logos/flux.png new file mode 100644 index 000000000..df4fde4b8 Binary files /dev/null and b/docs_new/cards/logos/flux.png differ diff --git a/docs_new/cards/logos/glm.png b/docs_new/cards/logos/glm.png new file mode 100644 index 000000000..6d0f33657 Binary files /dev/null and b/docs_new/cards/logos/glm.png differ diff --git a/docs_new/cards/logos/google.png b/docs_new/cards/logos/google.png new file mode 100644 index 000000000..8675ae2c4 Binary files /dev/null and b/docs_new/cards/logos/google.png differ diff --git a/docs_new/cards/logos/inclusionai.png b/docs_new/cards/logos/inclusionai.png new file mode 100644 index 000000000..0128c8371 Binary files /dev/null and b/docs_new/cards/logos/inclusionai.png differ diff --git a/docs_new/cards/logos/internlm.png b/docs_new/cards/logos/internlm.png new file mode 100644 index 000000000..655f7d467 Binary files /dev/null and b/docs_new/cards/logos/internlm.png differ diff --git a/docs_new/cards/logos/internvl.png b/docs_new/cards/logos/internvl.png new file mode 100644 index 000000000..e6f972289 Binary files /dev/null and b/docs_new/cards/logos/internvl.png differ diff --git a/docs_new/cards/logos/jina.png b/docs_new/cards/logos/jina.png new file mode 100644 index 000000000..2a660ab68 Binary files /dev/null and b/docs_new/cards/logos/jina.png differ diff --git a/docs_new/cards/logos/llama.png b/docs_new/cards/logos/llama.png new file mode 100644 index 000000000..e101baba7 Binary files /dev/null and b/docs_new/cards/logos/llama.png differ diff --git a/docs_new/cards/logos/minimax.png b/docs_new/cards/logos/minimax.png new file mode 100644 index 000000000..dbb8f23ad Binary files /dev/null and b/docs_new/cards/logos/minimax.png differ diff --git a/docs_new/cards/logos/mistral.png b/docs_new/cards/logos/mistral.png new file mode 100644 index 000000000..337646d72 Binary files /dev/null and b/docs_new/cards/logos/mistral.png differ diff --git a/docs_new/cards/logos/moonshotai.png b/docs_new/cards/logos/moonshotai.png new file mode 100644 index 000000000..0789af8d6 Binary files /dev/null and b/docs_new/cards/logos/moonshotai.png differ diff --git a/docs_new/cards/logos/mova.png b/docs_new/cards/logos/mova.png new file mode 100644 index 000000000..4de81e642 Binary files /dev/null and b/docs_new/cards/logos/mova.png differ diff --git a/docs_new/cards/logos/nvidia.png b/docs_new/cards/logos/nvidia.png new file mode 100644 index 000000000..fa35ada3c Binary files /dev/null and b/docs_new/cards/logos/nvidia.png differ diff --git a/docs_new/cards/logos/openai.png b/docs_new/cards/logos/openai.png new file mode 100644 index 000000000..89c332dd2 Binary files /dev/null and b/docs_new/cards/logos/openai.png differ diff --git a/docs_new/cards/logos/qwen.png b/docs_new/cards/logos/qwen.png new file mode 100644 index 000000000..2958e815e Binary files /dev/null and b/docs_new/cards/logos/qwen.png differ diff --git a/docs_new/cards/logos/stepfun.png b/docs_new/cards/logos/stepfun.png new file mode 100644 index 000000000..18403cd18 Binary files /dev/null and b/docs_new/cards/logos/stepfun.png differ diff --git a/docs_new/cards/logos/wan.png b/docs_new/cards/logos/wan.png new file mode 100644 index 000000000..2958e815e Binary files /dev/null and b/docs_new/cards/logos/wan.png differ diff --git a/docs_new/cards/logos/xiaomi.png b/docs_new/cards/logos/xiaomi.png new file mode 100644 index 000000000..22623d5e8 Binary files /dev/null and b/docs_new/cards/logos/xiaomi.png differ diff --git a/docs_new/cards/logos/zimage.png b/docs_new/cards/logos/zimage.png new file mode 100644 index 000000000..2958e815e Binary files /dev/null and b/docs_new/cards/logos/zimage.png differ diff --git a/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-Math-V2.mdx b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-Math-V2.mdx new file mode 100644 index 000000000..04b92b4de --- /dev/null +++ b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-Math-V2.mdx @@ -0,0 +1,522 @@ +--- +title: DeepSeek-Math-V2 +metatags: + description: "Deploy DeepSeek-Math-V2 with SGLang - advanced mathematical reasoning model with gold-level IMO/CMO performance and theorem-proving capabilities." +--- + +import { DeepSeekMathV2Deployment } from '/src/snippets/autoregressive/deepseek-math-v2-deployment.jsx'; + +## 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/installation) 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. + + + +### 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 `--dp` 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 +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 +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 +=============== 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 +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 +=============== 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 +python3 benchmark/gsm8k/bench_sglang.py --num-questions 200 --port 30000 +``` + +**Test Results:** + +```text Output +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 +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 +============ 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 +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 +============ 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 +================================================== +``` diff --git a/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-OCR-2.mdx b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-OCR-2.mdx new file mode 100644 index 000000000..53207e200 --- /dev/null +++ b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-OCR-2.mdx @@ -0,0 +1,250 @@ +--- +title: DeepSeek-OCR-2 +metatags: + description: "Deploy DeepSeek-OCR-2 with SGLang - high-accuracy text extraction from images and documents for OCR tasks." +--- + +import { DeepSeekOCR2Deployment } from '/src/snippets/autoregressive/deepseek-ocr-v2-deployment.jsx'; + +## 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/installation) 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. SGLang supports serving DeepSeek-OCR-2 on NVIDIA H200 and B200, and AMD MI300X, MI355X, and MI325X GPUs. + + + +**Note**: DeepSeek-OCR-2 has ~3.58B 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 + +For more detailed configuration tips, please refer to [DeepSeek V3/V3.1/R1 Usage](../../../docs/basic_usage/deepseek_v3). + +## 4. Model Invocation + +### 4.1 Basic Usage + +**OpenAI-compatible request example** + +```python Example +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 + +<|grounding|>Convert the document to markdown. +``` + +**Free-form OCR** — extracts without layouts: + +```text Example + +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 +sglang serve \ + --model-path deepseek-ai/DeepSeek-OCR-2 \ + --enable-multimodal \ + --host 0.0.0.0 \ + --port 30000 +``` + +- Benchmark Command: + +```shell Command +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 +============ 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 +sglang serve \ + --model-path deepseek-ai/DeepSeek-OCR-2 \ + --enable-multimodal \ + --tp 1 \ + --ep 1 \ + --dp 1 \ + --enable-dp-attention \ + --host 0.0.0.0 \ + --port 30000 +``` + +- Benchmark Command: + +```shell Command +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 +============ 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 +================================================== +``` diff --git a/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-OCR.mdx b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-OCR.mdx new file mode 100644 index 000000000..0964f86ba --- /dev/null +++ b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-OCR.mdx @@ -0,0 +1,204 @@ +--- +title: DeepSeek-OCR +metatags: + description: "Deploy DeepSeek-OCR with SGLang - high-accuracy text extraction from images and documents for OCR tasks." +--- + +## 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/installation) 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. + +import { DeepSeekOCRDeployment } from "/src/snippets/autoregressive/deepseek-ocr-deployment.jsx"; + + + +### 3.2 Configuration Tips + +For more detailed configuration tips, please refer to [DeepSeek V3/V3.1/R1 Usage](../../../docs/basic_usage/deepseek_v3). + +## 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) + + +## 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 +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-OCR \ + --tp 1 \ + --dtype float16 \ + --host 0.0.0.0 \ + --port 8000 +``` + +- Benchmark Command: + +```shell Command +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 +============ 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 +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-OCR \ + --tp 1 \ + --ep 1 \ + --dp 1 \ + --enable-dp-attention \ + --dtype float16 \ + --host 0.0.0.0 \ + --port 8000 +``` + +- Benchmark Command: + +```shell Command +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 +============ 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 +================================================== +``` diff --git a/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-R1.mdx b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-R1.mdx new file mode 100644 index 000000000..6ced51128 --- /dev/null +++ b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-R1.mdx @@ -0,0 +1,910 @@ +--- +title: DeepSeek-R1 +metatags: + description: "Deploy DeepSeek-R1 reasoning model with SGLang - advanced step-by-step reasoning with FP8/FP4 quantization for NVIDIA and AMD GPUs." +--- + +import { DeepSeekR1BasicDeployment } from '/src/snippets/autoregressive/deepseek-r1-basic-deployment.jsx'; +import { DeepSeekR1AdvancedDeployment } from '/src/snippets/autoregressive/deepseek-r1-advanced-deployment.jsx'; + +## 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, and AMD MI300X, MI325X and MI355X GPUs +- **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 + +**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/installation) 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. + + + +### 3.2 Optimal Configurations + +Pareto-optimal configurations for B200, H200, MI300X, MI325X, and MI355X hardware. + + + +### 3.3 Configuration Tips + +For more detailed configuration tips and advanced tuning, please refer to [DeepSeek V3/V3.1/R1 Usage](../../../docs/basic_usage/deepseek_v3). + +## 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 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-R1-0528 \ + --reasoning-parser deepseek-r1 \ + --tp 8 +``` + +**Streaming with Thinking Process:** + +```python Example +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 +=============== 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 +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 +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 +=============== 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 +# 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." +``` + +## 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: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ScenarioInput LengthOutput LengthUse Case
**Chat**1K1KMost common conversational AI workload
**Reasoning**1K8KLong-form generation, complex reasoning tasks
**Summarization**8K1KDocument 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 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-R1-0528 \ + --tp 8 +``` + +- Low Concurrency (Latency-Optimized) + +```bash Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 benchmark/gsm8k/bench_sglang.py \ + --num-shots 8 \ + --num-questions 1316 \ + --parallel 1316 +``` + +**Test Results:** + +```text Output +Accuracy: 0.959 +Invalid: 0.000 +Latency: 29.185 s +Output throughput: 4854.672 token/s +``` diff --git a/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3.mdx b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3.mdx new file mode 100644 index 000000000..56e8b3260 --- /dev/null +++ b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3.mdx @@ -0,0 +1,520 @@ +--- +title: "DeepSeek-V3" +metatags: + description: "Deploy DeepSeek-V3 MoE model with SGLang - efficient architecture with strong reasoning, coding, and tool-augmented capabilities." +--- + + +## 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/installation) 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. + +import { DeepSeekV3Deployment } from "/src/snippets/autoregressive/deepseek-v3-deployment.jsx"; + + + +### 3.2 Configuration Tips +For more detailed configuration tips, please refer to [DeepSeek-V3 Usage](../../../docs/basic_usage/deepseek_v3). + +## 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 +python -m sglang.launch_server \ + --model deepseek-ai/DeepSeek-V3 \ + --reasoning-parser deepseek-v3 \ + --tp 8 +``` + +**Streaming with Thinking Process:** + +```python Example +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", + 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 +=============== 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 +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 8000 +``` + + +**Python Example (with Thinking Process):** + +```python Example +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", + 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 +=============== Thinking ================= +<|tool▁calls▁begin|><|tool▁call▁begin|>function<|tool▁sep|>get_weather +```json +{"location": "Beijing", "unit": "celsius"} +```<|tool▁call▁end|><|tool▁calls▁end|> +``` + +**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 +# 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." +``` + +## 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 +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3 \ + --tp 8 \ + --dp 8 \ + --enable-dp-attention \ + --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 +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 +============ 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 +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3 \ + --tp 8 \ + --ep 8 \ + --dp 8 \ + --enable-dp-attention \ + --host 0.0.0.0 \ + --port 8000 +``` + +- Benchmark Command: + +```shell Command +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 +============ 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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 --port 8000 +``` + +- **Test Results**: + - DeepSeek-V3 + ```text Output + 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 +cd sglang +bash benchmark/mmlu/download_data.sh +python3 benchmark/mmlu/bench_sglang.py --nsub 10 --port 8000 +``` + +- **Test Results**: + - DeepSeek-V3 + ```text Output + 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 + ``` diff --git a/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3_1.mdx b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3_1.mdx new file mode 100644 index 000000000..945e0e815 --- /dev/null +++ b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3_1.mdx @@ -0,0 +1,941 @@ +--- +title: DeepSeek-V3.1 +metatags: + description: "Deploy DeepSeek-V3.1 MoE model with SGLang - hybrid reasoning, improved tool calling, and agentic behavior for complex multi-step tasks." +--- + +## 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/installation) 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. + +import { DeepSeekV31Deployment } from "/src/snippets/autoregressive/deepseek-v31-deployment.jsx"; + + + +### 3.2 Configuration Tips +For more detailed configuration tips, please refer to [DeepSeek V3/V3.1/R1 Usage](../../../docs/basic_usage/deepseek_v3). + +## 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 +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 +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 +=============== 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: + +**Note:** DeepSeek-V3.1-Speciale does **NOT** support tool calling. It is designed exclusively for deep reasoning tasks. + +**Deployment Command:** + +```shell Command +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 +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 +=============== 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 +# 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." +``` + +## 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: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ScenarioInput LengthOutput LengthUse Case
**Chat**1K1KMost common conversational AI workload
**Reasoning**1K8KLong-form generation, complex reasoning tasks
**Summarization**8K1KDocument 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 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.1 \ + --tp 8 +``` + +- Low Concurrency (Latency-Optimized) + +```bash Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 benchmark/gsm8k/bench_sglang.py \ + --num-shots 8 \ + --num-questions 1316 \ + --parallel 1316 +``` + +**Test Results:** + +```text Output +Accuracy: 0.959 +Invalid: 0.000 +Latency: 29.185 s +Output throughput: 4854.672 token/s +``` diff --git a/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3_2.mdx b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3_2.mdx new file mode 100644 index 000000000..594f6f214 --- /dev/null +++ b/docs_new/cookbook/autoregressive/DeepSeek/DeepSeek-V3_2.mdx @@ -0,0 +1,827 @@ +--- +title: DeepSeek-V3.2 +metatags: + description: "Deploy DeepSeek-V3.2 with SGLang - featuring DeepSeek Sparse Attention for efficient long-context processing and deep reasoning capabilities." +--- + +## 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/installation) 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. SGLang supports serving DeepSeek V3.2 on NVIDIA H200, B200, and AMD MI300X/MI355X GPUs. + +import { DeepSeekV32Deployment } from "/src/snippets/autoregressive/deepseek-v32-deployment.jsx"; + + + +### 3.2 Configuration Tips +For more detailed configuration tips, please refer to [DeepSeek-V3.2 Usage](../../../docs/basic_usage/deepseek_v32). + +## 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 +sglang serve \ + --model 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 +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 +=============== 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. It is designed exclusively for deep reasoning tasks. + +**Deployment Command:** + +For DeepSeek-V3.2-Exp: + +```shell Command +sglang serve \ + --model 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 +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 +=============== 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 +# 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 Enabling PP, CP and TP with FP8 KV cache + +We suggested `DP2` + `MTP` for local deployment of agentic workflow with DeepSeek V3.2 on Hopper platform: + +```shell Command +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 \ + --dp 2 --enable-dp-attention --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 + DP** + +`CP` is currently enabled with `PP=2` on Hopper platform and we can reduce TP=16 to TP=8 from standalone deployment: + +```shell Command +# 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 --dp 1 --enable-dp-attention \ + --moe-a2a-backend deepep --ep-size 16 \ + --page-size 128 \ + --chunked-prefill-size 16384 \ + --attention-backend nsa \ + --nsa-prefill-backend flashmla_sparse \ + --nsa-decode-backend flashmla_sparse \ + --enable-nsa-prefill-context-parallel \ + --nsa-prefill-cp-mode round-robin-split \ + --cuda-graph-max-bs 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-nsa-pp-cp-ep-dp +) + +sglang_args=($sglang_args) + +sglang "${sglang_args[@]}" 2>&1 | tee $LOG_DIR/$RANK.log +``` + +**fp8 KV + CP + PP** + +With FP8 KV, we can have less memory footprint. This can be combined with various parallel schemes: + +```shell Command +# verified in Hopper platform +dp=1 + +dp_config=" \ + --dp 1 --enable-dp-attention \ +" + +cp_config=" \ + --enable-nsa-prefill-context-parallel \ +" + +if [ "$dp" -eq 1 ]; then + +cp_config=" \ + $cp_config \ + --nsa-prefill-cp-mode round-robin-split \ +" + +else +cp_config=" \ + $cp_config \ + --nsa-prefill-cp-mode in-seq-split \ +" +fi + +# 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 \ + $dp_config \ + --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 +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 +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 +============ 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 +sglang serve \ + --model-path deepseek-ai/DeepSeek-V3.2-Exp \ + --tp 8 \ + --ep 8 \ + --dp 8 \ + --enable-dp-attention \ + --host 0.0.0.0 \ + --port 30000 +``` + +- Benchmark Command: + +```shell Command +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 +============ 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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 --port 30000 +``` + +- **Test Results**: + - DeepSeek-V3.2-Exp + ``` + Accuracy: 0.980 + Invalid: 0.000 + Latency: 19.128 s + Output throughput: 965.919 token/s + ``` + +#### 5.2.2 MMLU Benchmark + +- **Benchmark Command:** + +```shell Command +cd sglang +bash benchmark/mmlu/download_data.sh +python3 benchmark/mmlu/bench_sglang.py --nsub 10 --port 30000 +``` + +- **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.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 +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 \ + --dp 2 --enable-dp-attention --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 +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 +============ 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 +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 +============ 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 +============ 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 +================================================== +``` diff --git a/docs_new/cookbook/autoregressive/Ernie/Ernie4.5-VL.mdx b/docs_new/cookbook/autoregressive/Ernie/Ernie4.5-VL.mdx new file mode 100644 index 000000000..fbd280360 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Ernie/Ernie4.5-VL.mdx @@ -0,0 +1,28 @@ +--- +title: Ernie4.5-VL +metatags: + description: "Deploy Ernie4.5-VL vision-language model with SGLang - community contribution guide for Baidu's multimodal model." +--- + +## 📝 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 +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!** 🌟 diff --git a/docs_new/cookbook/autoregressive/Ernie/Ernie4.5.mdx b/docs_new/cookbook/autoregressive/Ernie/Ernie4.5.mdx new file mode 100644 index 000000000..83a38c1e6 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Ernie/Ernie4.5.mdx @@ -0,0 +1,696 @@ +--- +title: Ernie4.5 +metatags: + description: "Deploy Ernie4.5 with SGLang - community contribution guide for Baidu's Ernie 4.5 model deployment." +--- + +import { Ernie45Deployment } from '/src/snippets/autoregressive/ernie-45-deployment.jsx'; + +## 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, and MI355X GPUs. + +## 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/installation) 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. + + + +## 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 +python -m sglang.launch_server \ + --model baidu/ERNIE-4.5-21B-A3B-PT \ + --tp 1 +``` + +**Basic Python Client Example:** + +```python Example +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 +**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 +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 +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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 benchmark/gsm8k/bench_sglang.py \ + --num-shots 8 \ + --num-questions 1316 \ + --parallel 1316 +``` + +- Test Results: + - ERNIE-4.5-21B-A3B-PT + ``` + Accuracy: 0.865 + Invalid: 0.000 + Latency: 21.669 s + Output throughput: 10359.790 token/s + ``` diff --git a/docs_new/cookbook/autoregressive/FlashLabs/Chroma1.0.mdx b/docs_new/cookbook/autoregressive/FlashLabs/Chroma1.0.mdx new file mode 100644 index 000000000..3632bc805 --- /dev/null +++ b/docs_new/cookbook/autoregressive/FlashLabs/Chroma1.0.mdx @@ -0,0 +1,193 @@ +--- +title: Chroma-1.0 +metatags: + description: "Deploy Chroma-1.0 end-to-end speech conversation model with SGLang - real-time speech generation, voice cloning, and speech reasoning." +tag: NEW +--- + +## 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 +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 +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 +# 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 +git clone https://github.com/FlashLabs-AI-Corp/Chroma-SGLang.git + +cd Chroma-SGLang +``` + +### Step 4: Run the Server + +```bash Command +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 +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 +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 +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 +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 +``` diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-4.5.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-4.5.mdx new file mode 100644 index 000000000..cf5bd5dfb --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-4.5.mdx @@ -0,0 +1,490 @@ +--- +title: GLM-4.5 +metatags: + description: "Deploy GLM-4.5 with SGLang on AMD GPUs - advanced reasoning, function calling, BF16/FP8 quantization options." +--- + +## 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/installation) 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. + +import { GLM45Deployment } from "/src/snippets/autoregressive/glm-45-deployment.jsx"; + + + +### 3.2 Configuration Tips + +For more detailed configuration tips, please refer to [GLM-4.5/GLM-4.6 Usage](../../../docs/basic_usage/glm45). + +## 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 +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 +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 +=============== 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 + +GLM-4.5 supports tool calling capabilities. Enable the tool call parser: + +```shell Command +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 +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 +=============== 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"} +``` + +## 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: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ScenarioInput LengthOutput LengthUse Case
**Chat**1K1KMost common conversational AI workload
**Reasoning**1K8KLong-form generation, complex reasoning tasks
**Summarization**8K1KDocument 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 +python -m sglang.launch_server \ + --model zai-org/GLM-4.5 \ + --tp 8 +``` + + +- Low Concurrency (Latency-Optimized) + +```bash Command +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 +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 +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 +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 +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 +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 +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 +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 +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 +python -m sglang.test.few_shot_gsm8k \ + --num-questions 200 \ + --port 30000 +``` diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-4.5V.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-4.5V.mdx new file mode 100644 index 000000000..8951a1242 --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-4.5V.mdx @@ -0,0 +1,533 @@ +--- +title: GLM-4.5V +metatags: + description: "Deploy GLM-4.5V vision-language model with SGLang - SOTA multimodal performance, 64K context, image reasoning and video understanding." +--- + +## 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/installation) 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. + +import { GLM45VDeployment } from "/src/snippets/autoregressive/glm-45v-deployment.jsx"; + + + +### 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}'`. +- For more detailed configuration tips, please refer to [GLM-4.5V/GLM-4.6V Usage](../../../docs/basic_usage/glmv). + +## 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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +=============== 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 +# 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." +``` + +## 5. Benchmark + +### 5.1 Accuracy Benchmark + +Document model accuracy on standard benchmarks: + +#### 5.1.1 MMMU Benchmark + +- Benchmark Command + +```bash Command +python3 benchmark/mmmu/bench_sglang.py --response-answer-regex "<\|begin_of_box\|>(.*)<\|end_of_box\|>" --port 30000 --concurrency 64 +``` + +- Test Result + +```text Output +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 +``` diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-4.6.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-4.6.mdx new file mode 100644 index 000000000..cc21908ab --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-4.6.mdx @@ -0,0 +1,888 @@ +--- +title: GLM-4.6 +metatags: + description: "Deploy GLM-4.6 with SGLang - 200K context window, superior coding, advanced reasoning, and enhanced agentic capabilities." +--- + +## 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/installation) 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. + +import { GLM46Deployment } from "/src/snippets/autoregressive/glm-46-deployment.jsx"; + + + +### 3.2 Configuration Tips + +For more detailed configuration tips, please refer to [GLM-4.5/GLM-4.6 Usage](../../../docs/basic_usage/glm45). + +## 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 +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 +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 +=============== 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 + +GLM-4.6 supports tool calling capabilities. Enable the tool call parser: + +```shell Command +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 +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 +=============== 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 +# 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." +``` + +## 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: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ScenarioInput LengthOutput LengthUse Case
**Chat**1K1KMost common conversational AI workload
**Reasoning**1K8KLong-form generation, complex reasoning tasks
**Summarization**8K1KDocument 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 +python -m sglang.launch_server \ + --model zai-org/GLM-4.6 \ + --tp 8 +``` + + +- Low Concurrency (Latency-Optimized) + +```bash Command +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 +============ 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 +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 + +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python -m sglang.test.few_shot_gsm8k \ + --num-questions 200 \ + --port 30000 +``` + +- Test Result +```text Output +Accuracy: 0.975 +Invalid: 0.000 +Latency: 16.574 s +Output throughput: 1194.637 token/s +``` diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-4.6V.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-4.6V.mdx new file mode 100644 index 000000000..4766898d4 --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-4.6V.mdx @@ -0,0 +1,382 @@ +--- +title: GLM-4.6V +metatags: + description: "Deploy GLM-4.6V vision-language model with SGLang - native function calling, 128K context, multimodal document understanding and frontend replication." +--- + +## 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](#tool-call-example). +- **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 +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 +# 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 -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/installation). + +## 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. + +import { GLM46VDeployment } from "/src/snippets/autoregressive/glm-46v-deployment.jsx"; + + + +### 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}'`. +- For more detailed configuration tips, please refer to [GLM-4.5V/GLM-4.6V Usage](../../../docs/basic_usage/glmv). + +## 4. Example APIs + +### Image Input Example + +#### API Payload +```python Example +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": "/home/jobuser/sgl_logo.png" + }} + }}, + {{ + "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) +``` + +#### API Response +```text Output +{"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 Example + +#### API Payload +```python Example +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": "/home/jobuser/jobs_presenting_ipod.mp4" + }} + }}, + {{ + "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) +``` + +#### API Response +```text Output +{"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"}} +``` + +### Tool Call Example + +#### API Payload +```python Example +from openai import OpenAI +import argparse +import sys +import base64 + +def image_to_base64(image_path): + """Convert image file to base64 data URL format for OpenAI API""" + with open(image_path, 'rb') as image_file: + image_data = image_file.read() + base64_string = base64.b64encode(image_data).decode('utf-8') + return f"data:image/png;base64,{base64_string}" + +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": "/home/jobuser/sgl_logo.png" + } + } + ] + }, +] + +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 + +```text Output +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). +``` + +## 5. Benchmark + +### 5.1. Text Benchmark: Latency, Throughput and Accuracy + +#### Command +```shell Command +python3 ./benchmark/gsm8k/bench_sglang.py +``` +#### Result Output +```text Output +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 +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 +============ 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 +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 +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 +``` diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-4.7-Flash.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-4.7-Flash.mdx new file mode 100644 index 000000000..6acd54c89 --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-4.7-Flash.mdx @@ -0,0 +1,931 @@ +--- +title: GLM-4.7-Flash +metatags: + description: "Deploy GLM-4.7-Flash 30B-A3B MoE model with SGLang - lightweight, efficient inference optimized for single-GPU deployment." +--- + +## 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/installation) 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. + +import { GLM47FlashDeployment } from "/src/snippets/autoregressive/glm-47-flash-deployment.jsx"; + + + +### 3.2 Configuration Tips + +For more detailed configuration tips, please refer to [GLM-4.7 Usage](../../../docs/basic_usage/glm45). + +## 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 +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 +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 +=============== 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 + +GLM-4.7-Flash supports tool calling capabilities. Enable the tool call parser: + +```shell Command +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 +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 +=============== 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 +# 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: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ScenarioInput LengthOutput LengthUse Case
**Chat**1K1KMost common conversational AI workload
**Reasoning**1K8KLong-form generation, complex reasoning tasks
**Summarization**8K1KDocument 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 +python -m sglang.launch_server \ + --model zai-org/GLM-4.7-Flash \ + --attention-backend triton \ + --tp 1 +``` + +- Low Concurrency (Latency-Optimized) + +```bash Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python -m sglang.test.few_shot_gsm8k \ + --num-questions 200 \ + --port 30000 +``` + +- Result + +```text Output +Accuracy: 0.845 +Invalid: 0.000 +Latency: 8.431 s +Output throughput: 2195.387 token/s +``` diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-4.7.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-4.7.mdx new file mode 100644 index 000000000..172dcce64 --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-4.7.mdx @@ -0,0 +1,546 @@ +--- +title: GLM-4.7 +metatags: + description: "Deploy GLM-4.7 with SGLang on AMD GPUs - state-of-the-art reasoning, enhanced coding, and robust tool calling capabilities." +--- + +## 1. Model Introduction + +[GLM-4.7](https://huggingface.co/zai-org/GLM-4.7) is the latest and most powerful language model in the GLM series developed by Zhipu AI, featuring state-of-the-art capabilities in reasoning, function calling, and multi-modal understanding. + +As the newest iteration in the GLM series, GLM-4.7 achieves significant improvements across all 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 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.7](https://huggingface.co/zai-org/GLM-4.7) - Recommended for MI300X/MI325X/MI355X +- **FP8 (8-bit quantized)**: [zai-org/GLM-4.7-FP8](https://huggingface.co/zai-org/GLM-4.7-FP8) - Recommended for MI300X/MI325X/MI355X + +**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/installation) 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. + +import { GLM47Deployment } from "/src/snippets/autoregressive/glm-47-deployment.jsx"; + + + +### 3.2 Configuration Tips + +For more detailed configuration tips, please refer to [GLM-4.7 Usage](../../../docs/basic_usage/glm45). + +## 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 +python -m sglang.launch_server \ + --model zai-org/GLM-4.7 \ + --reasoning-parser glm47 \ + --tp 8 \ + --host 0.0.0.0 \ + --port 8000 +``` + +**Streaming with Thinking Process:** + +```python Example +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 +=============== 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 + +GLM-4.7 supports tool calling capabilities. Enable the tool call parser: + +```shell Command +python -m sglang.launch_server \ + --model zai-org/GLM-4.7 \ + --reasoning-parser glm47 \ + --tool-call-parser glm47 \ + --tp 8 \ + --host 0.0.0.0 \ + --port 8000 +``` + +**Python Example (with Thinking Process):** + +```python Example +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 +=============== 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 +# 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." +``` + +## 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.7 +- 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: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ScenarioInput LengthOutput LengthUse Case
**Chat**1K1KMost common conversational AI workload
**Reasoning**1K8KLong-form generation, complex reasoning tasks
**Summarization**8K1KDocument 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 +python -m sglang.launch_server \ + --model zai-org/GLM-4.7 \ + --tp 8 +``` + + +- Low Concurrency (Latency-Optimized) + +```bash Command +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 +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 +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 +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 +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 +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 +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 +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 +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 +``` + +#### 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 +python -m sglang.test.few_shot_gsm8k \ + --num-questions 200 \ + --port 30000 +``` diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-5.1.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-5.1.mdx new file mode 100644 index 000000000..97afecca0 --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-5.1.mdx @@ -0,0 +1,641 @@ +--- +title: GLM-5.1 +metatags: + description: "Deploy GLM-5.1 with SGLang on NVIDIA H100/H200/B200/GB300 and AMD MI300X/MI325X/MI355X." +tag: NEW +--- + +## 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) + +**License:** MIT + +## 2. SGLang Installation + +Please refer to the [official SGLang installation guide](../../../docs/get-started/installation) 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, B200, GB300, and AMD MI300X/MI325X/MI355X GPUs. + +import { GLM51Deployment } from '/src/snippets/autoregressive/glm-51-deployment.jsx' + + + +### 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. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HardwareFP8BF16
H100tp=16tp=32
H200tp=8tp=16
B200tp=8tp=16
GB300tp=4
MI300X/MI325Xtp=8tp=8
MI355Xtp=8tp=8
+ +- **AMD GPUs**: Both BF16 and FP8 checkpoints are supported on MI300X/MI325X/MI355X at tp=8. Use `--nsa-prefill-backend tilelang --nsa-decode-backend tilelang` for the NSA attention backend. Add `--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 not currently supported on AMD for GLM-5.1. +- **GB300**: Only the FP8 checkpoint is recommended on GB300, with `tp=4`. For high-throughput DP attention on GB300, use `--dp 4`. +- For other configuration tips, please refer to [DeepSeek V3.2 documentation](../../../docs/basic_usage/deepseek_v32). GLM-5.1 and DeepSeek V3.2 share the same model structure, so the optimization techniques between these two models are also common (MTP, DSA kernel, Context Parallel...). +- Use `--json-model-override-args '{"index_topk_pattern": "FFSFSSSFSSFFFSSSFFFSFSSSSSSFFSFFSFFSSFFFFFFSFFFFFSFFSSSSSSFSFFFSFSSSFSFFSFFSSS"}'` for GLM-5.1-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.1 with the following command (FP8 on H200, all features enabled): + +```shell Command +SGLANG_ENABLE_SPEC_V2=1 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 MI300X/MI325X/MI355X (ROCm) Server Command + +The following ROCm commands are additional options for AMD GPUs and do not replace the NVIDIA instructions above. + +#### FP8 (Recommended) + +```shell Command +sglang serve \ + --model-path zai-org/GLM-5.1-FP8 \ + --tp 8 \ + --trust-remote-code \ + --tool-call-parser glm47 \ + --reasoning-parser glm45 \ + --nsa-prefill-backend tilelang \ + --nsa-decode-backend tilelang \ + --chunked-prefill-size 131072 \ + --mem-fraction-static 0.80 \ + --watchdog-timeout 1200 \ + --host 0.0.0.0 \ + --port 30000 +``` + +#### BF16 + +```shell Command +sglang serve \ + --model-path zai-org/GLM-5.1 \ + --tp 8 \ + --trust-remote-code \ + --nsa-prefill-backend tilelang \ + --nsa-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.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 +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 +=============== 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 +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 +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.3.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 +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 +=============== 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 +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 +============ 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 +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 +============ 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 + +#### 5.2.1 GSM8K Benchmark + +- Benchmark Command +```bash Command +python3 benchmark/gsm8k/bench_sglang.py --port 30000 +``` + +- Test Result +```text Output +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 +python3 benchmark/mmlu/bench_sglang.py --port 30000 +``` + +- Test Result +```text Output +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 NSA backends) + +```bash Command +python3 benchmark/gsm8k/bench_sglang.py --num-questions 200 +``` + +```text Output +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). diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-5.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-5.mdx new file mode 100644 index 000000000..4a51a8078 --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-5.mdx @@ -0,0 +1,667 @@ +--- +title: GLM-5 +metatags: + description: "Deploy GLM-5 with SGLang on NVIDIA H100/H200/B200 and AMD MI300X/MI325X/MI355X — state-of-the-art reasoning, enhanced coding, and robust tool calling capabilities." +tag: NEW +--- + +## 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/installation) 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. + +import { GLM5Deployment } from '/src/snippets/autoregressive/glm-5-deployment.jsx' + + + +### 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. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HardwareFP8BF16
H100tp=16tp=32
H200tp=8tp=16
B200tp=8tp=16
MI300X/MI325Xtp=8
MI355Xtp=8
+ +- **B200 (FP8)**: Use `--ep 1 --attention-backend nsa --nsa-decode-backend trtllm --nsa-prefill-backend trtllm --moe-runner-backend flashinfer_trtllm --enable-flashinfer-allreduce-fusion` for optimized NSA and MoE backends on Blackwell. Also add `--quantization fp8` for FP8 weight quantization. + +- **AMD GPUs**: Use `--nsa-prefill-backend tilelang --nsa-decode-backend tilelang` for the NSA 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, please refer to [DeepSeek V3.2 documentation](../../../docs/basic_usage/deepseek_v32). GLM-5 and DeepSeek V3.2 share the same model structure, so the optimization techniques between these two models are also common (MTP, DSA kernel, Context Parallel...). +- 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. + + +**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 not included in the generated commands above; add it manually only if memory constraints require the trade-off. + + +## 4. Model Invocation + +Deploy GLM-5 with the following command (FP8 on H200, all features enabled): + +```shell Command +sglang serve \ + --model 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 \ + --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 +sglang serve \ + --model zai-org/GLM-5 \ + --tp 8 \ + --trust-remote-code \ + --nsa-prefill-backend tilelang \ + --nsa-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 +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 +=============== 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 +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 +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 +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 +=============== 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 +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 +============ 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 +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 +============ 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 + +#### 5.2.1 GSM8K Benchmark + +- Benchmark Command +```bash Command +python3 benchmark/gsm8k/bench_sglang.py --port 30000 +``` + +- Test Result +```text Output +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 +python3 benchmark/mmlu/bench_sglang.py --port 30000 +``` + +- Test Result +```text Output +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 NSA backends) + +```bash Command +python3 benchmark/gsm8k/bench_sglang.py --num-questions 200 +``` + +```text Output +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). diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-Glyph.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-Glyph.mdx new file mode 100644 index 000000000..51971f4d5 --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-Glyph.mdx @@ -0,0 +1,829 @@ +--- +title: GLM Glyph +metatags: + description: "Deploy GLM-Glyph with SGLang - community contribution guide for Zhipu AI's GLM Glyph model deployment." +--- + +import { GLMGlyphDeployment } from '/src/snippets/autoregressive/glm-glyph-deployment.jsx'; + +## 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/installation) 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. + + + +### 3.2 Configuration Tips + +For more detailed configuration tips, please refer to [GLM-4.5/GLM-4.6 Usage](../../../docs/basic_usage/glm45). + +## 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 +python -m sglang.launch_server \ + --model-path zai-org/Glyph \ + --reasoning-parser glm45 \ + --tp 4 +``` + +**Streaming with Thinking Process:** + +```python Example +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 +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 +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 +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 +=============== 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 +# 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 +python -m sglang.launch_server \ + --model zai-org/Glyph \ + --tp 2 +``` + +##### 5.1.1.1 Low Concurrency +- **Benchmark Command**: +```bash Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python -m sglang.test.few_shot_gsm8k \ + --num-questions 200 +``` + +- Test Result + +```text Output +Accuracy: 0.890 +Invalid: 0.000 +Latency: 3.718 s +Output throughput: 5245.606 token/s +``` diff --git a/docs_new/cookbook/autoregressive/GLM/GLM-OCR.mdx b/docs_new/cookbook/autoregressive/GLM/GLM-OCR.mdx new file mode 100644 index 000000000..774258ea6 --- /dev/null +++ b/docs_new/cookbook/autoregressive/GLM/GLM-OCR.mdx @@ -0,0 +1,227 @@ +--- +title: GLM-OCR +metatags: + description: "Deploy GLM-OCR with SGLang - state-of-the-art OCR performance for complex document understanding." +--- + +## 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/installation) 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. + +import { GLMOCRDeployment } from '/src/snippets/autoregressive/glm-ocr-deployment.jsx' + + + +### 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 +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 +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 +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 +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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TasksVersionFiltern-shotMetricValueStderr
ocrbenchYamlnone0ocrbench_accuracy0.806N/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. diff --git a/docs_new/cookbook/autoregressive/Google/Gemma4.mdx b/docs_new/cookbook/autoregressive/Google/Gemma4.mdx new file mode 100644 index 000000000..75bd0804b --- /dev/null +++ b/docs_new/cookbook/autoregressive/Google/Gemma4.mdx @@ -0,0 +1,1290 @@ +--- +title: Gemma 4 +metatags: + description: "Deploy Gemma 4 with SGLang - Google's next-generation open models with MoE variants and multimodal support for text, vision, and audio." +--- + +import { Gemma4Deployment } from '/src/snippets/autoregressive/gemma4-deployment.jsx'; + +## 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:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelArchitectureParameters
[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-31B-it](https://huggingface.co/google/gemma-4-31B-it)Dense31B
[google/gemma-4-26B-A4B-it](https://huggingface.co/google/gemma-4-26B-A4B-it)MoE26B total / 4B active
+ +## 2. SGLang Installation + +Gemma 4 support requires [sgl-project/sglang#21952](https://github.com/sgl-project/sglang/pull/21952) and a specific transformers commit: + +```bash Command +# Install SGLang from main branch (after sglang#21952 is merged) +pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' + +# Install transformers with Gemma 4 support +pip install 'git+https://github.com/huggingface/transformers.git@91b1ab1fdfa81a552644a92fbe3e8d88de40e167' + +# Or use Docker AMD64 +docker pull lmsysorg/sglang:gemma4 # CUDA 12.9 +docker pull lmsysorg/sglang:cu13-gemma4 # CUDA 13 + +# For ARM64 (GB200 / GB300) +docker pull lmsysorg/sglang:dev-gemma4 # CUDA 12.9 +docker pull lmsysorg/sglang:dev-cu13-gemma4 # CUDA 13 +``` + +For the full Docker setup and other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/installation). + +## 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 and model variant. + + + +### 3.2 Configuration Tips + +- SGLang automatically selects the Triton attention backend for Gemma 4 models (required for bidirectional image-token attention during prefill). +- For the 26B-A4B MoE model, consider `--tp 2` for high-throughput workloads. +- Hardware requirements: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelHardwareTP
gemma-4-E2B-it1x H200 / 1x MI300X / 1x MI325X / 1x MI355X1
gemma-4-E4B-it1x H200 / 1x MI300X / 1x MI325X / 1x MI355X1
gemma-4-31B-it2x H200 / 1x MI300X / 1x MI325X / 1x MI355X2 (H200) / 1 (AMD)
gemma-4-26B-A4B-it1x H200 / 1x MI300X / 1x MI325X / 1x MI355X1
+ +### 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 +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](#51-speed-benchmark). + +## 4. Model Invocation + +Deploy gemma-4-26B-A4B-it (MoE) with all features enabled: + +```bash Command +sglang serve --model-path google/gemma-4-26B-A4B-it \ + --reasoning-parser gemma4 \ + --tool-call-parser gemma4 \ + --host 0.0.0.0 --port 30000 +``` + +### 4.1 Basic Usage + +```python Example +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 +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 +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 +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 +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 +=============== 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 +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 +=============== Tool Calls ================ +Tool Call: get_weather + Arguments: {"location": "Tokyo"} +``` + +
+ +## 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 +sglang serve --model-path google/gemma-4-E2B-it +``` + +**Latency Benchmark (Text)** + +```bash Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +sglang serve --model-path google/gemma-4-E4B-it +``` + +**Latency Benchmark (Text)** + +```text Output +============ 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 +============ 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 +============ 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 +============ 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 +sglang serve --model-path google/gemma-4-31B-it --tp 2 +``` + +**Latency Benchmark (Text)** + +```text Output +============ 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 +============ 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 +============ 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 +============ 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 +sglang serve --model-path google/gemma-4-26B-A4B-it +``` + +> **Tip**: Consider `--tp 2` for high-throughput workloads. + +**Latency Benchmark (Text)** + +```text Output +============ 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 +============ 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 +============ 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 +============ 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 +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 +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 +============ 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 +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 +============ 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 +sglang serve --model-path google/gemma-4-26B-A4B-it +``` + +**Latency Benchmark (Text)** + +```bash Command +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 +============ 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 +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 +============ 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 +================================================== +``` + +### 5.2 Accuracy Benchmark + +**Test Environment:** + +- Hardware: H200 +- SGLang Version: gemma4 branch + +#### MMLU + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelHumanitiesSocial SciencesSTEMOtherOverall
gemma-4-E2B-it0.6210.7390.8300.736**0.720**
gemma-4-E4B-it0.7030.8620.9020.825**0.810**
gemma-4-31B-it0.8780.9210.8840.911**0.896**
gemma-4-26B-A4B-it0.8530.9060.9380.886**0.891**
+ +#### GSM8K + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelAccuracyInvalidLatency (s)Output Throughput (tok/s)
gemma-4-E2B-it0.1700.0003.9908041.739
gemma-4-E4B-it0.7450.0004.1744672.030
gemma-4-31B-it0.8050.00516.1481559.914
gemma-4-26B-A4B-it0.4500.01013.0014089.457
+ +#### MMMU + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelOverall
gemma-4-E2B-it**0.307**
gemma-4-E4B-it**0.396**
gemma-4-31B-it**0.589**
gemma-4-26B-A4B-it**0.549**
+ +
+MMMU detailed scores (per domain) + +**gemma-4-E2B-it** + +```json Config +{"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 +{"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-31B-it** + +```json Config +{"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 +{"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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelWERAvg Latency (s)Throughput (req/s)
gemma-4-E2B-it23.86%0.2122.99
gemma-4-E4B-it29.55%0.3662.46
gemma-4-31B-itNot Supported
gemma-4-26B-A4B-itNot Supported
+ +#### FLEUR (EN_US) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelWERAvg Latency (s)Throughput (req/s)
gemma-4-E2B-it7.37%0.8963s16.25
gemma-4-E4B-it6.08%0.8707s16.20
gemma-4-31B-itNot Supported
gemma-4-26B-A4B-itNot Supported
+ +### 5.3 Logits correctness validation + +**gemma-4-E2B-it** +```shell Command +$ python -m sglang.bench_one_batch --correct --model gg-hf-gg/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 gg-hf-gg/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 +$ python -m sglang.bench_one_batch --correct --model gg-hf-gg/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 gg-hf-gg/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 +$ python -m sglang.bench_one_batch --correct --model gg-hf-gg/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 gg-hf-gg/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) +.... +``` + +
diff --git a/docs_new/cookbook/autoregressive/InclusionAI/LLaDA-2.1.mdx b/docs_new/cookbook/autoregressive/InclusionAI/LLaDA-2.1.mdx new file mode 100644 index 000000000..162bfa761 --- /dev/null +++ b/docs_new/cookbook/autoregressive/InclusionAI/LLaDA-2.1.mdx @@ -0,0 +1,701 @@ +--- +title: LLaDA 2.1 +metatags: + description: "Deploy LLaDA 2.1 with SGLang - large-scale discrete diffusion language model with parallel token generation, iterative denoising, MoE architecture, and reinforcement learning for reasoning." +tag: NEW +--- + +import { LLaDA21Deployment } from '/src/snippets/autoregressive/llada-21-deployment.jsx'; + +## 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:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelParametersArchitectureContext LengthHuggingFace
**LLaDA2.1-mini**16BMoE (20 layers, 16 attention heads)32,768 tokens[inclusionAI/LLaDA2.1-mini](https://huggingface.co/inclusionAI/LLaDA2.1-mini)
**LLaDA2.1-flash**100BMoE32,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/installation) 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. + + + +### 3.2 Configuration Tips + +**dLLM-Specific Parameters:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescriptionRecommended Value
`--dllm-algorithm`Diffusion decoding algorithm`JointThreshold`
`--trust-remote-code`Required for LLaDA model loadingAlways 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:** + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModeThresholdSpeedQualityBest For
**Quality Mode (Q)**ConservativeModerateHigher benchmark scoresAccuracy-critical tasks
**Speed Mode (S)**AggressiveVery fast, relies on T2T editingSlightly lowerThroughput-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 +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 +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 +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 +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 +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 +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 +```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 +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 +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 +============ 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 +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 +============ 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 +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 +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 +============ 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 +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 +============ 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 +python -m sglang.test.few_shot_gsm8k \ + --num-questions 200 \ + --port 8000 +``` + +**Results:** + +```text Output +Accuracy: 0.895 +Invalid: 0.000 +Latency: 100.552 s +Output throughput: 262.094 token/s +``` diff --git a/docs_new/cookbook/autoregressive/InclusionAI/Ling-2.5-1T.mdx b/docs_new/cookbook/autoregressive/InclusionAI/Ling-2.5-1T.mdx new file mode 100644 index 000000000..d9bbceb39 --- /dev/null +++ b/docs_new/cookbook/autoregressive/InclusionAI/Ling-2.5-1T.mdx @@ -0,0 +1,221 @@ +--- +title: Ling-2.5-1T +metatags: + description: "Deploy Ling-2.5-1T with SGLang - 1T parameter MoE model with 63B active parameters, trillion-scale context length up to 1M tokens, and agentic tool calling capabilities." +tag: NEW +--- + +## 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 requires a specific SGLang Docker image: + +```bash Command +# For H200/B200 +docker pull lmsysorg/sglang:nightly-dev-20260213-a0ebaa64 + +# For GB200/GB300 +docker pull lmsysorg/sglang:nightly-dev-cu13-20260213-a0ebaa64 +``` + +For other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/installation). + +Ling-2.5-1T is also supported via the **nightly PyPI builds**. See the [SGLang Installation (PyPI)](../../../docs/get-started/installation) 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. + +import { Ling251TDeployment } from '/src/snippets/autoregressive/ling-25-1t-deployment.jsx' + + + +### 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 +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 +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 +{ + "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 +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 +{ + "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 +python3 benchmark/gsm8k/bench_sglang.py +``` + +- Test Result +```text Output +Accuracy: 0.960 +Invalid: 0.000 +Latency: 45.410 s +Output throughput: 560.642 token/s +``` diff --git a/docs_new/cookbook/autoregressive/InclusionAI/Ring-2.5-1T.mdx b/docs_new/cookbook/autoregressive/InclusionAI/Ring-2.5-1T.mdx new file mode 100644 index 000000000..0cd4d7f6b --- /dev/null +++ b/docs_new/cookbook/autoregressive/InclusionAI/Ring-2.5-1T.mdx @@ -0,0 +1,266 @@ +--- +title: Ring-2.5-1T +metatags: + description: "Deploy Ring-2.5-1T with SGLang - world's first open-source 1T parameter reasoning model with hybrid linear attention, deep reasoning, and agentic tool calling capabilities." +tag: NEW +--- + +## 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 requires a specific SGLang Docker image: + +```bash Command +# For H200/B200 +docker pull lmsysorg/sglang:nightly-dev-20260213-a0ebaa64 + +# For GB200/GB300 +docker pull lmsysorg/sglang:nightly-dev-cu13-20260213-a0ebaa64 + +# 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/installation). + +## 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. + +import { Ring251TDeployment } from '/src/snippets/autoregressive/ring-25-1t-deployment.jsx' + + + +### 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 +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 +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 +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 +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 +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 +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 +[ChatCompletionMessageFunctionToolCall(id='call_770360e31d194ed79d32cd8c', function=Function(arguments='{"location": "Beijing"}', name='get_weather'), type='function', index=0)] +``` + +## 5. Benchmark + +### GSM8K + +- Deployment Command +```bash Command +sglang serve \ + --model-path inclusionAI/Ring-2.5-1T \ + --tp-size 8 \ + --trust-remote-code +``` + +- Benchmark Command +```bash Command +python3 benchmark/gsm8k/bench_sglang.py --temperature 1.2 --top-p 0.8 --max-new-tokens 32768 --num-questions 200 --tokenizer-path inclusionAI/Ring-2.5-1T --enable-thinking +``` + +- Test Result +```text Output +Accuracy: 0.955 +Invalid: 0.010 +Latency: 615.833 s +Output throughput: 412.360 token/s +``` diff --git a/docs_new/cookbook/autoregressive/InternLM/Intern-S1.mdx b/docs_new/cookbook/autoregressive/InternLM/Intern-S1.mdx new file mode 100644 index 000000000..ae68d7be0 --- /dev/null +++ b/docs_new/cookbook/autoregressive/InternLM/Intern-S1.mdx @@ -0,0 +1,28 @@ +--- +title: Intern-S1 +metatags: + description: "Deploy Intern-S1 with SGLang - community contribution guide for InternLM's Intern-S1 model deployment." +--- + +## 📝 Community Contribution Welcome + +This guide is currently under development. We welcome community contributions! + +If you have experience deploying **Intern-S1** with SGLang, please help us complete this documentation. + +## 🚀 How to Contribute + +```shell Command +git clone https://github.com/YOUR_USERNAME/sglang-cookbook.git +cd sglang-cookbook +git checkout -b add-intern-s1-guide +# Edit this file and submit a PR +``` + +## 📚 Reference + +- [GLM-4.6V](../GLM/GLM-4.6V) + +--- + +**Let's build this together!** 🌟 diff --git a/docs_new/cookbook/autoregressive/InternVL/InternVL3.5.mdx b/docs_new/cookbook/autoregressive/InternVL/InternVL3.5.mdx new file mode 100644 index 000000000..a235290d7 --- /dev/null +++ b/docs_new/cookbook/autoregressive/InternVL/InternVL3.5.mdx @@ -0,0 +1,29 @@ +--- +title: InternVL3.5 +metatags: + description: "Deploy InternVL3.5 vision-language model with SGLang - community contribution guide for OpenGVLab's multimodal model." +--- + + +## 📝 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 +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!** 🌟 diff --git a/docs_new/cookbook/autoregressive/Jina/Jina-reranker-m0.mdx b/docs_new/cookbook/autoregressive/Jina/Jina-reranker-m0.mdx new file mode 100644 index 000000000..25acd214b --- /dev/null +++ b/docs_new/cookbook/autoregressive/Jina/Jina-reranker-m0.mdx @@ -0,0 +1,28 @@ +--- +title: Jina-reranker-m0 +metatags: + description: "Deploy Jina-reranker-m0 with SGLang - community contribution guide for Jina AI's reranker model deployment." +--- + +## 📝 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 +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!** 🌟 diff --git a/docs_new/cookbook/autoregressive/Llama/Llama3.1.mdx b/docs_new/cookbook/autoregressive/Llama/Llama3.1.mdx new file mode 100644 index 000000000..95bdbd2d6 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Llama/Llama3.1.mdx @@ -0,0 +1,644 @@ +--- +title: Llama-3.1 +metatags: + description: "Deploy Llama 3.1 (8B/70B/405B) with SGLang - 128K context, tool use, multilingual support, and speculative decoding optimization." +--- +## 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/installation) 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 generate a launch command for Llama 3.1 collection of models. + +import { Llama31Deployment } from "/src/snippets/autoregressive/llama31-deployment.jsx"; + + +### 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 + +## 4. Model Invocation + +### 4.1 Basic Usage + +SGLang exposes an OpenAI-compatible endpoint. First, start the server + +```shell Command +sglang serve \ + --model-path Meta-Llama/Llama-3.1-405B-Instruct \ + --tp 8 +``` + +```python Example +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 +**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 +sglang serve \ + --model-path Meta-Llama/Llama-3.1-405B-Instruct \ + --tool-call-parser llama3 \ + --tp 8 +``` + +**Python Example** + +```python Example +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 +🔧 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 +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 +sglang serve \ + --model-path Meta-Llama/Llama-3.1-70B \ + --tp 8 +``` + +##### 5.1.1.1 Low Concurrency + +- Benchmark Command: + +```shell Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 +``` + +- **Results**: + +```text Output +Accuracy: 0.830 +Invalid: 0.000 +Latency: 11.794 s +Output throughput: 1406.961 token/s +``` diff --git a/docs_new/cookbook/autoregressive/Llama/Llama3.3-70B.mdx b/docs_new/cookbook/autoregressive/Llama/Llama3.3-70B.mdx new file mode 100644 index 000000000..b74da9e0e --- /dev/null +++ b/docs_new/cookbook/autoregressive/Llama/Llama3.3-70B.mdx @@ -0,0 +1,229 @@ +--- +title: Llama-3.3-70B +metatags: + description: "Deploy Llama-3.3-70B-Instruct with SGLang on AMD GPUs - 128K context, enhanced reasoning, tool calling, and multilingual support." +--- +## 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/installation) for installation instructions. + +## 3. Model Deployment + +This section provides deployment configurations optimized for AMD GPUs (MI300X, MI325X, MI355X). + +### 3.1 Interactive Configuration + +**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your AMD GPU setup. + +import { Llama33Deployment } from "/src/snippets/autoregressive/llama33-70b-deployment.jsx"; + + + +### 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 + +## 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 +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 +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 +# 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 +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 +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/) diff --git a/docs_new/cookbook/autoregressive/Llama/Llama4.mdx b/docs_new/cookbook/autoregressive/Llama/Llama4.mdx new file mode 100644 index 000000000..bd624433c --- /dev/null +++ b/docs_new/cookbook/autoregressive/Llama/Llama4.mdx @@ -0,0 +1,474 @@ +--- +title: Llama 4 +metatags: + description: "Deploy Llama 4 Scout and Maverick with SGLang - Meta's latest generation open-source LLMs with industry-leading performance." +--- + +import { Llama4ScoutDeployment } from '/src/snippets/autoregressive/llama4-scout-deployment.jsx'; +import { Llama4MaverickDeployment } from '/src/snippets/autoregressive/llama4-maverick-deployment.jsx'; + +## 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/ + +## 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/installation) 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. + + + + + +## 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 +docker pull lmsysorg/sglang:v0.5.9-rocm720-mi30x +``` + +```shell Command +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 +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 +sglang serve \ + --model-path meta-llama/Llama-4-Maverick-17B-128E-Instruct \ + --tp 8 \ + --context-length 1000000 \ + --trust-remote-code +``` + +## 5. Benchmark +### 5.1 Speed Benchmark +Test Environment: + +Hardware: AMD MI300x GPU + +Model: Llama-4-Scout + +Tensor Parallelism: 8 + +sglang version: 0.5.9 + +- **Model Deployment** +```bash Command +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +Test Environment: + +Hardware: AMD MI300x GPU + +Model: Llama-4-Maverick + +Tensor Parallelism: 8 + +sglang version: 0.5.9 + +- **Model Deployment** +```bash Command +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 +``` + - Llama-4-Scout-17B-16E-Instruct +```text Output +Accuracy: 0.945 +Invalid: 0.000 +Latency: 12.731 s +Output throughput: 1595.418 token/s +``` + - Llama-4-Maverick-17B-128E-Instruct +```text Output +Accuracy: 0.895 +Invalid: 0.000 +Latency: 9.739 s +Output throughput: 2405.505 token/s +``` diff --git a/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.5.mdx b/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.5.mdx new file mode 100644 index 000000000..c24ff680d --- /dev/null +++ b/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.5.mdx @@ -0,0 +1,1041 @@ +--- +title: MiniMax-M2.5 +metatags: + description: "Deploy MiniMax-M2.5 with SGLang - community contribution guide for MiniMax M2.5 model deployment." +tag: NEW +--- + +import { MiniMaxM25Deployment } from '/src/snippets/autoregressive/minimax-m25-deployment.jsx'; + +## 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/installation) for installation instructions. + +**For AMD MI300X/MI325X/MI355X GPUs:** + +```bash Command +# 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 +``` + +## 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. + + + +### 3.2 Configuration Tips + +**Key Parameters:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescriptionRecommended 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 loadingAlways 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 + +## 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) + +**Testing Deployment:** + +After startup, you can test the SGLang OpenAI-compatible API with the following command: + +```bash Command +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 +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 +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 +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 +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 +=============== 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 +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 +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 +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 +# 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." +``` + +## 5. Benchmark + +This section uses **industry-standard configurations** for comparable benchmark results. + +### 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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python benchmark/gsm8k/bench_sglang.py --port 30000 +``` +- Test Results: +```text Output +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 +cd benchmark/mmlu +bash download_data.sh +python3 bench_sglang.py --port 30000 +``` +- Test Results: +```text Output +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 +``` diff --git a/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.7.mdx b/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.7.mdx new file mode 100644 index 000000000..46dc5d044 --- /dev/null +++ b/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.7.mdx @@ -0,0 +1,723 @@ +--- +title: MiniMax-M2.7 +metatags: + description: "Deploy MiniMax-M2.7 with SGLang on NVIDIA and AMD GPUs — model self-evolution, professional software engineering, and native agent teams." +tag: NEW +--- + +## 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/installation) for installation instructions. + +**Docker Images by Hardware Platform:** + + + + + + + + + + + + + + + + + + + + + + + + + + +
Hardware PlatformDocker 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. + +import { MiniMaxM27Deployment } from '/src/snippets/autoregressive/minimax-m27-deployment.jsx' + + + +### 3.2 Configuration Tips + +**Key Parameters:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescriptionRecommended 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 loadingAlways 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 + +## 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 +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 +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 +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 +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 +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 +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 +=============== 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 +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 +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 +Tool Call: get_weather + Arguments: {"location": "Beijing"} +``` + +**Handling Tool Call Results:** + +```python Example +# 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 +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**: [NVIDIA NeMo-Skills](https://github.com/NVIDIA-NeMo/Skills) + +**Evaluation Settings**: temperature=0.6, top_p=0.95, 8 seeds, max_tokens=120,000, `parse_reasoning=True` + +#### 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)) +- Evaluation command: +```bash Command +ns prepare_data gpqa + +ns eval \ + --cluster=local \ + --server_type=openai \ + --model=MiniMaxAI/MiniMax-M2.7 \ + --server_address=http://localhost:30000/v1 \ + --output_dir=./m2.7-eval/ \ + --benchmarks=gpqa:8 \ + ++prompt_config=eval/aai/mcq-4choices \ + ++inference.tokens_to_generate=120000 \ + ++inference.temperature=0.6 \ + ++inference.top_p=0.95 \ + ++parse_reasoning=True +``` +- Test Results: + + + + + + + + + + + + + + + + + + + + + + + + + + +
Evaluation ModeAccuracyNo Answer
pass@1 (avg-of-8)84.91%3.54%
**majority@8****88.89%**0.00%
pass@896.46%0.00%
+ +#### 5.1.2 AIME 2025 + +- Dataset: AIME 2025 (30 problems) +- Prompt: `generic/math` (boxed answer format) +- Evaluation command: +```bash Command +ns prepare_data aime25 + +ns eval \ + --cluster=local \ + --server_type=openai \ + --model=MiniMaxAI/MiniMax-M2.7 \ + --server_address=http://localhost:30000/v1 \ + --output_dir=./m2.7-eval/ \ + --benchmarks=aime25:8 \ + ++inference.tokens_to_generate=120000 \ + ++inference.temperature=0.6 \ + ++inference.top_p=0.95 \ + ++parse_reasoning=True +``` +- Test Results: + + + + + + + + + + + + + + + + + + + + + + + + + + +
Evaluation ModeAccuracyNo Answer
pass@1 (avg-of-8)92.50% ± 5.56%2.92%
**majority@8****97.08%**0.00%
pass@8100.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) +- Evaluation command: +```bash Command +ns prepare_data mmlu-pro + +ns eval \ + --cluster=local \ + --server_type=openai \ + --model=MiniMaxAI/MiniMax-M2.7 \ + --server_address=http://localhost:30000/v1 \ + --output_dir=./m2.7-eval/ \ + --benchmarks=mmlu-pro \ + ++prompt_config=eval/aai/mcq-10choices \ + ++inference.tokens_to_generate=32768 \ + ++inference.temperature=0.0 \ + ++parse_reasoning=True +``` +- Test Results: + + + + + + + + + + + + + + + + +
Evaluation ModeAccuracyNo 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 +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 +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 +============ 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 +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 +============ 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 +================================================== +``` diff --git a/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.mdx b/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.mdx new file mode 100644 index 000000000..4d5e8d00c --- /dev/null +++ b/docs_new/cookbook/autoregressive/MiniMax/MiniMax-M2.mdx @@ -0,0 +1,541 @@ +--- +title: MiniMax-M2 +metatags: + description: "Deploy MiniMax-M2 with SGLang - community contribution guide for MiniMax M2 model deployment." +--- + +import { MiniMaxM2Deployment } from '/src/snippets/autoregressive/minimax-m2-deployment.jsx'; + +## 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/installation) 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 +docker pull lmsysorg/sglang:v0.5.9-rocm720-mi30x +``` +```shell Command +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 +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 +#@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. + + + +## 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 + 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 +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 +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 +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 +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 +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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +sglang serve \ + --model-path MiniMaxAI/MiniMax-M2 \ + --tp-size 4 \ + --trust-remote-code \ + --mem-fraction-static 0.85 +``` + +- **Benchmark Command**: +```shell Command + python3 -m sglang.test.few_shot_gsm8k --num-questions 200 +``` +- **Result**: + - MiniMax-M2 +```text Output + Accuracy: 0.950 + Invalid: 0.000 + Latency: 15.120 s + Output throughput: 1306.711 token/s +``` diff --git a/docs_new/cookbook/autoregressive/Mistral/Devstral-2.mdx b/docs_new/cookbook/autoregressive/Mistral/Devstral-2.mdx new file mode 100644 index 000000000..c8c525fb0 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Mistral/Devstral-2.mdx @@ -0,0 +1,518 @@ +--- +title: Devstral 2 (Mistral) +metatags: + description: "Deploy Devstral 2 agentic coding models with SGLang - optimized for tool use, codebase exploration, and multi-file edits with 256K context." +--- + +## 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/installation) for installation instructions. + + +Devstral 2 requires a recent `transformers`. Please verify `transformers >= 5.0.0.rc`: + +```shell Command +python -c "import transformers; print(transformers.__version__)" +``` + +If your version is lower, upgrade: + +```shell Command +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). + + +The TP size is set to the minimum required for the selected model size. + + + +import { Devstral2Deployment } from "/src/snippets/autoregressive/devstral-2-deployment.jsx"; + + + +### 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 +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 + 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 +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 +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 +🔧 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 +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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 benchmark/gsm8k/bench_sglang.py \ + --num-shots 8 \ + --num-questions 1316 \ + --parallel 1316 \ + --port 8888 +``` + +**Test Results:** + +```text Output +Accuracy: 0.922 +Invalid: 0.000 +Latency: 35.800 s +Output throughput: 4507.697 token/s +``` diff --git a/docs_new/cookbook/autoregressive/Mistral/Ministral-3.mdx b/docs_new/cookbook/autoregressive/Mistral/Ministral-3.mdx new file mode 100644 index 000000000..8c858e947 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Mistral/Ministral-3.mdx @@ -0,0 +1,288 @@ +--- +title: Ministral-3 +metatags: + description: "Deploy Mistral 3 with SGLang - deployment configurations and usage patterns for Mistral's latest model." +--- + +import { Ministral3Deployment } from '/src/snippets/autoregressive/ministral-3-deployment.jsx'; + +## 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/installation) 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. + + + +### 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 +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 +docker pull lmsysorg/sglang:v0.5.9-rocm720-mi30x +``` + +```shell Command +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 +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 +sglang serve \ + --model-path mistralai/Ministral-3-14B-Instruct-2512 \ + --tp 1 \ + --trust-remote-code +``` + +##### Low Concurrency +- Benchmark Command: +```bash Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 benchmark/gsm8k/bench_sglang.py \ + --num-shots 8 \ + --num-questions 1316 \ + --parallel 1316 +``` + +**Test Results:** + +```text Output +Accuracy: 0.959 +Invalid: 0.000 +Latency: 29.185 s +Output throughput: 4854.672 token/s +``` diff --git a/docs_new/cookbook/autoregressive/Mistral/Mistral-Small-4.mdx b/docs_new/cookbook/autoregressive/Mistral/Mistral-Small-4.mdx new file mode 100644 index 000000000..7dc4d179e --- /dev/null +++ b/docs_new/cookbook/autoregressive/Mistral/Mistral-Small-4.mdx @@ -0,0 +1,393 @@ +--- +title: Mistral Small 4 +metatags: + description: "Deploy Mistral Small 4 with SGLang - unified hybrid model combining instruct, reasoning, and agentic capabilities with multimodal support." +--- + +import { MistralSmall4Deployment } from '/src/snippets/autoregressive/mistral-small-4-deployment.jsx'; + +## 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/installation) for installation instructions. + + +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/installation). + + +--- + +## 3. Model Deployment + +### 3.1 Basic Configuration + +**Interactive Command Generator**: Use the configuration selector below to generate a launch command for Mistral Small 4. + + + +### 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 +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 +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 +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 +# 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 +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 +=== 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 +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 +Tool: get_weather +Args: {"location": "Paris"} +``` + +### 4.5 Vision (Image Input) + +Mistral Small 4 accepts image inputs alongside text: + +```python Example +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 +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 +python3 benchmark/gsm8k/bench_sglang.py --port 30000 +``` + +**Results:** + +```text Output +TODO +``` + +#### MMLU + +```bash Command +python3 benchmark/mmlu/bench_sglang.py --port 30000 +``` + +**Results:** + +```text Output +TODO +``` + +### 5.2 Speed Benchmarks + +#### Latency (Low Concurrency) + +```bash Command +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 +TODO +``` + +#### Throughput (High Concurrency) + +```bash Command +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 +TODO +``` diff --git a/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.5.mdx b/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.5.mdx new file mode 100644 index 000000000..162efb738 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.5.mdx @@ -0,0 +1,1244 @@ +--- +title: Kimi-K2.5 +metatags: + description: "Deploy Kimi-K2.5 MoE model with SGLang - 1T total parameters, 32B active, step-by-step reasoning and tool calling capabilities." +--- + +## 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/installation). + +## 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. + +import { KimiK25Deployment } from '/src/snippets/autoregressive/kimi-k25-deployment.jsx' + + + +### 3.2 Configuration Tips + +- **Memory**: Requires GPUs with >=140GB each. Supported platforms: H200 (8x, TP=8), B300 (8x, TP=8), 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 `--dp --enable-dp-attention` for production throughput. A common choice is to set `--dp` 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 +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 +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 +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 +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 +====== 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 +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 +Tool Call: get_weather + Arguments: {"location": "Beijing"} +``` + +**Handling Tool Call Results:** + +```python Example +# 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 +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 +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 +=== 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/B200, all features enabled): + +```shell Command +SGLANG_ENABLE_SPEC_V2=1 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 \ + --trust-remote-code \ + --host 0.0.0.0 \ + --port 30000 +``` + +Deploy Kimi-K2.5-NVFP4 with the following command (B200, all features enabled): + +```shell Command +SGLANG_ENABLE_SPEC_V2=1 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 \ + --trust-remote-code \ + --host 0.0.0.0 \ + --port 30000 +``` + +## 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 +python3 benchmark/mmmu/bench_sglang.py \ + --response-answer-regex "(?i)(?:answer|ans)[:\s]*(?:\*\*)?[\(\[]?([A-Za-z])[\)\]]?(?:\*\*)?" \ + --port 30000 \ + --concurrency 64 +``` + +- **Result:** + +```text Output +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 +sglang serve \ + --model-path moonshotai/Kimi-K2.5 \ + --tp 8 \ + --trust-remote-code \ + --host 0.0.0.0 \ + --port 30000 +``` + +- **Benchmark Command:** + +```bash Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +Waiting for completion... +``` + +**Scenario 3: Summarization (8K/1K)** + +- Low Concurrency + +```bash Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +SGLANG_ENABLE_SPEC_V2=1 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 \ + --trust-remote-code \ + --host 0.0.0.0 \ + --port 30000 +``` + +- **Benchmark Command:** + +```bash Command +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 +Pending update... +``` + +- Medium Concurrency (Balanced) + +```bash Command +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 +Pending update... +``` + +- High Concurrency (Throughput-Optimized) + +```bash Command +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 +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 +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 +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 +============ 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 +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 +============ 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 +================================================== +``` diff --git a/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.6.mdx b/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.6.mdx new file mode 100644 index 000000000..38f04897a --- /dev/null +++ b/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.6.mdx @@ -0,0 +1,1309 @@ +--- +title: Kimi-K2.6 +metatags: + description: "Deploy Kimi-K2.6 native multimodal agentic model with SGLang - reasoning, tool calling, and multimodal capabilities." +tag: NEW +--- + +## 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):** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BenchmarkScore
HLE w/ tools54.0
SWE-Bench Pro58.6
SWE-bench Multilingual76.7
BrowseComp83.2
Toolathlon50.0
AIME 202696.4
GPQA-Diamond90.5
LiveCodeBench89.6
+ +**Recommended Generation Parameters:** +- Thinking Mode: `temperature=1.0`, `top_p=0.95` +- Instant Mode: `temperature=0.6`, `top_p=0.95` + +**License:** Modified MIT + +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/installation). + +## 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. + +import { KimiK26Deployment } from '/src/snippets/autoregressive/kimi-k26-deployment.jsx' + + + +### 3.2 Configuration Tips + +- **Memory**: Requires GPUs with ≥140GB each. Supported platforms: H200 (8×, TP=8), B300 (8×, TP=8), MI300X/MI325X (4×, TP=4), MI350X/MI355X (4×, TP=4). Use `--context-length 128000` to conserve memory. +- **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 `--dp --enable-dp-attention` for production throughput. A common choice is to set `--dp` 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 +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 +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 +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 +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 +====== 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 +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 +Tool Call: get_weather + Arguments: {"location": "Beijing"} +``` + +**Handling Tool Call Results:** + +```python Example +# 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 +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 +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 +=== 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"} +``` + + +## 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` + +#### 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 +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:** + + + + + + + + + + + + + + + + + + + + + + + + + + +
MetricValue
Success Rate99.95% (1999/2000)
Tool Call Triggered970
Tool Call Valid89.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: [NVIDIA NeMo-Skills](https://github.com/NVIDIA/NeMo-Skills) +- Prompt: `eval/matharena/aime` (MathArena format with `\boxed{}` answers) +- Settings: temperature=1.0, top_p=0.95, max_tokens=131,072, 32 seeds + +**Evaluation Command:** + +```shell Command +# Prepare dataset +python3 nemo_skills/dataset/aime25/prepare.py + +# Run 32 seeds in parallel +for RS in $(seq 0 31); do + python3 nemo_skills/inference/generate.py \ + input_file=nemo_skills/dataset/aime25/test.jsonl \ + output_file=results/kimi-k26/aime25/output-rs${RS}.jsonl \ + prompt_config=eval/matharena/aime \ + prompt_format=openai \ + +server.server_type=openai \ + +server.model=moonshotai/Kimi-K2.6 \ + +server.base_url=http://localhost:30000/v1 \ + ++inference.temperature=1.0 \ + ++inference.top_p=0.95 \ + ++inference.tokens_to_generate=131072 \ + ++inference.random_seed=${RS} \ + max_concurrent_requests=512 & +done +``` + +**Results:** + + + + + + + + + + + + + + + + + + + + + + +
Evaluation ModeAccuracy
pass@1 (avg-of-32)98.9% (29.7/30)
majority@32100.0% (30/30)
pass@32100.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 +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 ModeAccuracy
pass@1 (avg across epochs)96.9%
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
EpochAccuracy
196.4% (160/166)
296.9% (156/161)
396.9% (155/160)
498.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 +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 ModeAccuracy
pass@190.8%
+ +#### 5.1.5 MMMU Pro Vision + +```text Output +Pending update... +``` + +### 5.2 Speed Benchmark + +**Test Environment:** + +- Hardware: NVIDIA H200 GPU (8x) +- Model: Kimi-K2.6 +- Tensor Parallelism: 8 +- SGLang Version: 0.5.9 + + +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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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. + + +**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 +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 +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 +============ 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 +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 +============ 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 +================================================== +``` diff --git a/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.mdx b/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.mdx new file mode 100644 index 000000000..0d858c56b --- /dev/null +++ b/docs_new/cookbook/autoregressive/Moonshotai/Kimi-K2.mdx @@ -0,0 +1,520 @@ +--- +title: Kimi-K2 +metatags: + description: "Deploy Kimi-K2 MoE model with SGLang - 1T total parameters, 32B active, step-by-step reasoning and tool calling capabilities." +--- + +import { KimiK2Deployment } from '/src/snippets/autoregressive/kimi-k2-deployment.jsx'; + +## 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/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 capabilities. + + + +### 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 `--dp 4 --enable-dp-attention` 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 +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 +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 +=============== 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 +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 +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 +=============== 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 +# 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 +python3 -m sglang.launch_server \ + --model-path moonshotai/Kimi-K2-Instruct \ + --tp 8 \ + --dp 4 \ + --enable-dp-attention \ + --trust-remote-code \ + --host 0.0.0.0 \ + --port 8000 +``` + +- Benchmark Command: + +```shell Command +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 +============ 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 +python3 -m sglang.launch_server \ + --model-path moonshotai/Kimi-K2-Instruct \ + --tp 8 \ + --dp 4 \ + --ep 4 \ + --enable-dp-attention \ + --trust-remote-code \ + --host 0.0.0.0 \ + --port 8000 +``` + +- Benchmark Command: + +```shell Command +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 +============ 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 +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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 --port 8000 +``` + +- **Result**: + +```text Output +Accuracy: 0.960 +Invalid: 0.000 +Latency: 15.956 s +Output throughput: 1231.699 token/s +``` diff --git a/docs_new/cookbook/autoregressive/Moonshotai/Kimi-Linear.mdx b/docs_new/cookbook/autoregressive/Moonshotai/Kimi-Linear.mdx new file mode 100644 index 000000000..c0b4abd27 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Moonshotai/Kimi-Linear.mdx @@ -0,0 +1,297 @@ +--- +title: Kimi-Linear +metatags: + description: "Deploy Kimi-Linear with SGLang - community contribution guide for Moonshot AI's Kimi-Linear model deployment." +--- + +import { KimiLinearDeployment } from '/src/snippets/autoregressive/kimi-linear-deployment.jsx'; + +## 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 + +## 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/installation) 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. + + + +## 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 +docker pull lmsysorg/sglang:v0.5.7-rocm700-mi30x +``` + +```shell Command +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 +pip install sentencepiece tiktoken +``` + +#### 4.2.3 Launch the server +```shell Command +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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 +``` + +- **Result**: + +```text Output +Accuracy: 0.705 +Invalid: 0.000 +Latency: 11.855 s +Output throughput: 3224.982 token/s +``` diff --git a/docs_new/cookbook/autoregressive/NVIDIA/Nemotron3-Nano.mdx b/docs_new/cookbook/autoregressive/NVIDIA/Nemotron3-Nano.mdx new file mode 100644 index 000000000..4406459dd --- /dev/null +++ b/docs_new/cookbook/autoregressive/NVIDIA/Nemotron3-Nano.mdx @@ -0,0 +1,375 @@ +--- +title: Nemotron3-Nano +metatags: + description: "Deploy NVIDIA Nemotron3-Nano 30B hybrid LLM with SGLang - MoE, Mamba2, and attention layers with BF16/FP8 precision options." +--- + +import { Nemotron3NanoDeployment } from '/src/snippets/autoregressive/nemotron3-nano-deployment.jsx'; + +## 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/installation), or install nightly wheel through: +```bash Command +uv pip install 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 + +**Interactive Command Generator**: select hardware, model variant, and common knobs to generate a launch 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 +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 +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 +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 +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 +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 +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 +``` + +- **Test Results:** + +```text Output +============ 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 +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 +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 +``` + +- **Test Results:** + +```text Output +============ 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 +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 lm-eval** +```bash Command +pip install lm-eval[api]==0.4.9.2 + +lm_eval --model local-completions --tasks gsm8k --model_args "model=nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16,base_url=http://127.0.0.1:30000/v1/completions,num_concurrent=4,max_retries=3,tokenized_requests=False,max_lengths=16384" --gen_kwargs '{"chat_template_kwargs":{"thinking":true}}' --batch_size 256 +``` + +**Test Results:** +```text Output +|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| +``` diff --git a/docs_new/cookbook/autoregressive/NVIDIA/Nemotron3-Super.mdx b/docs_new/cookbook/autoregressive/NVIDIA/Nemotron3-Super.mdx new file mode 100644 index 000000000..abcc1f48d --- /dev/null +++ b/docs_new/cookbook/autoregressive/NVIDIA/Nemotron3-Super.mdx @@ -0,0 +1,571 @@ +--- +title: NVIDIA Nemotron3-Super +metatags: + description: "Deploy NVIDIA Nemotron3-Super with SGLang - 120B hybrid MoE model (12B active) with 1M context window optimized for multi-agent systems and tool use." +--- + +import { Nemotron3SuperDeployment } from '/src/snippets/autoregressive/nemotron3-super-deployment.jsx'; + +## 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 +# Install from source +uv pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' + +# Or use Docker +docker pull lmsysorg/sglang:nightly-dev-20260310-0fd9a57d +``` + +For the full Docker setup and other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/installation). + +## 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. + + + +### 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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +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 +============ 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 +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 +python3 benchmark/gsm8k/bench_sglang.py --port 5000 +``` + +**Test Results:** +```text Output +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 +python3 benchmark/mmlu/bench_sglang.py --port 5000 +``` + +**Test Results:** +```text Output +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 +``` diff --git a/docs_new/cookbook/autoregressive/OpenAI/GPT-OSS.mdx b/docs_new/cookbook/autoregressive/OpenAI/GPT-OSS.mdx new file mode 100644 index 000000000..791316982 --- /dev/null +++ b/docs_new/cookbook/autoregressive/OpenAI/GPT-OSS.mdx @@ -0,0 +1,572 @@ +--- +title: GPT-OSS +metatags: + description: "Deploy GPT-OSS (20B/120B) with SGLang - configurable reasoning, full chain-of-thought, MXFP4 quantization for single GPU deployment." +--- + +## 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/installation) 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. + +import { GPTOSSDeployment } from "/src/snippets/autoregressive/gpt-oss-deployment.jsx"; + + + +### 3.2 Configuration Tips + +For more detailed configuration tips, please refer to [GPS-OSS Usage](../../../docs/basic_usage/gpt_oss). + +## 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 +python -m sglang.launch_server \ + --model openai/gpt-oss-120b \ + --reasoning-parser gpt-oss \ + --tp 8 +``` + +```python Example +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 +=============== 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 +python -m sglang.launch_server \ + --model openai/gpt-oss-120b \ + --tool-call-parser gpt-oss \ + --tp 8 +``` + +```python Example +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 +🔧 Tool Call: get_weather + Arguments: {"location": "Beijing", "unit": "celsius"} +``` + +**Python Example (with Thinking Process):** + +Start sglang server: + +```shell Command +python -m sglang.launch_server \ + --model openai/gpt-oss-120b \ + --reasoning-parser gpt-oss \ + --tool-call-parser gpt-oss \ + --tp 8 +``` + +```python Example +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 +=============== 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 +# 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!" +``` + +## 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 +python -m sglang.launch_server \ + --model openai/gpt-oss-120b \ + --tp 8 +``` + +- Test Command: + +```shell Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --num-prompt 100 \ + --max-concurrency 1 +``` + +- Test Results: + +```text Output +============ 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 +python -m sglang.launch_server \ + --model openai/gpt-oss-120b \ + --tp 8 +``` + +- Test Command: + +```shell Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --num-prompt 1000 \ + --max-concurrency 100 +``` + +**Test Results:** + +```text Output +============ 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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 --port 8000 +``` + +- **Results**: + + - GPT-OSS-120b + + ```text Output + Accuracy: 0.880 + Invalid: 0.005 + Latency: 5.262 s + Output throughput: 12143.675 token/s + ``` + + - GPT-OSS-20b + + ```text Output + Accuracy: 0.535 + Invalid: 0.165 + Latency: 4.157 s + Output throughput: 19589.165 token/s + ``` diff --git a/docs_new/cookbook/autoregressive/Qwen/Qwen2.5-VL.mdx b/docs_new/cookbook/autoregressive/Qwen/Qwen2.5-VL.mdx new file mode 100644 index 000000000..650e68791 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Qwen/Qwen2.5-VL.mdx @@ -0,0 +1,392 @@ +--- +title: Qwen2.5-VL +metatags: + description: "Deploy Qwen2.5-VL vision-language models with SGLang on AMD MI300X - available in 3B to 72B sizes with enhanced visual understanding." +--- + +import { Qwen25VLDeployment } from '/src/snippets/autoregressive/qwen25-vl-deployment.jsx'; + +## 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/installation) for installation instructions. + +## 3. Model Deployment + +This section provides deployment configurations optimized for AMD MI300X, MI325X and MI355X 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. + +**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and model size. + + + +### 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. + +## 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 +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 +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 +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 +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 +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 +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 +python -m sglang.launch_server \ + --model Qwen/Qwen2.5-VL-72B-Instruct \ + --tp 8 \ + --host 0.0.0.0 \ + --port 30000 +``` +- Result: +```text Output +============ 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 +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 +============ 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 +python3 benchmark/mmmu/bench_sglang.py \ + --port 30000 \ + --concurrency 64 +``` +```text Output +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 +``` diff --git a/docs_new/cookbook/autoregressive/Qwen/Qwen3-Coder-Next.mdx b/docs_new/cookbook/autoregressive/Qwen/Qwen3-Coder-Next.mdx new file mode 100644 index 000000000..9016a2bd9 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Qwen/Qwen3-Coder-Next.mdx @@ -0,0 +1,902 @@ +--- +title: Qwen3-Coder-Next +metatags: + description: "Deploy Qwen3-Coder-Next code-focused models with SGLang on AMD MI300X - available in 3B to 80B sizes with enhanced code understanding." +--- + +import { Qwen3CoderNextDeployment } from '/src/snippets/autoregressive/qwen3-coder-next-deployment.jsx'; + +## 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/installation) for installation instructions. + +**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. + + + +### 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-scheduler-strategy`: + - **V1 (`no_buffer`)**: Default. No overlap scheduler, lower memory usage. + - **V2 (`extra_buffer`)**: Enables overlap scheduling and branching point caching with `--mamba-scheduler-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). + +## 4. Model Invocation + +**Deployment Command:** + +```shell Command +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 +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 +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 +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 +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 +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 +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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python benchmark/gsm8k/bench_sglang.py --port 30000 +``` + +- **Test Results:** + +```text Output +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 +cd benchmark/mmlu +bash download_data.sh +python3 bench_sglang.py --port 30000 +``` + +- **Test Results:** + +```text Output +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 +``` diff --git a/docs_new/cookbook/autoregressive/Qwen/Qwen3-Coder.mdx b/docs_new/cookbook/autoregressive/Qwen/Qwen3-Coder.mdx new file mode 100644 index 000000000..c02d69088 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Qwen/Qwen3-Coder.mdx @@ -0,0 +1,520 @@ +--- +title: Qwen3-Coder +metatags: + description: "Deploy Qwen3-Coder(480B, 30B) MoE coding model with SGLang on AMD MI300X (MI325X, MI355X)" +--- + +import { Qwen3CoderDeployment } from '/src/snippets/autoregressive/qwen3-coder-deployment.jsx'; + +## 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/installation) for installation instructions. + +## 3. Model Deployment + +This section provides deployment configurations verified on AMD MI300X, MI325X, MI355X and NVIDIA B200, GB200 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. + + + +### 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):** +* **MOE Runner Backend**: FP8 uses `--moe-runner-backend triton`, NVFP4 uses `--moe-runner-backend flashinfer_cutlass`. +* **NVFP4 Quantization**: Requires `--quantization modelopt_fp4` and uses a different model path (`nvidia/Qwen3-Coder-...`). +* **DP Attention**: NVFP4 configuration supports `--enable-dp-attention` for improved throughput. + +**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 +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 +```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 +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 +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 +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 Standard Scenario Benchmark + +- Model Deployment Command: + +```shell Command +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 +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 +============ 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 +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 +============ 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 +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 +============ 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.2 Accuracy Benchmark + +#### 5.2.1 GSM8K Benchmark + +- **Benchmark Command:** + +```shell Command +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 +``` + +##### 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](#31-configuration). + + - Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8 (tp=8, ep=2) + ``` + Accuracy: 0.950 + Invalid: 0.000 + Latency: 12.914 s + Output throughput: 2065.515 token/s + ``` + + - nvidia/Qwen3-Coder-480B-A35B-Instruct-NVFP (NVFP4, tp=8, ep=1) + ``` + Accuracy: 0.970 + Invalid: 0.000 + Latency: 71.280 s + Output throughput: 390.080 token/s + ``` diff --git a/docs_new/cookbook/autoregressive/Qwen/Qwen3-Next.mdx b/docs_new/cookbook/autoregressive/Qwen/Qwen3-Next.mdx new file mode 100644 index 000000000..44f91fbfe --- /dev/null +++ b/docs_new/cookbook/autoregressive/Qwen/Qwen3-Next.mdx @@ -0,0 +1,774 @@ +--- +title: Qwen3-Next +metatags: + description: "Deploy Qwen3-Next with SGLang - hybrid attention architecture supporting 262K context, 80B MoE with 3B active parameters, and multi-token prediction." +--- + +import { Qwen3NextDeployment } from '/src/snippets/autoregressive/qwen3-next-deployment.jsx'; + +## 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/installation) 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. + + + +### 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-scheduler-strategy`: + - **V1 (`no_buffer`)**: Default. No overlap scheduler, lower memory usage. + - **V2 (`extra_buffer`)**: Enables overlap scheduling and branching point caching with `--mamba-scheduler-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). + +## 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 +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 +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 +=============== 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 +python -m sglang.launch_server \ + --model Qwen/Qwen3-Next-80B-A3B-Instruct \ + --tp 8 \ + --host 0.0.0.0 \ + --port 8000 +``` + +```python Example +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 +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 +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 +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 + +{"name": "get_weather", "arguments": {"location": "Beijing"}} + +``` + +**Python Example (with Thinking Process):** + +Start sglang server: + +```shell Command +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 +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 +=============== 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 +# 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 +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 +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 + +``` + +## 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 +python -m sglang.launch_server \ + --model Qwen/Qwen3-Next-80B-A3B-Instruct \ + --tp 8 +``` + +- Test Command: + +```shell Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --num-prompt 100 \ + --max-concurrency 1 +``` + +- Test Results: + +```text Output +============ 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 +python -m sglang.launch_server \ + --model Qwen/Qwen3-Next-80B-A3B-Instruct \ + --tp 8 \ +``` + +- Test Command: + +```shell Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --num-prompt 1000 \ + --max-concurrency 100 +``` + +**Test Results:** + +```text Output +============ 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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 --port 8000 +``` + +- **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 +cd sglang +bash benchmark/mmlu/download_data.sh +python3 benchmark/mmlu/bench_sglang.py --nsub 10 +``` + +- **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 + ``` diff --git a/docs_new/cookbook/autoregressive/Qwen/Qwen3-VL.mdx b/docs_new/cookbook/autoregressive/Qwen/Qwen3-VL.mdx new file mode 100644 index 000000000..8e7588fe9 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Qwen/Qwen3-VL.mdx @@ -0,0 +1,777 @@ +--- +title: Qwen3-VL +metatags: + description: "Deploy Qwen3-VL vision-language models with SGLang - open model for text, 262K context, enhanced visual reasoning and agent capabilities." +--- + + +## 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/installation) 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-VL series offers models in various sizes and architectures, optimized for different hardware platforms including NVIDIA and AMD GPUs. 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. + +import { Qwen3VLDeployment } from "/src/snippets/autoregressive/qwen3-vl-deployment.jsx"; + + + +### 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). + +## 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 +import time +from openai import OpenAI + +client = OpenAI( + api_key="EMPTY", + base_url="http://localhost:8000/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 +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 +import time +from openai import OpenAI + +client = OpenAI( + api_key="EMPTY", + base_url="http://localhost:8000/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 +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 +import time +from openai import OpenAI + +client = OpenAI( + api_key="EMPTY", + base_url="http://localhost:8000/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 +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 +python -m sglang.launch_server \ + --model Qwen/Qwen3-VL-235B-A22B-Thinking \ + --reasoning-parser qwen3 \ + --tp 8 \ + --host 0.0.0.0 \ + --port 8000 +``` + +**Streaming with Thinking Process:** + +```python Example +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-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 +=============== 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 +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 8000 +``` + +**Python Example (with Thinking Process):** + +```python Example +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-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 +=============== 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 +# 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 +python -m sglang.launch_server \ + --model Qwen/Qwen3-VL-235B-A22B-Instruct \ + --tp 8 \ + --host 0.0.0.0 \ + --port 8000 +``` + +- Benchmark Command: + +```shell Command +python3 -m sglang.bench_serving \ + --backend sglang-oai-chat \ + --host 127.0.0.1 \ + --port 8000 \ + --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 +============ 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 +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 8000 +``` + +- Benchmark Command: + +```shell Command +python3 -m sglang.bench_serving \ + --backend sglang-oai-chat \ + --host 127.0.0.1 \ + --port 8000 \ + --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 +============ 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 +python -m sglang.launch_server \ + --model Qwen/Qwen3-VL-235B-A22B-Instruct \ + --tp 8 \ + --host 0.0.0.0 \ + --port 8000 +``` + +- Benchmark Command: + +```shell Command +python3 -m sglang.bench_serving \ + --backend sglang-oai-chat \ + --host 127.0.0.1 \ + --port 8000 \ + --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 +============ 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 +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:8000/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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TasksVersionFiltern-shotMetricValueStderr
mmmu_val0none0mmmu_acc0.6567±N/A
+``` diff --git a/docs_new/cookbook/autoregressive/Qwen/Qwen3.5.mdx b/docs_new/cookbook/autoregressive/Qwen/Qwen3.5.mdx new file mode 100644 index 000000000..3f8349fde --- /dev/null +++ b/docs_new/cookbook/autoregressive/Qwen/Qwen3.5.mdx @@ -0,0 +1,1001 @@ +--- +title: Qwen3.5 +metatags: + description: "Deploy Qwen3.5 with SGLang - flagship Qwen model with unified vision-language foundation, hybrid architecture, and scalable reasoning." +--- + +import { Qwen35Deployment } from '/src/snippets/autoregressive/qwen35-deployment.jsx' + +## 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. + +**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:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelBF16 (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/Qwen3.5-397B-A17B-NVFP4](https://huggingface.co/nvidia/Qwen3.5-397B-A17B-NVFP4)
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 +# Install from source +uv pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' + +# Or use Docker (NVIDIA GPUs) +docker pull lmsysorg/sglang:nightly-dev-20260216-d3bae71e + +# Or use Docker (AMD MI300X/MI325X) +docker pull lmsysorg/sglang:v0.5.9-rocm720-mi30x + +# Or use Docker (AMD MI355X) +docker pull lmsysorg/sglang:v0.5.9-rocm720-mi35x +``` + +For the full Docker setup and other installation methods, please refer to the [official SGLang installation guide](../../../docs/get-started/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 and capabilities. + + + +### 3.2 Configuration Tips + +- Speculative decoding (MTP) can significantly reduce latency for interactive use cases. +- **Mamba Radix Cache**: Qwen3.5's hybrid Gated Delta Networks architecture supports two mamba scheduling strategies via `--mamba-scheduler-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-scheduler-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. +- 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. Only compatible with B200/B300 (Blackwell architecture). + - **B200 (183GB)** runs with tp=4. + - **B300 (275GB)** runs with tp=2. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HardwareMemoryBF16 TPFP8 TPFP4 TP
H10080GB168N/A
H200141GB84N/A
B200183GB844
B300275GB422
MI300X192GB84N/A
MI325X256GB42N/A
MI355X288GB42N/A
+ + +**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 not included in the generated commands above; add it manually only if memory constraints require the trade-off. + + +## 4. Model Invocation + +**NVIDIA:** + +Deploy Qwen3.5-397B-A17B with the following command (H200, all features enabled): + +```shell Command +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 +sglang serve \ + --model-path Qwen/Qwen3.5-397B-A17B \ + --tp 8 \ + --reasoning-parser qwen3 \ + --tool-call-parser qwen3_coder \ + --mem-fraction-static 0.8 \ + --attention-backend triton \ + --host 0.0.0.0 \ + --port 30000 +``` +> **Note:** TP8 works on all MI GPUs. For MI325X/MI355X, you can use --tp 4 as the minimum requirement. + +### 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 +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 +=============== 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 +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 +=============== 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 +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 +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 +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 +=============== 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: } +``` + +## 5. Benchmark + +### 5.1 Accuracy Benchmark + +#### 5.1.1 GSM8K Benchmark + +- Benchmark Command +```bash Command +python3 benchmark/gsm8k/bench_sglang.py --port 30000 +``` + +- Test Result +```text Output +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 MMMU Benchmark + +- Benchmark Command +```bash Command +python3 benchmark/mmmu/bench_sglang.py --concurrency 128 --port 30000 --max-new-tokens 512 +``` + +- Test Result +```text Output +{'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 +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.3.1 Latency Benchmark + +```bash Command +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 +============ 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.3.2 Throughput Benchmark + +```bash Command +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 +============ 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 +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 +TODO +``` + +#### 5.3.2 Throughput Benchmark + +```bash Command +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 +TODO +``` diff --git a/docs_new/cookbook/autoregressive/Qwen/Qwen3.6.mdx b/docs_new/cookbook/autoregressive/Qwen/Qwen3.6.mdx new file mode 100644 index 000000000..ebf49b82d --- /dev/null +++ b/docs_new/cookbook/autoregressive/Qwen/Qwen3.6.mdx @@ -0,0 +1,471 @@ +--- +title: Qwen3.6 +metatags: + description: "Deploy Qwen3.6 with SGLang - open-weight 35B MoE multimodal model with 3B active parameters, thinking preservation, tool calling, MTP, and long-context support." +tag: NEW +--- + +import { Qwen36Deployment } from '/src/snippets/autoregressive/qwen36-deployment.jsx'; + +## 1. Model Introduction + +[Qwen3.6-35B-A3B](https://huggingface.co/Qwen/Qwen3.6-35B-A3B) is the first open-weight variant of the Qwen3.6 series 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. + +Qwen3.6 features a Gated Delta Networks combined with sparse Mixture-of-Experts architecture (35B total parameters, 3B activated), supporting multimodal inputs (text, image, video) and natively handles 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 + sparse MoE (35B total / 3B 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 +- **Multimodal**: Unified vision-language model supporting text, image, and video inputs + +**Available Models:** + + + + + + + + + + + + + + + + + + +
ModelWeights
Qwen3.6-35B-A3B (BF16)[Qwen/Qwen3.6-35B-A3B](https://huggingface.co/Qwen/Qwen3.6-35B-A3B)
Qwen3.6-35B-A3B (FP8)[Qwen/Qwen3.6-35B-A3B-FP8](https://huggingface.co/Qwen/Qwen3.6-35B-A3B-FP8)
+ +**License:** Apache 2.0 + +## 2. SGLang Installation + +SGLang `>=0.5.10` is required for Qwen3.6. You can install from source or use a Docker image: + +```bash Command +# Install from PyPI +uv pip install "sglang[all]" + +# Or install from source +uv pip install 'git+https://github.com/sgl-project/sglang.git#subdirectory=python' + +# Or use Docker (NVIDIA GPUs) +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/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 and capabilities. + + + + +### 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-scheduler-strategy`: + - **V1 (`no_buffer`)**: Default. No overlap scheduler, lower memory usage. + - **V2 (`extra_buffer`)**: Enables overlap scheduling and branching point caching with `--mamba-scheduler-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. +- For processing large images or videos, you may need to lower `--mem-fraction-static` to leave room for image feature tensors. +- Hardware requirements: + - **BF16**: ~35B parameters require ~70GB of GPU memory for weights. TP=1 fits on all supported hardware. + - **FP8**: The FP8 quantized model requires ~35GB for weights. TP=1 fits on all supported hardware. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
HardwareMemoryBF16 TPFP8 TP
H10080GB11
H200141GB11
B200183GB11
+ + +## 4. Model Invocation + +Deploy Qwen3.6-35B-A3B with the following command (H200, all features enabled): + +```shell Command +SGLANG_ENABLE_SPEC_V2=1 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 +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 +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 +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 +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 +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 +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() +``` diff --git a/docs_new/cookbook/autoregressive/Qwen/Qwen3.mdx b/docs_new/cookbook/autoregressive/Qwen/Qwen3.mdx new file mode 100644 index 000000000..74b5684f0 --- /dev/null +++ b/docs_new/cookbook/autoregressive/Qwen/Qwen3.mdx @@ -0,0 +1,884 @@ +--- +title: Qwen3 +metatags: + description: "Deploy Qwen3 series models with SGLang - featuring advanced reasoning, 256K context, and flexible Dense/MoE architectures for edge to cloud." +--- + + +## 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/installation) 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 and AMD GPUs. 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. + +import { Qwen3Deployment } from "/src/snippets/autoregressive/qwen3-deployment.jsx"; + + + +### 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). +- **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). + +## 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 +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 +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 +=============== 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 +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 +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 +=============== 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 +# 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 +python -m sglang.launch_server \ + --model Qwen/Qwen3-235B-A22B-Instruct-2507 \ + --tp 8 +``` + +##### 5.1.1.1 Low Concurrency + +- Benchmark Command: + +```shell Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +python -m sglang.launch_server \ + --model Qwen/Qwen3-235B-A22B-Instruct-2507 \ + --tp 8 +``` + +##### 5.1.2.1 Low Concurrency + +- Benchmark Command: + +```shell Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 +``` + +- **Results**: + + - Qwen/Qwen3-235B-A22B-Instruct-2507 + ```text Output + Accuracy: 0.945 + Invalid: 0.000 + Latency: 11.980 s + Output throughput: 2358.105 token/s + ``` diff --git a/docs_new/cookbook/autoregressive/StepFun/Step3-VL-10B.mdx b/docs_new/cookbook/autoregressive/StepFun/Step3-VL-10B.mdx new file mode 100644 index 000000000..6cf33cb52 --- /dev/null +++ b/docs_new/cookbook/autoregressive/StepFun/Step3-VL-10B.mdx @@ -0,0 +1,695 @@ +--- +title: Step3-VL-10B +metatags: + description: "Deploy Step3-VL-10B multimodal model with SGLang - compact 10B dense model with frontier-level vision understanding, complex reasoning, and tool calling capabilities." +tag: NEW +--- + +import { Step3VL10BDeployment } from '/src/snippets/autoregressive/step-3vl-10b-deployment.jsx'; + +## 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/installation) 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. + + + +### 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 +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 +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 +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 +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 +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 +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 +=============== 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 +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 +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 +=============== 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 +# 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 +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 +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 +============ 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 +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 +============ 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 +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 +python3 benchmark/mmmu/bench_sglang.py \ + --port 30000 \ + --concurrency 64 +``` + +- Result: + +```text Output +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 +``` diff --git a/docs_new/cookbook/autoregressive/StepFun/Step3.5.mdx b/docs_new/cookbook/autoregressive/StepFun/Step3.5.mdx new file mode 100644 index 000000000..edb98a7e5 --- /dev/null +++ b/docs_new/cookbook/autoregressive/StepFun/Step3.5.mdx @@ -0,0 +1,529 @@ +--- +title: Step-3.5 +metatags: + description: "Deploy Step-3.5 reasoning engine with SGLang. " +tag: NEW +--- + +import { Step35Deployment } from '/src/snippets/autoregressive/step-35-deployment.jsx'; + +## 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 +# Pull the docker image +docker pull lmsysorg/sglang:dev-pr-18084 + +# Launch the container +docker run -it --gpus all \ + --shm-size=32g \ + --ipc=host \ + --network=host \ + lmsysorg/sglang:dev-pr-18084 bash +``` + +### Docker (AMD ROCm) +```bash Command +# 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. + + + +### 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 +sglang serve \ + --model-path stepfun-ai/Step-3.5-Flash \ + --tp 4 \ + --ep 4 \ + --reasoning-parser step3p5 +``` + +```python Example +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 +=============== 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 +sglang serve \ + --model-path stepfun-ai/Step-3.5-Flash \ + --tp 4 \ + --ep 4 \ + --reasoning-parser step3p5 \ + --tool-call-parser step3p5 +``` + +```python Example +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 +--- 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 +sglang serve \ + --model-path stepfun-ai/Step-3.5-Flash \ + --tp 4 \ + --ep 4 +``` + +##### 5.1.1.1 Low Concurrency + +- Benchmark Command: + +```shell Command +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 +============ 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 +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 +============ 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 +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 +============ 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 +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 +``` + +- **Results**: + + - Step-3.5-Flash + ``` + Accuracy: 0.885 + Invalid: 0.005 + Latency: 9.986 s + Output throughput: 1972.911 token/s + ``` diff --git a/docs_new/cookbook/autoregressive/Xiaomi/MiMo-V2-Flash.mdx b/docs_new/cookbook/autoregressive/Xiaomi/MiMo-V2-Flash.mdx new file mode 100644 index 000000000..3823ba0eb --- /dev/null +++ b/docs_new/cookbook/autoregressive/Xiaomi/MiMo-V2-Flash.mdx @@ -0,0 +1,106 @@ +--- +title: MiMo-V2-Flash +metatags: + description: "Deploy MiMo-V2-Flash 309B MoE model with SGLang - hybrid attention, multi-token prediction, and 256K context for efficient inference." +--- + +## 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 +# Pull the docker image +docker pull lmsysorg/sglang:dev-pr-15207 + +# Launch the container +docker run -it --gpus all \ + --shm-size=32g \ + --ipc=host \ + --network=host \ + lmsysorg/sglang:dev-pr-15207 bash +``` + +### Pip Installation + +```bash Command +# 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:nightly-dev-20251215-4449c170 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. + +import { MiMoV2FlashDeployment } from "/src/snippets/autoregressive/mimo-v2-flash-deployment.jsx"; + + + +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 +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 +{ + "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`. diff --git a/docs_new/cookbook/autoregressive/intro.mdx b/docs_new/cookbook/autoregressive/intro.mdx new file mode 100644 index 000000000..896a8f563 --- /dev/null +++ b/docs_new/cookbook/autoregressive/intro.mdx @@ -0,0 +1,118 @@ +--- +title: Overview +mode: wide +description: Practical guides for deploying and using large language models and vision language models with SGLang. +metatags: + description: "Explore SGLang autoregressive model cookbooks for LLM and VLM deployment, invocation, optimization, and benchmarking examples." +--- + + + + + + + + + + + + + + + + + + + + + diff --git a/docs_new/cookbook/base/benchmarks/autoregressive_model_benchmark.mdx b/docs_new/cookbook/base/benchmarks/autoregressive_model_benchmark.mdx new file mode 100644 index 000000000..6d04c632f --- /dev/null +++ b/docs_new/cookbook/base/benchmarks/autoregressive_model_benchmark.mdx @@ -0,0 +1,287 @@ +--- +title: Autoregressive Model Benchmark Documentation +metatags: + description: "Benchmark LLM and VLM serving throughput and latency with sglang.bench_serving - supports SGLang, vLLM, and multiple datasets." +--- + +`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 +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 +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. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescription
`--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. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescription
`--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. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescription
`--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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescription
`--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. diff --git a/docs_new/cookbook/base/benchmarks/diffusion_model_benchmark.mdx b/docs_new/cookbook/base/benchmarks/diffusion_model_benchmark.mdx new file mode 100644 index 000000000..4c8e7a092 --- /dev/null +++ b/docs_new/cookbook/base/benchmarks/diffusion_model_benchmark.mdx @@ -0,0 +1,235 @@ +--- +title: Diffusion Models Benchmark Documentation +metatags: + description: "Benchmark diffusion model serving throughput and latency with SGLang - supports image and video generation with flexible configurations." +--- + +`sglang.multimodal_gen.benchmarks.bench_serving` is a command-line tool designed to benchmark the online serving throughput and latency of Diffusion Models. It supports two backends (`sglang-image`, `sglang-video`) 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 +# For text to video: such as Wan2.2-T2V-A14B-Diffusers +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-video --dataset vbench --task t2v --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 \ + --backend sglang-video --dataset vbench --task i2v --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 \ + --backend sglang-video --dataset vbench --task ti2v --num-prompts 1 --max-concurrency 1 + +# For text to image: such as Qwen-Image +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task t2i --num-prompts 1 --max-concurrency 1 + +# For image-text to image: such as Qwen-Image-Edit +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task ti2i --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 +# For text to video: such as Wan2.2-T2V-A14B-Diffusers +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-video --dataset vbench --task t2v --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 \ + --backend sglang-video --dataset vbench --task i2v --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 \ + --backend sglang-video --dataset vbench --task ti2v --num-prompts 20 --max-concurrency 20 + +# For text to image: such as Qwen-Image +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task t2i --num-prompts 20 --max-concurrency 20 + +# For image-text to image: such as Qwen-Image-Edit +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task ti2i --num-prompts 20 --max-concurrency 20 +``` + +## 2. Parameter Reference + +### 2.1 Connection & Backend Settings + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultDescription
`--backend`**Required**The backend type to use. Choices: `sglang-image`, `sglang-video`.
`--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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentChoicesDescription
`--task``t2v`, `i2v`, `ti2v`, `t2i`, `ti2i`Defines the generation task: `t2v` (Text-to-Video), `i2v` (Image-to-Video), `ti2v` (Text+Image-to-Video), `t2i` (Text-to-image), `ti2i` (Text+Image-to-Image).
`--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 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescription
`--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 + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescription
`--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 + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescription
`--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 diff --git a/docs_new/cookbook/base/reference/server_arguments.mdx b/docs_new/cookbook/base/reference/server_arguments.mdx new file mode 100644 index 000000000..737a1b35f --- /dev/null +++ b/docs_new/cookbook/base/reference/server_arguments.mdx @@ -0,0 +1,46 @@ +--- +title: Server Arguments +metatags: + description: "SGLang server CLI arguments reference - tensor parallelism, data parallelism, expert parallelism, and configuration options." +--- + +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 FieldSGLang CLI ArgumentDescription
`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
`enable_dp_attention``--enable-dp-attention`DP for attention, TP for FFN (hybrid)
diff --git a/docs_new/cookbook/diffusion/FLUX/FLUX.mdx b/docs_new/cookbook/diffusion/FLUX/FLUX.mdx new file mode 100644 index 000000000..ada4058ab --- /dev/null +++ b/docs_new/cookbook/diffusion/FLUX/FLUX.mdx @@ -0,0 +1,294 @@ +--- +title: FLUX +metatags: + description: "Deploy FLUX diffusion models with SGLang - 12B/32B rectified flow transformers for high-quality text-to-image generation." +--- + +import { FluxDeployment } from '/src/snippets/diffusion/flux-deployment.jsx'; + +## 1. Model Introduction + +[FLUX](https://blackforestlabs.ai/) is a family of rectified flow transformer models developed by Black Forest Labs for high-quality image generation from text descriptions. + +[FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) is a 12 billion parameter rectified flow transformer capable of generating images from text descriptions. + +**Key Features:** + +- **Cutting-edge Output Quality**: Second only to the state-of-the-art FLUX.1 [pro] model +- **Competitive Prompt Following**: Matches the performance of closed-source alternatives +- **Guidance Distillation**: Trained using guidance distillation for improved efficiency +- **Open Weights**: Available for personal, scientific, and commercial purposes under the FLUX [dev] Non-Commercial License + +[FLUX.2-dev](https://huggingface.co/black-forest-labs/FLUX.2-dev) is a 32 billion parameter rectified flow transformer capable of generating, editing, and combining images based on text instructions. + +**Key Features:** + +- **State-of-the-art Performance**: Leading open model in text-to-image generation, single-reference editing, and multi-reference editing +- **No Finetuning Required**: Character, object, and style reference without additional training in one model +- **Guidance Distillation**: Trained using guidance distillation for improved efficiency +- **Open Weights**: Available for personal, scientific, and commercial purposes under the FLUX [dev] Non-Commercial License + +For more details, please refer to the [FLUX.1-dev HuggingFace page](https://huggingface.co/black-forest-labs/FLUX.1-dev), [FLUX.2-dev HuggingFace page](https://huggingface.co/black-forest-labs/FLUX.2-dev), and the [official blog post](https://blackforestlabs.ai/announcing-black-forest-labs/). + +## 2. SGLang-diffusion Installation + +SGLang-diffusion 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-diffusion installation guide](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/install.md) for installation instructions. + +## 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. + +**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform and model version. SGLang supports serving FLUX on NVIDIA B200, H200, H100, and AMD MI355X, MI325X, MI300X GPUs. + + + +### 3.2 Configuration Tips + +Current supported optimization all listed [here](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/support_matrix.md). + +- `--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 + +## 4. API Usage + +For complete API documentation, please refer to the [official API usage guide](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/openai_api.md). + +### 4.1 Generate an Image + +```python Example +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](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/cache_dit.md). + +**Basic Usage** + +```bash Command +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: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Fn`SGLANG_CACHE_DIT_FN`1Number of first blocks to always compute
Bn`SGLANG_CACHE_DIT_BN`0Number of last blocks to always compute
W`SGLANG_CACHE_DIT_WARMUP`4Warmup steps before caching starts
R`SGLANG_CACHE_DIT_RDT`0.24Residual difference threshold
MC`SGLANG_CACHE_DIT_MC`3Maximum continuous cached steps
+- TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Enable`SGLANG_CACHE_DIT_TAYLORSEER`falseEnable TaylorSeer calibrator
Order`SGLANG_CACHE_DIT_TS_ORDER`1Taylor expansion order (1 or 2)
+ + Combined Configuration Example: + +```bash Command +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". + +## 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 + +**Server Command**: + +```shell Command +sglang serve --model-path black-forest-labs/FLUX.1-dev --port 30000 +``` + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-video --dataset vbench --task t2v --num-prompts 1 --max-concurrency 1 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Backend: sglang-image +Model: black-forest-labs/FLUX.1-dev +Dataset: vbench +Task: t2v +-------------------------------------------------- +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 +============================================================ +``` + +#### 5.1.2 Generate images with high concurrency + +**Server Command** : + +```shell Command +sglang serve --model-path black-forest-labs/FLUX.1-dev --port 30000 +``` + +**Benchmark Command** : + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task t2v --num-prompts 20 --max-concurrency 20 +``` + +**Result** : + +```text Output +================= Serving Benchmark Result ================= +Backend: sglang-image +Model: black-forest-labs/FLUX.1-dev +Dataset: vbench +Task: t2v +-------------------------------------------------- +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 +============================================================ +``` diff --git a/docs_new/cookbook/diffusion/MOVA/MOVA.mdx b/docs_new/cookbook/diffusion/MOVA/MOVA.mdx new file mode 100644 index 000000000..8f7235b82 --- /dev/null +++ b/docs_new/cookbook/diffusion/MOVA/MOVA.mdx @@ -0,0 +1,268 @@ +--- +title: MOVA +metatags: + description: "Deploy MOVA with SGLang - simultaneous video and audio generation with asymmetric dual-tower architecture, precise lip-sync, and environment-aware sound effects." +--- + +## 1. Model Introduction + +[MOVA](https://github.com/OpenMOSS/MOVA) (MOSS Video and Audio) is a foundation model developed by the SII-OpenMOSS Team, designed to break the "silent era" of open-source video generation. Unlike cascaded pipelines that generate sound as an afterthought, MOVA synthesizes video and audio simultaneously in a single inference pass for perfect alignment. It adopts an Asymmetric Dual-Tower Architecture, fusing pre-trained video and audio towers through a bidirectional cross-attention mechanism to maintain tight synchronization between video and audio during generation. + +[MOVA-360p](https://huggingface.co/OpenMOSS-Team/MOVA-360p) is suitable for fast inference and resource-constrained environments. [MOVA-720p](https://huggingface.co/OpenMOSS-Team/MOVA-720p) provides higher resolution video generation. Both versions support generating up to 8 seconds of video-audio content. + +**Key Features:** + +- **Native Bimodal Generation**: Generates high-fidelity video and synchronized audio in a single inference pass, eliminating error accumulation from cascaded pipelines +- **Precise Lip-Sync**: Achieves state-of-the-art performance in multilingual lip-synchronization (LSE-D: 7.094, LSE-C: 7.452 with Dual CFG on Verse-Bench Set3) +- **Environment-Aware Sound Effects**: Generates corresponding environmental sound effects including physical interaction sounds, ambient sounds, and spatial/textural sound feedback +- **Fully Open-Source**: Model weights, inference code, training pipelines, and LoRA fine-tuning scripts are all open-sourced + +For more details, please refer to the [MOVA-360p HuggingFace page](https://huggingface.co/OpenMOSS-Team/MOVA-360p), the [MOVA-720p HuggingFace page](https://huggingface.co/OpenMOSS-Team/MOVA-720p), the [GitHub repository](https://github.com/OpenMOSS/MOVA), and the [technical report (arXiv)](https://arxiv.org/abs/2602.08794). + +## 2. SGLang-diffusion Installation + +SGLang-diffusion 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-diffusion installation guide](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/install.md) for installation instructions. + +## 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. + +**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform. + +import { MOVADeployment } from '/src/snippets/diffusion/mova-deployment.jsx' + + + +### 3.2 Configuration Tips + +Current supported optimization all listed [here](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/support_matrix.md). + +- `--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](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/openai_api.md). + +### 4.1 CLI Generation (sglang generate) + +```bash Command +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 +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](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/cache_dit.md). + +**Basic Usage** + +```bash Command +SGLANG_CACHE_DIT_ENABLED=true sglang serve --model-path OpenMOSS-Team/MOVA-720p +``` + +**Advanced Usage** + +- DBCache Parameters: DBCache controls block-level caching behavior: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Fn`SGLANG_CACHE_DIT_FN`1Number of first blocks to always compute
Bn`SGLANG_CACHE_DIT_BN`0Number of last blocks to always compute
W`SGLANG_CACHE_DIT_WARMUP`4Warmup steps before caching starts
R`SGLANG_CACHE_DIT_RDT`0.24Residual difference threshold
MC`SGLANG_CACHE_DIT_MC`3Maximum continuous cached steps
+ +- TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion: + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Enable`SGLANG_CACHE_DIT_TAYLORSEER`falseEnable TaylorSeer calibrator
Order`SGLANG_CACHE_DIT_TS_ORDER`1Taylor expansion order (1 or 2)
+ + Combined Configuration Example: + +```bash Command +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 +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 +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 +================= 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 +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 +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --task image-to-video --dataset vbench --num-prompts 20 --max-concurrency 20 \ + --port 30002 +``` diff --git a/docs_new/cookbook/diffusion/Qwen-Image/Qwen-Image-Edit.mdx b/docs_new/cookbook/diffusion/Qwen-Image/Qwen-Image-Edit.mdx new file mode 100644 index 000000000..d833289e2 --- /dev/null +++ b/docs_new/cookbook/diffusion/Qwen-Image/Qwen-Image-Edit.mdx @@ -0,0 +1,280 @@ +--- +title: Qwen-Image-Edit-2511 +metatags: + description: "Deploy Qwen-Image-Edit-2511 with SGLang - 20B image editing model with text rendering, character consistency, and geometric reasoning." +--- + +import { QwenImageEditDeployment } from '/src/snippets/diffusion/qwen-image-edit-deployment.jsx'; + +## 1. Model Introduction + +[Qwen-Image-Edit-2511](https://huggingface.co/Qwen/Qwen-Image-Edit-2511) is an enhanced version over Qwen-Image-Edit-2509, featuring multiple improvements—including notably better consistency. Built upon the 20B Qwen-Image model, Qwen-Image-Edit-2511 successfully extends Qwen-Image's unique text rendering capabilities to image editing tasks, enabling precise text editing. + +Key Enhancements in Qwen-Image-Edit-2511: + +- **Mitigate Image Drift**: Reduces unwanted changes in non-edited regions of the image. +- **Improved Character Consistency**: The model can perform imaginative edits based on an input portrait while preserving the identity and visual characteristics of the subject. +- **Multi-Person Consistency**: Enhanced consistency in multi-person group photos, enabling high-fidelity fusion of two separate person images into a coherent group shot. +- **Integrated LoRA Capabilities**: Selected popular community-created LoRAs are integrated directly into the base model, unlocking their effects without extra tuning (e.g., lighting enhancement, viewpoint generation). +- **Enhanced Industrial Design Generation**: Special attention to practical engineering scenarios, including batch industrial product design and material replacement for industrial components. +- **Strengthened Geometric Reasoning**: Stronger geometric reasoning capability for generating auxiliary construction lines for design or annotation purposes. + +For more details, please refer to the [official Qwen-Image-Edit-2511 HuggingFace page](https://huggingface.co/Qwen/Qwen-Image-Edit-2511), the [Blog](https://qwenlm.github.io/blog/qwen-image-edit-2511/), and the [Tech Report](https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/Qwen_Image.pdf). + +## 2. SGLang-diffusion Installation + +SGLang-diffusion 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-diffusion installation guide](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/install.md) for installation instructions. + +## 3. Model Deployment + +This section provides deployment configurations optimized for different hardware platforms and use cases. + +### 3.1 Basic Configuration + +Qwen-Image-Edit-2511 is a 20B parameter model optimized for image editing tasks. The recommended launch configurations vary by hardware. + +**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform. + + + +### 3.2 Configuration Tips + +Current supported optimization all listed [here](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/support_matrix.md). + +- `--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 + +## 4. API Usage + +For complete API documentation, please refer to the [official API usage guide](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/openai_api.md). + +### 4.1 Edit an Image + +```python Example +import base64 +from openai import OpenAI + +client = OpenAI(api_key="EMPTY", base_url="http://localhost:3000/v1") + +response = client.images.edit( + model="Qwen/Qwen-Image-Edit-2511", + image=open("input.png", "rb"), + prompt="Change the color of the taxi to black.", + n=1, + response_format="b64_json", +) + +# Save the edited 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](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/cache_dit.md). + +**Basic Usage** + +```bash Command +SGLANG_CACHE_DIT_ENABLED=true sglang serve --model-path Qwen/Qwen-Image-Edit-2511 +``` + +**Advanced Usage** + +- DBCache Parameters: DBCache controls block-level caching behavior: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Fn`SGLANG_CACHE_DIT_FN`1Number of first blocks to always compute
Bn`SGLANG_CACHE_DIT_BN`0Number of last blocks to always compute
W`SGLANG_CACHE_DIT_WARMUP`4Warmup steps before caching starts
R`SGLANG_CACHE_DIT_RDT`0.24Residual difference threshold
MC`SGLANG_CACHE_DIT_MC`3Maximum continuous cached steps
+- TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Enable`SGLANG_CACHE_DIT_TAYLORSEER`falseEnable TaylorSeer calibrator
Order`SGLANG_CACHE_DIT_TS_ORDER`1Taylor expansion order (1 or 2)
+ + Combined Configuration Example: + +```bash Command +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 Qwen/Qwen-Image-Edit-2511 +``` + +#### 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. +- `--image-encoder-cpu-offload`: Use CPU offload for image 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 + +Test Environment: + +- Hardware: NVIDIA B200 GPU (1x) +- Model: Qwen/Qwen-Image-Edit-2511 +- sglang diffusion version: 0.5.6.post2 + +### 5.1 Speedup Benchmark + +#### 5.1.1 Edit a image + +**Server Command**: + +```shell Command +sglang serve --model-path Qwen/Qwen-Image-Edit-2511 --port 30000 +``` + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task ti2i --num-prompts 1 --max-concurrency 1 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Backend: sglang-image +Model: Qwen/Qwen-Image-Edit-2511 +Dataset: vbench +Task: ti2i +-------------------------------------------------- +Benchmark duration (s): 35.31 +Request rate: inf +Max request concurrency: 1 +Successful requests: 1/1 +-------------------------------------------------- +Request throughput (req/s): 0.03 +Latency Mean (s): 35.3053 +Latency Median (s): 35.3053 +Latency P99 (s): 35.3053 +-------------------------------------------------- +Peak Memory Max (MB): 47959.35 +Peak Memory Mean (MB): 47959.35 +Peak Memory Median (MB): 47959.35 +============================================================ +``` + +#### 5.1.2 Edit a image with high concurrency + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task ti2i --num-prompts 20 --max-concurrency 20 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Backend: sglang-image +Model: Qwen/Qwen-Image-Edit-2511 +Dataset: vbench +Task: ti2i +-------------------------------------------------- +Benchmark duration (s): 286.11 +Request rate: inf +Max request concurrency: 20 +Successful requests: 20/20 +-------------------------------------------------- +Request throughput (req/s): 0.07 +Latency Mean (s): 150.0428 +Latency Median (s): 150.0600 +Latency P99 (s): 283.3843 +-------------------------------------------------- +Peak Memory Max (MB): 47971.82 +Peak Memory Mean (MB): 47971.49 +Peak Memory Median (MB): 47971.29 +============================================================ +``` diff --git a/docs_new/cookbook/diffusion/Qwen-Image/Qwen-Image.mdx b/docs_new/cookbook/diffusion/Qwen-Image/Qwen-Image.mdx new file mode 100644 index 000000000..84970ef9c --- /dev/null +++ b/docs_new/cookbook/diffusion/Qwen-Image/Qwen-Image.mdx @@ -0,0 +1,271 @@ +--- +title: Qwen-Image +metatags: + description: "Deploy Qwen-Image with SGLang - community contribution guide for Qwen's image generation model." +--- + +import { QwenImageDeployment } from '/src/snippets/diffusion/qwen-image-deployment.jsx'; + +## 1. Model Introduction + +[Qwen-Image](https://huggingface.co/Qwen/Qwen-Image) is a text-to-image diffusion model developed by the Qwen team. + +For more details, please refer to the [official Qwen-Image HuggingFace page](https://huggingface.co/Qwen/Qwen-Image), the [Blog](https://qwenlm.github.io/blog/qwen-image/), and the [Tech Report](https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/Qwen_Image.pdf). + +## 2. SGLang-diffusion Installation + +SGLang-diffusion 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-diffusion installation guide](../../../docs/sglang-diffusion/installation) for installation instructions. + +## 3. Model Deployment + +This section provides deployment configurations optimized for different hardware platforms and use cases. + +### 3.1 Basic Configuration + +Qwen-Image is a text-to-image model. The recommended launch configurations vary by hardware. + +**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform. + + + +### 3.2 Configuration Tips + +Current supported optimization all listed [here](../../../docs/sglang-diffusion/attention-backends#platform-support-matrix). + +- `--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 + +**AMD ROCm Notes**: Requires SGLang >= v0.5.8. + +## 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 +import base64 +from openai import OpenAI + +client = OpenAI(api_key="EMPTY", base_url="http://localhost:30000/v1") + +response = client.images.generate( + model="Qwen/Qwen-Image", + prompt="A logo With Bold Large text: SGL Diffusion", + 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 +SGLANG_CACHE_DIT_ENABLED=true sglang serve --model-path Qwen/Qwen-Image +``` + +**Advanced Usage** + +- DBCache Parameters: DBCache controls block-level caching behavior: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Fn`SGLANG_CACHE_DIT_FN`1Number of first blocks to always compute
Bn`SGLANG_CACHE_DIT_BN`0Number of last blocks to always compute
W`SGLANG_CACHE_DIT_WARMUP`4Warmup steps before caching starts
R`SGLANG_CACHE_DIT_RDT`0.24Residual difference threshold
MC`SGLANG_CACHE_DIT_MC`3Maximum continuous cached steps
+- TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Enable`SGLANG_CACHE_DIT_TAYLORSEER`falseEnable TaylorSeer calibrator
Order`SGLANG_CACHE_DIT_TS_ORDER`1Taylor expansion order (1 or 2)
+ + Combined Configuration Example: + +```bash Command +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 Qwen/Qwen-Image +``` + +#### 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". + +## 5. Benchmark + +Test Environment: + +- Hardware: AMD Instinct MI300X GPU (1x) +- Model: Qwen/Qwen-Image +- Docker Image: lmsysorg/sglang:v0.5.8-rocm700-mi30x +- sglang diffusion version: 0.5.8 + +### 5.1 Speedup Benchmark + +#### 5.1.1 Generate an image + +**Server Command**: + +```shell Command +sglang serve --model-path Qwen/Qwen-Image \ + --ulysses-degree=1 --ring-degree=1 --port 30000 +``` + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task text-to-image --num-prompts 1 --max-concurrency 1 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Task: text-to-image +Model: Qwen/Qwen-Image +Dataset: vbench +-------------------------------------------------- +Benchmark duration (s): 29.04 +Request rate: inf +Max request concurrency: 1 +Successful requests: 1/1 +-------------------------------------------------- +Request throughput (req/s): 0.03 +Latency Mean (s): 29.0378 +Latency Median (s): 29.0378 +Latency P99 (s): 29.0378 +-------------------------------------------------- +Peak Memory Max (MB): 48018.83 +Peak Memory Mean (MB): 48018.83 +Peak Memory Median (MB): 48018.83 +============================================================ +``` + +#### 5.1.2 Generate images with high concurrency + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task text-to-image --num-prompts 20 --max-concurrency 20 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Task: text-to-image +Model: Qwen/Qwen-Image +Dataset: vbench +-------------------------------------------------- +Benchmark duration (s): 300.79 +Request rate: inf +Max request concurrency: 20 +Successful requests: 14/20 +-------------------------------------------------- +Request throughput (req/s): 0.05 +Latency Mean (s): 154.5368 +Latency Median (s): 154.8363 +Latency P99 (s): 285.4603 +-------------------------------------------------- +Peak Memory Max (MB): 48030.31 +Peak Memory Mean (MB): 48030.30 +Peak Memory Median (MB): 48030.29 +============================================================ +``` diff --git a/docs_new/cookbook/diffusion/README.mdx b/docs_new/cookbook/diffusion/README.mdx new file mode 100644 index 000000000..75e37534b --- /dev/null +++ b/docs_new/cookbook/diffusion/README.mdx @@ -0,0 +1,91 @@ +--- +title: "Diffusion Cookbook" +description: "Cookbook recipes for running diffusion models with SGLang" +metatags: + description: "Explore SGLang diffusion cookbook structure, categories, and contribution guidance for image and video generation recipes." +--- + +# SGLang Diffusion Cookbook + +
+ License + PRs Welcome +
+ +Create a comprehensive cookbook for diffusion models in SGLang, demonstrating SGLang's performance advantages for image and video generation workloads. + +## 🎯 What You'll Find Here + +This cookbook aggregates battle-tested SGLang recipes covering: + +- **Models**: Mainstream Image and Video generation Models +- **Use Cases**: Inference serving, deployment strategies +- **Hardware**: GPU and CPU configurations, optimization for different accelerators +- **Best Practices**: Configuration templates, performance tuning, troubleshooting guides + +Each recipe provides step-by-step instructions to help you quickly implement SGLang solutions for your specific requirements. + +## 🚀 Quick Start + +1. Browse the recipe index above to find your model +2. Follow the step-by-step instructions in each guide +3. Adapt configurations to your specific hardware and requirements +4. Join our community to share feedback and improvements + +The sglang diffusion cookbook directory structure are shown below: + +```text Example +sgl-cookbook/docs/diffusion/ +├── README.md # Main cookbook (this file) +├── Qwen-Image/ # Qwen-Image series models docs +│ ├── Qwen-Image.md +│ └── Qwen-Image-Edit.md +├── Wan/ # Wan series models docs +│ ├── Wan2.1.md +│ └── Wan2.2.md +├── Z-Image/ # Z-Image series models docs +│ └── Z-Image-Turbo.md +└── ... +``` + +## 🤝 Contributing + +We believe the best documentation comes from practitioners. Whether you've optimized SGLang for a specific model, solved a tricky deployment challenge, or discovered performance improvements, we encourage you to contribute your recipes! + +**💪How to Contribute** + +- Comment below if interested (mention which role) +- Join discussion on implementation details +- Fork repo and work on assigned section +- Submit PR following SGLang cookbook standards +- Iterate based on review feedback + +**To contribute:** + +```shell Command +# Fork the repo and clone locally +git clone https://github.com/YOUR_USERNAME/sglang-cookbook.git +cd sglang-cookbook + +# Create a new branch +git checkout -b add-my-recipe + +# Add your recipe following the template in DeepSeek-V3.2 +# Submit a PR! +``` + +## 📖 Resources + +- [SGLang GitHub](https://github.com/sgl-project/sglang) +- [SGLang Documentation](https://sgl-project.github.io) +- [SGLANG Diffusion Documentation](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/README.md) +- [SLACK Channel](https://sgl-fru7574.slack.com/archives/C07GLLLESNR) +- [Community Slack/Discord](https://discord.gg/MpEEuAeb) + +## 📄 License + +This project is licensed under the Apache License 2.0 - see the [LICENSE](https://github.com/sgl-project/sgl-cookbook/blob/main/LICENSE) file for details. + +--- + +**Let's build this resource together!** 🚀 Star the repo and contribute your recipes to help the SGLang community grow. diff --git a/docs_new/cookbook/diffusion/Wan/Wan2.1.mdx b/docs_new/cookbook/diffusion/Wan/Wan2.1.mdx new file mode 100644 index 000000000..f69f3f86c --- /dev/null +++ b/docs_new/cookbook/diffusion/Wan/Wan2.1.mdx @@ -0,0 +1,268 @@ +--- +title: Wan2.1 +metatags: + description: "Deploy Wan2.1 video generation models with SGLang - community contribution guide for Wan Video's diffusion models." +--- + +import { Wan21Deployment } from '/src/snippets/diffusion/wan21-deployment.jsx'; + +## 1. Model Introduction + +[Wan2.1 series](https://github.com/Wan-Video/Wan2.1) is an open and advanced suite of large-scale video generative models from Wan-AI. + +Key characteristics: + +- **State-of-the-art video quality**: Consistently outperforms many open-source and commercial video models on internal and public benchmarks, especially for motion richness and temporal consistency. +- **Consumer GPU friendly**: The T2V-1.3B variant can generate 5-second 480P videos on consumer GPUs with modest VRAM requirements. +- **Multi-capability suite**: Supports Text-to-Video (T2V), Image-to-Video (I2V), video editing, text-to-image, and video-to-audio generation. +- **Robust text rendering**: First-generation Wan model capable of generating both Chinese and English text in videos with strong readability. +- **Powerful Wan-VAE**: A 3D causal VAE that encodes/decodes long 1080P videos while preserving temporal information, enabling efficient high-resolution video generation. + +For more details, refer to the official Wan2.1 resources: + +- **GitHub**: [Wan-Video/Wan2.1](https://github.com/Wan-Video/Wan2.1) +- **Hugging Face collection**: [Wan-AI Wan2.1](https://huggingface.co/Wan-AI/Wan2.1-T2V-14B) + +## 2. SGLang-diffusion Installation + +SGLang-diffusion 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-diffusion installation guide](../../../docs/sglang-diffusion/installation) for installation instructions. + +## 3. Model Deployment + +This section provides deployment configurations optimized for different hardware platforms and use cases. + +### 3.1 Basic Configuration + +The Wan2.1 series offers models in multiple sizes and resolutions, optimized for different hardware platforms. The recommended launch configurations vary by hardware and model size. + +**Interactive Command Generator**: Use the configuration selector below to automatically generate an appropriate deployment command for your model variant and options. + + + +### 3.2 Configuration Tips + +Current supported optimization options are listed in the [SGLang diffusion support matrix](../../../docs/sglang-diffusion/attention-backends#platform-support-matrix). + +- `--vae-path`: Path to a custom VAE model or HuggingFace model ID. If not specified, the VAE will be loaded from the main model path. +- `--num-gpus {NUM_GPUS}`: Number of GPUs to use. +- `--tp-size {TP_SIZE}`: Tensor parallelism size (for the encoder/DiT; keep \(\leq 1\) if relying heavily on CPU offload). +- `--sp-degree {SP_SIZE}`: Sequence parallelism degree. +- `--ulysses-degree {ULYSSES_DEGREE}`: Degree of DeepSpeed-Ulysses-style SP in USP. +- `--ring-degree {RING_DEGREE}`: Degree of ring attention-style SP in USP. +- `--text-encoder-cpu-offload`, `--dit-cpu-offload`, `--vae-cpu-offload`: Use CPU offload to reduce peak GPU memory when needed. + +## 4. Model Invocation + +### 4.1 Basic Usage + +For more API usage and request examples, please refer to: +[SGLang Diffusion OpenAI API](../../../docs/sglang-diffusion/api/openai-api) + +#### 4.1.1 Launch a server and then send requests + +```bash Command +sglang serve --model-path Wan-AI/Wan2.1-T2V-14B-Diffusers --port 30000 + +curl http://127.0.0.1:30000/v1/images/generations \ + -o >(jq -r '.data[0].b64_json' | base64 --decode > example.png) \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "Wan-AI/Wan2.1-T2V-14B-Diffusers", + "prompt": "A cute baby sea otter", + "n": 1, + "size": "1024x1024", + "response_format": "b64_json" + }' +``` + +#### 4.1.2 Generate a video without launching a server + +```bash Command +SERVER_ARGS=( + --model-path Wan-AI/Wan2.1-T2V-14B-Diffusers + --text-encoder-cpu-offload + --pin-cpu-memory + --num-gpus 4 + --ulysses-degree=2 + --enable-cfg-parallel +) + +SAMPLING_ARGS=( + --prompt "A curious raccoon" + --save-output + --output-path outputs + --output-file-name "A curious raccoon.mp4" +) + +sglang generate "${SERVER_ARGS[@]}" "${SAMPLING_ARGS[@]}" +``` + +### 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 significant inference speedups 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 +SGLANG_CACHE_DIT_ENABLED=true sglang serve --model-path Wan-AI/Wan2.1-T2V-14B-Diffusers +``` + +**Advanced Usage** + + Combined Configuration Example: + ```bash Command + 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 Wan-AI/Wan2.1-T2V-14B-Diffusers + ``` + +#### 4.2.2 GPU Optimization + +- `--dit-cpu-offload`: Use CPU offload for DiT inference. Enable if you run out of memory with FSDP. +- `--text-encoder-cpu-offload`: Use CPU offload for text encoder inference. +- `--image-encoder-cpu-offload`: Use CPU offload for image encoder inference. +- `--vae-cpu-offload`: Use CPU offload for VAE. +- `--pin-cpu-memory`: Pin memory for CPU offload. Use as a workaround if you see "CUDA error: invalid argument". + +#### 4.2.3 Supported LoRA Registry + +SGLang supports applying Wan2.1 LoRA adapters on top of base models: + + + + + + + + + + + + + + + + + + + + + + +
origin modelsupported LoRA
[Wan-AI/Wan2.1-T2V-14B](https://huggingface.co/Wan-AI/Wan2.1-T2V-14B)[NIVEDAN/wan2.1-lora](https://huggingface.co/NIVEDAN/wan2.1-lora)
[Wan-AI/Wan2.1-I2V-14B-720P](https://huggingface.co/Wan-AI/Wan2.1-I2V-14B-720P)[valiantcat/Wan2.1-Fight-LoRA](https://huggingface.co/valiantcat/Wan2.1-Fight-LoRA)
+ +**Example**: + +```bash Command +sglang serve --model-path Wan-AI/Wan2.1-T2V-14B-Diffusers --port 30000 \ + --lora-path NIVEDAN/wan2.1-lora +``` + +## 5. Benchmark + +Test Environment: + +- Hardware: AMD MI300X GPU (1x) +- Model: Wan-AI/Wan2.1-T2V-14B-Diffusers +- SGLang Docker Image Version: 0.5.9 + +### 5.1 How to Run Benchmarks with SGLang + +You can use the built-in SGLang diffusion benchmark script to evaluate Wan2.1 performance on your hardware. + +#### 5.1.1 Generate a single video + +**Server Command**: + +```bash Command +sglang serve --model-path Wan-AI/Wan2.1-T2V-14B-Diffusers +``` + +**Benchmark Command**: + +```bash Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-video --dataset vbench --task text-to-video --num-prompts 1 --max-concurrency 1 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Task: text-to-video +Model: Wan-AI/Wan2.1-T2V-14B-Diffusers +Dataset: vbench +-------------------------------------------------- +Benchmark duration (s): 1958.41 +Request rate: inf +Max request concurrency: 1 +Successful requests: 1/1 +-------------------------------------------------- +Request throughput (req/s): 0.00 +Latency Mean (s): 1958.4059 +Latency Median (s): 1958.4059 +Latency P99 (s): 1958.4059 +-------------------------------------------------- +Peak Memory Max (MB): 59662.00 +Peak Memory Mean (MB): 59662.00 +Peak Memory Median (MB): 59662.00 +============================================================ +``` + +#### 5.1.2 Generate videos with Cache-DiT acceleration + +**Server Command**: + +```bash Command +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 Wan-AI/Wan2.1-T2V-14B-Diffusers +``` + +**Benchmark Command**: + +```bash Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-video --dataset vbench --task text-to-video --num-prompts 1 --max-concurrency 1 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Task: text-to-video +Model: Wan-AI/Wan2.1-T2V-14B-Diffusers +Dataset: vbench +-------------------------------------------------- +Benchmark duration (s): 556.99 +Request rate: inf +Max request concurrency: 1 +Successful requests: 1/1 +-------------------------------------------------- +Request throughput (req/s): 0.00 +Latency Mean (s): 556.9885 +Latency Median (s): 556.9885 +Latency P99 (s): 556.9885 +-------------------------------------------------- +Peak Memory Max (MB): 69306.00 +Peak Memory Mean (MB): 69306.00 +Peak Memory Median (MB): 69306.00 +============================================================ +``` diff --git a/docs_new/cookbook/diffusion/Wan/Wan2.2.mdx b/docs_new/cookbook/diffusion/Wan/Wan2.2.mdx new file mode 100644 index 000000000..1a4f3a5c6 --- /dev/null +++ b/docs_new/cookbook/diffusion/Wan/Wan2.2.mdx @@ -0,0 +1,346 @@ +--- +title: Wan2.2 +metatags: + description: "Deploy Wan2.2 video generation models with SGLang - MoE architecture, cinematic aesthetics, and efficient 720P@24fps generation." +--- + +import { Wan22Deployment } from '/src/snippets/diffusion/wan22-deployment.jsx'; + +## 1. Model Introduction + +[Wan2.2 series](https://github.com/Wan-Video/Wan2.2) are the most popular and open and advanced large-scale video generative models. + +This generation delivers comprehensive upgrades across the board: + +- **Effective MoE Architecture**: Introduces a Mixture-of-Experts (MoE) architecture into video diffusion models. By separating the denoising process cross timesteps with specialized powerful expert models, this enlarges the overall model capacity while maintaining the same computational cost. +- **Cinematic-level Aesthetics**: Incorporates meticulously curated aesthetic data, complete with detailed labels for lighting, composition, contrast, color tone, and more. This allows for more precise and controllable cinematic style generation, facilitating the creation of videos with customizable aesthetic preferences. +- **Complex Motion Generation**: Trained on a significantly larger data, with +65.6% more images and +83.2% more videos. This expansion notably enhances the model's generalization across multiple dimensions such as motions, semantics, and aesthetics, achieving TOP performance among all open-sourced and closed-sourced models. +- **Efficient High-Definition Hybrid TI2V**: Open-sources a 5B model built with our advanced Wan2.2-VAE that achieves a compression ratio of 16×16×4. This model supports both text-to-video and image-to-video generation at 720P resolution with 24fps and can also run on consumer-grade graphics cards like 4090. It is one of the fastest 720P@24fps models currently available, capable of serving both the industrial and academic sectors simultaneously. + +For more details, please refer to the [official Wan2.2 GitHub Repository](https://github.com/Wan-Video/Wan2.2). + +## 2. SGLang-diffusion Installation + +SGLang-diffusion 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-diffusion installation guide](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/install.md) for installation instructions. + +## 3. Model Deployment + +This section provides deployment configurations optimized for different hardware platforms and use cases. + +### 3.1 Basic Configuration + +The Wan2.2 series offers models in various sizes, architectures and input types, optimized for different hardware platforms. 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. SGLang supports serving Wan2.2 on NVIDIA B200, H200 and AMD MI300X, MI325X and MI355X GPUs. + + + +### 3.2 Configuration Tips + +Current supported optimization all listed [here](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/support_matrix.md). + +- `--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 {NUM_GPUS}`: Number of GPUs to use +- `--tp-size {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 {SP_SIZE}`: Sequence parallelism size (typically should match the number of GPUs) +- `--ulysses-degree {ULYSSES_DEGREE}`: The degree of DeepSpeed-Ulysses-style SP in USP +- `--ring-degree {RING_DEGREE}`: The degree of ring attention-style SP in USP + +## 4. Model Invocation + +### 4.1 Basic Usage + +For more API usage and request examples, please refer to: +[SGLang Diffusion OpenAI API](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/openai_api.md) + +#### 4.1.1 Launch a server and then send requests + +```shell Command +sglang serve --model-path Wan-AI/Wan2.2-T2V-A14B-Diffusers --port 3000 + +curl http://127.0.0.1:3000/v1/images/generations \ + -o >(jq -r '.data[0].b64_json' | base64 --decode > example.png) \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "black-forest-labs/FLUX.1-dev", + "prompt": "A cute baby sea otter", + "n": 1, + "size": "1024x1024", + "response_format": "b64_json" + }' +``` + +#### 4.1.2 Generate a video without launching a server + +```shell Command +SERVER_ARGS=( + --model-path Wan-AI/Wan2.2-T2V-A14B-Diffusers + --text-encoder-cpu-offload + --pin-cpu-memory + --num-gpus 4 + --ulysses-degree=2 + --enable-cfg-parallel +) + +SAMPLING_ARGS=( + --prompt "A curious raccoon" + --save-output + --output-path outputs + --output-file-name "A curious raccoon.mp4" +) + +sglang generate "${SERVER_ARGS[@]}" "${SAMPLING_ARGS[@]}" + +``` + +### 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](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/cache/cache_dit.md). + +**Basic Usage** + +```shell Command +SGLANG_CACHE_DIT_ENABLED=true sglang serve --model-path Wan-AI/Wan2.2-T2V-A14B-Diffusers +``` + +**Advanced Usage** + +- DBCache Parameters: DBCache controls block-level caching behavior: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Fn`SGLANG_CACHE_DIT_FN`1Number of first blocks to always compute
Bn`SGLANG_CACHE_DIT_BN`0Number of last blocks to always compute
W`SGLANG_CACHE_DIT_WARMUP`4Warmup steps before caching starts
R`SGLANG_CACHE_DIT_RDT`0.24Residual difference threshold
MC`SGLANG_CACHE_DIT_MC`3Maximum continuous cached steps
+ +- TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Enable`SGLANG_CACHE_DIT_TAYLORSEER`falseEnable TaylorSeer calibrator
Order`SGLANG_CACHE_DIT_TS_ORDER`1Taylor expansion order (1 or 2)
+ + Combined Configuration Example: + +```shell Command +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 Wan-AI/Wan2.2-T2V-A14B-Diffusers +``` + +#### 4.2.2 GPU Optimization + +- `--dit-cpu-offload`: Use CPU offload for DiT inference. Enable if run out of memory with FSDP. +- `--text-encoder-cpu-offload`: Use CPU offload for text encoder inference. Enable if run out of memory with FSDP. +- `--image-encoder-cpu-offload`: Use CPU offload for image encoder inference. Enable if run out of memory with FSDP. +- `--vae-cpu-offload`: Use CPU offload for VAE. Enable if run out of memory. +- `--pin-cpu-memory`: Pin memory for CPU offload. Only added as a temp workaround if it throws "CUDA error: invalid argument". + +#### 4.2.3 Supported LoRA Registry + + + + + + + + + + + + + + + + + + + + + +
origin modelsupported LoRA
[Wan-AI/Wan2.2-I2V-A14B-Diffusers](https://huggingface.co/Wan-AI/Wan2.2-I2V-A14B-Diffusers)[lightx2v/Wan2.2-Distill-Loras](https://huggingface.co/lightx2v/Wan2.2-Distill-Loras)
[Wan-AI/Wan2.2-T2V-A14B-Diffusers](https://huggingface.co/Wan-AI/Wan2.2-T2V-A14B-Diffusers)[Cseti/wan2.2-14B-Arcane_Jinx-lora-v1](https://huggingface.co/Cseti/wan2.2-14B-Arcane_Jinx-lora-v1)
+**Example**: +```shell Command +sglang serve --model-path Wan-AI/Wan2.2-T2V-A14B-Diffusers --port 3000 \ + --lora-path Cseti/wan2.2-14B-Arcane_Jinx-lora-v1 +``` + +## 5. Benchmark + +Test Environment: + +- Hardware: NVIDIA B200 GPU (1x) +- Model: Wan-AI/Wan2.2-T2V-A14B-Diffusers +- sglang diffusion version: 0.5.6.post2 + +### 5.1 Speedup Benchmark + +#### 5.1.1 Generate a video + +**Server Command**: + +```shell Command +sglang serve --model-path Wan-AI/Wan2.2-T2V-A14B-Diffusers +``` + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-video --dataset vbench --task t2v --num-prompts 1 --max-concurrency 1 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Backend: sglang-video +Model: Wan-AI/Wan2.2-T2V-A14B-Diffusers +Dataset: vbench +Task: t2v +-------------------------------------------------- +Benchmark duration (s): 630.43 +Request rate: inf +Max request concurrency: 1 +Successful requests: 1/1 +-------------------------------------------------- +Request throughput (req/s): 0.00 +Latency Mean (s): 630.4277 +Latency Median (s): 630.4277 +Latency P99 (s): 630.4277 +-------------------------------------------------- +Peak Memory Max (MB): 62627.41 +Peak Memory Mean (MB): 62627.41 +Peak Memory Median (MB): 62627.41 + +============================================================ +``` + +#### 5.1.2 Generate videos with high concurrency + +**Server Command**: + +```shell Command +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 Wan-AI/Wan2.2-T2V-A14B-Diffusers +``` + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-video --dataset vbench --task t2v --num-prompts 20 --max-concurrency 20 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Backend: sglang-video +Model: Wan-AI/Wan2.2-T2V-A14B-Diffusers +Dataset: vbench +Task: t2v +-------------------------------------------------- +Benchmark duration (s): 5163.21 +Request rate: inf +Max request concurrency: 20 +Successful requests: 20/20 +-------------------------------------------------- +Request throughput (req/s): 0.00 +Latency Mean (s): 2739.7695 +Latency Median (s): 2742.0673 +Latency P99 (s): 5121.6331 +-------------------------------------------------- +Peak Memory Max (MB): 72523.56 +Peak Memory Mean (MB): 70253.34 +Peak Memory Median (MB): 70824.46 + +============================================================ +``` diff --git a/docs_new/cookbook/diffusion/Z-Image/Z-Image-Turbo.mdx b/docs_new/cookbook/diffusion/Z-Image/Z-Image-Turbo.mdx new file mode 100644 index 000000000..8e43ce374 --- /dev/null +++ b/docs_new/cookbook/diffusion/Z-Image/Z-Image-Turbo.mdx @@ -0,0 +1,281 @@ +--- +title: Z-Image-Turbo +metatags: + description: "Deploy Z-Image-Turbo with SGLang - community contribution guide for Z-Image's fast image generation model." +--- + +import { ZImageTurboDeployment } from '/src/snippets/diffusion/zimage-turbo-deployment.jsx'; + +## 1. Model Introduction + +[Z-Image](https://github.com/Tongyi-MAI/Z-Image) is a powerful and highly efficient image generation model family with 6B parameters, developed by Tongyi-MAI. It adopts a Scalable Single-Stream DiT (S3-DiT) architecture, where text, visual semantic tokens, and image VAE tokens are concatenated at the sequence level to serve as a unified input stream, maximizing parameter efficiency compared to dual-stream approaches. + +[Z-Image-Turbo](https://huggingface.co/Tongyi-MAI/Z-Image-Turbo) is a distilled version of Z-Image that matches or exceeds leading competitors with only 8 NFEs (Number of Function Evaluations). It is powered by two core techniques: **Decoupled-DMD** (few-step distillation) and **DMDR** (fusing DMD with Reinforcement Learning). + +**Key Features:** + +- **Sub-second Inference Latency**: Achieves sub-second inference on enterprise-grade H800 GPUs and fits comfortably within 16GB VRAM consumer devices +- **Photorealistic Image Generation**: Excels in high-quality photorealistic image generation with rich aesthetics +- **Bilingual Text Rendering**: Supports accurate bilingual text rendering in both English and Chinese +- **Robust Instruction Adherence**: Strong prompt following and instruction adherence capabilities +- **#1 Open-Source Model**: Ranked 8th overall and #1 among open-source models on the [Artificial Analysis Text-to-Image Leaderboard](https://artificialanalysis.ai/image/leaderboard/text-to-image) + +For more details, please refer to the [Z-Image-Turbo HuggingFace page](https://huggingface.co/Tongyi-MAI/Z-Image-Turbo), the [GitHub repository](https://github.com/Tongyi-MAI/Z-Image), and the [technical report (arXiv)](https://arxiv.org/abs/2511.22699). + +## 2. SGLang-diffusion Installation + +SGLang-diffusion 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-diffusion installation guide](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/install.md) for installation instructions. + +## 3. Model Deployment + +This section provides deployment configurations optimized for different hardware platforms and use cases. + +### 3.1 Basic Configuration + +Z-Image-Turbo is optimized for high-quality image generation with only 8 inference steps. The recommended launch configurations vary by hardware. + +**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate deployment command for your hardware platform. + + + +### 3.2 Configuration Tips + +Current supported optimization all listed [here](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/support_matrix.md). + +- `--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 + +**AMD ROCm Notes**: Requires SGLang >= v0.5.8. + +## 4. API Usage + +For complete API documentation, please refer to the [official API usage guide](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/openai_api.md). + +### 4.1 Generate an Image + +```python Example +import base64 +from openai import OpenAI + +client = OpenAI(api_key="EMPTY", base_url="http://localhost:30000/v1") + +response = client.images.generate( + model="Tongyi-MAI/Z-Image-Turbo", + prompt="A logo With Bold Large text: SGL Diffusion", + 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](https://github.com/sgl-project/sglang/blob/main/python/sglang/multimodal_gen/docs/cache_dit.md). + +**Basic Usage** + +```bash Command +SGLANG_CACHE_DIT_ENABLED=true sglang serve --model-path Tongyi-MAI/Z-Image-Turbo +``` + +**Advanced Usage** + +- DBCache Parameters: DBCache controls block-level caching behavior: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Fn`SGLANG_CACHE_DIT_FN`1Number of first blocks to always compute
Bn`SGLANG_CACHE_DIT_BN`0Number of last blocks to always compute
W`SGLANG_CACHE_DIT_WARMUP`4Warmup steps before caching starts
R`SGLANG_CACHE_DIT_RDT`0.24Residual difference threshold
MC`SGLANG_CACHE_DIT_MC`3Maximum continuous cached steps
+- TaylorSeer Configuration: TaylorSeer improves caching accuracy using Taylor expansion: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Enable`SGLANG_CACHE_DIT_TAYLORSEER`falseEnable TaylorSeer calibrator
Order`SGLANG_CACHE_DIT_TS_ORDER`1Taylor expansion order (1 or 2)
+ + Combined Configuration Example: + +```bash Command +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 Tongyi-MAI/Z-Image-Turbo +``` + +#### 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". + +## 5. Benchmark + +Test Environment: + +- Hardware: AMD Instinct MI300X GPU (1x) +- Model: Tongyi-MAI/Z-Image-Turbo +- Docker Image: lmsysorg/sglang:v0.5.8-rocm700-mi30x +- sglang diffusion version: 0.5.8 + +### 5.1 Speedup Benchmark + +#### 5.1.1 Generate an image + +**Server Command**: + +```shell Command +sglang serve --model-path Tongyi-MAI/Z-Image-Turbo \ + --ulysses-degree=1 --ring-degree=1 --port 30000 +``` + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task text-to-image --num-prompts 1 --max-concurrency 1 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Task: text-to-image +Model: Tongyi-MAI/Z-Image-Turbo +Dataset: vbench +-------------------------------------------------- +Benchmark duration (s): 1.84 +Request rate: inf +Max request concurrency: 1 +Successful requests: 1/1 +-------------------------------------------------- +Request throughput (req/s): 0.54 +Latency Mean (s): 1.8435 +Latency Median (s): 1.8435 +Latency P99 (s): 1.8435 +-------------------------------------------------- +Peak Memory Max (MB): 30689.20 +Peak Memory Mean (MB): 30689.20 +Peak Memory Median (MB): 30689.20 +============================================================ +``` + +#### 5.1.2 Generate images with high concurrency + +**Benchmark Command**: + +```shell Command +python3 -m sglang.multimodal_gen.benchmarks.bench_serving \ + --backend sglang-image --dataset vbench --task text-to-image --num-prompts 20 --max-concurrency 20 +``` + +**Result**: + +```text Output +================= Serving Benchmark Result ================= +Task: text-to-image +Model: Tongyi-MAI/Z-Image-Turbo +Dataset: vbench +-------------------------------------------------- +Benchmark duration (s): 35.32 +Request rate: inf +Max request concurrency: 20 +Successful requests: 20/20 +-------------------------------------------------- +Request throughput (req/s): 0.57 +Latency Mean (s): 18.5672 +Latency Median (s): 18.5573 +Latency P99 (s): 34.9880 +-------------------------------------------------- +Peak Memory Max (MB): 30689.26 +Peak Memory Mean (MB): 30689.21 +Peak Memory Median (MB): 30689.21 +============================================================ +``` diff --git a/docs_new/cookbook/diffusion/intro.mdx b/docs_new/cookbook/diffusion/intro.mdx new file mode 100644 index 000000000..540a23ccb --- /dev/null +++ b/docs_new/cookbook/diffusion/intro.mdx @@ -0,0 +1,40 @@ +--- +title: Overview +mode: wide +description: Practical guides for deploying and using diffusion models with SGLang. +metatags: + description: "Explore SGLang diffusion model cookbooks for image and video generation deployment, invocation, optimization, and benchmarking examples." +--- + + + + + + + + diff --git a/docs_new/cookbook/intro copy.mdx b/docs_new/cookbook/intro copy.mdx new file mode 100644 index 000000000..59600608f --- /dev/null +++ b/docs_new/cookbook/intro copy.mdx @@ -0,0 +1,224 @@ +--- +title: SGLang Cookbook +metatags: + description: The SGLang Cookbook is a practical collection of examples and guides that show developers how to efficiently run SGLang with a variety of models on different platforms. +--- + +[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) +[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/sgl-project/sgl-cookbook/pulls) + +A community-maintained repository of practical guides and recipes for deploying and using SGLang in production environments. Our mission is simple: answer the question **"How do I use SGLang (and related models) on hardware Y for task Z?"** with clear, actionable solutions. + +## 🎯 What You'll Find Here + +This cookbook aggregates battle-tested SGLang recipes covering: + +- **Models**: Mainstream LLMs and Vision-Language Models (VLMs) +- **Use Cases**: Inference serving, deployment strategies, multimodal applications +- **Hardware**: GPU and CPU configurations, optimization for different accelerators +- **Best Practices**: Configuration templates, performance tuning, troubleshooting guides + +Each recipe provides step-by-step instructions to help you quickly implement SGLang solutions for your specific requirements. + +## Guides + +### Autoregressive Models + +#### Qwen + +- [x] [Qwen3.5](./autoregressive/Qwen/Qwen3.5) NEW +- [x] [Qwen3](./autoregressive/Qwen/Qwen3) +- [x] [Qwen3-Next](./autoregressive/Qwen/Qwen3-Next) +- [x] [Qwen3-VL](./autoregressive/Qwen/Qwen3-VL) +- [x] [Qwen3-Coder](./autoregressive/Qwen/Qwen3-Coder) +- [x] [Qwen3-Coder-Next](./autoregressive/Qwen/Qwen3-Coder-Next) NEW +- [x] [Qwen2.5-VL](./autoregressive/Qwen/Qwen2.5-VL) + +#### DeepSeek + +- [x] [DeepSeek-V3.2](./autoregressive/DeepSeek/DeepSeek-V3_2) +- [x] [DeepSeek-V3.1](./autoregressive/DeepSeek/DeepSeek-V3_1) +- [x] [DeepSeek-V3](./autoregressive/DeepSeek/DeepSeek-V3) +- [x] [DeepSeek-R1](./autoregressive/DeepSeek/DeepSeek-R1) +- [x] [DeepSeek-OCR](./autoregressive/DeepSeek/DeepSeek-OCR) +- [x] [DeepSeek-OCR-2](./autoregressive/DeepSeek/DeepSeek-OCR-2) NEW + +#### Llama + +- [ ] [Llama4-Scout](./autoregressive/Llama/Llama4) +- [x] [Llama3.3-70B](./autoregressive/Llama/Llama3.3-70B) +- [x] [Llama3.1](./autoregressive/Llama/Llama3.1) + +#### GLM + +- [ ] [GLM-Glyph](./autoregressive/GLM/GLM-Glyph) +- [x] [GLM-5](./autoregressive/GLM/GLM-5) NEW +- [x] [GLM-OCR](./autoregressive/GLM/GLM-OCR) NEW +- [x] [GLM-4.5](./autoregressive/GLM/GLM-4.5) +- [x] [GLM-4.5V](./autoregressive/GLM/GLM-4.5V) +- [x] [GLM-4.6](./autoregressive/GLM/GLM-4.6) +- [x] [GLM-4.6V](./autoregressive/GLM/GLM-4.6V) +- [x] [GLM-4.7](./autoregressive/GLM/GLM-4.7) +- [x] [GLM-4.7-Flash](./autoregressive/GLM/GLM-4.7-Flash) NEW + +#### OpenAI + +- [x] [gpt-oss](./autoregressive/OpenAI/GPT-OSS) + +#### Moonshotai + +- [x] [Kimi-K2.6](./autoregressive/Moonshotai/Kimi-K2.6) NEW +- [x] [Kimi-K2.5](./autoregressive/Moonshotai/Kimi-K2.5) +- [x] [Kimi-K2](./autoregressive/Moonshotai/Kimi-K2) +- [x] [Kimi-Linear](./autoregressive/Moonshotai/Kimi-Linear) + +#### MiniMax + +- [ ] [MiniMax-M2](./autoregressive/MiniMax/MiniMax-M2) +- [x] [MiniMax-M2.5](./autoregressive/MiniMax/MiniMax-M2.5) NEW + +#### NVIDIA + +- [x] [Nemotron-Nano-3-30B-A3B](./autoregressive/NVIDIA/Nemotron3-Nano) + +#### Ernie + +- [x] [Ernie4.5](./autoregressive/Ernie/Ernie4.5) +- [ ] [Ernie4.5-VL](./autoregressive/Ernie/Ernie4.5-VL) + +#### InternVL + +- [ ] [InternVL3.5](./autoregressive/InternVL/InternVL3.5) + +#### InternLM + +- [ ] [Intern-S1](./autoregressive/InternLM/Intern-S1) + +#### Jina AI + +- [ ] [Jina-reranker-m0](./autoregressive/Jina/Jina-reranker-m0) + +#### Mistral + +- [ ] [Mistral-3](./autoregressive/Mistral/Ministral-3) +- [x] [Devstral 2](./autoregressive/Mistral/Devstral-2) + +#### Xiaomi + +- [x] [MiMo-V2-Flash](./autoregressive/Xiaomi/MiMo-V2-Flash) + +#### FlashLabs + +- [x] [Chroma 1.0](./autoregressive/FlashLabs/Chroma1.0)NEW + +#### StepFun + +- [x] [Step-3.5-Flash](./autoregressive/StepFun/Step3.5) NEW +- [x] [Step3-VL-10B](./autoregressive/StepFun/Step3-VL-10B) NEW + +#### InclusionAI + +- [x] [Ling-2.5-1T](./autoregressive/InclusionAI/Ling-2.5-1T) NEW +- [x] [Ring-2.5-1T](./autoregressive/InclusionAI/Ring-2.5-1T) NEW +- [x] [LLaDA-2.1](./autoregressive/InclusionAI/LLaDA-2.1) NEW + +### Diffusion Models + +#### FLUX + +- [x] [FLUX](./diffusion/FLUX/FLUX) + +#### Qwen-Image + +- [ ] [Qwen-Image](./diffusion/Qwen-Image/Qwen-Image) +- [x] [Qwen-Image-Edit](./diffusion/Qwen-Image/Qwen-Image-Edit) + +#### Wan + +- [ ] [Wan2.1](./diffusion/Wan/Wan2.1) +- [x] [Wan2.2](./diffusion/Wan/Wan2.2) + +#### Z-Image + +- [x] [Z-Image-Turbo](./diffusion/Z-Image/Z-Image-Turbo) + +### Benchmarks + +- [x] [Diffusion Model Benchmark](./base/benchmarks/diffusion_model_benchmark.mdx) +- [x] [LLM Benchmark](./base/benchmarks/autoregressive_model_benchmark.mdx) + +## Reference + +- [Installation (PyPI)](../docs/get-started/installation) - Install SGLang via pip or uv (stable and nightly) +- [Server arguments](./base/reference/server_arguments) - Understanding all the arguments + +## 🚀 Quick Start + +1. Browse the recipe index above to find your model +2. Follow the step-by-step instructions in each guide +3. Adapt configurations to your specific hardware and requirements +4. Join our community to share feedback and improvements + +## 🤝 Contributing + +We believe the best documentation comes from practitioners. Whether you've optimized SGLang for a specific model, solved a tricky deployment challenge, or discovered performance improvements, we encourage you to contribute your recipes! + +**Ways to contribute:** + +- Add a new recipe for a model not yet covered +- Improve existing recipes with additional tips or configurations +- Report issues or suggest enhancements +- Share your production deployment experiences + +**To contribute:** + + +```bash Contribute a Recipe +# Fork the repo and clone locally +git clone https://github.com/YOUR_USERNAME/sglang-cookbook.git +cd sglang-cookbook + +# Create a new branch +git checkout -b add-my-recipe + +# Add your recipe following the template in DeepSeek-V3.2 +# Submit a PR! +``` + + +## 🛠️ Local Development + +### Prerequisites + +- Node.js >= 20.0 +- npm or yarn + +### Setup and Run + +Install dependencies and start the development server: + + +```bash Local Development +# Install dependencies +npm install + +# Start development server (hot reload enabled) +npm start +``` + + +The site will automatically open in your browser at `http://localhost:3000`. + +## 📖 Resources + +- [SGLang GitHub](https://github.com/sgl-project/sglang) +- [SGLang Documentation](https://sgl-project.github.io) +- [Community Slack/Discord](https://discord.gg/MpEEuAeb) + +## 📄 License + +This project is licensed under the Apache License 2.0 - see the [LICENSE](https://github.com/sgl-project/sgl-cookbook/blob/main/LICENSE) file for details. + +--- + +**Let's build this resource together!** 🚀 Star the repo and contribute your recipes to help the SGLang community grow. diff --git a/docs_new/cookbook/intro.mdx b/docs_new/cookbook/intro.mdx new file mode 100644 index 000000000..3cd1747ee --- /dev/null +++ b/docs_new/cookbook/intro.mdx @@ -0,0 +1,42 @@ +--- +title: SGLang Cookbook +metatags: + description: The SGLang Cookbook is a practical collection of examples and guides that show developers how to efficiently run SGLang with a variety of models on different platforms. +--- + +A community-maintained repository of practical guides and recipes for deploying and using SGLang in production environments. Our mission is simple: answer the question **"How do I use SGLang (and related models) on hardware Y for task Z?"** with clear, actionable solutions. + + +## Guides + + + + + + +## Benchmarks + + + + + diff --git a/docs_new/cookbook/omni/FishAudio/S2-Pro.mdx b/docs_new/cookbook/omni/FishAudio/S2-Pro.mdx new file mode 100644 index 000000000..2c659fd46 --- /dev/null +++ b/docs_new/cookbook/omni/FishAudio/S2-Pro.mdx @@ -0,0 +1,208 @@ +--- +title: FishAudio S2 Pro +metatags: + description: "Deploy FishAudio S2 Pro with SGLang - state-of-the-art text-to-speech with dual-autoregressive architecture, voice cloning, prosody control, and 80+ language support." +tag: NEW +--- + +## 1. Model Introduction + +[FishAudio S2 Pro](https://huggingface.co/fishaudio/s2-pro) is a state-of-the-art text-to-speech model developed by [FishAudio](https://fish.audio), featuring fine-grained prosody and emotion control. Built on a Dual-Autoregressive (Dual-AR) transformer architecture with RVQ-based audio codec, S2 Pro achieves state-of-the-art quality across multiple TTS benchmarks. + +S2 Pro tops the Audio Turing Test (0.515 posterior mean) and EmergentTTS-Eval (81.88% win rate against gpt-4o-mini-tts) while achieving the lowest WER on Seed-TTS Eval among all evaluated models including closed-source systems. Trained on over 10 million hours of audio across approximately 100 languages and aligned with GRPO-based reinforcement learning, it supports voice cloning and fine-grained inline control of prosody and emotion through natural-language tags. + +**Key Features:** + +- **Dual-AR Architecture**: 5B parameter model (4B Slow AR + 400M Fast AR) with RVQ-based audio codec at 10 codebooks (~21 Hz frame rate) +- **Voice Cloning**: High-quality voice cloning from a short reference audio clip +- **Prosody & Emotion Control**: Fine-grained inline control of prosody and emotion through natural-language tags +- **Multilingual**: 80+ language support (Tier 1: Japanese, English, Chinese; Tier 2: Korean, Spanish, Portuguese, Arabic, Russian, French, German) +- **SGLang Integration**: Inherits LLM-native serving optimizations (paged KV cache, radix prefix caching) + +**License:** [FISH AUDIO RESEARCH LICENSE AGREEMENT](https://huggingface.co/fishaudio/s2-pro/blob/main/LICENSE.md) + +This work is a collaboration between the SGLang Omni Team and [FishAudio Team](https://fish.audio). For more details on S2 Pro's model design and training, see FishAudio's [S2 release blog post](https://fish.audio/blog/fish-audio-open-sources-s2/). + +## 2. Installation + +S2 Pro uses `sglang-omni`, an ecosystem project for SGLang. Start with the Docker image, then install the `sglang-omni` package inside the container. + +### 2.1 Docker + +```bash Command +docker pull frankleeeee/sglang-omni:dev + +docker run -it --shm-size 32g --gpus all frankleeeee/sglang-omni:dev /bin/zsh +``` + +### 2.2 Install sglang-omni (inside Docker) + +```bash Command +git clone https://github.com/sgl-project/sglang-omni.git +cd sglang-omni +uv venv .venv -p 3.12 && source .venv/bin/activate +uv pip install -v ".[s2pro]" +huggingface-cli download fishaudio/s2-pro +``` + +## 3. Model Deployment + +S2 Pro can be served via an OpenAI-compatible HTTP server or explored interactively through a Gradio playground. + +### 3.1 Server + +```bash Command +python -m sglang_omni.cli.cli serve \ + --model-path fishaudio/s2-pro \ + --config examples/configs/s2pro_tts.yaml \ + --port 8000 +``` + +### 3.2 Interactive Playground + +We provide a Gradio-based interactive playground. We highly recommend using the playground since audio data is hard to interact with by CLI. + +```bash Command +./playground/tts/start.sh +``` + +## 4. Model Invocation + +### 4.1 Text-to-Speech + +Generate speech from text using the OpenAI-compatible `/v1/audio/speech` endpoint. + + +Without a reference audio clip, the generated voice will use a default voice. Provide a reference audio for voice cloning. + + +```bash Command +curl -X POST http://localhost:8000/v1/audio/speech \ + -H "Content-Type: application/json" \ + -d '{"input": "Hello, how are you?"}' \ + --output output.wav +``` + +### 4.2 Voice Cloning + +Provide a reference audio file and its transcript for high-quality voice cloning: + +```bash Command +curl -X POST http://localhost:8000/v1/audio/speech \ + -H "Content-Type: application/json" \ + -d '{ + "input": "Hello, how are you?", + "references": [{"audio_path": "ref.wav", "text": "Transcript of ref audio."}] + }' \ + --output output.wav +``` + +## 5. Architecture + +S2 Pro uses a 3-stage pipeline: + +```text Example +Text input ──► Preprocessing ──► SGLang AR Engine ──► DAC Vocoder ──► Audio output + (CPU) (GPU) (GPU) +``` + +**Stage 1 — Preprocessing:** Tokenizes the input text into a Qwen3-style chat prompt. For voice cloning, encodes the reference audio into VQ codes via the DAC codec and prepends them to the prompt as a system message. + +**Stage 2 — Dual-AR Generation:** The Slow AR runs inside SGLang along the time axis. At each decode step, it predicts a semantic token, then the Fast AR (4-layer transformer) generates the remaining 9 residual codebook tokens conditioned on the hidden state. VQ embeddings are injected into the input embedding at masked positions, allowing the model to attend over both text and audio context through SGLang's KV cache. + +**Stage 3 — Vocoder:** The accumulated codebook indices are decoded into a waveform by a DAC codec, producing the final audio output. + +## 6. Performance + +Evaluated on the full seed-tts-eval EN testset (1,088 samples) on a single H200 GPU. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MetricBS=1BS=2BS=4BS=8
Tok/s (mean)63.345.831.919.6
RTF (mean)0.3400.4730.6761.097
Latency (mean)1.33s1.80s2.69s4.36s
TTFT (mean)19.6 ms22.0 ms31.6 ms50.7 ms
TTFB (mean)172.8 ms249.9 ms319.1 ms509.6 ms
+ +## 7. SGLang Omni Optimizations + +By integrating S2 Pro's Dual-AR backbone into SGLang's paged-attention engine, we inherit LLM-native optimizations: + +- **Paged KV cache** — SGLang manages KV cache for the Slow AR path, enabling efficient memory usage and high concurrency. +- **Radix prefix caching** — Shared system prompt and reference audio prefixes are cached across requests, keeping TTFT consistently low (~18ms). +- **torch.compile on Fast AR** — The 9-step codebook loop is compiled with torch.compile, achieving 5x speedup over eager mode. +- **FlashAttention 3** — Forced FA3 backend to match training-time attention numerics, avoiding early-EOS divergence from flashinfer. + +## 8. Future Optimizations + +To further improve throughput and latency in the future: + +- **CUDA Graphs while torch.compile enabled.** The current implementation uses torch.compile on the Fast AR codebook loop (achieving 5x over eager), but does not capture CUDA graphs for the Slow AR path. Enabling CUDA graphs requires resolving numerical divergence from deterministic-mode constraints and adapting SGLang's graph capture to S2 Pro's interleaved VQ embedding injection, involving significant engineering that we leave for a future release. + +- **Batched Fast AR head processing.** Currently, the Fast AR codebook decoding loop runs sequentially per request. Batching these steps across concurrent requests would improve GPU utilization at higher batch sizes, potentially improving throughput. + +## 9. Engineering Appendix + + + +### BF16 RoPE Precision Mismatch + +SGLang's default RoPE implementation precomputes `cos_sin_cache` in float32, but S2 Pro's model was trained entirely in bfloat16 including the RoPE frequencies. The precision difference caused logit divergence producing garbled audio with abnormally long sequences of tokens. + +It's worth attention for any future engineering for fish audio inference infrastructure, since it's uncommon and hard to debug when accuracy of inference engine is higher than the precision of the model. Below is a simple fix once problem identified. + +```python Example +def _truncate_rope_to_bf16(model: torch.nn.Module) -> None: + for module in model.modules(): + if hasattr(module, "cos_sin_cache"): + module.cos_sin_cache.data = module.cos_sin_cache.data.to(torch.bfloat16).to( + torch.float32 + ) +``` + +### Attention Backend Divergence Causing Early Stopping + +SGLang defaults to flashinfer for attention, but S2 Pro was trained with FlashAttention. When future engineering meet early EOS token issue, this could suggest the fix. + + diff --git a/docs_new/cookbook/omni/intro.mdx b/docs_new/cookbook/omni/intro.mdx new file mode 100644 index 000000000..28702aae1 --- /dev/null +++ b/docs_new/cookbook/omni/intro.mdx @@ -0,0 +1,16 @@ +--- +title: Overview +mode: wide +description: Practical guides for deploying and using omni models (TTS, audio) with SGLang. +metatags: + description: "Explore SGLang omni model cookbooks for speech, audio, and multimodal deployment examples." +--- + + + + diff --git a/docs_new/cookbook/specbundle/specbundle_usage.mdx b/docs_new/cookbook/specbundle/specbundle_usage.mdx new file mode 100644 index 000000000..c8735077e --- /dev/null +++ b/docs_new/cookbook/specbundle/specbundle_usage.mdx @@ -0,0 +1,152 @@ +--- +title: SpecBundle Usage +metatags: + description: "SpecBundle usage guide - production-grade EAGLE3 speculative decoding with SGLang for faster LLM inference." +--- + +![specbundle logo](/logo/logo.png) + +## About SpecBundle + +Speculative decoding, especially EAGLE3, offer strong theoretical guarantees alongside consistent empirical improvements in token acceptance rate and end-to-end inference speed. However, despite these advances, adoption of speculative decoding—especially EAGLE3—remains limited in the open-source ecosystem, due primarily to three key factors. + +1. Lack of production-ready training infrastructure: Existing speculative decoding toolchains are largely research prototypes, offering limited system-level optimization and inadequate support for diverse architectures and large-scale models. +2. Scarcity of high-quality draft models: Effective speculative decoding depends on strong draft models, yet publicly available EAGLE3-compatible checkpoints are extremely limited, primarily originating from the original authors. +3. Insufficient training scale of existing drafts: Most available draft models are trained on small or curated datasets and fail to generalize to the large, diverse corpora used in modern LLM training, resulting in low token acceptance rates and diminished practical speedups. + +**SpecBundle** is a direct response to these limitations. Jointly driven by the open-source community and industry partners including **Ant Group**, **Meituan**, **Nex-AGI** and **EigenAI**, **SpecBundle** represents the **first open initiative** aimed at democratizing speculative decoding by providing high-performance, production-grade EAGLE3 draft model weights for mainstream open-source LLMs. This initiative also serves to verify the robustness of the [**SpecForge**](https://github.com/sgl-project/SpecForge) framework through multiple scales and architectures. + +## Installation + +```bash Command +git clone https://github.com/sgl-project/SpecForge.git +``` + +## Usage + +### Launch SGLang Server with SpecBundle models + +You can use the following command to launch the SGLang server with SpecBundle models. Please add `--tp`, `--ep` and `--mem-fraction-static` arguments when you encounter memory issues. + +```bash Command +python3 -m sglang.launch_server \ + --model \ + --speculative-algorithm EAGLE3 \ + --speculative-draft-model-path \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 +``` + +For example: + +```bash Command +SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 python3 -m sglang.launch_server \ + --model Qwen/Qwen3-30B-A3B-Instruct-2507 \ + --speculative-algorithm EAGLE3 \ + --speculative-draft-model-path lmsys/SGLang-EAGLE3-Qwen3-30B-A3B-Instruct-2507-SpecForge-Nex \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 \ + --tp 4 +``` + +### Use SpecBundle to compare the performance of Speculative Decoding draft models + +We provide a benchmark suite to evaluate the performance of SpecBundle draft models [here](https://github.com/sgl-project/SpecForge/tree/main/benchmarks). + +#### Example: + +1. Launch a SGLang Server + +```bash Command +SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 python3 -m sglang.launch_server \ + --model Qwen/Qwen3-30B-A3B-Instruct-2507 \ + --speculative-algorithm EAGLE3 \ + --speculative-draft-model-path lmsys/SGLang-EAGLE3-Qwen3-30B-A3B-Instruct-2507-SpecForge-Nex \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 \ + --tp 4 +``` + +2. Use the benchmark suite to evaluate the performance of SpecBundle draft models + +`bench_eagle3.py` can help you launch a SGLang server process and a Benchmarking process concurrently. In this way, you don't have to launch the SGLang server manually, this script will manually handle the SGLang launch under different speculative decoding configurations. Some important arguments are: + +- `--model-path`: the path to the target model. +- `--speculative-draft-model-path`: the path to the draft model. +- `--port`: the port to launch the SGLang server. +- `--trust-remote-code`: trust the remote code. +- `--mem-fraction-static`: the memory fraction for the static memory. +- `--tp-size`: the tensor parallelism size. +- `--attention-backend`: the attention backend. +- `--config-list`: the list of speculative decoding configuration to test, the format is `,,,`. +- `--benchmark-list`: the list of benchmarks to test, the format is `::`. + +```bash Command +cd SpecForge/benchmarks +python bench_eagle3.py \ + --model-path Qwen/Qwen3-30B-A3B-Instruct-2507 \ + --port 30000 \ + --config-list 1,3,1,4 \ + --benchmark-list mtbench:5 gsm8k:100 \ + --skip-launch-server +``` + +**Interactive Command Generator**: Use the configuration selector below to automatically generate the appropriate test command for your model and benchmark. + +import { SpecBundleDeployment } from "/src/snippets/specbundle/specbundle-deployment.jsx"; + + + +It will generate a json file, content is listed below: + +```json Config +{ + "mtbench": [ + { + "batch_size": 1, + "steps": null, + "topk": null, + "num_draft_tokens": null, + "metrics": [ + { + "latency": 12.232808108034078, + "output_throughput": 319.71399906382845, + "accept_length": 2.170366259711432, + "accuracy": null, + "num_questions": 5, + "num_valid_predictions": 0, + "categorical_performance": null + } + ], + "num_samples": 5 + } + ], + "gsm8k": [ + { + "batch_size": 1, + "steps": null, + "topk": null, + "num_draft_tokens": null, + "metrics": [ + { + "latency": 37.42077191895805, + "output_throughput": 373.6160234823207, + "accept_length": 2.643410852713178, + "accuracy": 0.96, + "num_questions": 100, + "num_valid_predictions": 100, + "categorical_performance": null + } + ], + "num_samples": 100 + } + ] +} +``` + +## Performance Scores + +We evaluate the performance of SpecBundle draft models on various benchmarks, please visit the [Performance Dashboard](https://docs.sglang.io/SpecForge/SpecBundle/index.html) for more details. diff --git a/docs_new/cookbook/specbundle/supported_models.mdx b/docs_new/cookbook/specbundle/supported_models.mdx new file mode 100644 index 000000000..f3b0f6bf7 --- /dev/null +++ b/docs_new/cookbook/specbundle/supported_models.mdx @@ -0,0 +1,191 @@ +--- +title: Supported Models +metatags: + description: "SpecBundle supported EAGLE3 draft models for speculative decoding - Llama, Qwen, DeepSeek, GLM, and more." +--- + +## [Released Models](https://huggingface.co/collections/lmsys/specbundle) + +We list the models released by the SpecForge and several industrial partners below. These models are released as part of the SpecBundle models, which are trained on large-scale multi-domain datasets and deliver exceptional performance on various benchmarks. + +> We also include some of the models previously trained by the SpecForge team but not technically part of the SpecBundle release. +> We mark models trained on ShareGPT+Ultrachat datasets with a **\*** mark and models trained on Perfect-Blend datasets but released before SpecBundle with **+** mark. + +### Llama Series + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Target ModelEAGLE3 Draft Model
meta-llama/Llama-3.1-8B-Instruct[🤗 Hugging Face](https://huggingface.co/lmsys/SGLang-EAGLE3-Llama-3.1-8B-Instruct-SpecForge)
meta-llama/Llama-3.3-70B-Instruct[🤗 Hugging Face](https://huggingface.co/lmsys/SGLang-EAGLE3-Llama-3.3-70B-Instruct-SpecForge)
meta-llama/Llama-4-Scout-17B-16E-Instruct[🤗 Hugging Face](https://huggingface.co/lmsys/SGLang-EAGLE3-Llama-4-Scout-17B-16E-Instruct-SpecForge)
meta-llama/Llama-4-Maverick-17B-128E-Instruct[🤗 Hugging Face \*](https://huggingface.co/lmsys/sglang-EAGLE3-Llama-4-Maverick-17B-128E-Instruct-v1)
+ +### Qwen Series + + + + + + + + + + + + + + + + + + + + + + + + + + +
Target ModelEAGLE3 Draft Model
Qwen/Qwen3-30B-A3B-Instruct-2507[🤗 Hugging Face](https://huggingface.co/lmsys/SGLang-EAGLE3-Qwen3-30B-A3B-Instruct-2507-SpecForge-Nex)
Qwen/Qwen3-235B-A22B-Instruct-2507[🤗 Hugging Face](https://huggingface.co/lmsys/SGLang-EAGLE3-Qwen3-235B-A22B-Instruct-2507-SpecForge-Meituan)
Qwen/Qwen3-Next-80B-A3B-Instruct-FP8[🤗 Hugging Face](https://huggingface.co/lmsys/SGLang-EAGLE3-Qwen3-Next-80B-A3B-Instruct-FP8-perfect-blend-regenerated)
+ +### Qwen Coder Series + + + + + + + + + + + + + + + + + + + + + + +
Target ModelEAGLE3 Draft Model
Qwen/Qwen3-Coder-30B-A3B-Instruct[🤗 Hugging Face](https://huggingface.co/lmsys/SGLang-EAGLE3-Qwen3-Coder-30B-A3B-Instruct-SpecForge)
Qwen/Qwen3-Coder-480B-A35B-Instruct[🤗 Hugging Face](https://huggingface.co/lmsys/SGLang-EAGLE3-Qwen3-Coder-480B-A35B-Instruct-SpecForge-EigenAI)
+ +### Ling Series + + + + + + + + + + + + + + + + + + +
Target ModelEAGLE3 Draft Model
inclusionAI/Ling-flash-2.0[🤗 Hugging Face](https://huggingface.co/AQ-MedAI/Ling-Flash-2.0-eagle3)
+ +### Kimi Series + + + + + + + + + + + + + + + + + + +
Target ModelEAGLE3 Draft Model
moonshotai/Kimi-K2-Instruct[🤗 Hugging Face](https://huggingface.co/AQ-MedAI/Kimi-K2-Instruct-eagle3)
+ +### GPT-OSS Series + + + + + + + + + + + + + + + + + + + + + + +
Target ModelEAGLE3 Draft Model
openai/gpt-oss-20b[🤗 Hugging Face +](https://huggingface.co/zhuyksir/EAGLE3-gpt-oss-20b-bf16)
openai/gpt-oss-120b[🤗 Hugging Face +](https://huggingface.co/lmsys/EAGLE3-gpt-oss-120b-bf16)
+ +### Nex Series + + + + + + + + + + + + + + + + + + + + + + +
Target ModelEAGLE3 Draft Model
nex-agi/Qwen3-30B-A3B-Nex-N1[🤗 Hugging Face](https://huggingface.co/nex-agi/SGLANG-EAGLE3-Qwen3-30B-A3B-Nex-N1)
nex-agi/Qwen3-32B-Nex-N1[🤗 Hugging Face](https://huggingface.co/nex-agi/SGLANG-EAGLE3-Qwen3-32B-Nex-N1)
diff --git a/docs_new/custom.css b/docs_new/custom.css new file mode 100644 index 000000000..3dd898727 --- /dev/null +++ b/docs_new/custom.css @@ -0,0 +1,101 @@ +:where(*) { + scrollbar-width: none; + -ms-overflow-style: none; +} + +:where(*)::-webkit-scrollbar { + width: 0; + height: 0; +} + +:where(pre, code, .code-block, .code-group, #request-example, #response-example), +:where(pre, code, .code-block, .code-group, #request-example, #response-example) * { + scrollbar-width: auto; + -ms-overflow-style: auto; +} + +:where(pre, code, .code-block, .code-group, #request-example, #response-example)::-webkit-scrollbar, +:where(pre, code, .code-block, .code-group, #request-example, #response-example) *::-webkit-scrollbar { + width: 10px; + height: 10px; +} + +/* Global table styling to match vision-language-models.mdx reference */ +table { + width: 100%; + border-collapse: collapse; + table-layout: fixed; +} + +table thead tr { + border-bottom: 2px solid #d55816; +} + +table thead th { + text-align: left; + padding: 10px 12px; + font-weight: 700; + white-space: nowrap; +} + +table thead th:nth-child(odd) { + background-color: rgba(255,255,255,0.02); +} + +table thead th:nth-child(even) { + background-color: rgba(255,255,255,0.05); +} + +table tbody tr:nth-child(odd) td { + background-color: rgba(255,255,255,0.02); +} + +table tbody tr:nth-child(even) td { + background-color: rgba(255,255,255,0.05); +} + +table tbody td { + padding: 9px 12px; +} + +table tbody td:first-child { + font-weight: 500; +} + +/* Dark mode support for tables */ +html.dark table thead th:nth-child(odd), +[data-theme="dark"] table thead th:nth-child(odd) { + background-color: rgba(255,255,255,0.02); +} + +html.dark table thead th:nth-child(even), +[data-theme="dark"] table thead th:nth-child(even) { + background-color: rgba(255,255,255,0.05); +} + +html.dark table tbody tr:nth-child(odd) td, +[data-theme="dark"] table tbody tr:nth-child(odd) td { + background-color: rgba(255,255,255,0.02); +} + +html.dark table tbody tr:nth-child(even) td, +[data-theme="dark"] table tbody tr:nth-child(even) td { + background-color: rgba(255,255,255,0.05); +} + +/* Bold text (**text**) */ +.prose strong, .prose b { + font-weight: 600; +} + +/* Inline code (single backtick) */ +:not(pre) > code { + background-color: rgba(0, 0, 0, 0.07); + font-weight: 600; +} + +html.dark :not(pre) > code, +[data-theme="dark"] :not(pre) > code { + background-color: rgba(255, 255, 255, 0.13); + font-weight: 600; +} diff --git a/docs_new/docs.json b/docs_new/docs.json new file mode 100644 index 000000000..21db5501c --- /dev/null +++ b/docs_new/docs.json @@ -0,0 +1,564 @@ +{ + "$schema": "https://mintlify.com/docs.json", + "theme": "aspen", + "name": "SGLang Documentation", + "seo": { + "metatags": { + "google-site-verification": "bX3ofyYQhraIpAYf4DpyZQXZO_G4xLR_RqeBAKnJA7g" + } + }, + "redirects": [ + { + "source": "/docs/references/learn_more", + "destination": "/" + } + ], + "colors": { + "primary": "#d55816", + "light": "#d55816", + "dark": "#d55816" + }, + "background": { + "decoration": "grid", + "color": { + "dark": "#1d1d1d", + "light": "#fffcfb" + } + }, + "fonts": { + "heading": { + "family": "Inter", + "weight": 600 + }, + "body": { + "family": "Inter", + "weight": 400 + } + }, + "favicon": "/favicon.png", + "navigation": { + "tabs": [ + { + "tab": "Get Started", + "groups": [ + { + "group": "Get Started", + "icon": "play", + "pages": [ + "index", + "docs/get-started/installation", + "docs/get-started/quickstart", + "docs/basic_usage/send_request" + ] + } + ] + }, + { + "tab": "User Guide", + "groups": [ + { + "group": "Basic Usage", + "icon": "book-open", + "pages": [ + "docs/basic_usage/overview", + { + "group": "OpenAI-Compatible APIs", + "pages": [ + "docs/basic_usage/openai_api", + "docs/basic_usage/openai_api_completions", + "docs/basic_usage/openai_api_vision", + "docs/basic_usage/openai_api_embeddings" + ] + }, + "docs/basic_usage/ollama_api", + "docs/basic_usage/offline_engine_api", + "docs/basic_usage/native_api", + "docs/basic_usage/sampling_params", + { + "group": "Popular Model Usage", + "pages": [ + "docs/basic_usage/popular_model_usage", + "docs/basic_usage/deepseek_v3", + "docs/basic_usage/deepseek_v32", + "docs/basic_usage/glm45", + "docs/basic_usage/glmv", + "docs/basic_usage/gpt_oss", + "docs/basic_usage/kimi_k2_5", + "docs/basic_usage/minimax_m2", + "docs/basic_usage/qwen3", + "docs/basic_usage/qwen3_vl", + "docs/basic_usage/llama4" + ] + } + ] + }, + { + "group": "Advanced Features", + "icon": "gears", + "pages": [ + "docs/advanced_features/overview", + "docs/advanced_features/server_arguments", + "docs/advanced_features/object_storage", + "docs/advanced_features/hyperparameter_tuning", + "docs/advanced_features/attention_backend", + "docs/advanced_features/speculative_decoding", + "docs/advanced_features/structured_outputs", + "docs/advanced_features/structured_outputs_for_reasoning_models", + "docs/advanced_features/tool_parser", + "docs/advanced_features/separate_reasoning", + "docs/advanced_features/quantization", + "docs/advanced_features/quantized_kv_cache", + "docs/advanced_features/dp_dpa_smg_guide", + "docs/advanced_features/expert_parallelism", + "docs/advanced_features/lora", + "docs/advanced_features/pd_disaggregation", + "docs/advanced_features/epd_disaggregation", + "docs/advanced_features/pipeline_parallelism", + { + "group": "Hierarchical KV Caching (HiCache)", + "pages": [ + "docs/advanced_features/hicache", + "docs/advanced_features/hicache_best_practices", + "docs/advanced_features/hicache_design", + "docs/advanced_features/hicache_storage_runtime_attach_detach" + ] + }, + "docs/advanced_features/vlm_query", + "docs/advanced_features/dp_for_multi_modal_encoder", + "docs/advanced_features/cuda_graph_for_multi_modal_encoder", + "docs/advanced_features/breakable_cuda_graph", + "docs/advanced_features/piecewise_cuda_graph", + "docs/advanced_features/sgl_model_gateway", + "docs/advanced_features/deterministic_inference", + "docs/advanced_features/observability", + "docs/advanced_features/checkpoint_engine", + "docs/advanced_features/sglang_for_rl" + ] + }, + { + "group": "Supported Models", + "icon": "cubes", + "pages": [ + "docs/supported-models", + { + "group": "Text Generation", + "pages": [ + "docs/supported-models/large-language-models", + "docs/supported-models/vision-language-models", + "docs/supported-models/diffusion-language-models" + ] + }, + { + "group": "Retrieval and Ranking", + "pages": [ + "docs/supported-models/embedding-models", + "docs/supported-models/rerank-models", + "docs/supported-models/classification-models" + ] + }, + { + "group": "Specialized Models", + "pages": [ + "docs/supported-models/reward-models" + ] + }, + { + "group": "Extending SGLang", + "pages": [ + "docs/supported-models/new-model-support", + "docs/supported-models/transformers-fallback", + "docs/supported-models/modelscope", + "docs/supported-models/mindspore-models" + ] + } + ] + }, + { + "group": "Developer Guide", + "icon": "code", + "pages": [ + "docs/developer_guide/overview", + "docs/developer_guide/contribution_guide", + { + "group": "Development", + "pages": [ + "docs/developer_guide/development_guide_using_docker", + "docs/developer_guide/JIT_kernels" + ] + }, + { + "group": "Benchmarking", + "pages": [ + "docs/developer_guide/benchmark_and_profiling", + "docs/developer_guide/bench_serving" + ] + }, + "docs/developer_guide/evaluating_new_models" + ] + }, + { + "group": "References", + "icon": "bookmark", + "pages": [ + "docs/references/overview", + "docs/references/faq", + "docs/references/environment_variables", + "docs/references/production_metrics", + "docs/references/production_request_trace", + { + "group": "Multi-Node Deployment", + "pages": [ + "docs/references/multi_node_deployment/multi_node_index", + "docs/references/multi_node_deployment/multi_node", + "docs/references/multi_node_deployment/deploy_on_k8s", + "docs/references/multi_node_deployment/lws_pd/lws_pd_deploy", + "docs/references/multi_node_deployment/rbg_pd/deepseekv32_pd" + ] + }, + "docs/references/custom_chat_template", + { + "group": "Frontend Language", + "pages": [ + "docs/references/frontend/frontend_index", + "docs/references/frontend/frontend_tutorial", + "docs/references/frontend/choices_methods" + ] + }, + { + "group": "Cookbook", + "pages": [ + "cookbook/base/reference/server_arguments" + ] + }, + "docs/references/post_training_integration" + ] + } + ] + }, + { + "tab": "Hardware", + "groups": [ + { + "group": "Hardware Platforms", + "icon": "microchip", + "pages": [ + "docs/hardware-platforms/overview", + "docs/hardware-platforms/nvidia-gpus", + "docs/hardware-platforms/amd-gpus", + { + "group": "Ascend NPUs", + "pages": [ + "docs/hardware-platforms/ascend-npus/Best-Practice-on-Ascend-NPU", + "docs/hardware-platforms/ascend-npus/DeepSeek-Examples", + "docs/hardware-platforms/ascend-npus/GLM-5", + "docs/hardware-platforms/ascend-npus/MindSpore-Models", + "docs/hardware-platforms/ascend-npus/Qwen3-Examples", + "docs/hardware-platforms/ascend-npus/Qwen3.5", + "docs/hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support", + "docs/hardware-platforms/ascend-npus/Support-Features-on-Ascend-NPU", + "docs/hardware-platforms/ascend-npus/Support-Models-on-Ascend-NPU" + ] + }, + "docs/hardware-platforms/cpu-server", + { + "group": "Edge & Embedded", + "pages": [ + "docs/hardware-platforms/nvidia" + ] + }, + "docs/hardware-platforms/tpu", + "docs/hardware-platforms/xpu" + ] + } + ] + }, + { + "tab": "Cookbook", + "groups": [ + { + "group": "Cookbook", + "icon": "book", + "pages": [ + "cookbook/intro", + { + "group": "Autoregressive Models", + "pages": [ + "cookbook/autoregressive/intro", + { + "group": "Qwen", + "pages": [ + "cookbook/autoregressive/Qwen/Qwen3.6", + "cookbook/autoregressive/Qwen/Qwen3.5", + "cookbook/autoregressive/Qwen/Qwen3", + "cookbook/autoregressive/Qwen/Qwen3-Next", + "cookbook/autoregressive/Qwen/Qwen3-Coder", + "cookbook/autoregressive/Qwen/Qwen3-Coder-Next", + "cookbook/autoregressive/Qwen/Qwen3-VL", + "cookbook/autoregressive/Qwen/Qwen2.5-VL" + ] + }, + { + "group": "DeepSeek", + "pages": [ + "cookbook/autoregressive/DeepSeek/DeepSeek-V3_2", + "cookbook/autoregressive/DeepSeek/DeepSeek-V3_1", + "cookbook/autoregressive/DeepSeek/DeepSeek-V3", + "cookbook/autoregressive/DeepSeek/DeepSeek-R1", + "cookbook/autoregressive/DeepSeek/DeepSeek-Math-V2", + "cookbook/autoregressive/DeepSeek/DeepSeek-OCR", + "cookbook/autoregressive/DeepSeek/DeepSeek-OCR-2" + ] + }, + { + "group": "Llama", + "pages": [ + "cookbook/autoregressive/Llama/Llama4", + "cookbook/autoregressive/Llama/Llama3.3-70B", + "cookbook/autoregressive/Llama/Llama3.1" + ] + }, + { + "group": "GLM", + "pages": [ + "cookbook/autoregressive/GLM/GLM-4.5", + "cookbook/autoregressive/GLM/GLM-4.6", + "cookbook/autoregressive/GLM/GLM-4.7", + "cookbook/autoregressive/GLM/GLM-4.7-Flash", + "cookbook/autoregressive/GLM/GLM-5", + "cookbook/autoregressive/GLM/GLM-5.1", + "cookbook/autoregressive/GLM/GLM-Glyph", + "cookbook/autoregressive/GLM/GLM-OCR", + "cookbook/autoregressive/GLM/GLM-4.5V", + "cookbook/autoregressive/GLM/GLM-4.6V" + ] + }, + { + "group": "Google", + "pages": [ + "cookbook/autoregressive/Google/Gemma4" + ] + }, + { + "group": "OpenAI", + "pages": [ + "cookbook/autoregressive/OpenAI/GPT-OSS" + ] + }, + { + "group": "Moonshotai", + "pages": [ + "cookbook/autoregressive/Moonshotai/Kimi-K2.6", + "cookbook/autoregressive/Moonshotai/Kimi-K2.5", + "cookbook/autoregressive/Moonshotai/Kimi-K2", + "cookbook/autoregressive/Moonshotai/Kimi-Linear" + ] + }, + { + "group": "MiniMax", + "pages": [ + "cookbook/autoregressive/MiniMax/MiniMax-M2.7", + "cookbook/autoregressive/MiniMax/MiniMax-M2", + "cookbook/autoregressive/MiniMax/MiniMax-M2.5" + ] + }, + { + "group": "NVIDIA", + "pages": [ + "cookbook/autoregressive/NVIDIA/Nemotron3-Nano", + "cookbook/autoregressive/NVIDIA/Nemotron3-Super" + ] + }, + { + "group": "Ernie", + "pages": [ + "cookbook/autoregressive/Ernie/Ernie4.5", + "cookbook/autoregressive/Ernie/Ernie4.5-VL" + ] + }, + { + "group": "StepFun", + "pages": [ + "cookbook/autoregressive/StepFun/Step3.5", + "cookbook/autoregressive/StepFun/Step3-VL-10B" + ] + }, + { + "group": "InclusionAI", + "pages": [ + "cookbook/autoregressive/InclusionAI/Ling-2.5-1T", + "cookbook/autoregressive/InclusionAI/Ring-2.5-1T", + "cookbook/autoregressive/InclusionAI/LLaDA-2.1" + ] + }, + { + "group": "InternLM", + "pages": [ + "cookbook/autoregressive/InternLM/Intern-S1" + ] + }, + { + "group": "InternVL", + "pages": [ + "cookbook/autoregressive/InternVL/InternVL3.5" + ] + }, + { + "group": "Jina AI", + "pages": [ + "cookbook/autoregressive/Jina/Jina-reranker-m0" + ] + }, + { + "group": "Mistral", + "pages": [ + "cookbook/autoregressive/Mistral/Ministral-3", + "cookbook/autoregressive/Mistral/Mistral-Small-4", + "cookbook/autoregressive/Mistral/Devstral-2" + ] + }, + { + "group": "Xiaomi", + "pages": [ + "cookbook/autoregressive/Xiaomi/MiMo-V2-Flash" + ] + }, + { + "group": "FlashLabs", + "pages": [ + "cookbook/autoregressive/FlashLabs/Chroma1.0" + ] + } + ] + }, + { + "group": "Diffusion Models", + "pages": [ + "cookbook/diffusion/intro", + { + "group": "FLUX", + "pages": [ + "cookbook/diffusion/FLUX/FLUX" + ] + }, + { + "group": "Wan", + "pages": [ + "cookbook/diffusion/Wan/Wan2.1", + "cookbook/diffusion/Wan/Wan2.2" + ] + }, + { + "group": "Qwen-Image", + "pages": [ + "cookbook/diffusion/Qwen-Image/Qwen-Image", + "cookbook/diffusion/Qwen-Image/Qwen-Image-Edit" + ] + }, + { + "group": "Z-Image", + "pages": [ + "cookbook/diffusion/Z-Image/Z-Image-Turbo" + ] + }, + { + "group": "MOVA", + "pages": [ + "cookbook/diffusion/MOVA/MOVA" + ] + } + ] + }, + { + "group": "SpecBundle", + "pages": [ + "cookbook/specbundle/supported_models", + "cookbook/specbundle/specbundle_usage" + ] + }, + { + "group": "Benchmarks", + "pages": [ + "cookbook/base/benchmarks/autoregressive_model_benchmark", + "cookbook/base/benchmarks/diffusion_model_benchmark" + ] + } + ] + } + ] + }, + { + "tab": "SGLang Diffusion", + "groups": [ + { + "group": "SGLang Diffusion", + "icon": "sparkles", + "pages": [ + "sglang-diffusion/intro", + "docs/sglang-diffusion/installation", + "docs/sglang-diffusion/supported-models", + { + "group": "Usage", + "pages": [ + "docs/sglang-diffusion/api/cli", + "docs/sglang-diffusion/api/openai-api" + ] + }, + { + "group": "Performance Optimization", + "pages": [ + "docs/sglang-diffusion/performance-optimization", + "docs/sglang-diffusion/attention-backends", + "docs/sglang-diffusion/profiling", + "docs/sglang-diffusion/ci-performance" + ] + }, + { + "group": "Caching Strategies", + "pages": [ + "docs/sglang-diffusion/caching-acceleration", + "docs/sglang-diffusion/cache-dit", + "docs/sglang-diffusion/tea-cache" + ] + }, + { + "group": "References", + "pages": [ + "docs/sglang-diffusion/environment-variables", + "docs/sglang-diffusion/supported-models" + ] + } + ] + } + ] + } + ], + "global": { + "anchors": [] + } + }, + "logo": { + "light": "/logo/logo.png", + "dark": "/logo/logo.png" + }, + "contextual": { + "options": [ + "copy", + "view", + "chatgpt", + "claude", + "perplexity", + "mcp", + "cursor", + "vscode" + ] + }, + "footer": { + "socials": { + "github": "https://github.com/sgl-project/sglang", + "x": "https://x.com/lmsysorg", + "linkedin": "https://www.linkedin.com/company/sgl-project/posts?feedView=all", + "slack": "https://slack.sglang.io/", + "discord": "https://discord.gg/4ugb2t6YY2" + } + } +} diff --git a/docs_new/docs/advanced_features/attention_backend.mdx b/docs_new/docs/advanced_features/attention_backend.mdx new file mode 100644 index 000000000..2d07fa02c --- /dev/null +++ b/docs_new/docs/advanced_features/attention_backend.mdx @@ -0,0 +1,520 @@ +--- +title: "Attention Backend" +metatags: + description: "SGLang attention backend guide: FlashInfer, FA3, FA4, Triton, FlashMLA, TRTLLM MLA, hybrid attention. Support matrix for MHA and MLA models." +--- +SGLang supports a large variety of attention backends. Each of them has different pros and cons. +You can test them according to your needs. + + +Selecting an optimal attention backend is crucial for maximizing your performance. Different backends excel in various scenarios, so choose based on your model, hardware, and use case. Not all backends are supported on all platforms and model architectures. + +If you don't specify `--attention-backend`, SGLang makes a best effort to automatically select the most performant backend based on your hardware and model architecture. + + +## Support Matrix + +The support matrix is split into two parts: MHA (standard attention) and MLA (multi-head latent attention). For an explanation of the key differences between MHA and MLA, please see the [SGLang documentation on DeepSeek MLA](../basic_usage/deepseek_v3.md#multi-head-latent-attention-mla-throughput-optimizations) and the original [DeepSeek MLA paper](https://arxiv.org/pdf/2405.04434). + +### MHA Backends + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Backend****Page Size > 1 (native)****FP8 KV Cache****FP4 KV Cache****Spec topk=1****Spec topk>1****Sliding Window****MultiModal**
**FlashInfer**
**FA3 (FlashAttention 3)**
**FA4 (FlashAttention 4)**128
**Triton**
**Torch Native (SDPA)**
**FlexAttention (PyTorch)**
**TRTLLM MHA**16, 32 or 64
**Dual Chunk FlashAttention**
**AITER (ROCm)**
**Wave (ROCm)**
**Ascend (NPU)**
**Intel XPU**
**Intel AMX (CPU)**
+ +### MLA Backends + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Backend****Native Page Sizes****FP8 KV Cache****FP4 KV Cache****Chunked Prefix Cache****Spec topk=1****Spec topk>1**
**FlashInfer MLA**1
**FlashMLA**64
**Cutlass MLA**128
**TRTLLM MLA (Blackwell)**32 or 64
**FA3 (FlashAttention 3)**n/a⚠️ (page_size=1 only)
**Triton**n/a⚠️ (page_size=1 only)
**FA4**1
**Ascend MLA (NPU)**128
+ + +Multimodal attention is selected by `--mm-attention-backend`. The "MultiModal" column indicates whether a corresponding multimodal implementation exists for that backend family. + + + +- FlashAttention 4 is prefill-only for now. +- NSA is specifically designed for [DeepSeek V3.2 DSA](https://lmsys.org/blog/2025-09-29-deepseek-V32/). + + + +For the KV4 FA4 scenario, FA4 requires using a different --decode-attention-backend to run. Except for trtllm_mha being incompatible with FA4, all other decode backends behave as shown in the table. + + + +Speculative decoding topk: `topk` is the number of draft tokens sampled per step from the draft model. `topk = 1` follows classic EAGLE; `topk > 1` explores multiple branches and requires backend support in both draft and verification paths. + + + +Page size controls how many tokens are grouped into a KV cache block. For the prefix cache to take effect, the number of tokens must fill at least one complete page. For example, if your prompt is only 32 tokens and `page_size = 64`, it won't fill a complete page and cannot be matched in the prefix cache (pages cannot be padded). With 65 tokens and `page_size = 64`, only the first page of 64 tokens will be cached and matched; the remaining 1 token is discarded. Use `page_size = 1` for maximum prefix reuse (token-level matching). + + +Many backends that do not natively operate on pages can emulate `page_size > 1` at the wrapper layer by expanding page tables to per-token indices. The "Page Size > 1 (native)" column indicates true in-kernel paging. Some backends require fixed native page sizes and cannot be reduced/emulated differently: TRTLLM MHA (16/32/64), TRTLLM MLA (32/64), FlashMLA (64), Cutlass MLA (128), Ascend (128). + +MLA page-size constraints: +- FlashInfer MLA: page_size = 1. +- FlashMLA: page_size = 64. +- Cutlass MLA: page_size = 128. +- TRTLLM MLA: page_size ∈ {32, 64}. + +### Hybrid attention (different backends for prefill vs decode) (Experimental) + + +Hybrid attention is an experimental feature. + + +You can mix-and-match attention backends for prefill and decode. This is useful when one backend excels at prefill and another excels at decode. For the implementation details, please see `python/sglang/srt/layers/attention/hybrid_attn_backend.py`. + +```bash Command +# Example: Prefill with FA4, Decode with TRTLLM MLA (Blackwell) +python3 -m sglang.launch_server \ + --model-path nvidia/DeepSeek-R1-FP4 \ + --tp 8 \ + --attention-backend trtllm_mla \ + --moe-runner-backend flashinfer_trtllm \ + --quantization modelopt_fp4 \ + --prefill-attention-backend fa4 +``` + +#### Speculative decoding with hybrid attention + +Hybrid attention also works with speculative decoding. The backend used for draft decoding and target verification depends on `--speculative-attention-mode`: + +- `--speculative-attention-mode decode` (recommended): draft/verify use the decode backend. +- `--speculative-attention-mode prefill` (default): draft/verify use the prefill backend. + +Constraints when combining hybrid attention with speculative decoding: + +- If any attention backend is `trtllm_mha`, speculative decoding supports only `--speculative-eagle-topk 1`. +- For paged MHA backends with `--page-size > 1` and `--speculative-eagle-topk > 1`, only `flashinfer` is supported. +- CUDA Graph: the decode backend is always captured; the prefill backend is captured only when `--speculative-attention-mode prefill`. + + + +If you set only one of `--prefill-attention-backend` or `--decode-attention-backend`, the unspecified phase inherits `--attention-backend`. +If both are specified and differ, SGLang automatically enables a hybrid wrapper to dispatch to the chosen backend per phase. + + +## Attention Backend Selection Guide (CUDA) + +If the `--attention-backend` argument is not specified, SGLang automatically selects the best backend based on the hardware (CUDA) and model architecture. + +### Automatic Selection Logic + +**1. MHA Models (e.g., Llama, Qwen)** +- **Hopper (e.g., H100, H200)**: Defaults to `fa3` if using CUDA 12.3+ and the model configuration is supported. +- **Blackwell (e.g., B200)**: Defaults to `trtllm_mha`, unless using speculative decoding with `topk > 1`. +- **Other Architectures (Ampere, Ada, etc.)**: Defaults to `flashinfer` if available; otherwise falls back to `triton`. + +**2. MLA Models (e.g., DeepSeek V3)** +- **Hopper**: Defaults to `fa3` (requires CUDA 12.3+). +- **Blackwell**: Defaults to `trtllm_mla`. +- **Other Architectures**: Defaults to `triton`. + + +## User Guide + +### Launch Command for Different Attention Backends + +- FlashInfer (Default for Non-Hopper Machines, e.g., A100, A40) +```bash Command +python3 -m sglang.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --attention-backend flashinfer +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-V3 \ + --attention-backend flashinfer \ + --trust-remote-code +``` + +- FlashAttention 3 (Default for Hopper Machines, e.g., H100, H200, H20) +```bash Command +python3 -m sglang.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --attention-backend fa3 +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-V3 \ + --trust-remote-code \ + --attention-backend fa3 +``` + +- Triton +```bash Command +python3 -m sglang.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --attention-backend triton +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-V3 \ + --attention-backend triton \ + --trust-remote-code +``` + +- FlashMLA +```bash Command +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-R1 \ + --attention-backend flashmla \ + --trust-remote-code +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-R1 \ + --attention-backend flashmla \ + --kv-cache-dtype fp8_e4m3 \ + --trust-remote-code +``` + +- TRTLLM MLA (Optimized for Blackwell Architecture, e.g., B200) +```bash Command +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-R1 \ + --attention-backend trtllm_mla \ + --trust-remote-code +``` + +- TRTLLM MLA with FP8 KV Cache (Higher concurrency, lower memory footprint) +```bash Command +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-R1 \ + --attention-backend trtllm_mla \ + --kv-cache-dtype fp8_e4m3 \ + --trust-remote-code +``` + +- FlashAttention 4 (MHA & MLA) +```bash Command +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-R1 \ + --prefill-attention-backend fa4 \ + --trust-remote-code +``` + +- Cutlass MLA +```bash Command +python3 -m sglang.launch_server \ + --tp 8 \ + --model deepseek-ai/DeepSeek-R1 \ + --attention-backend cutlass_mla \ + --trust-remote-code +``` + +- Ascend +```bash Command +python3 -m sglang.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --attention-backend ascend +``` + +- Intel XPU +```bash Command +python3 -m sglang.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --attention-backend intel_xpu +``` + +- Wave +```bash Command +python3 -m sglang.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --attention-backend wave +``` + +- FlexAttention +```bash Command +python3 -m sglang.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --attention-backend flex_attention +``` + +- Dual Chunk FlashAttention +```bash Command +python3 -m sglang.launch_server \ + --model Qwen/Qwen2.5-14B-Instruct-1M \ + --attention-backend dual_chunk_flash_attn +``` + +- Torch Native +```bash Command +python3 -m sglang.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --attention-backend torch_native +``` + +## Steps to add a new attention backend +To add a new attention backend, you can learn from the existing backends +(`python/sglang/srt/layers/attention/triton_backend.py`, `python/sglang/srt/layers/attention/flashattention_backend.py`) +and follow the steps below. + +1. Run without cuda graph. Support the two forward functions + - forward_extend + - Will be used for prefill, prefill with KV cache, and target verification + - It will be called once per layer + - forward_decode + - Will be used for normal decode, and draft decode + - It will be called once per layer + - init_forward_metadata + - Initialize the class and common metadata shared by all layers + - Call the plan function for optimizations like split_kv + - It will be called once per forward +2. Run with cuda graph. It has two phases (capture and replay) and you need to implement three functions + - init_cuda_graph_state + - It will be called once during life time + - Create all common shared buffers + - init_forward_metadata_capture_cuda_graph + - It will be called before capturing a cuda graph + - It is similar to init_forward_metadata but write the medatada to some pre-defined buffers + - init_forward_metadata_replay_cuda_graph + - It will be called before replaying a cuda graph + - This function is in the critical path and needs to be fast diff --git a/docs_new/docs/advanced_features/breakable_cuda_graph.mdx b/docs_new/docs/advanced_features/breakable_cuda_graph.mdx new file mode 100644 index 000000000..3497ba837 --- /dev/null +++ b/docs_new/docs/advanced_features/breakable_cuda_graph.mdx @@ -0,0 +1,192 @@ +--- +title: "Breakable CUDA Graph" +metatags: + description: "Use Breakable CUDA Graph to insert targeted eager graph breaks for debugging and CUDA graph compatibility." +--- + +## Motivation + +Standard CUDA graphs capture an entire forward pass as a single, opaque graph. This is great for performance, but creates two problems: + +1. **Debugging is hard.** When something goes wrong inside a captured graph (wrong outputs, numerical mismatches, crashes), there is no way to step through the operations or insert print statements because the graph replays as a monolithic unit. + +2. **Some ops are incompatible.** Certain operations — dynamic control flow, host-device synchronization, JIT compilation, or ops that change behavior across iterations — cannot be captured into a CUDA graph at all. Today, the only workaround is to disable CUDA graphs entirely, which sacrifices the kernel launch overhead savings for the rest of the model. + +**Breakable CUDA Graph** solves both problems by allowing graph breaks to be inserted at specific points. The computation is split into multiple captured graph segments with eager (non-graph) execution in between. This preserves most of the CUDA graph performance benefit while allowing targeted operations to run outside the graph. + +## Usage + +### Debug Mode: Run Everything Eagerly + +The simplest use case is debugging. The `--debug-cuda-graph` flag wraps the entire decode forward pass in a graph break, so every operation runs eagerly while still going through the full CUDA graph capture/replay code path. This lets you debug CUDA graph issues without changing model code. + +```bash +python -m sglang.launch_server \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --debug-cuda-graph +``` + +This mode is intended for debugging only — it eliminates the performance benefit of CUDA graphs since every op runs eagerly. + +### Selective Graph Breaks in Model Code + +For production use, you can mark specific functions as "non-graphable" using the `@eager_on_graph` decorator. During CUDA graph capture, these functions run eagerly between captured graph segments. Outside of capture, they behave normally. + +```python +from sglang.srt.model_executor.breakable_cuda_graph.breakable_cuda_graph import eager_on_graph + +@eager_on_graph(enable=True) +def my_dynamic_op(x): + # This op is incompatible with CUDA graph capture + return some_dynamic_operation(x) +``` + +You can also insert a bare graph break (no computation) using the `break_graph()` helper: + +```python +from sglang.srt.model_executor.breakable_cuda_graph.breakable_cuda_graph import break_graph + +def forward(self, x): + x = self.layer1(x) + break_graph() # force a segment split here + x = self.layer2(x) + return x +``` + +To enable breakable CUDA graph at the environment level (without debug mode), set the environment variable: + +```bash +export SGLANG_USE_BREAKABLE_CUDA_GRAPH=1 +python -m sglang.launch_server \ + --model meta-llama/Llama-3.1-8B-Instruct +``` + +### Server Args + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultDescription
--debug-cuda-graphFalseEnable debug/eager mode. Wraps the entire forward pass in a graph break so every op runs eagerly through the capture/replay path.
SGLANG_USE_BREAKABLE_CUDA_GRAPH0Environment variable. Enables breakable CUDA graph without debug mode. Required for @eager_on_graph decorators to take effect.
+ +## How It Works + +### Capture + +Breakable CUDA graph extends PyTorch's `torch.cuda.CUDAGraph` by splitting a single capture into multiple segments separated by graph breaks. + +During capture, the flow is: + +``` +Begin capture (segment 1) + ... graphable ops ... + @eager_on_graph function encountered: + 1. End current capture segment + 2. Run the function eagerly (allocates output tensors) + 3. Record the function for later replay + 4. Begin new capture segment + ... more graphable ops ... +End capture (segment N) +``` + +Each segment is independently instantiated as a CUDA graph executable. The non-graph functions and their argument references are stored for replay. + +### Replay + +During replay: + +``` +For each segment i: + 1. Launch CUDA graph segment i + 2. Run the recorded non-graph function i eagerly +Launch final CUDA graph segment +``` + +The non-graph functions are re-invoked with the same tensor references as capture time. Since these references point to the CUDA graph's static input/output buffers, they see updated values on each replay. + +### Output Writeback + +When a non-graph function produces output during replay, the result must be written back into the same tensor buffers that downstream graph segments reference. The mechanism handles: + +- **Plain tensors**: In-place `copy_()` into the original buffer. +- **Structured outputs** (dataclasses, objects with tensor attributes): Tensor fields are copied in-place; non-tensor fields are replaced. +- **Dicts of tensors**: Tensor values are copied in-place; non-tensor values are replaced. + +### Stream Fork/Join Tracking + +Some models fork work onto secondary CUDA streams (e.g., for overlapped computation). Breakable CUDA graph hooks `torch.cuda.Stream.wait_stream` to track which streams are forked from the capture stream. When a graph break occurs, all forked streams are automatically joined back before ending the capture segment, and re-forked after beginning the next segment. + +## Compatibility + +- **NVIDIA CUDA only.** Breakable CUDA graph is not supported on ROCm/HIP or other non-CUDA platforms. On unsupported platforms, `--debug-cuda-graph` is automatically disabled with a warning. +- **Requires `cuda-python`.** The `cuda.bindings` package must be installed (`pip install cuda-python`). +- **Not compatible with memory saver mode.** Cannot be used together with `SGLANG_MEMORY_SAVER_CUDA_GRAPH`. + +## Performance + +When no graph breaks are inserted, breakable CUDA graph has minimal overhead compared to standard CUDA graph — the capture/replay path is nearly identical. + +Each graph break adds: +- One `cudaGraphLaunch` call (to replay the segment before the break) +- One eager Python function call +- One `cudaStreamBeginCapture` / `cudaStreamEndCapture` pair during capture + +For typical use cases with a small number of graph breaks, the overhead is negligible compared to the saved kernel launch overhead from the captured segments. + +## Code Reference + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileDescription
python/sglang/srt/model_executor/breakable_cuda_graph/breakable_cuda_graph.pyCore implementation: eager_on_graph, BreakableCUDAGraph, BreakableCUDAGraphCapture
python/sglang/srt/model_executor/breakable_cuda_graph/cuda_utils.pyCUDA runtime binding utilities
python/sglang/srt/model_executor/cuda_graph_runner.pyIntegration with the main CUDA graph runner
python/sglang/srt/server_args.py--debug-cuda-graph flag and environment variable handling
python/sglang/srt/environ.pySGLANG_USE_BREAKABLE_CUDA_GRAPH environment variable definition
diff --git a/docs_new/docs/advanced_features/checkpoint_engine.mdx b/docs_new/docs/advanced_features/checkpoint_engine.mdx new file mode 100644 index 000000000..59472e609 --- /dev/null +++ b/docs_new/docs/advanced_features/checkpoint_engine.mdx @@ -0,0 +1,257 @@ +--- +title: "Checkpoint Engine Integration" +metatags: + description: "SGLang checkpoint engine: distributed model weight loading, parallel multi-node setup, broadcast and P2P modes. Reduces loading time for large models." +--- +The SGLang checkpoint engine integration provides an efficient way to load model weights using a distributed checkpoint loading system. This feature significantly reduces model loading time, especially for large models and multi-node setups, by parallelizing the weight loading process across multiple processes and nodes. + +## Overview + +The checkpoint engine integration allows SGLang to: +- Load model weights in parallel using multiple processes +- Distribute weight loading across multiple nodes to increase effective disk bandwidth +- Overlap weight loading with other initialization tasks like CUDA graph capture +- Support both single-node and multi-node deployments + +## Installation + +First, install the checkpoint engine package: + +```bash Command +pip install 'checkpoint-engine[p2p]' +``` + +## Architecture + +The system consists of two main components: + +1. **SGLang Server**: Runs with `--wait-for-initial-weights` flag to wait for weights before becoming ready +2. **Checkpoint Engine Workers**: Separate processes (managed by torchrun) that load and distribute model weights + +The checkpoint engine uses a parameter server architecture with support for: +- **Broadcast mode**: Weights are broadcast from loading processes to inference processes +- **P2P mode**: Direct peer-to-peer weight transfer between processes +- **All mode**: Combination of both broadcast and P2P methods + +## Usage Examples + +### Single Node Setup + +**Terminal 1 - Launch SGLang Server:** +```bash Command +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-8B \ + --tp 8 \ + --load-format dummy \ + --wait-for-initial-weights +``` + +**Terminal 2 - Run Checkpoint Engine:** + +Using sglang entrypoint: +```bash Command +python -m sglang.srt.checkpoint_engine.update \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 8 +``` + +Using torchrun directly: +```bash Command +torchrun --nproc-per-node 8 \ + examples/checkpoint_engine/update.py \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 8 +``` + +### Multi-Node Setup (2 Nodes) + +**Node 0:** + +Launch SGLang server: +```bash Command +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-8B \ + --tp 8 \ + --load-format dummy \ + --wait-for-initial-weights \ + --host [IP] +``` + +Run checkpoint engine: + +Using sglang entrypoint (recommended): +```bash Command +python -m sglang.srt.checkpoint_engine.update \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 8 +``` + +Using torchrun directly: +```bash Command +torchrun --nproc-per-node 8 \ + --nnodes 2 \ + --node-rank 0 \ + --master-addr [IP] \ + --master-port 29500 \ + examples/checkpoint_engine/update.py \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 8 +``` + +**Node 1:** + +Launch SGLang server: +```bash Command +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-8B \ + --tp 8 \ + --load-format dummy \ + --wait-for-initial-weights \ + --host [IP] +``` + +Run checkpoint engine: + +Using sglang entrypoint (recommended): +```bash Command +python -m sglang.srt.checkpoint_engine.update \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 8 +``` + +Using torchrun directly: +```bash Command +torchrun --nproc-per-node 8 \ + --nnodes 2 \ + --node-rank 1 \ + --master-addr [IP] \ + --master-port 29500 \ + examples/checkpoint_engine/update.py \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 8 +``` + +### Multi-Node Setup with Tensor Parallelism (TP=16) + +**Node 0:** + +Launch SGLang server: +```bash Command +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-8B \ + --tp 8 \ + --load-format dummy \ + --wait-for-initial-weights \ + --host [IP] \ + --dist-init-addr [IP]:9120 \ + --nnodes 2 \ + --node-rank 0 +``` + +Run checkpoint engine: + +Using sglang entrypoint (recommended): +```bash Command +python -m sglang.srt.checkpoint_engine.update \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 16 +``` + +Using torchrun directly: +```bash Command +torchrun --nproc-per-node 8 \ + --nnodes 2 \ + --node-rank 0 \ + --master-addr [IP] \ + --master-port 29500 \ + examples/checkpoint_engine/update.py \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 16 +``` + +**Node 1:** + +Launch SGLang server: +```bash Command +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-8B \ + --tp 8 \ + --load-format dummy \ + --wait-for-initial-weights \ + --host [IP] \ + --dist-init-addr [IP]:9120 \ + --nnodes 2 \ + --node-rank 1 +``` + +Run checkpoint engine: + +Using sglang entrypoint (recommended): +```bash Command +python -m sglang.srt.checkpoint_engine.update \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 16 +``` + +Using torchrun directly: +```bash Command +torchrun --nproc-per-node 8 \ + --nnodes 2 \ + --node-rank 1 \ + --master-addr [IP] \ + --master-port 29500 \ + examples/checkpoint_engine/update.py \ + --update-method broadcast \ + --checkpoint-path /path/to/Qwen/Qwen3-8B/ \ + --inference-parallel-size 16 +``` + +## Configuration Options + +### SGLang Server Options + +- `--load-format dummy`: Use dummy format for initial loading (allows overlapping with other tasks) +- `--wait-for-initial-weights`: Wait for checkpoint engine to provide weights before becoming ready +- `--host`: Host address for multi-node setups +- `--dist-init-addr`: Distributed initialization address for tensor parallelism + +### Checkpoint Engine Options + +- `--update-method`: Weight update method (`broadcast`, `p2p`, or `all`) +- `--checkpoint-path`: Path to model checkpoint directory +- `--inference-parallel-size`: Number of inference parallel processes +- `--endpoint`: SGLang server endpoint (default: `http://localhost:19730`) +- `--checkpoint-name`: Name for the checkpoint (default: `my-checkpoint-iter-0`) +- `--save-metas-file`: File to save checkpoint metadata +- `--load-metas-file`: File to load checkpoint metadata from +- `--uds`: Unix domain socket path for communication +- `--weight-version`: Version identifier for weights + +## Performance Benefits + +The checkpoint engine provides significant time savings in two main aspects: + +1. **Multi-node Loading**: Each node only loads a portion of weights from disk, effectively increasing disk bandwidth. More participating nodes provide greater acceleration. Preliminary tests show 20-second acceleration when loading DeepSeek-R1 on H20-3e with two nodes. + +2. **Single Process Optimization**: Using dummy format allows overlapping disk-to-CPU transfer with CUDA graph capture and other initialization tasks, providing additional time savings. + +## Troubleshooting + +- Ensure checkpoint engine package is installed: `pip install 'checkpoint-engine[p2p]'` +- Verify network connectivity between nodes in multi-node setups +- Check that the checkpoint path contains valid model files +- Monitor logs for connection errors between SGLang server and checkpoint engine +- Use `--sleep-time` parameter to add delays if needed for debugging + +## References + +- [Checkpoint Engine Repository](https://github.com/MoonshotAI/checkpoint-engine) diff --git a/docs_new/docs/advanced_features/cuda_graph_for_multi_modal_encoder.mdx b/docs_new/docs/advanced_features/cuda_graph_for_multi_modal_encoder.mdx new file mode 100644 index 000000000..1ee463979 --- /dev/null +++ b/docs_new/docs/advanced_features/cuda_graph_for_multi_modal_encoder.mdx @@ -0,0 +1,76 @@ +--- +title: "Cuda Graph for Multi-Modal Encoder in SGLang" +metatags: + description: "CUDA Graph optimization for ViT in SGLang: reduce kernel launch overhead, dynamic input handling, support for Qwen2.5-VL and Qwen3-VL models." +--- +## Motivation + +In multimodal reasoning services, the visual encoder (ViT / Vision Transformer) typically has a few characteristic traits: + +Many layers, fragmented operators: Each layer includes LN, QKV projections, attention, MLP, residual connections, etc., resulting in extremely frequent kernel launches. + +Server-side “small batch / low latency” is common: The batch size is very small (sometimes it looks like 1 after “flattening” the batch), so kernel launch overhead accounts for a large portion of end-to-end latency. + +Input token count (number of patches) varies frequently: Different image/video resolutions and different batch composition lead to different sequence lengths +S — and this is precisely the biggest obstacle for CUDA Graph (unstable shapes). + +The value of CUDA Graph: It captures a long sequence of GPU kernels with fixed shapes and fixed memory addresses into a graph; later, for the same shapes, it can replay the graph directly, dramatically reducing launch overhead and making GPU scheduling more compact. + +This led us to seek a CUDA Graph enabled feature for ViT in order to improve ViT performance. + +## Design and Restrictions + +The new CUDA Graph enabled ViT logic is built on ViTCudaGraphRunner. This runner captures the "blocks + merger + deepstack merger (optional)" part of a vision transformer into a CUDA graph and replays it for identical shapes. See the following design consideration and restrictions for more details. + +### Dynamic inputs to fit static constraints of CUDA Graph + +Variable sequence length S is very common in ViT. While CUDA Graph requires fixed shapes. The solution is to build a graph cache by S(e.g., graph_key = S). The first time create a new S, and then capture a graph; afterwards, replay it. + +If there are many distinct S values, we need to increase VRAM usage which is graph-private memory pools for many graphs. + +### Stable addresses + +Everything "parameter-like" becomes a static buffer: + +- block_input / block_ws / block_output +- cu_full_len / cu_window_len and their kk variants +- sin_cos_ws + +In this way to solve the underlying requirement: during replay, not allowed to swap tensors, can only modify tensor contents. + +### Attention backend arguments +Attention backend arguments are fixed inside the graph: + +TritonAttn expects [cu_seqlens, cu_seqlens_kk, max_len] +FA3 expects [cu_seqlens, max_len] + +max_len is frozen as an int constant. +cu_seqlens is cached into a dict during create_graph(), and its contents are not updated during subsequent replays. + +For the same graph_key = S, you not only require the input shape to match, but also require the segmentation pattern in cu_seqlens (and window seqlens) to be identical. Otherwise, attention will segment the sequence incorrectly. + +### Rotary buffer management +The feature reallocates a larger sin_cos_ws when seq_len increases. +The max_content_len is used to make sure the maximum size of the allocated rotary buffer. + + +## Command Example +You can enable CUDA Graph for ViT by setting env variable `SGLANG_VIT_ENABLE_CUDA_GRAPH=1`, for example: +```shell Command +SGLANG_VIT_ENABLE_CUDA_GRAPH=1 \ +python3 -m sglang.launch_server \ + --model Qwen/Qwen3-VL-8B-Instruct +``` +Or you can run CUDA Graph for ViT together with Piecewise CUDA Graph feature by both setting env variable `SGLANG_VIT_ENABLE_CUDA_GRAPH=1` and setting `--enable-piecewise-cuda-graph`, for example: +```shell Command +SGLANG_VIT_ENABLE_CUDA_GRAPH=1 \ +python3 -m sglang.launch_server \ + --model Qwen/Qwen3-VL-8B-Instruct \ + --piecewise-cuda-graph-max-tokens 4096 \ + --enable-piecewise-cuda-graph \ + --piecewise-cuda-graph-compiler eager +``` + +## Known supported models +- Qwen2.5-VL (https://github.com/sgl-project/sglang/pull/14422) +- Qwen3-VL (https://github.com/sgl-project/sglang/pull/15320) diff --git a/docs_new/docs/advanced_features/deterministic_inference.mdx b/docs_new/docs/advanced_features/deterministic_inference.mdx new file mode 100644 index 000000000..9c6732810 --- /dev/null +++ b/docs_new/docs/advanced_features/deterministic_inference.mdx @@ -0,0 +1,215 @@ +--- +title: "Deterministic Inference" +metatags: + description: "SGLang deterministic inference: consistent outputs for RL training, testing, and production. Supports FlashInfer, FA3, Triton backends with CUDA Graph." +--- +## Why Deterministic Inference Matters + +Deterministic inference ensures consistent LLM outputs across runs, which is critical for: +- **Reinforcement Learning**: Ensures consistent logprobs across runs, reducing stochastic noise and making RL training more stable, reproducible, and debuggable. +- **Testing & Debugging**: Enables reproducible validation +- **Production**: Improves reliability and user experience + +Even with `temperature=0`, standard LLM inference can produce different outputs due to dynamic batching and varying reduction orders in GPU kernels. + +## The Root Cause of Non-Determinism + +The main source is **varying batch sizes**. Different batch sizes cause GPU kernels to split reduction operations differently, leading to different addition orders. Due to floating-point non-associativity (`(a + b) + c ≠ a + (b + c)`), this produces different results even for identical inputs. + + +## SGLang's Solution + +Building on [Thinking Machines Lab's batch-invariant operators](https://github.com/thinking-machines-lab/batch_invariant_ops), SGLang achieves fully deterministic inference while maintaining compatibility with chunked prefill, CUDA graphs, radix cache, and non-greedy sampling. The development roadmap for deterministic inference features can be found in this [issue](https://github.com/sgl-project/sglang/issues/10278). + +### Supported Backends + +Deterministic inference is only supported with the following three attention backends: **FlashInfer**, **FlashAttention 3 (FA3)**, and **Triton**. + +The following table shows feature compatibility for deterministic inference across different attention backends: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Attention BackendCUDA GraphChunked PrefillRadix CacheNon-greedy Sampling (Temp > 0)
**FlashInfer**✅ Yes✅ Yes❌ No✅ Yes
**FlashAttention 3 (FA3)**✅ Yes✅ Yes✅ Yes✅ Yes
**Triton**✅ Yes✅ Yes✅ Yes✅ Yes
+ +## Usage + +### Basic Usage + +Enable deterministic inference by adding the `--enable-deterministic-inference` flag: + +```bash Command +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-8B \ + --attention-backend fa3 \ + --enable-deterministic-inference +``` + +### Server Arguments + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentType/DefaultDescription
`--enable-deterministic-inference`flag; default: disabledEnable deterministic inference with batch-invariant operations
`--attention-backend`string; default: fa3Choose attention backend (flashinfer, fa3, or triton)
+ +### Example Configurations + +#### Qwen3-8B +```bash Command +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-8B \ + --attention-backend flashinfer \ + --enable-deterministic-inference +``` + +#### Llama Models +```bash Command +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --attention-backend fa3 \ + --enable-deterministic-inference +``` + +#### Qwen3-30B-A3B (MoE Model) +```bash Command +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-30B-A3B \ + --attention-backend fa3 \ + --enable-deterministic-inference +``` + +### Deterministic Inference with Non-Greedy Sampling (Temperature > 0) + +SGLang supports deterministic inference even with non-greedy sampling by using sampling seeds. This is particularly useful for reinforcement learning scenarios like GRPO (Group Relative Policy Optimization) where you need multiple diverse but reproducible responses. + +#### Default Behavior + +By default, SGLang uses a sampling seed of `42` for reproducible sampling: + +```python Example +import requests + +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "Tell me a joke", + "sampling_params": { + "temperature": 0.8, # Non-greedy sampling + "max_new_tokens": 128, + }, + }, +) +print(response.json()) +# This will always produce the same response across runs +``` + +#### Generating Multiple Reproducible Responses + +To sample different responses from the same prompt while maintaining reproducibility (e.g., for GRPO training), provide different sampling seeds in your requests: + +```python Example +import requests + +# Prepare a list of sampling seeds for different responses +sampling_seeds = [42, 43, 44, 45, 46] + +responses = [] +for seed in sampling_seeds: + response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "Tell me a joke", + "sampling_params": { + "temperature": 0.8, + "max_new_tokens": 128, + "sampling_seed": seed, # Specify sampling seed + }, + }, + ) + responses.append(response.json()) + +# Each seed will produce a different but reproducible response +# Using the same seed will always produce the same response +``` + +This approach ensures that: +- Different seeds produce diverse responses +- The same seed always produces the same response across different runs +- Results are reproducible for debugging and evaluation + + +## Verification + +Run deterministic tests to verify consistent outputs: + +```bash Command +# Single test: same prompt, varying batch sizes +python3 -m sglang.test.test_deterministic --test-mode single --n-trials 50 + +# Prefix test: prompts with different prefix lengths +python3 -m sglang.test.test_deterministic --test-mode prefix --n-trials 50 + +# Radix Cache Consistency mode: test radix cache determinism (cached vs uncached prefill) +python3 -m sglang.test.test_deterministic --test-mode radix_cache +``` + +Expected result: All tests should show `Unique samples: 1` (perfectly deterministic). diff --git a/docs_new/docs/advanced_features/dp_dpa_smg_guide.mdx b/docs_new/docs/advanced_features/dp_dpa_smg_guide.mdx new file mode 100644 index 000000000..cbb2545b7 --- /dev/null +++ b/docs_new/docs/advanced_features/dp_dpa_smg_guide.mdx @@ -0,0 +1,509 @@ +--- +title: "DP, DPA and SGLang DP Router" +metatags: + description: "Learn the differences between Data Parallelism, Data Parallelism Attention, and SGLang Model Gateway routing for production DP deployments." +--- + +This guide explains the difference between Data Parallelism (DP) and Data Parallelism Attention (DPA), how to enable each mode correctly, and how to use the SGLang Model Gateway (SMG) for production-grade DP deployments. + +## Data Parallelism (DP) + +**Data Parallelism (DP)** is the most common parallelism strategy that replicates the entire model across multiple GPU sets and processes different batches of requests in parallel. Each GPU set handles independent requests. With dedicated routing strategies, as we will introduce later, with those proper routing algorithms in SGLang Model Gateway, the throughput of your serving system could be multiplied nearly linearly. + +### Key characteristics + +- Each replica has a full copy of the model +- Requests are distributed/scattered across replicas +- No inter-replica communication during one request's inference (for simple DP) + +## Data Parallelism Attention (DPA) + +**Data Parallelism Attention (DPA)**, also known as DP Attention, is an advanced parallelism strategy. While DPA provides the most significant benefits for **Multi-Head Latent Attention (MLA)** models (such as DeepSeek, MiniMax, Kimi-K2), it also supports **standard attention models** like Qwen. + +### The Problem with Tensor Parallelism for MLA Models + +The most common parallelism strategy for inference is **Tensor Parallelism (TP)**. However, TP might not be the most efficient strategy for certain models. For example, DeepSeek models use MLA and only have **one KV head**. If we use tensor parallelism on 8 GPUs, it will lead to: + +- **Duplicated KV cache** across all GPUs +- **Unwanted memory usage** that limits batch size +- **Reduced throughput** due to memory constraints + +### How DPA Works + +DPA addresses these limitations by applying **data parallelism specifically to the attention component**. + + + + + + + + + + + + +
+ DPA + EP Architecture + +

Each DP replica:

+
    +
  • Processes different batches independently (can be in different forward modes: prefill, decode, or idle)
  • +
  • Maintains its own KV cache (no duplication)
  • +
  • Enables significantly larger batch sizes due to memory savings
  • +
+

Communication patterns in DPA + EP:

+
    +
  • All2All (Dispatch): Routes tokens to expert sub-groups based on gating decisions
  • +
  • All2All (Combine): Gathers computed results from experts back to original token positions
  • +
+
+ +### Key benefits of DPA + +1. **Significantly reduced KV cache memory**: Each DP replica only stores KV cache for its own batches +2. **Larger batch sizes**: Memory savings enable larger batch sizes +3. **Improved decoding throughput**: Significant throughput gains for MLA-based models +4. **Independent forward modes**: Each DP replica can be in different forward modes (prefill, decode, or idle) and handles its assigned batches independently during attention computation + +### DPA with Expert Parallelism for MoE + +For MoE models like DeepSeek, DPA is **often** paired with Expert Parallelism (EP) for best throughput at scale. However, **DPA does not require EP**: you can enable DPA without EP if your deployment does not need expert sharding. + +- Distribute 256+ expert weights across GPUs (cannot fit on a single GPU) +- Enable efficient all-to-all token routing via DeepEP +- Scale to large clusters (up to 5x throughput improvement over vanilla TP) + +### Recommended setup for DeepSeek + +```bash +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3 \ + --tp 8 \ + --dp-size 8 \ + --ep 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --moe-runner-backend deep_gemm +``` + +> **Note**: `--dp-size` must be explicitly set when using `--enable-dp-attention`. If `dp_size` is 1 (default), DPA will be disabled. + +For detailed EP configuration (DeepEP, Two-Batch Overlap, EPLB), see [Expert Parallelism](/docs/advanced_features/expert_parallelism). + +### Target Models + +DPA supports the following model architectures: + +- **MLA (Multi-Head Latent Attention) models** - where DPA provides the most significant benefits: + - DeepSeek family (DeepSeek-V2, DeepSeek-V3, DeepSeek-R1) + - MiniMax models + - Kimi-K2 + - Other models using MLA architecture + +- **Standard attention models** - also supported: + - Qwen models (see [PR #6121](https://github.com/sgl-project/sglang/pull/6121)) + +For models like Llama, with standard GQA, standard DP, or TP is typically recommended. + +To enable DPA, add `--enable-dp-attention` to your server launch command. + +### Activation Logic + +DPA is enabled explicitly via server arguments (CLI or config). You must set both `--dp-size` and `--enable-dp-attention`: + +```bash +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3 \ + --tp 8 \ + --dp-size 8 \ + --enable-dp-attention +``` + +**Important**: `--dp-size` must be greater than 1 for DPA to work. When `dp_size == 1` (default), `--enable-dp-attention` is automatically disabled. The constraint `tp_size % dp_size == 0` must also be satisfied. + +### Standard DP for MLA models + +Note that MLA models, of course, also support DP. Suppose you want to enable standard DP for MLA models. First, launch each MLA model's replica independently. You may launch these replicas one by one with DPA enabled. After launching each MLA model's replica, launch an SMG and connect all the replicas to the SMG. A detailed explanation of SMG is as follows. + +## Modern Data Parallelism SGLang Model Gateway (SMG) + +### Native DP Mode + +Native DP (built-in Data Parallelism) in SGLang creates multiple worker processes within a single SGLang instance, under the control of `DataParallelController` with the launching parameter of `dp-size`. + +```bash +# Native DP mode +python -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --dp-size 4 +``` + +**Limitations:** + +- Built-in in-process load balancing only (e.g., `round_robin`, `total_requests`, `total_tokens`) +- No cache-aware routing +- Limited observability and metrics +- No fault tolerance or circuit breakers +- Not suitable for production workloads + +⚠️ Native DP is **highly not recommended for use right now**. It is only used in some ancient/outdated RL frameworks. You can use SGLang Model Gateway (SMG) to power up your data parallelism in any use case. + +### SMG-Based DP (Recommended) + +Starting from September 2024, SGLang Model Gateway, i.e., SMG, formerly named as SGLang DP Router, was built especially as a production-ready DP routing system with Rust. It starts from DP routing, but later we further expanded its scope to coordinate RL, PD Disaggregation, and other scenarios. This doc only discusses SMG's usage in DP routing. For other usage, please refer to [SGLang Model Gateway Documentation](/docs/advanced_features/sgl_model_gateway). + +> To achieve the best production-level routing performance and reduce the overhead to an extreme extent, we use Rust to build SMG, but not Python, since Python is never FAST enough. + +**We strongly recommend using the SGLang Model Gateway (SMG) for production-grade Data Parallelism.** SMG provides significant advantages over native DP mode. + +```bash +# SMG-based DP mode (Recommended) +python -m sglang_router.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --dp-size 4 +``` + +⚠️ Note that **SMG and Naive DP share the same launching parameter, `--dp-size`**. But the entrypoint of Naive DP is `python -m sglang.launch_server`, and SMG's entrypoint is `python -m sglang_router.launch_server`. + +**Advantages of SMG-Based DP:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureNative DPSMG-Based DP
Load BalancingBuilt-in in-process methodsAdvanced policies (cache-aware, power-of-two, etc.)
Cache Awareness❌ No✅ Yes - significantly higher cache hit rate
ThroughputBaselineSignificant improvement
Multi-Node SupportLimited✅ Full support
Worker Health MonitoringBasic✅ Circuit breakers, health checks
ReliabilityBasic✅ Retries, rate limiting, queuing
ObservabilityBasic metrics✅ 40+ Prometheus metrics, OpenTelemetry
Hot Worker Add/Remove❌ No✅ Yes
+ +### SMG's Performance + +The cache-aware routing policy in SMG significantly improves performance for workloads with shared prefixes: + + + + + + + + + + + + + + + + + + + + + + + + + + +
MetricWithout Cache-AwareWith Cache-Aware SMG
Throughput (token/s)82,665158,596 (+92%)
Cache Hit Rate20%75% (+275%)
+ +*Benchmark from [SGLang v0.4 blog](https://lmsys.org/blog/2024-12-04-sglang-v0-4/), workload with multiple long prefix groups, 8x A100 80GB GPUs, dp-size=8* + +### When to Use Each + +**Use Native DP when:** + +- ~Never use Native/Naive DP~ +- Learning material of DP routing + +**Use SMG-Based DP when:** + +- In any case, when you think DP is needed +- Production deployments +- Multi-node distributed setups +- Workloads with shared prefixes (high cache reuse potential) +- You need high availability and reliability features +- You require detailed observability and metrics +- You want to have highly efficient RL rollout systems + +Note that for RL rollout systems, **there are four crucial reasons that SMG-Based DP is far better than naive DP routing**. Details can be found at [Load Balancing Router in RL](/docs/advanced_features/sglang_for_rl#load-balancing-router). + +### Quick Start For SMG + +**Installation** + +```bash +pip install sglang-router +# or +pip install "sglang[all]" +``` + +**Option A: Co-launch Workers and SMG (Simplest)** + +This is the easiest way to get started - SMG and workers are launched together: + +```bash +python -m sglang_router.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --dp-size 4 \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Option B: Separate Launch (Multi-Node)** + +For distributed deployments across multiple machines: + +1. Launch workers on each node + +```bash +# Node 1 +python -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --port 8000 + +# Node 2 +python -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --port 8000 +``` + +2. Launch SMG pointing to workers + +```bash +python -m sglang_router.launch_router \ + --worker-urls http://node1:8000 http://node2:8000 \ + --policy cache_aware \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Option C: Dynamic Worker Registration** + +For elastic deployments where workers can be added/removed dynamically: + +```bash +# Launch SMG first +python -m sglang_router.launch_router \ + --policy cache_aware \ + --host 0.0.0.0 \ + --port 30000 + +# Register workers dynamically +curl -X POST http://localhost:30000/workers \ + -H "Content-Type: application/json" \ + -d '{"url": "http://worker1:8000"}' + +curl -X POST http://localhost:30000/workers \ + -H "Content-Type: application/json" \ + -d '{"url": "http://worker2:8000"}' +``` + +### Load Balancing Policies + +SMG supports multiple load balancing policies: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PolicyDescriptionBest For
cache_awareCombines cache locality with load balancingRecommended for most workloads
round_robinCycles through workers in orderSimple, predictable distribution
randomRandom worker selectionBaseline, testing
power_of_twoSamples two workers, picks lighter oneLow latency requirements
+ +**Cache-Aware Policy (Default, Recommended)** + +The cache-aware policy provides the best performance for most workloads: + +```bash +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 http://worker2:8000 \ + --policy cache_aware \ + --cache-threshold 0.5 \ + --balance-abs-threshold 32 \ + --balance-rel-threshold 1.5 \ + --eviction-interval-secs 120 \ + --max-tree-size 67108864 +``` + +**How it works:** + +1. Maintains an approximate radix tree for each worker based on request history +2. Routes requests to workers with the highest prefix match (cache hit) +3. Falls back to shortest-queue routing when load is imbalanced +4. Automatically evicts old entries to prevent memory overflow + +### Best Practices + +1. **Start with `cache_aware` policy** - It provides the best balance between cache locality and load distribution for most workloads +2. **Use SMG for production** - Prefer `sglang_router.launch_server` over `sglang.launch_server` for better reliability and observability +3. **Enable health checks** - Configure `--router-health-check-interval-secs` to detect and remove unhealthy workers automatically + +**Recommended command with best practices applied:** + +```bash +python -m sglang_router.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --dp-size 4 \ + --router-policy cache_aware \ + --router-health-check-interval-secs 30 \ + --router-prometheus-port 10001 \ + --host 0.0.0.0 \ + --port 30000 +``` + +For advanced configuration (circuit breakers, retries, Prometheus metrics, K8s integration), see [SGLang Model Gateway Documentation](/docs/advanced_features/sgl_model_gateway). + +### Verifying Traffic Distribution + +After launching SMG, verify that traffic is being distributed correctly: + +**1. Check worker status:** + +```bash +curl http://localhost:30000/workers +``` + +**2. Check load distribution:** + +```bash +curl http://localhost:30000/get_loads +``` + +**3. Monitor metrics (if Prometheus enabled):** + +```bash +# Key metrics to check +smg_router_requests_total{model="..."} +smg_worker_requests_active{worker="..."} +sglang_cache_hit_rate{source="..."} +``` + +For detailed metrics and monitoring setup, see [SGLang Model Gateway Documentation](/docs/advanced_features/sgl_model_gateway). + +## Reference + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
StrategyUse CaseKey Benefit
Native DP (--dp-size)NeverEasy to understand, not rust based
SMG-Based DPProduction (recommended)Cache-aware routing, high availability
DPA (--dp-size N --enable-dp-attention)DeepSeek/MLA modelsEliminates KV cache duplication, improved throughput
DPA + EPDeepSeek MoE modelsSignificant throughput improvement vs vanilla TP
+ +**Recommended production setup for DeepSeek:** +1. Enable **DPA** for attention layers (`--dp-size 8 --enable-dp-attention`) +2. Enable **EP** for MoE layers (`--ep 8 --moe-a2a-backend deepep`) +3. Use **SMG** with **cache_aware** policy + +**Related documentation:** +- [Expert Parallelism](./expert_parallelism) - DeepEP, Two-Batch Overlap, EPLB +- [SGLang Model Gateway Documentation](./sgl_model_gateway) - SMG configuration & troubleshooting +- [Large-Scale EP Blog](https://lmsys.org/blog/2025-05-05-large-scale-ep/) - 96 GPU deployment guide diff --git a/docs_new/docs/advanced_features/dp_for_multi_modal_encoder.mdx b/docs_new/docs/advanced_features/dp_for_multi_modal_encoder.mdx new file mode 100644 index 000000000..afa991532 --- /dev/null +++ b/docs_new/docs/advanced_features/dp_for_multi_modal_encoder.mdx @@ -0,0 +1,33 @@ +--- +title: "DP for Multi-Modal Encoder in SGLang" +metatags: + description: "Data parallelism for VLM vision encoder in SGLang: reduce TTFT, boost throughput. Supports Qwen2.5-VL, Qwen3-VL, InternVL, GLM-4.5V/4.6V." +--- +A typical VLM architecture involves two main components: an multi-modal encoder and a text decoder. + +Most VLMs utilize a Vision Transformer (ViT) as their multi-modal encoder, it is responsible for processing visual data, extracting features (objects, colors, textures, etc.), and transforming them into a format that can be understood by the model. + +The text deocoder is based on LLM. It processes textual data and generates output based on the encoded visual features. + +However, since the size of ViT is very small compared to language decoders, +there is relatively little gain from TP. On the other hand, TP incurs significant communication +overhead because of all-reduce being performed after every layer. + +Placing the ViT in data parallel while keeping the LLM in tensor parallel consistently lowers TTFT and boosts end-to-end throughput. In this hybrid layout, the vision front-end becomes parallel and lightweight, while scarce interconnect bandwidth and collective ops are reserved for the LLM. + +Data parallelism replicates the entire model across multiple GPU sets and processes different batches of requests in parallel. + +## Command Example +You can enable batch-level DP by setting `mm-enable-dp-encoder`, for example: +```shell Command +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen2.5-VL-7B-Instruct \ + --tp 2 \ + --mm-enable-dp-encoder +``` + +## Known supported models +- Qwen2.5-VL (<https://github.com/sgl-project/sglang/pull/13126>) +- Qwen3-VL (<https://github.com/sgl-project/sglang/pull/13724>) +- InternVL (<https://github.com/sgl-project/sglang/pull/13925>) +- GLM-4.5V & GLM-4.6V (<https://github.com/sgl-project/sglang/pull/14097>) diff --git a/docs_new/docs/advanced_features/epd_disaggregation.mdx b/docs_new/docs/advanced_features/epd_disaggregation.mdx new file mode 100644 index 000000000..ca30ef2d4 --- /dev/null +++ b/docs_new/docs/advanced_features/epd_disaggregation.mdx @@ -0,0 +1,83 @@ +--- +title: "EPD Disaggregation" +metatags: + description: "SGLang EPD disaggregation: separate encoder, prefill, decode stages for VLM inference. Independent scaling, load balancing, three-tier architecture." +--- +## Why and What is EPD Disaggregation? + +In modern Vision-Language Model (VLM) inference, request execution naturally decomposes into three distinct stages: Encoder, Prefill, and Decode. +The Encoder stage performs vision preprocessing and ViT-based image encoding, which is highly compute-intensive but only required during request initialization. The Prefill stage processes the full multimodal input sequence to initialize the language model’s Key-Value (KV) cache, while the Decode stage is dominated by memory bandwidth and KV cache access for autoregressive token generation. + +Existing deployments typically colocate these stages within a unified execution engine, or at best apply Prefill–Decode (PD) disaggregation. However, such designs still tightly couple vision encoding with language prefill, leading to inefficient resource utilization, limited scalability for image-heavy workloads, and suboptimal scheduling under load. + +To address these challenges, we introduce Encoder–Prefill–Decode (EPD) Disaggregation in SGLang. EPD further separates vision encoding from language processing, enabling independent horizontal scaling of encoder servers, improved load balancing for multimodal requests, and seamless integration with existing PD disaggregation to form a fully decoupled three-tier inference architecture. + +### Usage + +You can launch a language-only model using `--language-only`, or an encoder-only model using `--encoder-only`. +When launching a language-only model, you must additionally specify the encoder service endpoints via `--encoder-urls`. + +We support multiple encoder transfer backends, including zmq_to_scheduler, zmq_to_tokenizer, and mooncake (the default is zmq_to_scheduler). The backend can be selected using `--encoder-transfer-backend`. + +#### Qwen VL + +- EP Disaggregation + +```bash Command +# encoder 0 +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-8B-Instruct \ + --encoder-only \ + --encoder-transfer-backend zmq_to_scheduler \ + --port 30000 +# encoder 1 +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-8B-Instruct \ + --encoder-only \ + --encoder-transfer-backend zmq_to_scheduler \ + --port 30001 +# language-only server +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-8B-Instruct \ + --language-only \ + --encoder-urls http://127.0.0.1:30000 http://127.0.0.1:30001 \ + --encoder-transfer-backend zmq_to_scheduler \ + --port 30002 +``` + +- EPD Disaggregation + +```bash Command +# encoder 0 +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-8B-Instruct \ + --encoder-only \ + --encoder-transfer-backend zmq_to_scheduler \ + --port 30000 +# encoder 1 +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-8B-Instruct \ + --encoder-only \ + --encoder-transfer-backend zmq_to_scheduler \ + --port 30001 +# prefill 0 +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-8B-Instruct \ + --disaggregation-mode prefill \ + --language-only \ + --encoder-urls http://127.0.0.1:30000 http://127.0.0.1:30001 \ + --encoder-transfer-backend zmq_to_scheduler \ + --port 30002 +# decode 0 +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-8B-Instruct \ + --disaggregation-mode decode \ + --port 30003 +# router +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --prefill http://$PREFILL_HOST:30002 \ + --decode http://$DECODE_HOST:30003 \ + --port 8000 + +``` diff --git a/docs_new/docs/advanced_features/expert_parallelism.mdx b/docs_new/docs/advanced_features/expert_parallelism.mdx new file mode 100644 index 000000000..aa53d57d2 --- /dev/null +++ b/docs_new/docs/advanced_features/expert_parallelism.mdx @@ -0,0 +1,288 @@ +--- +title: "Expert Parallelism" +metatags: + description: "SGLang Expert Parallelism: distribute MoE experts across GPUs, DeepEP all-to-all, grouped GEMMs, TBO/SBO overlap, EPLB load balancing." +--- +Expert Parallelism (EP) in SGLang distributes expert weights across multiple devices in Mixture-of-Experts (MoE) models, addressing memory bottlenecks and enabling efficient scaling for high-performance inference. It is particularly vital for serving large-scale MoE models where tokens are dynamically routed to specialized experts across GPUs. By leveraging optimized all-to-all communication and grouped matrix multiplications (GEMMs), EP reduces latency, boosts throughput, and minimizes idle GPU time. SGLang's EP offers strong extensibility through its modular framework, allowing seamless integration of custom kernels, backends, and optimizations without refactoring core logic, supporting diverse hardware and quantization schemes. + +## Supported Backends and Selection Guidance + +SGLang's EP integrates diverse, highly efficient backends for different use cases, allowing fine-grained control over performance trade-offs. Users specify backends via command-line flags: +- `--moe-a2a-backend`: Selects the backend for all-to-all communication. +- `--moe-runner-backend`: Selects the backend for MoE computation. + +### Backends for All-to-All Communication + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BackendDescriptionUse Cases
**`none` (default)**Disables all-to-all for EP. Uses All-Reduce or All-Gather for token dispatch.Hybrid EP and TP setups.
`deepep`DeepEP, a communication library for efficient token shuffling in MoE models.Large-scale EP deployments.
`mooncake`An extension of DeepEP for elastic inference, leveraging RDMA for high-performance data transfers.Elastic EP serving.
`flashinfer`Flashinfer implementation of all-to-all.Large-scale EP deployments.
`ascend_fuseep`Ascend NPU native fused all-to-all communication.Ascend NPU deployments.
+ +DeepEP and Mooncake backends support two modes for token dispatch: `normal` mode (optimized for prefill workloads with high throughput) and `low_latency` mode (optimized for decode workloads with low latency and CUDA Graph compatibility). Users are recommended to set `--deepep-mode auto` to enable automatic dispatch mode switching during runtime. Setting `--deepep-mode normal` or `--deepep-mode low_latency` is useful for debugging or development purposes. + +Currently, DeepEP and Mooncake only support cases where `ep_size = tp_size`. For hybrid EP and TP (i.e., `ep_size < tp_size`), only the `none` backend (All-Reduce or All-Gather-based dispatching) is supported. + +### Backends for MoE Computation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BackendDescriptionUse Cases
**`auto` (default)**Automatically selects the optimal backend based on model architecture, hardware (e.g., NVIDIA architecture like Ampere, Hopper, Blackwell), quantization scheme (e.g., FP8, FP4), and runtime conditions.General-purpose deployments; ensures compatibility and performance without user intervention.
`triton`Triton-based implementation for grouped GEMMs. To achieve higher performance, it's highly recommended to create [tuned configurations](https://github.com/sgl-project/sglang/blob/main/benchmark/kernels/fused_moe_triton/README).Custom kernel development or scenarios requiring high extensibility with Torch compilation support.
`deep_gemm`DeepGEMM backend optimized for MoE matrix multiplications, supporting contiguous layouts for prefill and masked layouts for decode; often JIT-compiled for performance.Large-scale EP deployments with FP8 block-wise quantization.
`cutlass`CUTLASS-based backend for efficient GEMMs.NVIDIA architectures with CUTLASS support.
`flashinfer_trtllm`FlashInfer integrated with TensorRT-LLM for accelerated MoE computations, supporting FP4 communication operators and high-performance GEMMs.Blackwell with TRT-LLM.
`flashinfer_cutlass`FlashInfer combined with CUTLASS for high-performance grouped GEMMs in MoE layers, handling FP4/FP8 quantization efficiently.Blackwell with FP4/FP8 models.
`flashinfer_mxfp4`FlashInfer variant optimized for MXFP4 (mixed FP4) quantization in MoE runners, focusing on memory-efficient low-precision inference.Low-precision models with MXFP4.
`flashinfer_cutedsl`FlashInfer with a custom DSL for flexible and efficient MoE kernel generation, integrated with ModelOpt FP4 quantization.Low-precision models with NVFP4.
+ +### Examples + +Launch with DeepEP and DeepGEMM for DeepSeek-V3: + +```bash Command +python -m sglang.launch_server --model-path deepseek-ai/DeepSeek-V3 --moe-a2a-backend deepep --moe-runner-backend deep_gemm --tp 8 --ep 8 +``` + +## Extensible EP Framework + +SGLang's EP framework provides modular abstractions for easy integration of custom kernels, backends, and optimizations. It decouples the MoE forward pass into stages (dispatch → pre-permute → core runner → post-permute → combine), enabling seamless extensions without refactoring core logic. + +### Framework Overview + +The framework centers on `FusedMoE` as the unified entry point for a single, extensible structure. Key components include: +- **Dispatcher**: Manages dispatch/combine for backends like DeepEP (implements `BaseDispatcher` subclasses). +- **MoeRunner**: Orchestrates grouped-GEMM execution via `MoeRunnerCore` implementations (e.g., `TritonRunnerCore`). +- **PermuteMethodPool**: Auto-registers layout conversions (e.g., pre/post-permute via `register_pre_permute` and `register_post_permute` for dynamic modes, or `register_fused_func` for static, torch.compile-compatible fused operations). +- **TopK Router**: Backend-agnostic expert selection. + +This design supports multiple backends via `--moe-a2a-backend` and `--moe-runner-backend`, with quantization integrated through a standardized `apply()` method. The computation flow ensures modularity: + +```text Output +[input_hidden_states] + | + v + TopK.forward -> select_experts / triton_kernels.routing / bypass + | + v + [TopKOutput] + | + v + FusedMoE.forward -> Dispatcher.dispatch -> DeepEP / bypass + | | + | v + | [DispatchOutput] + | | + | v + | quant_method.apply -> MoeRunner.forward + | | | + | | v + | | pre-permute + grouped_gemm + post-permute + | | | + | |-------------- + | v + | [CombineInput] + | | + | v + | Dispatcher.combine -> DeepEP / bypass + | | + |--------------------- + v +[final_hidden_states] +``` + +For details, see the [MoE Refactor Roadmap](https://github.com/sgl-project/sglang/issues/8715). + +### Implementing New Backends + +To add a new backend: +1. For a new all-to-all dispatcher, implement a `BaseDispatcher` subclass with `dispatch` and `combine` methods. +2. For a new MoE runner backend, define a `MoeRunnerCore` subclass for core operations (e.g., grouped GEMMs). +3. Define new input/output formats for the dispatcher or model runner (e.g., `RunnerInput`, `RunnerOutput`). +4. Register permute/unpermute methods to ensure compatibility: + - **Fused Mode** (static, torch.compile-compatible): Use `register_fused_func` for end-to-end operations. + - **Permute Mode** (dynamic): Register `register_pre_permute` and `register_post_permute` for flexible layouts. + +See the [MoE Refactor Implementation PR](https://github.com/sgl-project/sglang/pull/9269) for full changes, including type hints and config expansions. + +### Examples + +For an example implementation, see [moe_runner/triton.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/moe/moe_runner/triton.py), which demonstrates Triton-based grouped GEMMs with registered fused and permutation functions. + +## Computation and Communication Overlap + +SGLang's EP employs advanced overlap techniques to hide communication latency behind computation, maximizing GPU utilization in MoE layers. + +### Two-Batch Overlap (TBO) + +TBO splits requests into micro-batches, interleaving attention computation with dispatch/combine operations. Yield points in the execution graph allow pausing for overlaps, increasing overall throughput without peak memory spikes: + +```python Example +operations = [ + self._forward_attn, + YieldOperation(), # Overlap with dispatch of prior micro-batch + self._forward_dispatch, + self._forward_mlp, + YieldOperation(), # Overlap with combine + self._forward_combine, +] +``` + +Users need to specify `--enable-two-batch-overlap` to unlock up to 2x throughput. For details, see the [Large-Scale EP Blog](https://lmsys.org/blog/2025-05-05-large-scale-ep/#two-batch-overlap). + +### Single-Batch Overlap (SBO) + +SGLang introduces a dispatcher-hook system for Single-Batch Overlap (SBO), enabling the overlap of operations within a single batch—such as shared experts computation with communication—while decentralizing logic to enhance modularity. These hooks execute before and after the `dispatch` and `combine` operations without modifying core MoE modules. This design simplifies interfaces, reduces coupling, and improves extensibility. For implementation details and an example of overlapping shared experts with DeepEP's combine operation, refer to [PR #13327](https://github.com/sgl-project/sglang/pull/13327). Users can set `--enable-single-batch-overlap` to enable this feature. + + +## Workload Balancer + +SGLang integrates the [Expert Parallelism Load Balancer (EPLB)](https://github.com/deepseek-ai/EPLB) from DeepSeek to address routing imbalances in MoE models. By analyzing expert activation statistics, EPLB computes an optimal expert arrangement, strategically placing or replicating experts to minimize GPU utilization variance, reduce idle cycles, and enhance scalability. + +To enable EPLB, use the flags `--enable-eplb`. For optimal performance, increase batch sizes to stabilize activation statistics and configure periodic rebalancing (e.g., every 1000 requests) to adapt to evolving workloads. Simulations demonstrate significant improvements in load balancedness (ratio of mean to max computation time), correlating strongly with throughput gains. + +For more details, refer to the [EPLB Section in the Large-Scale EP Blog](https://lmsys.org/blog/2025-05-05-large-scale-ep/#expert-parallelism-load-balancer) and the [EPLB Repository](https://github.com/deepseek-ai/eplb). + + +## EP with Spectulative Decoding + + +When utilizing speculative decoding with MTP on MoE architectures, use the `--speculative-moe-runner-backend` and `--speculative-moe-a2a-backend` arguments to customize the MoE layer behavior for the draft model. While they default to the target model’s settings, users can differentiate them for varying precisions between target and draft models. + +For model like `nvidia/DeepSeek-R1-0528-NVFP4-v2`, the target model uses NVFP4 precision while the draft model uses BF16. To apply `flashinfer_trtllm` kernel for target MoE layer while falling back to triton fused MoE kernel for draft MoE layer, users can set the arguments as follows: +```text Output +... +--moe-runner-backend flashinfer_trtllm \ +--speculative-moe-runner-backend triton \ +... +``` + + +## Ascend NPU Guidance +### Guidance on SGLang configuration in Ascend NPU +- `--moe-a2a-backend` only supports deepep and ascend_fuseep backends, + + - `deepep`: The mechanism is consistent with the above description. + + - `ascend_fuseep`: Offer a large fused operator which integrates all operations between dispatch and combine to boost MoE computation. Only used for decode stage in PD Disaggregation Mode. + +- `--moe-runner-backend` parameter does not need to be configured. + +- `--deepep-mode`: + + - In PD mixed mode, please set `--deepep-mode` auto. + + - In PD Disaggregation Mode, prefill instance sets `--deepep-mode` normal, and decode instance sets `--deepep-mode` low_latency. + +### DeepEP Ascend Introduction +DeepEP Ascend is the adapted version of the DeepEP communication library for Huawei Ascend NPUs, specifically designed for Mixture-of-Experts (MoE) model Expert Parallelism (EP). It supports the Ant-moving Function (Split the sequence length into rounds for streaming batch transmission) to optimize the buffer size occupied during collective communication in prefill stage, especially for long sequences. + +Ant-moving Function can be enabled for both the dispatch and combine phases via the following environment variables: + +- `DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS`: Enable ant-moving function in dispatch stage. Indicates the number of tokens transmitted per round on each rank, default 8192. + +- `DEEPEP_NORMAL_LONG_SEQ_ROUND`: Enable ant-moving function in dispatch stage. Indicates the number of rounds transmitted on each rank, default 1. + +- `DEEPEP_NORMAL_COMBINE_ENABLE_LONG_SEQ`: Enable ant-moving function in combine stage, default 0 (means disabled). + +`DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS * DEEPEP_NORMAL_LONG_SEQ_ROUND` means input sequence length. When the input sequence length exceeds 8192, it is recommended to enable the ant-moving function in both dispatch and combine phase. + +The environment variable `HCCL_BUFFSIZE` is used to configure the buffer size (MB) actually allocated. Its calculation formula is as follows: +```text Output +# Enable Ant-moving Function +HCCL_BUFFSIZE >= 2 * (102MB + 4MB + DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS * (hidden_size + hidden_size + hidden_size) * topk) + PADDING_BUFFSIZE + +# Disable Ant-moving Function +HCCL_BUFFSIZE >= 2 * (102MB + 4MB + TOTAL_SEQ_LEN * (hidden_size + hidden_size) * topk) + PADDING_BUFFSIZE +``` +Wherein the parameters are described as follows: + +- `hidden_size`: hidden size in model config. + +- `topk`: The number of selected routing experts. + +- `TOTAL_SEQ_LEN`: input sequence length. + +- `PADDING_BUFFSIZE`: A value of 20 or greater is recommended. diff --git a/docs_new/docs/advanced_features/forward_hooks.mdx b/docs_new/docs/advanced_features/forward_hooks.mdx new file mode 100644 index 000000000..a66f1548c --- /dev/null +++ b/docs_new/docs/advanced_features/forward_hooks.mdx @@ -0,0 +1,298 @@ +--- +title: "Model Forward Hooks" +metatags: + description: "SGLang forward hooks: attach PyTorch hooks to model submodules via JSON config. Log activations, debug internals, export hidden states." +--- + +## Model Hooks + +SGLang supports attaching PyTorch forward hooks to specific submodules in the loaded model, configured entirely via `server_args` JSON. + +This is useful for: + +* Logging intermediate activations +* Debugging model internals +* Exporting hidden states to external tooling + +Hooks are attached once during `ModelRunner.initialize` and run on every forward pass. + +*** +### Configuration overview + +Hooks are configured via a `ServerArgs` field: + +```python Example +class ServerArgs: + ... + # For forward hooks + forward_hooks: Optional[List[dict[str, Any]]] = None +```` + +In JSON form, a minimal configuration looks like: + +```jsonc Example +{ + "forward_hooks": [ + { + "name": "outer_linear_hooks", + "target_modules": ["outer.0", "outer.1"], + "hook_factory": "my_project.hooks:dummy_hook_factory", + "config": { + "tag": "outer-layer" + } + } + ] +} +``` + +#### Top-level fields + +* `forward_hooks` (optional list of objects) + Each element is a hook spec describing: + + * Which modules to target + * Which Python factory to call + * What configuration to pass into that factory + +*** +### Hook spec schema + +Each entry in `forward_hooks` is a JSON object with the following shape: + +```jsonc Example +{ + "name": "optional-descriptive-name", + "target_modules": ["pattern1", "pattern2", "..."], + "hook_factory": "module.submodule:factory_name", + "config": { + "...": "arbitrary JSON" + } +} +``` + +#### `name` (optional) + +* Human-readable name for logging. +* Used only in log messages such as: + + ```text Output + Registered forward hook 'outer_linear_hooks' on outer.0 + ``` + +#### `target_modules` (required) + +* List of **module name patterns** used to match entries in `model.named_modules()`. +* Patterns are matched using `fnmatch.fnmatch`, so: + + * `"outer.0"` matches exactly `"outer.0"`. + * `"outer.*"` matches `"outer.0"`, `"outer.1"`, `"outer.inner"`, etc. + * `"outer.inner.*"` matches children under `outer.inner`. + +> If no modules match the given patterns, hook registration does **not** fail. +> Instead, SGLang logs a warning and continues: +> +> ```text +> No modules matched hook spec 'name' patterns=['...'] +> ``` + +#### `hook_factory` (required) + +* String path to the Python factory function that creates the hook. +* Supported formats: + + * `"package.module:factory_name"` + * `"package.module.submodule.factory_name"` + +The path is resolved via: + +```python Example +def resolve_callable(path: Optional[str]) -> Optional[Callable]: + if path is None: + return None + + if ":" in path: + module_name, fn_name = path.split(":", 1) + else: + parts = path.split(".") + if len(parts) < 2: + raise ValueError( + f"Invalid hook callable path '{path}'. " + "Expected 'module.submodule:factory' or 'module.submodule.factory'." + ) + *mod_parts, fn_name = parts + module_name = ".".join(mod_parts) + + module = importlib.import_module(module_name) + try: + return getattr(module, fn_name) + except AttributeError as e: + raise AttributeError( + f"Module '{module_name}' has no attribute '{fn_name}' " + f"(from hook path '{path}')" + ) from e +``` + +**Failure modes**: + +* If the path is malformed (not enough dots and no `:`), a `ValueError` is raised at startup. +* If the module imports but the attribute is missing, an `AttributeError` is raised with a clear error message. +* If the hook factory returns `None`, a warning is logged and no hook is registered for that spec (initialization continues). + +The first two cause initialization to fail fast with a descriptive error; the last one is non-fatal. + +#### `config` (optional) + +* Arbitrary JSON object. +* Passed directly to the hook factory as a Python `dict`. +* This lets you parameterize hook behavior from config (e.g. tags, log levels, sampling rates, etc.). + +*** +### Hook lifecycle and behavior + +Hooks are registered in `ModelRunner.initialize()`: + +```python Example +if server_args.forward_hooks: + register_forward_hooks(self.model, server_args.forward_hooks) +``` + +The actual registration logic is implemented by `register_forward_hooks`: + +```python Example +def register_forward_hooks(model: nn.Module, hook_specs: List[dict[str, Any]]) -> None: + """ + hook_specs is a list of dicts from server_args.forward_hooks. + Attaches forward hooks to the matching modules. + """ + name_to_module = dict(model.named_modules()) + + for spec in hook_specs: + spec_name = spec.get("name", "") + target_patterns = spec.get("target_modules", []) + if not target_patterns: + logger.warning( + f"Hook spec '{spec_name}' has no 'target_modules', skipping" + ) + continue + + hook_factory_path = spec.get("hook_factory") + if not hook_factory_path: + logger.warning( + f"Hook spec '{spec_name}' has no 'hook_factory', skipping" + ) + continue + + config = spec.get("config") or {} + hook_factory = resolve_callable(hook_factory_path) + + hook = hook_factory(config) if hook_factory else None + if hook is None: + logger.warning( + f"Hook factory '{hook_factory_path}' for spec '{spec_name}' " + "returned None, not registering any hook" + ) + continue + + # Resolve patterns like "model.layers.*.mlp" + matched = [] + for name, module in name_to_module.items(): + if any(fnmatch.fnmatch(name, pattern) for pattern in target_patterns): + matched.append((name, module)) + + if not matched: + logger.warning( + f"No modules matched hook spec '{spec_name}' " + f"patterns={target_patterns}" + ) + continue + + for module_name, module in matched: + if hook: + _ = module.register_forward_hook(hook) + logger.info( + f"Registered forward hook '{spec_name}' " + f"on {module_name}" + ) +``` + +Key points: + +* Hooks are **forward hooks only** (via `module.register_forward_hook`). +* They are attached once at initialization. +* Hook handles are currently not stored on `ModelRunner` (they cannot be removed later via this API). +* Failure to match any modules is non-fatal; a warning is logged instead. +* If a hook factory returns `None`, a warning is logged and that spec is skipped. + +*** +### Writing a hook factory + +A hook factory is a regular Python function: + +* Takes a `config: dict` (from JSON) +* Returns a forward hook function with signature `(module, inputs, output)` + +Example: + +```python Example +HOOK_CALLS = [] + +def dummy_hook_factory(config): + """Factory that returns a forward hook capturing a tag from config.""" + tag = config.get("tag", "default") + + def hook(module, inputs, output): + HOOK_CALLS.append( + { + "module_type": type(module).__name__, + "tag": tag, + "shape": tuple(output.shape), + } + ) + return output # must return output if you don’t want to modify the tensor + + return hook +``` + +In JSON: + +```jsonc Example +{ + "forward_hooks": [ + { + "name": "capture_outer", + "target_modules": ["outer.0", "outer.1"], + "hook_factory": "my_project.hooks:dummy_hook_factory", + "config": { + "tag": "outer" + } + } + ] +} +``` + +This will: + +* Resolve `my_project.hooks:dummy_hook_factory` to a Python callable. +* Call it with `config = {"tag": "outer"}`. +* Use the returned hook for all modules matching `outer.0` and `outer.1`. +* Append metadata about each call to `HOOK_CALLS`. + +*** +### Summary + +* Define `forward_hooks` as a list of specs in `ServerArgs` to turn on the feature. + +* Each spec: + + * selects modules via `target_modules` (glob patterns over `model.named_modules()`), + * points to a hook factory via `hook_factory`, + * passes arbitrary `config` into that factory. + +* Hook factories are resolved via `resolve_callable`, which supports `module:factory` and `module.submodule.factory`. + +* Hooks are standard PyTorch forward hooks, attached once at startup and invoked on every forward pass. + +* Misconfiguration is either: + + * **fatal and explicit** (bad path / missing attribute), or + * **non-fatal with clear warnings** (no targets matched, or factory returned `None`). diff --git a/docs_new/docs/advanced_features/hicache.mdx b/docs_new/docs/advanced_features/hicache.mdx new file mode 100644 index 000000000..6c083ad23 --- /dev/null +++ b/docs_new/docs/advanced_features/hicache.mdx @@ -0,0 +1,8 @@ +--- +title: "Hierarchical KV Caching (HiCache)" +metatags: + description: "SGLang HiCache: three-tier KV caching (GPU, CPU, storage) for long-context and multi-turn inference. Supports Mooncake, 3FS, NIXL backends." +--- +- [Hicache Best Practices](./hicache_best_practices) +- [Hicache Design](./hicache_design) +- [Hicache Storage Runtime Attach Detach](./hicache_storage_runtime_attach_detach) diff --git a/docs_new/docs/advanced_features/hicache.rst b/docs_new/docs/advanced_features/hicache.rst new file mode 100644 index 000000000..e7d83211d --- /dev/null +++ b/docs_new/docs/advanced_features/hicache.rst @@ -0,0 +1,9 @@ +Hierarchical KV Caching (HiCache) +================================= + +.. toctree:: + :maxdepth: 1 + + hicache_best_practices.md + hicache_design.md + hicache_storage_runtime_attach_detach.md diff --git a/docs_new/docs/advanced_features/hicache_best_practices.mdx b/docs_new/docs/advanced_features/hicache_best_practices.mdx new file mode 100644 index 000000000..d86e676e2 --- /dev/null +++ b/docs_new/docs/advanced_features/hicache_best_practices.mdx @@ -0,0 +1,202 @@ +--- +title: "SGLang HiCache Best Practices" +metatags: + description: "HiCache configuration guide: memory layout, prefetch policies, PD disaggregation, HF3FS and Mooncake deployment, custom storage backends." +--- +## Why HiCache Matters + +SGLang HiCache extends the traditional RadixAttention with a three-tier hierarchical KV caching system that dramatically improves performance for long-context and multi-turn conversation scenarios. By intelligently managing KV caches across GPU memory, host memory, and external storage backends, HiCache addresses the fundamental capacity bottleneck that limits cache hit rates in conventional systems. + +## Configuration Guidelines + +## Core HiCache Parameters + +```bash Command +# Essential HiCache flags +--page-size 64 # Page size for cache management +--enable-hierarchical-cache # Enable HiCache +--hicache-ratio 2 # Host memory ratio (2x GPU memory) +--hicache-size 100 # Host memory size in GBs, will override the above ratio +--hicache-io-backend kernel # The I/O backend of moving data between CPU and GPU +--hicache-write-policy write_through # Cache write policy from GPU to CPU +--hicache-storage-backend # Optional storage backend (e.g., hf3fs, mooncake, etc.) +``` + +Notes: + +- Besides configuring `--hicache-storage-backend` at startup, SGLang also supports **runtime attach/detach** of the HiCache storage backend (no restart required) via HTTP admin endpoints. See [Runtime Attach/Detach HiCache Storage Backend](./hicache_storage_runtime_attach_detach). + +## Key Configurations with Storage Backends Enabled + +### Memory Layout Optimization + +```bash Command +# Page-first: Optimized for I/O efficiency with zero-copy (recommended with kernel backend) +--hicache-mem-layout page_first +# Page-first-direct: Optimized for direct I/O operations (Compatible with fa3 and same zero-copy performance as page_first) +--hicache-mem-layout page_first_direct +# Layer-first +--hicache-mem-layout layer_first +``` +**Layout Compatibility:** +- `page_first`: Only compatible with `kernel` I/O backend, automatically switches to `layer_first` with `direct` backend +- `page_first_direct`: Specifically designed for `direct` I/O backend with optimized memory organization + +### Prefetch Policies + +```bash Command +# Best-effort: Terminate prefetch when needed +--hicache-storage-prefetch-policy best_effort +# Wait-complete: Ensure complete prefetch, higher cache reuse +--hicache-storage-prefetch-policy wait_complete +# Timeout: Balance between completion and best-effort +--hicache-storage-prefetch-policy timeout +``` + +### Integration with PD Disaggregation + +HiCache works seamlessly with PD Disaggregation. You can choose between two configurations: + +1. **Prefill-only HiCache**: Enable HiCache only on Prefill nodes, allowing KV cache sharing among Prefill instances +2. **Full HiCache with async offloading**: Enable HiCache on Prefill nodes and async KV cache offloading on Decode nodes, allowing Prefill nodes to reuse KV caches from Decode nodes in multi-turn dialogue scenarios + +```bash Command +# Prefill node with HiCache enabled for cross-prefill sharing (ideal for SystemPrompt scenarios) +python3 -m sglang.launch_server \ + --model-path /xxx/DeepSeek-R1/ \ + --tp 8 \ + --host 0.0.0.0 \ + --port 10000 \ + --enable-metrics \ + --enable-cache-report \ + --mem-fraction-static 0.85 \ + --page-size 64 \ + --enable-hierarchical-cache \ + --hicache-ratio 2 \ + --hicache-size 0 \ + --hicache-mem-layout page_first_direct \ + --hicache-io-backend direct \ + --hicache-write-policy write_through \ + --hicache-storage-backend hf3fs \ + --hicache-storage-prefetch-policy wait_complete \ + --disaggregation-ib-device mlx5_0 \ + --disaggregation-mode prefill \ + --disaggregation-transfer-backend mooncake + +# Decode node with async offloading enabled for KV cache reuse by Prefill (ideal for multi-turn conversations) +python3 -m sglang.launch_server \ + --model-path /xxx/DeepSeek-R1/ \ + --tp 8 \ + --host 0.0.0.0 \ + --port 10000 \ + --enable-metrics \ + --enable-cache-report \ + --page-size 64 \ + --hicache-ratio 2 \ + --hicache-size 0 \ + --hicache-mem-layout page_first_direct \ + --hicache-io-backend direct \ + --hicache-write-policy write_through \ + --hicache-storage-backend hf3fs \ + --hicache-storage-prefetch-policy wait_complete \ + --disaggregation-decode-enable-offload-kvcache \ # Enable async KV cache offloading in decode node + --disaggregation-ib-device mlx5_0 \ + --disaggregation-mode decode \ + --disaggregation-transfer-backend mooncake +``` + + +### Deployment with HF3FS + +Here is an example of deploying DeepSeek-R1 with HiCache-HF3FS. For more details, see the [HF3FS Documentation](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/mem_cache/storage/hf3fs/docs). + +```bash Command +python3 -m sglang.launch_server \ + --model-path /xxx/DeepSeek-R1/ \ + --log-level info \ + --tp 8 \ + --host 0.0.0.0 \ + --port 10000 \ + --enable-metrics \ + --enable-cache-report \ + --page-size 64 \ + --mem-fraction-static 0.85 \ + --enable-hierarchical-cache \ + --hicache-ratio 2 \ + --hicache-size 0 \ + --hicache-mem-layout page_first_direct \ + --hicache-io-backend direct \ + --hicache-write-policy write_through \ + --hicache-storage-backend hf3fs \ + --hicache-storage-prefetch-policy wait_complete \ +``` + +### Deployment with Mooncake + +Here is an example of deploying Qwen3-235B-A22B-Instruct-2507 with Mooncake. For more details, see the [Mooncake Documentation](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/mem_cache/storage/mooncake_store). + +```bash Command +# Set Mooncake environment variables +export MOONCAKE_TE_META_DATA_SERVER="http://127.0.0.1:8080/metadata" +export MOONCAKE_GLOBAL_SEGMENT_SIZE=816043786240 +export MOONCAKE_PROTOCOL="rdma" +export MOONCAKE_DEVICE="$DEVICE_LIST" +export MOONCAKE_MASTER=127.0.0.1:50051 + +# Launch SGLang server with Mooncake backend +python3 -m sglang.launch_server \ + --model-path $MODEL_PATH \ + --tp 8 \ + --page-size 64 \ + --enable-hierarchical-cache \ + --hicache-ratio 2 \ + --hicache-mem-layout page_first_direct \ + --hicache-io-backend direct \ + --hicache-storage-backend mooncake \ + --hicache-write-policy write_through \ + --hicache-storage-prefetch-policy timeout +``` + + +## Custom Storage Backend Integration + +To integrate a new storage backend: + +1. **Implement three core methods:** + - `get(key)`: Retrieve value by key + - `exists(key)`: Check key existence + - `set(key, value)`: Store key-value pair + +2. **Register your backend:** Add your storage backend to the HiCache [BackendFactory](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/mem_cache/storage/backend_factory.py#L188) + +The HiCache controller handles all scheduling and synchronization automatically. + +### Dynamic Backend Loading + +Alternatively, you can use dynamic loading to avoid hard-coding your backend in the repository: + +```bash Command +python3 -m sglang.launch_server \ + --model-path your-model \ + --enable-hierarchical-cache \ + --hicache-storage-backend dynamic \ + --hicache-storage-backend-extra-config '{"backend_name":"custom_backend_name", "module_path": "your_module_path", "class_name": "YourHiCacheClassName"}' +``` + +**Configuration Parameters:** +- `--hicache-storage-backend`: Set to `dynamic` +- `--hicache-storage-backend-extra-config`: JSON configuration with: + - `backend_name`: Custom backend identifier + - `module_path`: Python module path to your implementation + - `class_name`: Your HiCache implementation class name + - `interface_v1`: 0 (disable) or 1 (enable) to control usage of batch_get_v1 and batch_set_v1 methods + + +## Community and Support + +- **GitHub Issues**: Report bugs and feature requests +- **Slack Channel**: Join community discussions in #sgl-kv-cache-store +- **Documentation**: Refer to storage backend-specific guides + +*** +*This document will be continuously updated based on community feedback and new features. Contributions and suggestions are welcome!* diff --git a/docs_new/docs/advanced_features/hicache_design.mdx b/docs_new/docs/advanced_features/hicache_design.mdx new file mode 100644 index 000000000..15ab841af --- /dev/null +++ b/docs_new/docs/advanced_features/hicache_design.mdx @@ -0,0 +1,164 @@ +--- +title: "HiCache System Design and Optimization" +metatags: + description: "HiCache architecture: HiRadixTree metadata, L1/L2/L3 workflow, prefetch strategies, write-back policies, zero-copy transfers, multi-rank sync." +--- +This document provides a comprehensive overview of SGLang HiCache, covering its system architecture, workflow and key components. It also details configuration parameters, optimization techniques, and integration with various L3 storage backends, serving as a complete reference for users and developers to understand and tune HiCache for efficient LLM inference. + +## Why and What is HiCache? + +In large language model inference, the prefill phase is often time-consuming: input sequences need to be first converted into Key-Value cache (KV cache) for subsequent decoding. When multiple requests share the same prefix, the KV cache for that prefix is identical. By caching and reusing these shared KV caches, redundant computation can be avoided. To address this, SGLang introduced RadixAttention, which leverages idle GPU memory to cache and reuse prefix KV caches, and **HiCache**, which extends this idea to host memory and distributed storage. + +Inspired by the classic three-level cache design of modern CPUs, HiCache organizes GPU memory as L1, host memory as L2, and distributed storage as L3. This hierarchy enables HiCache to fully exploit the "idle" storage space of GPUs and CPUs, while integrating distributed cache systems such as Mooncake, 3FS, NIXL, and AIBrix KVCache for global KV cache storage and scheduling. As a result, HiCache significantly expands KV cache capacity while maintaining strong read performance—especially in workloads such as multi-QA and long-context inference, where KV cache reuse is frequent. For detailed benchmark results, see [this blog](https://lmsys.org/blog/2025-09-10-sglang-hicache/). + + +## System Design + +### Overall Architecture + +In many modern CPU architectures, the small but fast L1 and L2 caches are private to each core, enabling rapid access to the hottest data, while the larger L3 cache is shared across all cores to significantly reduce redundancy within the cache. Similarly, in HiCache, the L1 and L2 KV caches are private to each inference instance, whereas the L3 KV cache is shared among all inference instances within the cluster. + +### HiRadixTree: Metadata Organization in HiCache + +For KV cache data organization, HiCache builds upon the RadixTree structure introduced in RadixAttention and proposes HiRadixTree. In RadixAttention, each node of the RadixTree corresponds to the KV cache of a consecutive span of tokens in GPU memory. A path from the root to a leaf node represents the prefix of a request, and shared prefixes across multiple requests can reuse the same nodes, thereby avoiding redundant storage. + +HiRadixTree extends this idea: each node corresponds to the KV cache of a span of consecutive tokens and records where that KV cache is stored—whether in local GPU memory, CPU memory, L3 storage, or multiple of these tiers. If stored locally, HiRadixTree maintains precise metadata, including the exact storage address. However, to reduce overhead, HiRadixTree does not store or continuously synchronize metadata for L3 KV cache. Instead, when accessing L3 data, it queries the backend in real time to retrieve the necessary metadata, such as whether the data exists and on which server and location it resides. + +### Overall Workflow + +The workflow of HiCache mainly involves three key operations: **local match**, **prefetch** and **write-back**. When the system receives a new request, it first searches the local L1 and L2 caches for matching KV caches. For parts not found locally, it attempts to prefetch from L3. After prefetching, all required KV caches are loaded into the GPU for computation. Once the prefill computation is complete, the system considers storing the newly generated data into L2 or L3. + + + HiCache Workflow + + +### Local Match + +Local matching is the first step in HiCache's workflow, where incoming request tokens are matched against the HiRadixTree to locate cached KV data in local memory tiers (L1 GPU memory and L2 host memory). + +The matching algorithm traverses the HiRadixTree from the root node, following child nodes that match the token sequence prefix. At each node, the incoming token sequence is compared with the node’s stored token sequence. When `page_size > 1`, matching is performed at the page granularity to optimize memory access patterns. If a match terminates within a node’s stored sequence, the node is automatically split to create an exact boundary, improving the efficiency of future matches. + +The algorithm returns a continuous prefix of the request, with the first part residing in L1 and the latter part in L2. + +Since the process only requires traversing the local HiRadixTree and does not involve any actual data copying, local matching is extremely fast. + +### Prefetch from L3 + +Data prefetching is one of HiCache’s core optimization techniques, designed to proactively load KV caches from L3 storage into local L2 memory, thereby reducing access latency during subsequent operations. + +**Prefetch Trigger Conditions**: +After local matching, for the parts not found in L1 or L2, the system queries L3 to retrieve metadata for the next continuous matching KV caches. If the length of hit cache in L3 exceeds a threshold (default: 256 tokens, configurable), a prefetch operation is triggered. + +**Prefetch Strategies**: HiCache provides three different prefetch termination strategies to address different scenario needs: +- **best_effort**: Terminates immediately when GPU can execute prefill computation, with no waiting time, suitable for scenarios extremely sensitive to latency. +- **wait_complete**: Must wait for all prefetch operations to complete, suitable for scenarios requiring high cache hit rates. +- **timeout**: Terminates after specified time or when complete, balancing latency and cache hit rate needs. + +After prefetching stops, the data already fetched is used together with the local data for the prefill computation. + +For **timeout** strategy, HiCache introduces two configuration parameters to support fine-grained control over prefetch timeout conditions: + +* `prefetch_timeout_base`: the base timeout, representing overhead unrelated to the number of tokens (e.g., scheduling and synchronization). +* `prefetch_timeout_per_ki_token`: the incremental timeout per thousand tokens. + +The timeout is computed as: + +```python Example +timeout = prefetch_timeout_base + prefetch_timeout_per_ki_token * num_token_to_fetch / 1024 +``` + +### Data Write-back + +The write-back mechanism is responsible for moving frequently accessed KV caches from L1 to L2 and L3, enabling larger and longer-term storage as well as cache sharing across instances. + +**Configurable Write-back Policies**: HiCache supports three write-back strategies: + +* **write_through**: Every access is immediately written back to the next level. When bandwidth is sufficient, this strategy provides the strongest caching benefit. +* **write_through_selective**: Data is written back only after the access frequency exceeds a threshold. This strategy backs up only hot data, reducing I/O overhead. +* **write_back**: Data is written back to the next level only when it is evicted from the upper level. This strategy alleviates storage pressure and is suitable for scenarios where storage capacity is limited but memory utilization must be maximized. + +**Cross-instance Sharing**: When data is written back from L2 to L3, only data not already present in L3 is transferred. KV caches stored in L3 can then be shared across all SGLang instances in the cluster (depending on the L3 backend implementation), significantly improving cache hit rates within the same memory budget. + +### Multi-Rank Synchronization + +During multi-GPU parallel computation, such as tensor parallelism (TP), HiCache must ensure consistent states across different ranks. Therefore, critical computation steps require the use of `all_reduce` for state synchronization. + +For example, during prefetching, `all_reduce(op=min)` is used to ensure that all ranks obtain the same number of L3 hits, preventing inconsistent judgments about whether the prefetch threshold has been reached. Similarly, after prefetching completes or terminates, `all_reduce(op=min)` is again required to guarantee consensus among ranks on the prefix length of the successfully retrieved KV cache. + +### Data Transfer Optimization + +**Zero-Copy Data Transfers**: Both prefetching and write-back involve substantial data movement. Minimizing the number of data copies can significantly improve system performance. HiCache supports passing memory addresses and sizes directly when transferring data from L2 memory to an L3 backend. + +**“Batch-Oriented” Data Organization**: The granularity of data reads and writes has a major impact on performance. To address this, HiCache L3 stores and transfers KV cache data at the granularity of **pages** and supports different data layouts beyond the existing `layer first` scheme, including `page first` and `page first direct`. Under the `page first` and `page first direct` layouts, all KV cache data belonging to the same page is placed in contiguous memory, allowing it to be passed as a single object to L3 using zero-copy transfers. + + + HiCache L2 MEM layout + + +However, because GPU KV computation is naturally performed layer by layer, the GPU inherently operates in a `layer first` layout. When transferring `page first` data from L2 to the GPU, data must be transferred at the granularity of one token per layer. The `page first direct` layout mitigates this issue by grouping together all tokens of a given layer within a page, allowing transfers from L2 to GPU to be aggregated at the page-layer level. + +**CPU-to-GPU Transfer Optimizations**: In HiCache, moving data from CPU memory to GPU is as performance-critical as prefetching data from L3 to L2. HiCache employs several optimizations for this process: + +* **Compute-Transfer Overlap**: During the prefill phase, when transferring data from CPU to GPU, HiCache overlaps layers by concurrently loading the KV cache of layer N+1 while computing layer N. This effectively hides data transfer latency. +* **GPU-assisted I/O Kernels**: On top of `cudaMemcpyAsync`, HiCache implements a set of GPU-assisted I/O kernels specifically optimized for KV cache transfers between CPU and GPU. Compared to the baseline approach, these kernels achieve up to 3x higher transfer speed. + +**Write-back Optimization for MLA**: For MHA (Multi-Head Attention) models under multi-TP, each rank holds `1/tp_size` of a token’s KV data. In contrast, for MLA (Multi-Layer Attention) models, all ranks hold the complete and identical KV data for each token. HiCache includes a dedicated optimization for MLA: only one rank initiates the write-back operation, ensuring that data is not redundantly stored across ranks. + +### Integration with PD-Disaggregation Deployment Mode + +SGLang supports a PD (Prefill-Decode) disaggregation deployment mode through the Mooncake TransferEngine (for details, see [this doc](./pd_disaggregation)). In the PD-disaggregation deployment mode, HiCache can be enabled on both the prefill nodes and decode nodes to optimize prefill performance. If enabled on decode nodes, the decode output will also be written back to L3. + +### Unified Interfaces and Rich L3 Storage Backends + +HiCache encapsulates all read, write, and query operations on L3 backends within the `class HiCacheStorage(ABC)`, exposing a set of simple and consistent interfaces. This design supports a wide range of L3 storage backends and allows users to select the one that best fits their specific use cases. + +- **Mooncake**: Mooncake is a high-performance caching system for LLM inference that leverages RDMA and multi-NIC resources to enable zero-copy, ultra-fast data transfers. Try Mooncake [here](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/mem_cache/storage/mooncake_store). + +- **DeepSeek 3FS (HF3FS)**: HF3FS is a Kubernetes-native distributed storage solution with operator-based deployment. Try HF3FS [here](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/mem_cache/storage/hf3fs). + +- **NIXL**: NIXL provides a unified API for accessing various storage plugins, including but not limited to DeepSeek's 3FS, GPU Direct Storage (GDS) and Amazon S3-compatible object storage. Try NIXL [here](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/mem_cache/storage/nixl). + +- **AIBrix KVCache**: AIBrix KVCache is a production-ready KVCache Offloading Framework, which enables efficient memory tiering and low-overhead cross-engine reuse. Try AIBrix KVCache [here](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/mem_cache/storage/aibrix_kvcache). + +- **HiCacheFile**: A simple file-based storage backend for demonstration purposes. + +Specifically, **LMCache**, an efficient KV cache layer for enterprise-scale LLM inference, provides an alternative solution to HiCache. Try LMCache [here](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/mem_cache/storage/lmcache). + +## Related Parameters + +- **`--enable-hierarchical-cache`**: Enable hierarchical cache functionality. This is required to use HiCache. + +- **`--hicache-ratio HICACHE_RATIO`**: The ratio of the size of host KV cache memory pool to the size of device pool. For example, a value of 2 means the host memory pool is twice as large as the device memory pool. The value of this parameter must be greater than 1, as the current implementation requires the host memory allocated for the KV cache to be larger than the device memory allocated for the KV cache. + +- **`--hicache-size HICACHE_SIZE`**: The size of host KV cache memory pool in gigabytes. This parameter overrides `hicache-ratio` if set. For example, `--hicache-size 30` allocates 30GB (1GB = 1e9 bytes) for the host memory pool **for each rank**. If there are 8 ranks, then the total memory size is 240GB. Just like `hicache-ratio`, the value of this parameter must be larger than the size of device memory allocated for KV cache. + +**Note**: `--hicache-ratio` and `--hicache-size` are two critical parameters. In general, a larger HiCache size leads to a higher cache hit rate, which improves prefill performance. However, the relationship between cache size and hit rate is not linear. Once most reusable KV data—especially hot tokens—are already cached, further increasing the size may yield only marginal performance gains. Users can set these parameters based on their workload characteristics and performance requirements. + +- **`--page-size PAGE_SIZE`**: The number of tokens per page. This parameter determines the granularity of KV cache storage and retrieval. Larger page sizes reduce metadata overhead and improve I/O efficiency for storage backends, but may lower the cache hit rate when only part of a page matches the stored KV cache. For workloads with long common prefixes, larger pages can improve performance, while workloads with more diverse prefixes may benefit from smaller pages. See [Data Transfer Optimization](#data-transfer-optimization) for how page granularity affects I/O performance. + +- **`--hicache-storage-prefetch-policy {best_effort,wait_complete,timeout}`**: Controls when prefetching from storage should stop. See [Prefetch from L3](#prefetch-from-l3) for details. + - `best_effort`: Prefetch as much as possible without blocking + - `wait_complete`: Wait for prefetch to complete before proceeding + - `timeout`: Terminates after specified time or when complete (Recommended for production environments, as setting an appropriate timeout helps the system meet required SLOs) + +- **`--hicache-write-policy {write_back,write_through,write_through_selective}`**: Controls how data is written from faster to slower memory tiers. See [Data Write-back](#data-write-back) for details. + - `write_through`: Immediately writes data to all tiers (strongest caching benefits) + - `write_through_selective`: Uses hit-count tracking to back up only frequently accessed data + - `write_back`: Writes data back to slower tiers only when eviction is needed (reduces I/O load) + +- **`--hicache-io-backend {direct,kernel}`**: Choose the I/O backend for KV cache transfer between CPU and GPU. See [Data Transfer Optimization](#data-transfer-optimization) for details. + - `direct`: Standard CUDA memory copy operations + - `kernel`: GPU-assisted I/O kernels (recommended for better performance) + +- **`--hicache-mem-layout {layer_first,page_first,page_first_direct}`**: Memory layout for the host memory pool. See [Data Transfer Optimization](#data-transfer-optimization) for details. + - `layer_first`: Compatible with GPU computation kernels (default for GPU memory) + - `page_first`: Optimized for I/O efficiency + - `page_first_direct`: Groups all tokens of a given layer within a page, allowing transfers from L2 to GPU to be aggregated at the page-layer level + +- **`--hicache-storage-backend {file,mooncake,hf3fs,nixl,aibrix,dynamic}`**: Choose the storage backend for the L3 tier. Built-in backends: file, mooncake, hf3fs, nixl, aibrix. For dynamic backend, use --hicache-storage-backend-extra-config to specify: `backend_name` (custom name), `module_path` (Python module path), `class_name` (backend class name). See [Unified Interfaces and Rich L3 Storage Backends](#unified-interfaces-and-rich-l3-storage-backends) for available backends. + +- **`--enable-lmcache`**: Using LMCache as an alternative hierarchical cache solution. + +- **`--hicache-storage-backend-extra-config HICACHE_STORAGE_BACKEND_EXTRA_CONFIG`**: the extra config can be either + - a JSON string containing extra configuration for the storage backend, e.g., `--hicache-storage-backend-extra-config '{"prefetch_threshold":512, "prefetch_timeout_base": 0.5, "prefetch_timeout_per_ki_token": 0.25}' `, or + - a TOML or JSON or YAML file specifying the extra configuration for the storage backend (to differentiate from the JSON string input, prepend a `@` in front of the file name), e.g., `--hicache-storage-backend-extra-config "@config.toml"` where `config.toml` is the config file containing the complex configurations. This can be useful when the configuration consists of many or complex key-value pairs (for instance, it is preferred to use a config file for NIXL backend as its configurations can be complex). diff --git a/docs_new/docs/advanced_features/hicache_storage_runtime_attach_detach.mdx b/docs_new/docs/advanced_features/hicache_storage_runtime_attach_detach.mdx new file mode 100644 index 000000000..beb9aada8 --- /dev/null +++ b/docs_new/docs/advanced_features/hicache_storage_runtime_attach_detach.mdx @@ -0,0 +1,133 @@ +--- +title: "Runtime Attach/Detach HiCache Storage Backend (No Restart)" +metatags: + description: "Dynamically attach/detach HiCache L3 storage backends at runtime via HTTP API. No restart required, idle-state safety checks." +--- +This document explains how to **dynamically attach/detach the HiCache L3 storage backend at runtime** (e.g., `mooncake` / `hf3fs` / `nixl` / `file` / `aibrix` / `eic`) while **SGLang is already running and serving traffic**, without restarting the process. + +For safety and consistency, the current implementation **strictly requires** these operations to happen only when the service is **idle**: + +- **No running requests** +- **No waiting/queued requests** + +If the idle condition is not met, the API will fail fast (HTTP 400) and **will not modify** the current service state. + +*** +## 1. Background and implementation overview + +### 1.1 Architecture / control path + +The control path is: + +1. **HTTP Server** (`python/sglang/srt/entrypoints/http_server.py`) + - Exposes `PUT /hicache/storage-backend`, `DELETE /hicache/storage-backend`, `GET /hicache/storage-backend` +2. **TokenizerManager** (`python/sglang/srt/managers/tokenizer_communicator_mixin.py`) + - Sends the request to the Scheduler via `_Communicator` +3. **Scheduler** (`python/sglang/srt/managers/scheduler.py`) + - Performs a **strict idle check** + - Calls `tree_cache.attach_storage_backend(...)` / `detach_storage_backend(...)` +4. **HiRadixCache** (`python/sglang/srt/mem_cache/hiradix_cache.py`) + - Parses `hicache_storage_backend_extra_config_json` (supports both backend config and prefetch knobs) + - Calls `cache_controller.attach_storage_backend(...)` / `detach_storage_backend(...)` +5. **HiCacheController** (`python/sglang/srt/managers/cache_controller.py`) + - Creates/destroys the storage backend instance (via `StorageBackendFactory`) + - Starts/stops backend background threads at runtime (prefetch/backup) + +*** +## 2. Idle-state requirement (strict) + +The Scheduler uses a stricter `_is_idle_for_hicache_storage_op()`: + +- `_is_no_request()` is true (covers running/overlap/pp/disagg and other active states) +- `waiting_queue` is empty +- `grammar_queue` is empty (if the grammar backend is enabled) + +If the condition is not met, attach/detach returns an error like: + +- `Reject attach: scheduler is not idle. #queue-req=... #running-req=...` + + +before switching, drain upstream traffic and wait for the server to become idle, then call attach/detach. + + +### 2.1 DP (data parallel) semantics + +When `dp_size > 1`, the tokenizer dispatches the request to **all DP scheduler instances** and aggregates their responses: + +- The final `success` is **true only if all DP ranks return success** +- The final `message` concatenates messages from all DP ranks + +This is intended to prevent “silent partial success”, but it also means you may see: + +- Overall **failure** even though **some ranks already succeeded** + +Currently there is **no automatic partial rollback** across DP ranks (see TODO in code). Operationally: + +- Prefer to keep backend config identical across ranks +- If attach fails, immediately call detach (best-effort/idempotent), fix config, then retry attach + +*** +## 3. How to use (HTTP Admin API) + +The examples below assume your SGLang HTTP server is at `http://127.0.0.1:30000`. + +### 3.1 Query current storage backend status + +```bash Command +curl -s http://127.0.0.1:30000/hicache/storage-backend +``` + +Example response: + +```json Config +{ + "hicache_storage_backend": "mooncake", + "hicache_storage_backend_extra_config": "{\"master_server_address\":\"127.0.0.1:50051\", ...}" +} +``` + +### 3.2 Attach (enable) a storage backend +```bash Command +curl -s -X PUT http://127.0.0.1:30000/hicache/storage-backend \ + -H 'Content-Type: application/json' \ + -d '{ + "hicache_storage_backend": "mooncake" + }' +``` + +```bash Command +curl -s -X PUT http://127.0.0.1:30000/hicache/storage-backend \ + -H 'Content-Type: application/json' \ + -d '{ + "hicache_storage_backend": "mooncake", + "hicache_storage_backend_extra_config_json": "{\"master_server_address\":\"127.0.0.1:50051\",\"protocol\":\"tcp\",\"global_segment_size\":\"4gb\",\"prefetch_threshold\":256}", + "hicache_storage_prefetch_policy": "timeout" + }' +``` + +Notes: + +- `hicache_storage_backend_extra_config_json` can include both: + - **Backend configuration** (e.g., Mooncake master/metadata/protocol, etc.) + - **Prefetch configuration** (`prefetch_threshold`, `prefetch_timeout_base`, `prefetch_timeout_per_ki_token`, `hicache_storage_pass_prefix_keys`) + +### 3.3 Detach (disable) the storage backend + +```bash Command +curl -s -X DELETE http://127.0.0.1:30000/hicache/storage-backend +``` + +Notes: + +- Detach only makes SGLang **stop using** the L3 storage backend and stops prefetch/backup threads +- It **does not automatically delete** data stored in Mooncake/HF3FS (or other remote backends) + +*** +## 4. Behavior and caveats + +- **No restart required**: attach/detach switches in-process at runtime +- **Must be idle**: otherwise the request is rejected to avoid consistency issues +- **Host KV layout constraints still apply**: for example, Mooncake still requires layouts like `page_first/page_first_direct/page_head`; if the server's HiCache host-memory layout does not satisfy the backend requirements, attach will fail with an error +- **Observability**: + - After attach, `server_args.hicache_storage_backend*` is updated on both the tokenizer and scheduler sides + - If metrics are enabled, attach will create a storage metrics collector in `HiRadixCache` on demand diff --git a/docs_new/docs/advanced_features/hyperparameter_tuning.mdx b/docs_new/docs/advanced_features/hyperparameter_tuning.mdx new file mode 100644 index 000000000..6a52d5a36 --- /dev/null +++ b/docs_new/docs/advanced_features/hyperparameter_tuning.mdx @@ -0,0 +1,82 @@ +--- +title: "Hyperparameter Tuning" +metatags: + description: "SGLang performance tuning: batch size, token usage, mem-fraction-static, chunked-prefill-size, CUDA graph, DP/TP optimization." +--- +## Achieving high throughput for offline batch inference + +Achieving a large batch size is the most important thing for attaining high throughput in offline batch inference. +When the server is running at full load in a steady state, look for the following in the log: + +```text Output +Decode batch. #running-req: 233, #token: 370959, token usage: 0.82, cuda graph: True, gen throughput (token/s): 4594.01, #queue-req: 317 +``` + +### Adjust the request submission speed to control `#queue-req` + +`#queue-req` indicates the number of requests in the queue. +If you frequently see `#queue-req: 0`, it suggests that your client code is submitting requests too slowly. +A healthy range for `#queue-req` is `100 - 2000`. +However, avoid making `#queue-req` too large, as this will increase the scheduling overhead on the server. + +### Achieve a high `token usage` + +`token usage` indicates the KV cache memory utilization of the server. `token usage > 0.9` means good utilization. + +If you frequently see `token usage < 0.9` and `#queue-req > 0`, it means the server is too conservative about taking in new requests. You can decrease `--schedule-conservativeness` to a value like 0.3. +The case of a server being too conservative can happen when users send many requests with a large `max_new_tokens` but the requests stop very early due to EOS or stop strings. + +On the other hand, if you see `token usage` very high and you frequently see warnings like +`KV cache pool is full. Retract requests. #retracted_reqs: 1, #new_token_ratio: 0.9998 -> 1.0000`, you can increase `--schedule-conservativeness` to a value like 1.3. +If you see `KV cache pool is full. Retract requests.` occasionally but not frequently (~1 time per minute), it is okay. + +### Tune `--mem-fraction-static` to increase KV cache pool capacity +SGLang allocates memory as follows: + +Total memory usage = model weights + KV cache pool + CUDA graph buffers + activations + +The `--mem-fraction-static` parameter determines how much memory is allocated to the first two components: + +mem_fraction_static = (model weights + KV cache pool) / GPU memory capacity + +To support higher concurrency, you should maximize the KV cache pool capacity by setting `--mem-fraction-static` as high as possible while still reserving enough memory for activations and CUDA graph buffers. + +SGLang uses simple heuristics to set the default value of `--mem-fraction-static`, but you can optimize it for your use cases. +As a rule of thumb, reserving 5–8 GB of memory for activations is typically sufficient. You can check this by inspecting the logs just before the server is ready. +Look for log entries like this: + +```text Output +[2025-08-11 17:17:03] max_total_num_tokens=665690, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=4096, context_len=65536, available_gpu_mem=13.50 GB +``` + +Check the `available_gpu_mem` value. +- If it is between 5–8 GB, the setting is good. +- If it is too high (e.g., 10 - 20 GB), increase `--mem-fraction-static` to allocate more memory to the KV cache. +- If it is too low, you risk out-of-memory (OOM) errors later, so decrease `--mem-fraction-static`. + +Another straightforward approach is to increase `--mem-fraction-static` in increments of 0.01 until you encounter OOM errors for your workloads. + +### Avoid out-of-memory errors by tuning `--chunked-prefill-size`, `--mem-fraction-static`, and `--max-running-requests` + +If you encounter out-of-memory (OOM) errors, you can adjust the following parameters: + +- If OOM occurs during prefill, try reducing `--chunked-prefill-size` to `4096` or `2048`. This saves memory but slows down the prefill speed for long prompts. +- If OOM occurs during decoding, try lowering `--max-running-requests`. +- You can also reduce `--mem-fraction-static` to a smaller value, such as 0.8 or 0.7. This decreases the memory usage of the KV cache memory pool and helps prevent OOM errors during both prefill and decoding. However, it limits maximum concurrency and reduces peak throughput. + +### Tune `--cuda-graph-max-bs` +By default, CUDA graph is enabled only for small batch sizes (e.g., less than 160 or 256). +However, for some models, especially at large tensor parallelism sizes, CUDA graph can be useful for batch sizes up to 512 or 768. +Therefore, it may be beneficial to increase `--cuda-graph-max-bs` to a larger value. +Note that CUDA graph consumes more memory, so you may need to reduce `--mem-fraction-static` at the same time. + +### Tune `--dp-size` and `--tp-size` + +Data parallelism is better for throughput. When there is enough GPU memory, always favor data parallelism for throughput. Refer to [SGLang Model Gateway (former Router)](../advanced_features/sgl_model_gateway) for a better data parallelism rather than using `dp_size` parameter. + +### Try other options + +- `torch.compile` accelerates small models on small batch sizes. You can enable it with `--enable-torch-compile`. +- Try other quantization (e.g. FP8 quantization with `--quantization fp8`) +- Try other parallelism strategies (e.g. [expert parallelism](https://lmsys.org/blog/2025-05-05-large-scale-ep/)) or DP attention for deepseek models (with `--enable-dp-attention --dp-size 8`). +- If the workload has many shared prefixes, try `--schedule-policy lpm`. Here, `lpm` stands for longest prefix match. It reorders requests to encourage more cache hits but introduces more scheduling overhead. diff --git a/docs_new/docs/advanced_features/lora.ipynb b/docs_new/docs/advanced_features/lora.ipynb new file mode 100644 index 000000000..36fcf7aee --- /dev/null +++ b/docs_new/docs/advanced_features/lora.ipynb @@ -0,0 +1,714 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LoRA Serving" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "SGLang enables the use of [LoRA adapters](https://arxiv.org/abs/2106.09685) with a base model. By incorporating techniques from [S-LoRA](https://arxiv.org/pdf/2311.03285) and [Punica](https://arxiv.org/pdf/2310.18547), SGLang can efficiently support multiple LoRA adapters for different sequences within a single batch of inputs." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Arguments for LoRA Serving" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The following server arguments are relevant for multi-LoRA serving:\n", + "\n", + "* `enable_lora`: Enable LoRA support for the model. This argument is automatically set to True if `--lora-paths` is provided for backward compatibility.\n", + "\n", + "* `enable_lora_overlap_loading`: Enable asynchronous LoRA weight loading in order to overlap H2D transfers with GPU compute. This should be enabled if you find that your LoRA workloads are bottlenecked by adapter weight loading, for example when frequently loading large LoRA adapters.\n", + "\n", + "* `lora_paths`: The list of LoRA adapters to load. Each adapter must be specified in one of the following formats: | = | JSON with schema {\"lora_name\":str,\"lora_path\":str,\"pinned\":bool}.\n", + "\n", + "* `max_loras_per_batch`: Maximum number of adaptors used by each batch. This argument can affect the amount of GPU memory reserved for multi-LoRA serving, so it should be set to a smaller value when memory is scarce. Defaults to be 8.\n", + "\n", + "* `max_loaded_loras`: If specified, it limits the maximum number of LoRA adapters loaded in CPU memory at a time. The value must be greater than or equal to `max-loras-per-batch`.\n", + "\n", + "* `lora_eviction_policy`: LoRA adapter eviction policy when GPU memory pool is full. `lru`: Least Recently Used (default, better cache efficiency). `fifo`: First-In-First-Out.\n", + "\n", + "* `lora_backend`: The backend of running GEMM kernels for Lora modules. Currently we support Triton LoRA backend (`triton`) and Chunked SGMV backend (`csgmv`). In the future, faster backend built upon Cutlass or Cuda kernels will be added.\n", + "\n", + "* `max_lora_rank`: The maximum LoRA rank that should be supported. If not specified, it will be automatically inferred from the adapters provided in `--lora-paths`. This argument is needed when you expect to dynamically load adapters of larger LoRA rank after server startup.\n", + "\n", + "* `lora_target_modules`: The union set of all target modules where LoRA should be applied (e.g., `q_proj`, `k_proj`, `gate_proj`). If not specified, it will be automatically inferred from the adapters provided in `--lora-paths`. This argument is needed when you expect to dynamically load adapters of different target modules after server startup. You can also set it to `all` to enable LoRA for all supported modules. However, enabling LoRA on additional modules introduces a minor performance overhead. If your application is performance-sensitive, we recommend only specifying the modules for which you plan to load adapters.\n", + "\n", + "* `--max-lora-chunk-size`: Maximum chunk size for the ChunkedSGMV LoRA backend. Only used when --lora-backend is 'csgmv'. Choosing a larger value might improve performance. Please tune this value based on your hardware and workload as needed. Defaults to 16.\n", + "\n", + "* `tp_size`: LoRA serving along with Tensor Parallelism is supported by SGLang. `tp_size` controls the number of GPUs for tensor parallelism. More details on the tensor sharding strategy can be found in [S-Lora](https://arxiv.org/pdf/2311.03285) paper.\n", + "\n", + "From client side, the user needs to provide a list of strings as input batch, and a list of adaptor names that each input sequence corresponds to." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Usage\n", + "\n", + "### Serving Single Adaptor" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Note:** SGLang supports LoRA adapters through two APIs:\n", + "\n", + "1. **OpenAI-Compatible API** (`/v1/chat/completions`, `/v1/completions`): Use the `model:adapter-name` syntax. See [OpenAI API with LoRA](../basic_usage/openai_api_completions.ipynb#Using-LoRA-Adapters) for examples.\n", + "\n", + "2. **Native API** (`/generate`): Pass `lora_path` in the request body (shown below)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "import requests\n", + "\n", + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, terminate_process" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\n", + " # Here we set max-loras-per-batch to 2: one slot for adaptor and another one for base model\n", + " \"\"\"\n", + "python3 -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \\\n", + " --enable-lora \\\n", + " --lora-paths lora0=algoprog/fact-generation-llama-3.1-8b-instruct-lora \\\n", + " --max-loras-per-batch 2 \\\n", + " --log-level warning \\\n", + "\"\"\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://127.0.0.1:{port}\"\n", + "json_data = {\n", + " \"text\": [\n", + " \"List 3 countries and their capitals.\",\n", + " \"List 3 countries and their capitals.\",\n", + " ],\n", + " \"sampling_params\": {\"max_new_tokens\": 32, \"temperature\": 0},\n", + " # The first input uses lora0, and the second input uses the base model\n", + " \"lora_path\": [\"lora0\", None],\n", + "}\n", + "response = requests.post(\n", + " url + \"/generate\",\n", + " json=json_data,\n", + ")\n", + "print(f\"Output 0: {response.json()[0]['text']}\")\n", + "print(f\"Output 1: {response.json()[1]['text']}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Serving Multiple Adaptors" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \\\n", + " --enable-lora \\\n", + " --lora-paths lora0=algoprog/fact-generation-llama-3.1-8b-instruct-lora \\\n", + " lora1=Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16 \\\n", + " --max-loras-per-batch 2 \\\n", + " --log-level warning \\\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://127.0.0.1:{port}\"\n", + "json_data = {\n", + " \"text\": [\n", + " \"List 3 countries and their capitals.\",\n", + " \"List 3 countries and their capitals.\",\n", + " ],\n", + " \"sampling_params\": {\"max_new_tokens\": 32, \"temperature\": 0},\n", + " # The first input uses lora0, and the second input uses lora1\n", + " \"lora_path\": [\"lora0\", \"lora1\"],\n", + "}\n", + "response = requests.post(\n", + " url + \"/generate\",\n", + " json=json_data,\n", + ")\n", + "print(f\"Output 0: {response.json()[0]['text']}\")\n", + "print(f\"Output 1: {response.json()[1]['text']}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Dynamic LoRA loading" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Instead of specifying all adapters during server startup via `--lora-paths`. You can also load & unload LoRA adapters dynamically via the `/load_lora_adapter` and `/unload_lora_adapter` API.\n", + "\n", + "When using dynamic LoRA loading, it's recommended to explicitly specify both `--max-lora-rank` and `--lora-target-modules` at startup. For backward compatibility, SGLang will infer these values from `--lora-paths` if they are not explicitly provided. However, in that case, you would have to ensure that all dynamically loaded adapters share the same shape (rank and target modules) as those in the initial `--lora-paths` or are strictly \"smaller\"." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lora0 = \"Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16\" # rank - 4, target modules - q_proj, k_proj, v_proj, o_proj, gate_proj\n", + "lora1 = \"algoprog/fact-generation-llama-3.1-8b-instruct-lora\" # rank - 64, target modules - q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj\n", + "lora0_new = \"philschmid/code-llama-3-1-8b-text-to-sql-lora\" # rank - 256, target modules - q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj\n", + "\n", + "\n", + "# The `--target-lora-modules` param below is technically not needed, as the server will infer it from lora0 which already has all the target modules specified.\n", + "# We are adding it here just to demonstrate usage.\n", + "server_process, port = launch_server_cmd(\"\"\"\n", + " python3 -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \\\n", + " --enable-lora \\\n", + " --cuda-graph-max-bs 2 \\\n", + " --max-loras-per-batch 2 \\\n", + " --max-lora-rank 256\n", + " --lora-target-modules all\n", + " --log-level warning\n", + " \"\"\")\n", + "\n", + "url = f\"http://127.0.0.1:{port}\"\n", + "wait_for_server(url)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load adapter lora0" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = requests.post(\n", + " url + \"/load_lora_adapter\",\n", + " json={\n", + " \"lora_name\": \"lora0\",\n", + " \"lora_path\": lora0,\n", + " },\n", + ")\n", + "\n", + "if response.status_code == 200:\n", + " print(\"LoRA adapter loaded successfully.\", response.json())\n", + "else:\n", + " print(\"Failed to load LoRA adapter.\", response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Load adapter lora1:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = requests.post(\n", + " url + \"/load_lora_adapter\",\n", + " json={\n", + " \"lora_name\": \"lora1\",\n", + " \"lora_path\": lora1,\n", + " },\n", + ")\n", + "\n", + "if response.status_code == 200:\n", + " print(\"LoRA adapter loaded successfully.\", response.json())\n", + "else:\n", + " print(\"Failed to load LoRA adapter.\", response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Check inference output:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://127.0.0.1:{port}\"\n", + "json_data = {\n", + " \"text\": [\n", + " \"List 3 countries and their capitals.\",\n", + " \"List 3 countries and their capitals.\",\n", + " ],\n", + " \"sampling_params\": {\"max_new_tokens\": 32, \"temperature\": 0},\n", + " # The first input uses lora0, and the second input uses lora1\n", + " \"lora_path\": [\"lora0\", \"lora1\"],\n", + "}\n", + "response = requests.post(\n", + " url + \"/generate\",\n", + " json=json_data,\n", + ")\n", + "print(f\"Output from lora0: \\n{response.json()[0]['text']}\\n\")\n", + "print(f\"Output from lora1 (updated): \\n{response.json()[1]['text']}\\n\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Unload lora0 and replace it with a different adapter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = requests.post(\n", + " url + \"/unload_lora_adapter\",\n", + " json={\n", + " \"lora_name\": \"lora0\",\n", + " },\n", + ")\n", + "\n", + "response = requests.post(\n", + " url + \"/load_lora_adapter\",\n", + " json={\n", + " \"lora_name\": \"lora0\",\n", + " \"lora_path\": lora0_new,\n", + " },\n", + ")\n", + "\n", + "if response.status_code == 200:\n", + " print(\"LoRA adapter loaded successfully.\", response.json())\n", + "else:\n", + " print(\"Failed to load LoRA adapter.\", response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Check output again:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://127.0.0.1:{port}\"\n", + "json_data = {\n", + " \"text\": [\n", + " \"List 3 countries and their capitals.\",\n", + " \"List 3 countries and their capitals.\",\n", + " ],\n", + " \"sampling_params\": {\"max_new_tokens\": 32, \"temperature\": 0},\n", + " # The first input uses lora0, and the second input uses lora1\n", + " \"lora_path\": [\"lora0\", \"lora1\"],\n", + "}\n", + "response = requests.post(\n", + " url + \"/generate\",\n", + " json=json_data,\n", + ")\n", + "print(f\"Output from lora0: \\n{response.json()[0]['text']}\\n\")\n", + "print(f\"Output from lora1 (updated): \\n{response.json()[1]['text']}\\n\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### OpenAI-compatible API usage\n", + "\n", + "You can use LoRA adapters via the OpenAI-compatible APIs by specifying the adapter in the `model` field using the `base-model:adapter-name` syntax (for example, `qwen/qwen2.5-0.5b-instruct:adapter_a`). For more details and examples, see the “Using LoRA Adapters” section in the OpenAI API documentation: [openai_api_completions](../basic_usage/openai_api_completions).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### LoRA GPU Pinning" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Another advanced option is to specify adapters as `pinned` during loading. When an adapter is pinned, it is permanently assigned to one of the available GPU pool slots (as configured by `--max-loras-per-batch`) and will not be evicted from GPU memory during runtime. Instead, it remains resident until it is explicitly unloaded.\n", + "\n", + "This can improve performance in scenarios where the same adapter is frequently used across requests, by avoiding repeated memory transfers and reinitialization overhead. However, since GPU pool slots are limited, pinning adapters reduces the flexibility of the system to dynamically load other adapters on demand. If too many adapters are pinned, it may lead to degraded performance, or in the most extreme case (`Number of pinned adapters == max-loras-per-batch`), halt all unpinned requests. Therefore, currently SGLang limits maximal number of pinned adapters to `max-loras-per-batch - 1` to prevent unexpected starvations. \n", + "\n", + "In the example below, we start a server with `lora1` loaded as pinned, `lora2` and `lora3` loaded as regular (unpinned) adapters. Please note that, we intentionally specify `lora2` and `lora3` in two different formats to demonstrate that both are supported." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\"\"\"\n", + " python3 -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \\\n", + " --enable-lora \\\n", + " --cuda-graph-max-bs 8 \\\n", + " --max-loras-per-batch 3 \\\n", + " --max-lora-rank 256 \\\n", + " --lora-target-modules all \\\n", + " --lora-paths \\\n", + " {\"lora_name\":\"lora0\",\"lora_path\":\"Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16\",\"pinned\":true} \\\n", + " {\"lora_name\":\"lora1\",\"lora_path\":\"algoprog/fact-generation-llama-3.1-8b-instruct-lora\"} \\\n", + " lora2=philschmid/code-llama-3-1-8b-text-to-sql-lora\n", + " --log-level warning\n", + " \"\"\")\n", + "\n", + "\n", + "url = f\"http://127.0.0.1:{port}\"\n", + "wait_for_server(url)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also specify adapter as pinned during dynamic adapter loading. In the example below, we reload `lora2` as pinned adapter:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = requests.post(\n", + " url + \"/unload_lora_adapter\",\n", + " json={\n", + " \"lora_name\": \"lora1\",\n", + " },\n", + ")\n", + "\n", + "response = requests.post(\n", + " url + \"/load_lora_adapter\",\n", + " json={\n", + " \"lora_name\": \"lora1\",\n", + " \"lora_path\": \"algoprog/fact-generation-llama-3.1-8b-instruct-lora\",\n", + " \"pinned\": True, # Pin the adapter to GPU\n", + " },\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Verify that the results are expected:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://127.0.0.1:{port}\"\n", + "json_data = {\n", + " \"text\": [\n", + " \"List 3 countries and their capitals.\",\n", + " \"List 3 countries and their capitals.\",\n", + " \"List 3 countries and their capitals.\",\n", + " ],\n", + " \"sampling_params\": {\"max_new_tokens\": 32, \"temperature\": 0},\n", + " # The first input uses lora0, and the second input uses lora1\n", + " \"lora_path\": [\"lora0\", \"lora1\", \"lora2\"],\n", + "}\n", + "response = requests.post(\n", + " url + \"/generate\",\n", + " json=json_data,\n", + ")\n", + "print(f\"Output from lora0 (pinned): \\n{response.json()[0]['text']}\\n\")\n", + "print(f\"Output from lora1 (pinned): \\n{response.json()[1]['text']}\\n\")\n", + "print(f\"Output from lora2 (not pinned): \\n{response.json()[2]['text']}\\n\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Choosing LoRA Backend\n", + "\n", + "SGLang supports two LoRA backends that you can choose from using the `--lora-backend` argument:\n", + "\n", + "- `triton`: Basic Triton-based backend.\n", + "- `csgmv`: Default chunked SGMV backend optimized for high concurrency scenarios.\n", + "\n", + "The `csgmv` backend was recently introduced to improve performance especially at high-concurrency scenarios. Our benchmark shows that it achieves 20% to 80% latency improvements over the basic triton backend." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\"\"\"\n", + " python3 -m sglang.launch_server \\\n", + " --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \\\n", + " --enable-lora \\\n", + " --lora-backend csgmv \\\n", + " --max-loras-per-batch 16 \\\n", + " --lora-paths lora1=path/to/lora1 lora2=path/to/lora2\n", + " \"\"\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## LoRA Overlap Loading" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By using the `--enable-lora-overlap-loading` server argument, the SGLang engine is able to overlap the loading of LoRA weights with prefill and decode compute, essentially hiding the data movement for LoRA weights behind GPU computation. Our benchmarks show that under adversarial conditions, enabling this feature can result in a ~35% reduction in median TTFT - (see the [LoRA overlap loading PR](https://github.com/sgl-project/sglang/pull/15512) for detailed benchmarks)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "lora0 = \"Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16\"\n", + "lora1 = \"algoprog/fact-generation-llama-3.1-8b-instruct-lora\"\n", + "lora2 = \"philschmid/code-llama-3-1-8b-text-to-sql-lora\"\n", + "\n", + "\n", + "server_process, port = launch_server_cmd(\"\"\"\n", + " python3 -m sglang.launch_server \\\n", + " --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \\\n", + " --enable-lora \\\n", + " --enable-lora-overlap-loading \\\n", + " --lora-paths lora0=Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16 \\\n", + " lora1=algoprog/fact-generation-llama-3.1-8b-instruct-lora \\\n", + " lora2=philschmid/code-llama-3-1-8b-text-to-sql-lora \\\n", + " --max-lora-rank 256 \\\n", + " --max-loras-per-batch 2 \\\n", + " --max-loaded-loras 4\n", + " \"\"\")\n", + "\n", + "url = f\"http://127.0.0.1:{port}\"\n", + "wait_for_server(url)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "json_data = {\n", + " \"text\": [\n", + " \"Write a very long fairy-tale.\",\n", + " \"List 3 countries and their capitals.\",\n", + " \"List 3 countries and their capitals.\",\n", + " ],\n", + " \"sampling_params\": [\n", + " {\"max_new_tokens\": 1024, \"temperature\": 0},\n", + " {\"max_new_tokens\": 64, \"temperature\": 0},\n", + " {\"max_new_tokens\": 64, \"temperature\": 0},\n", + " ],\n", + " \"lora_path\": [\"lora0\", \"lora1\", \"lora2\"],\n", + "}\n", + "\n", + "# lora0 and lora1 will be loaded into the memory pool first, and because max_loras_per_batch = 2, lora2's request will remain in the queue.\n", + "# lora1's request will likely finish first, and once it does, lora2 will be loaded. With --enable-lora-overlap-loading, this loading will\n", + "# occur asynchronously and thus decoding for lora0's request won't be blocked.\n", + "response = requests.post(\n", + " url + \"/generate\",\n", + " json=json_data,\n", + ")\n", + "\n", + "for i in range(3):\n", + " print(f\"Output from lora{i}: \\n{response.json()[i]['text']}\\n\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Limitations of LoRA Overlap Loading" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "However, LoRA overlap loading is not free and comes with two important caveats:\n", + "\n", + "1. **Pinned CPU memory requirement**:\n", + " Asynchronous H2D memory copies require LoRA weights to be pinned in CPU memory, which is a finite system resource. To mitigate excessive pinned-memory usage, SGLang currently restricts `max_loaded_loras` to be at most 2× `max_loras_per_batch` when LoRA overlap loading is enabled.\n", + "\n", + "2. **Reduced multi-adapter prefill batching**:\n", + " With overlap loading, adapters become available on the GPU at different times because each adapter is loaded asynchronously. This can reduce the scheduler’s ability to form multi-adapter prefill batches, since only requests whose adapters are currently loaded can be grouped together. As a result, requests for different adapters will be scheduled in separate (or smaller) prefill batches, which can increase TTFT when adapter load time is small compared to prefill compute time. This is why LoRA overlap loading is disabled by default: it should only be enabled when users have determined that LoRA weight loading is a bottleneck (EG high adapter churn, heavy adapter weights, or PCIe-bottlenecked workloads).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Example When Overlap Loading Results in Higher Latency" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For instance, suppose we have four LoRA adapters: `lora0`, `lora1`, `lora2`, and `lora3`. Loading any adapter takes 2ms, while the prefill step for requests for that adapter takes 20ms.\n", + "\n", + "1. **Baseline**:\n", + " The engine loads all four adapters synchronously, then runs one combined prefill batch, giving us a total time of ≈ `2 * 4 + 20 = 28ms`\n", + "\n", + "2. **With LoRA overlap loading enabled**:\n", + " The engine begins loading `lora0` and, once it is ready, schedules a prefill batch containing only `lora0` while `lora1` loads in the background. Then it schedules `lora1`’s prefill while `lora2` loads, and so on. In the worst case where prefill cannot be batched across adapters, total time is ≈ `2 + 4 * 20 = 82ms`\n", + "\n", + "In this scenario, overlap loading reduces adapter-load overhead, but the loss of multi-adapter prefill batching dominates and leads to higher TTFT." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Future Works\n", + "\n", + "The development roadmap for LoRA-related features can be found in this [issue](https://github.com/sgl-project/sglang/issues/2929). Other features, including Embedding Layer, Unified Paging, Cutlass backend are still under development." + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/advanced_features/lora.mdx b/docs_new/docs/advanced_features/lora.mdx new file mode 100644 index 000000000..be2ad9d87 --- /dev/null +++ b/docs_new/docs/advanced_features/lora.mdx @@ -0,0 +1,507 @@ +--- +title: "LoRA Serving" +metatags: + description: "SGLang multi-LoRA serving: S-LoRA and Punica techniques, dynamic adapter loading, GPU pinning, overlap loading, Triton and CSGMV backends." +--- +SGLang enables the use of [LoRA adapters](https://arxiv.org/abs/2106.09685) with a base model. By incorporating techniques from [S-LoRA](https://arxiv.org/pdf/2311.03285) and [Punica](https://arxiv.org/pdf/2310.18547), SGLang can efficiently support multiple LoRA adapters for different sequences within a single batch of inputs. + + +## Arguments for LoRA Serving + + +The following server arguments are relevant for multi-LoRA serving: + +* `enable_lora`: Enable LoRA support for the model. This argument is automatically set to True if `--lora-paths` is provided for backward compatibility. + +* `enable_lora_overlap_loading`: Enable asynchronous LoRA weight loading in order to overlap H2D transfers with GPU compute. This should be enabled if you find that your LoRA workloads are bottlenecked by adapter weight loading, for example when frequently loading large LoRA adapters. + +* `lora_paths`: The list of LoRA adapters to load. Each adapter must be specified in one of the following formats: <PATH> | <NAME>=<PATH> | JSON with schema {"lora_name":str,"lora_path":str,"pinned":bool}. + +* `max_loras_per_batch`: Maximum number of adaptors used by each batch. This argument can affect the amount of GPU memory reserved for multi-LoRA serving, so it should be set to a smaller value when memory is scarce. Defaults to be 8. + +* `max_loaded_loras`: If specified, it limits the maximum number of LoRA adapters loaded in CPU memory at a time. The value must be greater than or equal to `max-loras-per-batch`. + +* `lora_eviction_policy`: LoRA adapter eviction policy when GPU memory pool is full. `lru`: Least Recently Used (default, better cache efficiency). `fifo`: First-In-First-Out. + +* `lora_backend`: The backend of running GEMM kernels for Lora modules. Currently we support Triton LoRA backend (`triton`) and Chunked SGMV backend (`csgmv`). In the future, faster backend built upon Cutlass or Cuda kernels will be added. + +* `max_lora_rank`: The maximum LoRA rank that should be supported. If not specified, it will be automatically inferred from the adapters provided in `--lora-paths`. This argument is needed when you expect to dynamically load adapters of larger LoRA rank after server startup. + +* `lora_target_modules`: The union set of all target modules where LoRA should be applied (e.g., `q_proj`, `k_proj`, `gate_proj`). If not specified, it will be automatically inferred from the adapters provided in `--lora-paths`. This argument is needed when you expect to dynamically load adapters of different target modules after server startup. You can also set it to `all` to enable LoRA for all supported modules. However, enabling LoRA on additional modules introduces a minor performance overhead. If your application is performance-sensitive, we recommend only specifying the modules for which you plan to load adapters. + +* `--max-lora-chunk-size`: Maximum chunk size for the ChunkedSGMV LoRA backend. Only used when --lora-backend is 'csgmv'. Choosing a larger value might improve performance. Please tune this value based on your hardware and workload as needed. Defaults to 16. + +* `tp_size`: LoRA serving along with Tensor Parallelism is supported by SGLang. `tp_size` controls the number of GPUs for tensor parallelism. More details on the tensor sharding strategy can be found in [S-Lora](https://arxiv.org/pdf/2311.03285) paper. + +From client side, the user needs to provide a list of strings as input batch, and a list of adaptor names that each input sequence corresponds to. + + +## Usage + +### Serving Single Adaptor + + +**Note:** SGLang supports LoRA adapters through two APIs: + +1. **OpenAI-Compatible API** (`/v1/chat/completions`, `/v1/completions`): Use the `model:adapter-name` syntax. See [OpenAI API with LoRA](../basic_usage/openai_api_completions.ipynb#Using-LoRA-Adapters) for examples. + +2. **Native API** (`/generate`): Pass `lora_path` in the request body (shown below). + + + +```python Example +import json +import requests + +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, terminate_process +``` + + +```python Example +server_process, port = launch_server_cmd( + # Here we set max-loras-per-batch to 2: one slot for adaptor and another one for base model + """ +python3 -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --enable-lora \ + --lora-paths lora0=algoprog/fact-generation-llama-3.1-8b-instruct-lora \ + --max-loras-per-batch 2 \ + --log-level warning \ +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + + +```python Example +url = f"http://127.0.0.1:{port}" +json_data = { + "text": [ + "List 3 countries and their capitals.", + "List 3 countries and their capitals.", + ], + "sampling_params": {"max_new_tokens": 32, "temperature": 0}, + # The first input uses lora0, and the second input uses the base model + "lora_path": ["lora0", None], +} +response = requests.post( + url + "/generate", + json=json_data, +) +print(f"Output 0: {response.json()[0]['text']}") +print(f"Output 1: {response.json()[1]['text']}") +``` + + +```python Example +terminate_process(server_process) +``` + +### Serving Multiple Adaptors + + + +```python Example +server_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --enable-lora \ + --lora-paths lora0=algoprog/fact-generation-llama-3.1-8b-instruct-lora \ + lora1=Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16 \ + --max-loras-per-batch 2 \ + --log-level warning \ +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + + +```python Example +url = f"http://127.0.0.1:{port}" +json_data = { + "text": [ + "List 3 countries and their capitals.", + "List 3 countries and their capitals.", + ], + "sampling_params": {"max_new_tokens": 32, "temperature": 0}, + # The first input uses lora0, and the second input uses lora1 + "lora_path": ["lora0", "lora1"], +} +response = requests.post( + url + "/generate", + json=json_data, +) +print(f"Output 0: {response.json()[0]['text']}") +print(f"Output 1: {response.json()[1]['text']}") +``` + + +```python Example +terminate_process(server_process) +``` + +### Dynamic LoRA loading + + +Instead of specifying all adapters during server startup via `--lora-paths`. You can also load & unload LoRA adapters dynamically via the `/load_lora_adapter` and `/unload_lora_adapter` API. + +When using dynamic LoRA loading, it's recommended to explicitly specify both `--max-lora-rank` and `--lora-target-modules` at startup. For backward compatibility, SGLang will infer these values from `--lora-paths` if they are not explicitly provided. However, in that case, you would have to ensure that all dynamically loaded adapters share the same shape (rank and target modules) as those in the initial `--lora-paths` or are strictly "smaller". + + + +```python Example +lora0 = "Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16" # rank - 4, target modules - q_proj, k_proj, v_proj, o_proj, gate_proj +lora1 = "algoprog/fact-generation-llama-3.1-8b-instruct-lora" # rank - 64, target modules - q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj +lora0_new = "philschmid/code-llama-3-1-8b-text-to-sql-lora" # rank - 256, target modules - q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj + + +# The `--target-lora-modules` param below is technically not needed, as the server will infer it from lora0 which already has all the target modules specified. +# We are adding it here just to demonstrate usage. +server_process, port = launch_server_cmd( + """ + python3 -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --enable-lora \ + --cuda-graph-max-bs 2 \ + --max-loras-per-batch 2 \ + --max-lora-rank 256 + --lora-target-modules all + --log-level warning + """ +) + +url = f"http://127.0.0.1:{port}" +wait_for_server(url) +``` + +Load adapter lora0 + + + +```python Example +response = requests.post( + url + "/load_lora_adapter", + json={ + "lora_name": "lora0", + "lora_path": lora0, + }, +) + +if response.status_code == 200: + print("LoRA adapter loaded successfully.", response.json()) +else: + print("Failed to load LoRA adapter.", response.json()) +``` + +Load adapter lora1: + + + +```python Example +response = requests.post( + url + "/load_lora_adapter", + json={ + "lora_name": "lora1", + "lora_path": lora1, + }, +) + +if response.status_code == 200: + print("LoRA adapter loaded successfully.", response.json()) +else: + print("Failed to load LoRA adapter.", response.json()) +``` + +Check inference output: + + + +```python Example +url = f"http://127.0.0.1:{port}" +json_data = { + "text": [ + "List 3 countries and their capitals.", + "List 3 countries and their capitals.", + ], + "sampling_params": {"max_new_tokens": 32, "temperature": 0}, + # The first input uses lora0, and the second input uses lora1 + "lora_path": ["lora0", "lora1"], +} +response = requests.post( + url + "/generate", + json=json_data, +) +print(f"Output from lora0: \n{response.json()[0]['text']}\n") +print(f"Output from lora1 (updated): \n{response.json()[1]['text']}\n") +``` + +Unload lora0 and replace it with a different adapter: + + + +```python Example +response = requests.post( + url + "/unload_lora_adapter", + json={ + "lora_name": "lora0", + }, +) + +response = requests.post( + url + "/load_lora_adapter", + json={ + "lora_name": "lora0", + "lora_path": lora0_new, + }, +) + +if response.status_code == 200: + print("LoRA adapter loaded successfully.", response.json()) +else: + print("Failed to load LoRA adapter.", response.json()) +``` + +Check output again: + + + +```python Example +url = f"http://127.0.0.1:{port}" +json_data = { + "text": [ + "List 3 countries and their capitals.", + "List 3 countries and their capitals.", + ], + "sampling_params": {"max_new_tokens": 32, "temperature": 0}, + # The first input uses lora0, and the second input uses lora1 + "lora_path": ["lora0", "lora1"], +} +response = requests.post( + url + "/generate", + json=json_data, +) +print(f"Output from lora0: \n{response.json()[0]['text']}\n") +print(f"Output from lora1 (updated): \n{response.json()[1]['text']}\n") +``` + + +```python Example +terminate_process(server_process) +``` + +### OpenAI-compatible API usage + +You can use LoRA adapters via the OpenAI-compatible APIs by specifying the adapter in the `model` field using the `base-model:adapter-name` syntax (for example, `qwen/qwen2.5-0.5b-instruct:adapter_a`). For more details and examples, see the “Using LoRA Adapters” section in the OpenAI API documentation: [openai_api_completions](../basic_usage/openai_api_completions). + + + +### LoRA GPU Pinning + + +Another advanced option is to specify adapters as `pinned` during loading. When an adapter is pinned, it is permanently assigned to one of the available GPU pool slots (as configured by `--max-loras-per-batch`) and will not be evicted from GPU memory during runtime. Instead, it remains resident until it is explicitly unloaded. + +This can improve performance in scenarios where the same adapter is frequently used across requests, by avoiding repeated memory transfers and reinitialization overhead. However, since GPU pool slots are limited, pinning adapters reduces the flexibility of the system to dynamically load other adapters on demand. If too many adapters are pinned, it may lead to degraded performance, or in the most extreme case (`Number of pinned adapters == max-loras-per-batch`), halt all unpinned requests. Therefore, currently SGLang limits maximal number of pinned adapters to `max-loras-per-batch - 1` to prevent unexpected starvations. + +In the example below, we start a server with `lora1` loaded as pinned, `lora2` and `lora3` loaded as regular (unpinned) adapters. Please note that, we intentionally specify `lora2` and `lora3` in two different formats to demonstrate that both are supported. + + + +```python Example +server_process, port = launch_server_cmd( + """ + python3 -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --enable-lora \ + --cuda-graph-max-bs 8 \ + --max-loras-per-batch 3 \ + --max-lora-rank 256 \ + --lora-target-modules all \ + --lora-paths \ + {"lora_name":"lora0","lora_path":"Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16","pinned":true} \ + {"lora_name":"lora1","lora_path":"algoprog/fact-generation-llama-3.1-8b-instruct-lora"} \ + lora2=philschmid/code-llama-3-1-8b-text-to-sql-lora + --log-level warning + """ +) + + +url = f"http://127.0.0.1:{port}" +wait_for_server(url) +``` + +You can also specify adapter as pinned during dynamic adapter loading. In the example below, we reload `lora2` as pinned adapter: + + + +```python Example +response = requests.post( + url + "/unload_lora_adapter", + json={ + "lora_name": "lora1", + }, +) + +response = requests.post( + url + "/load_lora_adapter", + json={ + "lora_name": "lora1", + "lora_path": "algoprog/fact-generation-llama-3.1-8b-instruct-lora", + "pinned": True, # Pin the adapter to GPU + }, +) +``` + +Verify that the results are expected: + + + +```python Example +url = f"http://127.0.0.1:{port}" +json_data = { + "text": [ + "List 3 countries and their capitals.", + "List 3 countries and their capitals.", + "List 3 countries and their capitals.", + ], + "sampling_params": {"max_new_tokens": 32, "temperature": 0}, + # The first input uses lora0, and the second input uses lora1 + "lora_path": ["lora0", "lora1", "lora2"], +} +response = requests.post( + url + "/generate", + json=json_data, +) +print(f"Output from lora0 (pinned): \n{response.json()[0]['text']}\n") +print(f"Output from lora1 (pinned): \n{response.json()[1]['text']}\n") +print(f"Output from lora2 (not pinned): \n{response.json()[2]['text']}\n") +``` + + +```python Example +terminate_process(server_process) +``` + +## Choosing LoRA Backend + +SGLang supports two LoRA backends that you can choose from using the `--lora-backend` argument: + +- `triton`: Basic Triton-based backend. +- `csgmv`: Default chunked SGMV backend optimized for high concurrency scenarios. + +The `csgmv` backend was recently introduced to improve performance especially at high-concurrency scenarios. Our benchmark shows that it achieves 20% to 80% latency improvements over the basic triton backend. + + + +```python Example +server_process, port = launch_server_cmd( + """ + python3 -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --enable-lora \ + --lora-backend csgmv \ + --max-loras-per-batch 16 \ + --lora-paths lora1=path/to/lora1 lora2=path/to/lora2 + """ +) +``` + + +```python Example +terminate_process(server_process) +``` + +## LoRA Overlap Loading + + +By using the `--enable-lora-overlap-loading` server argument, the SGLang engine is able to overlap the loading of LoRA weights with prefill and decode compute, essentially hiding the data movement for LoRA weights behind GPU computation. Our benchmarks show that under adversarial conditions, enabling this feature can result in a ~35% reduction in median TTFT - (see the [LoRA overlap loading PR](https://github.com/sgl-project/sglang/pull/15512) for detailed benchmarks). + + + +```python Example +lora0 = "Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16" +lora1 = "algoprog/fact-generation-llama-3.1-8b-instruct-lora" +lora2 = "philschmid/code-llama-3-1-8b-text-to-sql-lora" + + +server_process, port = launch_server_cmd( + """ + python3 -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --enable-lora \ + --enable-lora-overlap-loading \ + --lora-paths lora0=Nutanix/Meta-Llama-3.1-8B-Instruct_lora_4_alpha_16 \ + lora1=algoprog/fact-generation-llama-3.1-8b-instruct-lora \ + lora2=philschmid/code-llama-3-1-8b-text-to-sql-lora \ + --max-lora-rank 256 \ + --max-loras-per-batch 2 \ + --max-loaded-loras 4 + """ +) + +url = f"http://127.0.0.1:{port}" +wait_for_server(url) +``` + + +```python Example +json_data = { + "text": [ + "Write a very long fairy-tale.", + "List 3 countries and their capitals.", + "List 3 countries and their capitals.", + ], + "sampling_params": [ + {"max_new_tokens": 1024, "temperature": 0}, + {"max_new_tokens": 64, "temperature": 0}, + {"max_new_tokens": 64, "temperature": 0}, + ], + "lora_path": ["lora0", "lora1", "lora2"], +} + +# lora0 and lora1 will be loaded into the memory pool first, and because max_loras_per_batch = 2, lora2's request will remain in the queue. +# lora1's request will likely finish first, and once it does, lora2 will be loaded. With --enable-lora-overlap-loading, this loading will +# occur asynchronously and thus decoding for lora0's request won't be blocked. +response = requests.post( + url + "/generate", + json=json_data, +) + +for i in range(3): + print(f"Output from lora{i}: \n{response.json()[i]['text']}\n") +``` + + +```python Example +terminate_process(server_process) +``` + +#### Limitations of LoRA Overlap Loading + + +However, LoRA overlap loading is not free and comes with two important caveats: + +1. **Pinned CPU memory requirement**: + Asynchronous H2D memory copies require LoRA weights to be pinned in CPU memory, which is a finite system resource. To mitigate excessive pinned-memory usage, SGLang currently restricts `max_loaded_loras` to be at most 2× `max_loras_per_batch` when LoRA overlap loading is enabled. + +2. **Reduced multi-adapter prefill batching**: + With overlap loading, adapters become available on the GPU at different times because each adapter is loaded asynchronously. This can reduce the scheduler’s ability to form multi-adapter prefill batches, since only requests whose adapters are currently loaded can be grouped together. As a result, requests for different adapters will be scheduled in separate (or smaller) prefill batches, which can increase TTFT when adapter load time is small compared to prefill compute time. This is why LoRA overlap loading is disabled by default: it should only be enabled when users have determined that LoRA weight loading is a bottleneck (EG high adapter churn, heavy adapter weights, or PCIe-bottlenecked workloads). + + + +#### Example When Overlap Loading Results in Higher Latency + + +For instance, suppose we have four LoRA adapters: `lora0`, `lora1`, `lora2`, and `lora3`. Loading any adapter takes 2ms, while the prefill step for requests for that adapter takes 20ms. + +1. **Baseline**: + The engine loads all four adapters synchronously, then runs one combined prefill batch, giving us a total time of ≈ `2 * 4 + 20 = 28ms` + +2. **With LoRA overlap loading enabled**: + The engine begins loading `lora0` and, once it is ready, schedules a prefill batch containing only `lora0` while `lora1` loads in the background. Then it schedules `lora1`’s prefill while `lora2` loads, and so on. In the worst case where prefill cannot be batched across adapters, total time is ≈ `2 + 4 * 20 = 82ms` + +In this scenario, overlap loading reduces adapter-load overhead, but the loss of multi-adapter prefill batching dominates and leads to higher TTFT. + + +## Future Works + +The development roadmap for LoRA-related features can be found in this [issue](https://github.com/sgl-project/sglang/issues/2929). Other features, including Embedding Layer, Unified Paging, Cutlass backend are still under development. diff --git a/docs_new/docs/advanced_features/object_storage.mdx b/docs_new/docs/advanced_features/object_storage.mdx new file mode 100644 index 000000000..a6de5a206 --- /dev/null +++ b/docs_new/docs/advanced_features/object_storage.mdx @@ -0,0 +1,142 @@ +--- +title: "Loading Models from Object Storage" +metatags: + description: "Load SGLang models directly from S3, Google Cloud Storage, Azure Blob, and S3-compatible object storage with runai_streamer." +--- + +SGLang supports direct loading of models from object storage (S3 and Google Cloud Storage) without requiring a full local download. This feature uses the `runai_streamer` load format to stream model weights directly from cloud storage, significantly reducing startup time and local storage requirements. + +## Overview + +When loading models from object storage, SGLang uses a two-phase approach: + +1. **Metadata Download** (once, before process launch): Configuration files and tokenizer files are downloaded to a local cache +2. **Weight Streaming** (lazy, during model loading): Model weights are streamed directly from object storage as needed + +## Supported Storage Backends + +1. **Amazon S3**: `s3://bucket-name/path/to/model/` +2. **Google Cloud Storage**: `gs://bucket-name/path/to/model/` +3. **Azure Blob**: `az://some-azure-container/path/` +4. **S3 compatible**: `s3://bucket-name/path/to/model/` + +## Quick Start + +### Basic Usage + +Simply provide an object storage URI as the model path: + +```bash +# S3 +python -m sglang.launch_server \ + --model-path s3://my-bucket/models/llama-3-8b/ \ + --load-format runai_streamer + +# Google Cloud Storage +python -m sglang.launch_server \ + --model-path gs://my-bucket/models/llama-3-8b/ \ + --load-format runai_streamer +``` + +**Note**: The `--load-format runai_streamer` is automatically detected when using object storage URIs, so you can omit it: + +```bash +python -m sglang.launch_server \ + --model-path s3://my-bucket/models/llama-3-8b/ +``` + +### With Tensor Parallelism + +```bash +python -m sglang.launch_server \ + --model-path gs://my-bucket/models/llama-70b/ \ + --tp 4 \ + --model-loader-extra-config '{"distributed": true}' +``` + +## Configuration + +### Load Format + +The `runai_streamer` load format is specifically designed for object storage, ssd and shared file systems + +```bash +python -m sglang.launch_server \ + --model-path s3://bucket/model/ \ + --load-format runai_streamer +``` + +### Extended Configuration Parameters + +Use `--model-loader-extra-config` to pass additional configuration as a JSON string: + +```bash +python -m sglang.launch_server \ + --model-path s3://bucket/model/ \ + --model-loader-extra-config '{ + "distributed": true, + "concurrency": 8, + "memory_limit": 2147483648 + }' +``` + +#### Available Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescriptionDefault
distributedboolEnable distributed streaming for multi-GPU setups. Automatically set to true for object storage paths and cuda alike devices.Auto-detected
concurrencyintNumber of concurrent download streams. Higher values can improve throughput for large models.4
memory_limitintMemory limit (in bytes) for the streaming buffer.System-dependent
+ +## Performance Considerations + +### Distributed Streaming + +For multi-GPU setups, enable distributed streaming to parallelize weight loading between the processes: + +```bash +python -m sglang.launch_server \ + --model-path s3://bucket/model/ \ + --tp 8 \ + --model-loader-extra-config '{"distributed": true}' +``` + +## Limitations + +- **Supported Formats**: Currently only supports `.safetensors` weight format (recommended format) +- **Supported Device**: Distributed streaming is supported on cuda alike devices. Otherwise fallback to non distributed streaming + +## See Also + +- [Runai model streamer documentation](https://github.com/run-ai/runai-model-streamer) diff --git a/docs_new/docs/advanced_features/observability.mdx b/docs_new/docs/advanced_features/observability.mdx new file mode 100644 index 000000000..3b550f6ad --- /dev/null +++ b/docs_new/docs/advanced_features/observability.mdx @@ -0,0 +1,38 @@ +--- +title: "Observability" +metatags: + description: "SGLang observability: Prometheus metrics, request logging, request dump and replay, crash dump debugging." +--- +## Production Metrics +SGLang exposes the following metrics via Prometheus. You can enable them by adding `--enable-metrics` when launching the server. +You can query them by: +```bash Command +curl http://localhost:30000/metrics +``` + +See [Production Metrics](../references/production_metrics) and [Production Request Tracing](../references/production_request_trace) for more details. + +## Logging + +By default, SGLang does not log any request contents. You can log them by using `--log-requests`. +You can control the verbosity by using `--log-request-level`. +See [Logging](./server_arguments#logging) for more details. + +## Request Dump and Replay + +You can dump all requests and replay them later for benchmarking or other purposes. + +To start dumping, use the following command to send a request to a server: +```bash Command +python3 -m sglang.srt.managers.configure_logging --url http://localhost:30000 --dump-requests-folder /tmp/sglang_request_dump --dump-requests-threshold 100 +``` +The server will dump the requests into a pickle file for every 100 requests. + +To replay the request dump, use `scripts/playground/replay_request_dump.py`. + +## Crash Dump and Replay +Sometimes the server might crash, and you may want to debug the cause of the crash. +SGLang supports crash dumping, which will dump all requests from the 5 minutes before the crash, allowing you to replay the requests and debug the reason later. + +To enable crash dumping, use `--crash-dump-folder /tmp/crash_dump`. +To replay the crash dump, use `scripts/playground/replay_request_dump.py`. diff --git a/docs_new/docs/advanced_features/overview.mdx b/docs_new/docs/advanced_features/overview.mdx new file mode 100644 index 000000000..804f01bd4 --- /dev/null +++ b/docs_new/docs/advanced_features/overview.mdx @@ -0,0 +1,18 @@ +--- +title: Advanced Features +description: Advanced configuration, optimization, and deployment features for SGLang. +--- + +- [Server Arguments](./server_arguments) +- [Hyperparameter Tuning](./hyperparameter_tuning) +- [Attention Backend](./attention_backend) +- [Speculative Decoding](./speculative_decoding) +- [Structured Outputs](./structured_outputs) +- [Quantization](./quantization) +- [Expert Parallelism](./expert_parallelism) +- [LoRA](./lora) +- [PD Disaggregation](./pd_disaggregation) +- [Pipeline Parallelism](./pipeline_parallelism) +- [HiCache](./hicache_best_practices) +- [Observability](./observability) +- [And more…](./server_arguments) diff --git a/docs_new/docs/advanced_features/pd_disaggregation.mdx b/docs_new/docs/advanced_features/pd_disaggregation.mdx new file mode 100644 index 000000000..fa796a4fb --- /dev/null +++ b/docs_new/docs/advanced_features/pd_disaggregation.mdx @@ -0,0 +1,404 @@ +--- +title: "PD Disaggregation" +metatags: + description: "SGLang PD disaggregation: separate prefill and decode phases, Mooncake and NIXL transfer engines, multi-node DeepSeek deployment." +--- +## Why and What is PD Disaggregation? + +Large Language Model (LLM) inference comprises two distinct phases: **Prefill** and **Decode**. The Prefill phase is computation-intensive, processing the entire input sequence, while the Decode phase is memory-intensive, managing the Key-Value (KV) cache for token generation. Traditionally, these phases are handled within a unified engine, where combined scheduling of prefill and decode batches introduces inefficiencies. To address these challenges, we introduce **Prefill and Decoding (PD) Disaggregation** in SGLang. + +### Issues with Unified Scheduling + +The conventional unified engine, which processes prefill and decode batches together, results in two significant problems: + +1. **Prefill Interruption**: Incoming prefill batches frequently interrupt ongoing decode batches, causing substantial delays in token generation. +2. **DP Attention Imbalance**: In data-parallel (DP) attention, one DP worker may process a prefill batch while another handles a decode batch simultaneously, leading to increased decode latency. + +PD Disaggregation resolves these by separating the two stages, enabling tailored optimizations for each. + +For the design details, please refer to [link](https://docs.google.com/document/d/1rQXJwKd5b9b1aOzLh98mnyMhBMhlxXA5ATZTHoQrwvc/edit?tab=t.0). + +Currently, we support Mooncake and NIXL as the transfer engine. + +## Profiling in PD Disaggregation Mode + +When you need to profile prefill or decode workers in PD disaggregation mode, please refer to the [Profile In PD Disaggregation Mode](../developer_guide/benchmark_and_profiling#profile-in-pd-disaggregation-mode) section in the Benchmark and Profiling guide. Due to torch profiler limitations, prefill and decode workers must be profiled separately using dedicated command-line options. + +## Router Integration + +For deploying PD disaggregation at scale with load balancing and fault tolerance, SGLang provides a router. The router can distribute requests between prefill and decode instances using various routing policies. For detailed information on setting up routing with PD disaggregation, including configuration options and deployment patterns, see the [SGLang Model Gateway (former Router)](../advanced_features/sgl_model_gateway.md#prefill-decode-disaggregation). + + +## Mooncake +### Requirements + +```bash +uv pip install mooncake-transfer-engine +``` + +### Usage + +### Llama Single Node + +```bash +python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode prefill \ + --port 30000 \ + --disaggregation-ib-device mlx5_roce0 +python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode decode \ + --port 30001 \ + --base-gpu-id 1 \ + --disaggregation-ib-device mlx5_roce0 +python -m sglang_router.launch_router --pd-disaggregation --prefill http://127.0.0.1:30000 --decode http://127.0.0.1:30001 --host 0.0.0.0 --port 8000 +``` + +### DeepSeek Multi-Node + +```bash +# prefill 0 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-ib-device ${device_name} \ + --disaggregation-mode prefill \ + --host ${local_ip} \ + --port 30000 \ + --trust-remote-code \ + --dist-init-addr ${prefill_master_ip}:5000 \ + --nnodes 2 \ + --node-rank 0 \ + --tp-size 16 \ + --dp-size 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --mem-fraction-static 0.8 +# prefill 1 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-ib-device ${device_name} \ + --disaggregation-mode prefill \ + --host ${local_ip} \ + --port 30000 \ + --trust-remote-code \ + --dist-init-addr ${prefill_master_ip}:5000 \ + --nnodes 2 \ + --node-rank 1 \ + --tp-size 16 \ + --dp-size 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --mem-fraction-static 0.8 +# decode 0 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-ib-device ${device_name} \ + --disaggregation-mode decode \ + --host ${local_ip} \ + --port 30001 \ + --trust-remote-code \ + --dist-init-addr ${decode_master_ip}:5000 \ + --nnodes 2 \ + --node-rank 0 \ + --tp-size 16 \ + --dp-size 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --mem-fraction-static 0.8 \ + --max-running-requests 128 +# decode 1 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-ib-device ${device_name} \ + --disaggregation-mode decode \ + --host ${local_ip} \ + --port 30001 \ + --trust-remote-code \ + --dist-init-addr ${decode_master_ip}:5000 \ + --nnodes 2 \ + --node-rank 1 \ + --tp-size 16 \ + --dp-size 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --mem-fraction-static 0.8 \ + --max-running-requests 128 +``` +### Advanced Configuration + +PD Disaggregation with Mooncake supports the following environment variables for fine-grained control over system behavior. + +#### NVLink Transport Configuration +To enable NVLink transport for KV cache transfers with the mooncake backend (recommended for NVL72 deployments), set the following environment variables. Note that auxiliary data transfer will still use TCP as a temporary workaround. + +```bash +export SGLANG_MOONCAKE_CUSTOM_MEM_POOL=True +export MC_FORCE_MNNVL=True +``` + +#### Prefill Server Configuration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
VariableDescriptionDefault
**`SGLANG_DISAGGREGATION_THREAD_POOL_SIZE`**Controls the total number of worker threads for KVCache transfer operations per TP rankA dynamic value calculated by `int(0.75 * os.cpu_count()) // 8)`, which is limited to be larger than 4 and less than 12 to ensure efficiency and prevent thread race conditions
**`SGLANG_DISAGGREGATION_QUEUE_SIZE`**Sets the number of parallel transfer queues. KVCache transfer requests from multiple decode instances will be sharded into these queues so that they can share the threads and the transfer bandwidth at the same time. If it is set to `1`, then we transfer requests one by one according to fcfs strategy`4`
**`SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT`**Timeout (seconds) for receiving destination KV indices during request initialization`300`
+ +If a greater mean TTFT is acceptable, you can `export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600` (10 minutes) to relax the timeout condition. +Please be aware that this setting will cause prefill instances to take a longer time to clean up the affected memory resources when a running decode node loses connection. + +#### Decode Server Configuration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
VariableDescriptionDefault
**`SGLANG_DISAGGREGATION_HEARTBEAT_INTERVAL`**Interval (seconds) between health checks to prefill bootstrap servers`5.0`
**`SGLANG_DISAGGREGATION_HEARTBEAT_MAX_FAILURE`**Consecutive heartbeat failures before marking prefill server offline`2`
**`SGLANG_DISAGGREGATION_WAITING_TIMEOUT`**Timeout (seconds) for receiving KV Cache after request initialization`300`
+ +If a greater mean TTFT is acceptable, you can `export SGLANG_DISAGGREGATION_WAITING_TIMEOUT=600` (10 minutes) to relax the timeout condition. + + +## NIXL +### Requirements + +Install via pip. + +```bash +pip install nixl +``` + +Or build from source - may be required if you already have UCX installed. + +```bash +git clone https://github.com/ai-dynamo/nixl.git +cd nixl +pip install . --config-settings=setup-args="-Ducx_path=/path/to/ucx" +``` + + +### Usage + +### Llama Single Node + +```bash +python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode prefill \ + --port 30000 \ + --disaggregation-transfer-backend nixl +python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode decode \ + --port 30001 \ + --base-gpu-id 1 \ + --disaggregation-transfer-backend nixl +python -m sglang_router.launch_router --pd-disaggregation --prefill http://127.0.0.1:30000 --decode http://127.0.0.1:30001 --host 0.0.0.0 --port 8000 +``` + +### DeepSeek Multi-Node + +```bash +# prefill 0 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-transfer-backend nixl \ + --disaggregation-mode prefill \ + --host ${local_ip} \ + --port 30000 \ + --trust-remote-code \ + --dist-init-addr ${prefill_master_ip}:5000 \ + --nnodes 2 \ + --node-rank 0 \ + --tp-size 16 \ + --dp-size 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --mem-fraction-static 0.8 +# prefill 1 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-transfer-backend nixl \ + --disaggregation-mode prefill \ + --host ${local_ip} \ + --port 30000 \ + --trust-remote-code \ + --dist-init-addr ${prefill_master_ip}:5000 \ + --nnodes 2 \ + --node-rank 1 \ + --tp-size 16 \ + --dp-size 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --mem-fraction-static 0.8 +# decode 0 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-transfer-backend nixl \ + --disaggregation-mode decode \ + --host ${local_ip} \ + --port 30001 \ + --trust-remote-code \ + --dist-init-addr ${decode_master_ip}:5000 \ + --nnodes 2 \ + --node-rank 0 \ + --tp-size 16 \ + --dp-size 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --mem-fraction-static 0.8 \ + --max-running-requests 128 +# decode 1 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-transfer-backend nixl \ + --disaggregation-mode decode \ + --host ${local_ip} \ + --port 30001 \ + --trust-remote-code \ + --dist-init-addr ${decode_master_ip}:5000 \ + --nnodes 2 \ + --node-rank 1 \ + --tp-size 16 \ + --dp-size 8 \ + --enable-dp-attention \ + --moe-a2a-backend deepep \ + --mem-fraction-static 0.8 \ + --max-running-requests 128 +``` + +### Advanced Configuration + +#### NIXL Backend Selection + +By default, NIXL uses the **UCX** backend for KV cache transfers. You can select a different NIXL plugin backend depending on your infrastructure using the environment variable `SGLANG_DISAGGREGATION_NIXL_BACKEND`. + +Example: `export SGLANG_DISAGGREGATION_NIXL_BACKEND=LIBFABRIC` + +**Available backends:** UCX (default), LIBFABRIC, or any installed NIXL plugin. + +Example usage: +```bash +export SGLANG_DISAGGREGATION_NIXL_BACKEND=LIBFABRIC +python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode prefill \ + --disaggregation-transfer-backend nixl \ + --port 30000 +``` + +## ASCEND + +### Usage + +Use ascend backend with [memfabric_hybrid](https://gitcode.com/Ascend/memfabric_hybrid) and ASCEND_MF_STORE_URL being set + +```bash +pip install memfabric-hybrid==1.0.5 +export ASCEND_MF_STORE_URL="tcp://xxx.xx.xxx.xxx:xxxx" +``` +Use mooncake backend, more details can be found in mooncake section. +```bash +export ENABLE_ASCEND_TRANSFER_WITH_MOONCAKE=true +``` +ASCEND_NPU_PHY_ID need to be set in container env +```bash +export ASCEND_NPU_PHY_ID=xxx +``` + + +### Llama Single Node + +```bash +python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode prefill \ + --port 30000 \ + --disaggregation-transfer-backend ascend +python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode decode \ + --port 30001 \ + --base-gpu-id 1 \ + --disaggregation-transfer-backend ascend +python -m sglang_router.launch_router --pd-disaggregation --prefill http://127.0.0.1:30000 --decode http://127.0.0.1:30001 --host 0.0.0.0 --port 8000 +``` + +### DeepSeek Multi-Node + +```bash +# prefill 0 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-transfer-backend ascend \ + --disaggregation-mode prefill \ + --host ${local_ip} \ + --port 30000 \ + --trust-remote-code \ + --dist-init-addr ${prefill_master_ip}:5000 \ + --nnodes 1 \ + --node-rank 0 \ + --tp-size 16 +# decode 0 +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --disaggregation-transfer-backend ascend \ + --disaggregation-mode decode \ + --host ${local_ip} \ + --port 30001 \ + --trust-remote-code \ + --dist-init-addr ${decode_master_ip}:5000 \ + --nnodes 1 \ + --node-rank 0 \ + --tp-size 16 +``` diff --git a/docs_new/docs/advanced_features/piecewise_cuda_graph.mdx b/docs_new/docs/advanced_features/piecewise_cuda_graph.mdx new file mode 100644 index 000000000..701bb9ae1 --- /dev/null +++ b/docs_new/docs/advanced_features/piecewise_cuda_graph.mdx @@ -0,0 +1,299 @@ +--- +title: "Piecewise CUDA Graph" +metatags: + description: "Use Piecewise CUDA Graph to reduce prefill and extend kernel launch overhead while supporting dynamic token shapes." +--- + +## Motivation + +Standard CUDA graphs capture the entire model forward pass as a single graph. This works well for decode (fixed batch size), but not for extend/prefill where the number of tokens varies across iterations. + +Piecewise CUDA Graph (PCG) solves this by splitting the model's computation graph into pieces (roughly one per layer) at "split points" (e.g., MoE dispatch ops). Each piece is captured as a separate CUDA graph for a set of pre-defined token lengths. At runtime, the input is padded to the nearest captured size, and each piece is replayed. This eliminates kernel launch overhead for prefill/extend while still supporting dynamic shapes. + +Recently we **enabled PCG by default**, which means that the old `--enable-piecewise-cuda-graph` flag is deprecated. Use `--disable-piecewise-cuda-graph` to turn it off. + +## Usage + +PCG is enabled by default for supported configurations. No extra flags needed: + +```bash +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct +``` + +### Disable PCG + +```bash +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disable-piecewise-cuda-graph +``` + +### Custom capture sizes + +```bash +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --piecewise-cuda-graph-max-tokens 2048 +``` + +### Server Args + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultDescription
--disable-piecewise-cuda-graphFalseDisable PCG for extend/prefill.
--enforce-piecewise-cuda-graphFalseForce-enable PCG, skipping all auto-disable conditions. For testing only.
--piecewise-cuda-graph-max-tokensNone (auto)Maximum token count to capture. Defaults to chunked_prefill_size (non-MLA) or 2048 (MLA).
--piecewise-cuda-graph-tokensNone (auto)Explicit list of token lengths to capture. Auto-generated if not set.
--piecewise-cuda-graph-compiler"eager"Compiler backend for the captured subgraphs. Choices: eager, inductor.
--enable-piecewise-cuda-graphDeprecated. PCG is now enabled by default. Use --enforce-piecewise-cuda-graph to skip auto-disable conditions.
+ +## Bug Report + +PCG is enabled by default but is still in an experimental stage. Since PCG relies on `torch.compile` to trace the model's forward pass, most bugs are introduced by torch compile tracing failures (e.g., untraceable ops, dynamic control flow, or graph breaks). If you encounter any issues related to PCG, please disable it by adding `--disable-piecewise-cuda-graph` to your launch command and report the bug at [GitHub Issues](https://github.com/sgl-project/sglang/issues/new/choose). We greatly appreciate your help in improving this feature. + +### For Users + +If you see an error message like the following during server startup, it is a PCG bug: + +``` +Piecewise CUDA Graph is enabled by default as an experimental feature. +To work around this error, add --disable-piecewise-cuda-graph to your launch command. +Please report this issue at https://github.com/sgl-project/sglang/issues/new/choose +``` + +To work around it, add `--disable-piecewise-cuda-graph` to your launch command. When filing a bug report, please include: +1. The full error traceback +2. Model name and quantization method +3. Launch command with all arguments +4. GPU type and driver version + +### For Developers + +Since PCG relies on `torch.compile` to trace the model's forward pass, newly developed CUDA kernels (both JIT kernels and sgl-kernels) are typically not compatible with `torch.compile` out of the box. The tracing will fail on untraceable operations such as JIT compilation, file I/O, or dynamic module loading inside the kernel. + +To make a kernel compatible with PCG, you need to register it as a custom op using `register_custom_op` from `sglang.srt.utils.custom_op`. This wraps the kernel as an opaque node in the compiled graph so that `torch.compile` will not trace inside it. + +**Example usage (JIT kernel):** + +```python +from sglang.srt.utils.custom_op import register_custom_op + +# Inplace operator (no return value) +@register_custom_op(mutates_args=["output_q", "output_s"]) +def per_token_group_quant_8bit( + input: torch.Tensor, + output_q: torch.Tensor, + output_s: torch.Tensor, +) -> None: + # kernel implementation ... +``` + +**Example usage (operator with output):** + +```python +# out_shape indicates which argument has the same shape as the output +@register_custom_op(mutates_args=["x"], out_shape=0) +def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + return x.add_(y) +``` + +For wrapping external library functions (e.g., FlashInfer kernels), use `register_custom_op_from_extern` instead. See `python/sglang/srt/utils/custom_op.py` for full API documentation. + +## How it works + +### Torch compile backend + +PCG uses `torch.compile` with a custom backend (`SGLangBackend`) to split and compile the model's forward pass. The flow is: + +``` +model.forward wrapper +→ torch.compile(..., backend=SGLangBackend) +→ FX graph +→ split_graph() at registered split ops +→ split_gm (top-level graph that chains the pieces) +→ replace capturable submodules with CUDAPiecewiseBackend +→ runtime dispatch: eager split ops + per-piece capture/replay +``` + +- **Install**: `install_torch_compiled()` replaces `model.forward` with a wrapper function. When `is_in_piecewise_cuda_graph()` returns True, the wrapper dispatches to the compiled callable; otherwise it falls back to the original forward. The first invocation through this path triggers Dynamo tracing and graph compilation — CUDA graph replay only happens after the capture phase completes. + +- **Split**: When `torch.compile` traces the model, `SGLangBackend` receives the FX graph and calls `split_graph()`. Ops listed in `CompilationConfig.split_ops` are treated as split points, so the graph is cut at each one. These split-op submodules are left to run eagerly at runtime, while the surrounding submodules are compiled and wrapped by `CUDAPiecewiseBackend`. The result is a top-level "stitching graph" (`split_gm`) with children such as `submod_0`, `submod_1`, … interleaving capturable subgraphs and eager split-op submodules. + +- **Replace**: `PiecewiseCompileInterpreter` iterates over each capturable submodule in `split_gm`, compiles it for general (dynamic) shapes, and replaces it in-place with a `CUDAPiecewiseBackend` instance. Split-op submodules (e.g., attention, all-reduce) are left as-is and run eagerly at runtime. + +- **Dispatch**: At runtime, calling `split_gm` executes the stitching graph, which calls each submodule in order. Split-op submodules run eagerly. Each `CUDAPiecewiseBackend` submodule goes through three phases: + - **Compile warmup** — runs the general-shape compiled path. + - **Capture** — for each capture size, runs one warmup pass then records a CUDA graph. + - **Steady-state replay** — replays the captured CUDA graph for each forward pass. + +### Piecewise cuda graph runner + +`PiecewiseCudaGraphRunner` orchestrates the full lifecycle through three phases: + +- **Compile** — Warms up JIT kernels with a dummy forward pass, then wraps the model with `torch.compile`, triggering Dynamo tracing to split the FX graph and create `CUDAPiecewiseBackend` instances for each subgraph piece. + +- **Capture** — Iterates over capture sizes in reverse order (largest first). For each size, runs the forward pass twice (one warmup, one CUDA graph capture). + +- **Replay** — At runtime, finds the smallest captured size >= actual token count via binary search, copies inputs into static buffers with zero-padding, replays the captured CUDA graphs, and slices outputs back to the actual token count. + +### Memory optimization + +The memory cost of PCG comes from two parts: **torch memory allocator** and **non-torch memory**. + +The torch memory allocator overhead is trivial thanks to several optimizations: a global shared memory pool is reused across all CUDA graph runners and capture sizes, capture is done in reverse order (large to small) so smaller graphs reuse memory allocated by larger ones, and output tensors of the last subgraph are stored as weak references to maximize memory reuse. + +The main memory overhead comes from non-torch memory — the CUDA graph objects themselves require GPU memory to store the recorded kernel launch parameters and internal state. This overhead scales with the number of captured sizes, which is why `piecewise_cuda_graph_max_tokens` is capped conservatively by default. + +### Shape configuration + +Piecewise CUDA graph pre-captures graphs for a set of token counts. At runtime, the actual token count is rounded up to the nearest captured size (via binary search), and the corresponding graph is replayed. If the token count exceeds the largest captured size, the runtime falls back to the normal (non-graph) forward path. + +The default capture schedule is auto-generated with increasing granularity: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Token rangeStep size
4 – 324
48 – 25616
288 – 51232
576 – 102464
1280 – 4096256
4096+512
+ +For the auto-generated schedule, sizes are capped at `--piecewise-cuda-graph-max-tokens`. The default cap is `chunked_prefill_size` for non-MLA models and `2048` for MLA backend models. If `--max-total-tokens` is set, the cap is further limited to not exceed it. Additionally, Llama-2 models are auto-capped at 4096 tokens as a temporary workaround. + +## Compatibility + +PCG is auto-disabled in the following scenarios. We are actively working on expanding compatibility — support for many of these will be coming soon. + +- Disabled model architectures (e.g., `DeepseekV32ForCausalLM`) +- Speculative decoding +- DP attention +- Pipeline parallelism (`pp_size > 1`) +- Non-CUDA hardware (AMD ROCm, Ascend NPU) +- MoE A2A backend +- LoRA +- Multimodal / VLM models +- DLLM (diffusion LLM) +- Deterministic inference +- PD disaggregation +- Expert distribution recorder / EPLB + +Use `--enforce-piecewise-cuda-graph` to skip all auto-disable checks (for testing/debugging only). + +## Code Reference + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileDescription
python/sglang/srt/model_executor/piecewise_cuda_graph_runner.pyMain runner: init, capture, replay
python/sglang/srt/compilation/compile.pyinstall_torch_compiled trampoline
python/sglang/srt/compilation/backend.pySGLangBackend, graph splitting, piecewise compilation
python/sglang/srt/compilation/cuda_piecewise_backend.pyPer-subgraph CUDA graph capture/replay
python/sglang/srt/compilation/piecewise_context_manager.pyGlobal context flags and ForwardContext
python/sglang/srt/compilation/compilation_config.pyCapture sizes, split ops, compiler config
python/sglang/srt/utils/custom_op.pyregister_custom_op for torch.compile compatibility
python/sglang/srt/server_args.pyServer arguments and auto-disable logic
diff --git a/docs_new/docs/advanced_features/pipeline_parallelism.mdx b/docs_new/docs/advanced_features/pipeline_parallelism.mdx new file mode 100644 index 000000000..77c88c2c4 --- /dev/null +++ b/docs_new/docs/advanced_features/pipeline_parallelism.mdx @@ -0,0 +1,119 @@ +--- +title: "Pipeline Parallelism for Long Context" +metatags: + description: "SGLang pipeline parallelism: reduce TTFT for ultra-long sequences, dynamic chunking, async P2P communication, multi-node deployment." +--- +## Why Pipeline Parallelism? + +As Large Language Models (LLMs) scale toward trillion-parameter architectures and "infinite" context windows, the underlying serving infrastructure must evolve toward more granular, cross-node parallelization strategies. While KV cache techniques effectively mitigate redundant computation, they cannot circumvent the prohibitive Time to First Token (TTFT) inherent in ultra-long sequences with extremely large initial Input Token Length (ITL). Although Tensor Parallelism (TP) remains the conventional approach for intra-node scaling, it frequently encounters communication bottlenecks during multi-node deployments. On the other hand, pipeline parallelism only requires cross-node communication at the boundaries of each pipeline stage, which can achieve better computation-communication overlap compared to a large TP. Therefore, it is also a promising parallelization strategy for improving throughput. + +Detailed analysis can be found in this [blog](https://lmsys.org/blog/2026-01-15-chunked-pipeline/). + +## Implementation Refactoring based on Async Communication +With Dynamic Chunked Prefill, pipeline parallelism has the potential to reduce the TTFT of long-context inputs. For each request, its input tokens can be partitioned into multiple chunks, each no longer than the chunked prefill size. Different chunks of the same request can be processed simultaneously by different nodes, thus parallelizing the processing and reducing TTFT. SGLang has supported Pipeline Parallelism (#5724) for some time and made it compatible with the PD Disaggregation feature (#8846), but the implementation was not perfect and had significant room for performance improvements. + +To eliminate this performance hazard, SGLang implements a Micro-batching Event Loop with non-blocking asynchronous peer-to-peer (P2P) communication to overlap GPU computation with CPU metadata processing and PP communication. This ensures that while one micro-batch is being computed on the GPU, the next one is already being prepared and moved into position effectively, ensuring the pipeline remains as saturated as possible. This approach was first proposed in #7979 and has been redesigned and included in #11852. + +The key mechanisms of the implementation include: + +* **Decoupled Sync/Async Logic in the Event Loop:** The scheduler uses `async_send` in `_pp_send_pyobj_to_next_stage`. Instead of waiting for a transfer to complete, it returns a `P2PWork` handle. The actual synchronization (`P2PWork.work.wait()`) is deferred until `_pp_commit_comm_work` is called, allowing the CPU to perform other work—like scheduling the next batch or processing metadata—while data is in flight. +* **Multi-Stream Execution:** In addition to the main `default_stream`, which serves as the synchronization stream, SGLang utilizes dedicated `forward_stream` and `copy_stream` to execute forward pass GPU computation and Data-to-Host (D2H) memory transfers separately for better overlapping. While `_pp_launch_batch` is executing the current micro-batch on the GPU for the current stage, the CPU processes the previous micro-batch's results using `_pp_process_batch_result`. + +## Guidance about Dynamic Chunking + +### Why Dynamic Chunking +Chunked prefill with a fixed size can cause bubbles in the pipeline, especially when the pp size is large. The main reason behind this phenomenon is that the model has a non-uniform running time, even though each chunk size is identical (brought by the Transformer structure). The larger the prefix sequence length, the longer the running time of the chunk. And these bubbles will be propagated to the next stage, and will significantly degrade the scale efficiency of larger pp ranks. + +To address this issue, SGLang introduces a dynamic chunking mechanism to predict the optimal size for the next chunk such that it satisfies this condition: + +Runtime(L + Next Chunk Size) - Runtime(L) = Runtime(Initial Chunk Size) + +where ***L*** denotes the Prefix Sequence Length. By profiling a series of requests with different ITLs, we model the cumulative runtime as a quadratic function of sequence length. Using this model, we solve the optimal next chunk size for any given prefix length ***L***. Since the computation complexity of the Attention mechanism scales with ***L***, the next chunk size will be progressively reduced as ***L*** grows to maintain an aligned chunk execution time across pipeline stages. + +Based on this method, the scheduler can predict and dynamically reduce the chunk size during runtime to minimize the bubbles caused by the stage misalignment. To be noticed, the scheduler does not use the raw predicted value. To facilitate efficient KVCache memory management and ensure affinity with hardware execution efficiency, the value is aligned downward to the nearest multiple of max(`--page-size`, 64). + + +### Chunked Prefill Size and Smoothing Factor + +When `--enable-dynamic-chunking` is enabled, each chunk size of a sequence is determined dynamically based on the quadratic model that predicts the next chunk size based on the estimated runtime of the initial chunk length. In this case, we use `--chunked-prefill-size` to set up the initial chunk size. When switching to the dynamic chunking mode, the initial chunk size (`--chunked-prefill-size`) should be set to a larger value comparable to the original chunked prefill size, so that there won't be too many chunks. + +**`SGLANG_DYNAMIC_CHUNKING_SMOOTH_FACTOR`** is an environmental variable that controls the smoothing factor for the dynamic chunking algorithm, defaulting to 0.75. It determines how much the chunk size can change during the prefill phase. A larger value means a more aggressive chunk size change, which may lead to better performance but also to greater chunk size changes (the chunk size at the end may become very small, which could lead to performance degradation) and more total chunks. When it is set to 1, the chunk size will be adjusted strictly based on the aforementioned quadratic model that predicts the next chunk size. A smaller value means a more conservative chunk size change, which may lead to smaller chunk size changes and fewer total chunks. When it is set to 0, the chunk size will not be adjusted dynamically, so it is identical to the traditional way with a fixed chunked prefill size. + +Due to the variation in hardware, models, and target workloads, a static configuration is seldom optimal across all scenarios. Consequently, achieving peak performance necessitates a degree of hyperparameter tuning when switching to the dynamic chunking mode. + +**Tuning Guidance for Dynamic Chunked Prefill** + +* **Step 1 \- Iterate to find the optimal fixed chunked prefill size for the targeted PP size**: Different PP sizes for targeted ITL may have different optimal chunked prefill sizes. Therefore, users should iterate to obtain the baseline according to the available resources for scaling. +* **Step 2 \- Initial Chunk Size Selection for Dynamic Chunking**: Set the initial size to 2× or 3× the optimal fixed chunked prefill size. This reduces the total number of chunks and prevents "tail chunks" from underutilizing hardware. To maintain efficiency for extremely large Input Token Lengths (ITL), the dynamic predictor automatically ensures subsequent chunks are at least 1/4 of this initial size. In addition, it is recommended to use a larger initial chunk size (e.g., 4× the optimal fixed chunked prefill size) for such cases as well. +* **Step 3 \- Smooth Factor Adjustment**: This factor controls how strictly the chunk size adjusts the prediction given by the quadratic performance fitting model. + * 1.0: Follows the model strictly. + * **0.6 – 0.85 (Recommended)**: Typical range for the best balance between dynamic scaling and hardware stability. Through experiments, we find that a range between 0.6 and 0.85 typically yields the best performance for dynamic chunking. + * 0: Disables dynamic adjustment, reverting to traditional fixed-size chunking. +* **Another small optimization tip:** Put the larger partition in the higher PP rank when the layers are not evenly divisible across ranks. It can increase the GPU utilization when a larger PP rank is waiting for the previous stage’s result, hence reducing the bubbles on higher PP ranks. If we take DeepSeek-V3.1 as an example, `SGLANG_PP_LAYER_PARTITION=15,15,15,16` usually performs better than `16,15,15,15`. + +## Best Practice for Long Context + +### Tuning the Chunked Prefill Size +Optimizing the chunked prefill size is crucial for balancing pipeline efficiency and resource utilization. The ideal size depends on factors including model architecture, hardware configuration, and typical input lengths. We recommend starting with a small chunk size, such as 4K, and gradually increasing it until you find the optimal size for your specific use case (Different targeted ITL and PP Sizes may have different optimal chunked prefill sizes. Therefore, users should iterate to obtain the baseline according to the available resources for scaling). Alternatively, you can analyze the hardware capacity and determine the optimal chunk size based on the roofline model. + +### Enable Dynamic Chunking and Adjust Smoothing Factor for Ultra-long ITL +SGLang also offers a dynamic chunking solution that could further improve performance. This feature is currently an experimental feature that requires a certain amount of tuning experimentation and may not be suitable for all workloads. In addition, fine-tuning the smoothing factor can help optimize performance for specific workloads and model characteristics. + +### Case Study on NVIDIA H20 + +When evaluating pipeline parallelism with fixed chunked prefill sizes from 2K to 16K, experiment results show that a 4K chunk size delivered optimal prefill TTFT performance for the DeepSeek-V3.1, and a 6K chunk size delivered optimal prefill TTFT performance for the Qwen3-235B-A22B-FP8. + +When enabling dynamic chunking, we first scale the optimal fixed chunked prefill size by a factor of 3 as the initial chunk size. Through experimentation, we found that a multiplier of 2-3 provides an appropriate balance—avoiding excessive initial pipeline bubbles while ensuring that subsequent chunks don't become too small as context length increases. With the default dynamic chunking smoothing factor of 0.75, we performed parameter tuning and determined that a value of 0.65 works optimally with the 12K initial chunk size for the DeepSeek-V3.1, while a value of 0.8 works optimally with the 18K initial chunk size for the Qwen3-235B-A22B-FP8. + +#### DeepSeek-V3.1 with 128K Input Token Length +```bash Command +# prefill node 0 (fixed chunked prefill size) +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.1 --trust-remote-code \ + --nnodes 4 --node-rank 0 --tp 8 --pp-size 4 \ + --port 30000 --dist-init-addr \ + --disable-radix-cache --mem-fraction-static 0.8 \ + --attention-backend fa3 --host 0.0.0.0 --watchdog-timeout 3600 \ + --max-running-requests 128 --chunked-prefill-size 4096 +``` + +```bash Command +# prefill node 0 (with dynamic chunking) +export SGLANG_DYNAMIC_CHUNKING_SMOOTH_FACTOR=0.65 +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.1 --trust-remote-code \ + --nnodes 4 --node-rank 0 --tp 8 --pp-size 4 \ + --port 30000 --dist-init-addr \ + --disable-radix-cache --mem-fraction-static 0.8 \ + --attention-backend fa3 --host 0.0.0.0 --watchdog-timeout 3600 \ + --max-running-requests 128 --chunked-prefill-size 12288 --enable-dynamic-chunking +``` + +#### Qwen3-235B-A22B-FP8 with 128K Input Token Length +```bash Command +# prefill node 0 (fixed chunked prefill size) +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-235B-A22B-FP8 --trust-remote-code \ + --nnodes 4 --node-rank 0 --tp 4 --pp-size 8 \ + --port 30000 --dist-init-addr \ + --disable-radix-cache --mem-fraction-static 0.8 \ + --attention-backend fa3 --host 0.0.0.0 --watchdog-timeout 3600 \ + --max-running-requests 128 --chunked-prefill-size 6144 +``` + +```bash Command +# prefill node 0 (with dynamic chunking) +export SGLANG_DYNAMIC_CHUNKING_SMOOTH_FACTOR=0.8 +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-235B-A22B-FP8 --trust-remote-code \ + --nnodes 4 --node-rank 0 --tp 4 --pp-size 8 \ + --port 30000 --dist-init-addr \ + --disable-radix-cache --mem-fraction-static 0.8 \ + --attention-backend fa3 --host 0.0.0.0 --watchdog-timeout 3600 \ + --max-running-requests 128 --chunked-prefill-size 18432 --enable-dynamic-chunking +``` + +Note: `--disable-radix-cache` is enabled only for reproducible benchmarking purposes. It is not recommended to use it in production. + +## Best Practice for Pipeline Parallelism with PD Disaggregation +To be added. Stay tuned for the latest updates on Pipeline Parallelism with PD Disaggregation. diff --git a/docs_new/docs/advanced_features/quantization.mdx b/docs_new/docs/advanced_features/quantization.mdx new file mode 100644 index 000000000..3d26fc51e --- /dev/null +++ b/docs_new/docs/advanced_features/quantization.mdx @@ -0,0 +1,395 @@ +--- +title: "Quantization" +metatags: + description: "SGLang quantization: FP8, FP4, AWQ, GPTQ, ModelOpt, torchao. Offline and online quantization methods for efficient LLM inference." +--- +SGLang supports various quantization methods, including offline quantization and online dynamic quantization. + +Offline quantization loads pre-quantized model weights directly during inference. This is required for quantization methods +such as GPTQ and AWQ, which collect and pre-compute various statistics from the original weights using the calibration dataset. + +Online quantization dynamically computes scaling parameters—such as the maximum/minimum values of model weights—during runtime. +Like NVIDIA FP8 training's [delayed scaling](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/examples/fp8_primer.html#Mixed-precision-training-with-FP8) mechanism, online quantization calculates the appropriate scaling factors +on-the-fly to convert high-precision weights into a lower-precision format. + +**Note: For better performance, usability and convenience, offline quantization is recommended over online quantization.** + +If you use a pre-quantized model, do not add `--quantization` to enable online quantization at the same time. +For popular pre-quantized models, please visit [Unsloth](https://huggingface.co/unsloth), [NVIDIA ModelOpt](https://huggingface.co/collections/nvidia/inference-optimized-checkpoints-with-model-optimizer) +or [NeuralMagic](https://huggingface.co/collections/neuralmagic) collections on HF for some +popular quality validated quantized models. Quantized models must be validated via benchmarks post-quantization +to guard against abnormal quantization loss regressions. + +## Offline Quantization + +To load already quantized models, simply load the model weights and config. **Again, if the model has been quantized offline, +there's no need to add `--quantization` argument when starting the engine. The quantization method will be parsed from the +downloaded Hugging Face config. For example, DeepSeek V3/R1 models are already in FP8, so do not add redundant parameters.** + +```bash Command +python3 -m sglang.launch_server \ + --model-path hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4 \ + --port 30000 --host 0.0.0.0 +``` + +Take note, if your model is **per-channel quantized (INT8 or FP8) with per-token dynamic quantization activation**, you can opt to include `--quantization w8a8_int8` or `--quantization w8a8_fp8` to invoke the corresponding CUTLASS int8_kernel or fp8_kernel in sgl-kernel. This action will ignore the Hugging Face config's quantization settings. For instance, with `neuralmagic/Meta-Llama-3.1-8B-Instruct-FP8-dynamic`, if you execute with `--quantization w8a8_fp8`, the system will use the `W8A8Fp8Config` from SGLang to invoke the sgl-kernel, rather than the `CompressedTensorsConfig` for vLLM kernels. + +```bash Command +python3 -m sglang.launch_server \ + --model-path neuralmagic/Meta-Llama-3.1-8B-Instruct-FP8-dynamic \ + --quantization w8a8_fp8 \ + --port 30000 --host 0.0.0.0 +``` + +### Examples of Offline Model Quantization + +#### Using [Unsloth](https://docs.unsloth.ai/basics/inference-and-deployment/sglang-guide) + +We strongly suggest the use of Unsloth to quantize and load the model. Please refer to [SGLang Deployment & Inference Guide with Unsloth](https://docs.unsloth.ai/basics/inference-and-deployment/sglang-guide). + +#### Using [auto-round](https://github.com/intel/auto-round) + +```bash Command +# Install +pip install auto-round +``` + +- LLM quantization + +```py Example +# for LLM +from auto_round import AutoRound +model_id = "meta-llama/Llama-3.2-1B-Instruct" +quant_path = "Llama-3.2-1B-Instruct-autoround-4bit" +# Scheme examples: "W2A16", "W3A16", "W4A16", "W8A16", "NVFP4", "MXFP4" (no real kernels), "GGUF:Q4_K_M", etc. +scheme = "W4A16" +format = "auto_round" +autoround = AutoRound(model_id, scheme=scheme) +autoround.quantize_and_save(quant_path, format=format) # quantize and save + +``` + +- VLM quantization +```py Example +# for VLMs +from auto_round import AutoRoundMLLM +model_name = "Qwen/Qwen2-VL-2B-Instruct" +quant_path = "Qwen2-VL-2B-Instruct-autoround-4bit" +scheme = "W4A16" +format = "auto_round" +autoround = AutoRoundMLLM(model_name, scheme) +autoround.quantize_and_save(quant_path, format=format) # quantize and save + +``` + +- Command Line Usage (Gaudi/CPU/Intel GPU/CUDA) + +```bash Command +auto-round \ + --model meta-llama/Llama-3.2-1B-Instruct \ + --bits 4 \ + --group_size 128 \ + --format "auto_round" \ + --output_dir ./tmp_autoround +``` + +- known issues + +Several limitations currently affect offline quantized model loading in sglang, These issues might be resolved in future updates of sglang. If you experience any problems, consider using Hugging Face Transformers as an alternative. + +1. Mixed-bit Quantization Limitations + + Mixed-bit quantization is not fully supported. Due to vLLM's layer fusion (e.g., QKV fusion), applying different bit-widths to components within the same fused layer can lead to compatibility issues. + + +2. Limited Support for Quantized MoE Models + + Quantized MoE models may encounter inference issues due to kernel limitations (e.g., lack of support for mlp.gate layer quantization). please try to skip quantizing these layers to avoid such errors. + + +3. Limited Support for Quantized VLMs + + {/* VLM failure cases */} + + Qwen2.5-VL-7B + + auto_round:auto_gptq format: Accuracy is close to zero. + + GPTQ format: Fails with: + ```text Output + The output size is not aligned with the quantized weight shape + ``` + auto_round:auto_awq and AWQ format: These work as expected. + + +#### Using [GPTQModel](https://github.com/ModelCloud/GPTQModel) + +```bash Command +# install +pip install gptqmodel --no-build-isolation -v +``` + +```py Example +from datasets import load_dataset +from gptqmodel import GPTQModel, QuantizeConfig + +model_id = "meta-llama/Llama-3.2-1B-Instruct" +quant_path = "Llama-3.2-1B-Instruct-gptqmodel-4bit" + +calibration_dataset = load_dataset( + "allenai/c4", data_files="en/c4-train.00001-of-01024.json.gz", + split="train" + ).select(range(1024))["text"] + +quant_config = QuantizeConfig(bits=4, group_size=128) # quantization config +model = GPTQModel.load(model_id, quant_config) # load model + +model.quantize(calibration_dataset, batch_size=2) # quantize +model.save(quant_path) # save model +``` + +#### Using [LLM Compressor](https://github.com/vllm-project/llm-compressor/) + +```bash Command +# install +pip install llmcompressor +``` + +Here, we take quantize `meta-llama/Meta-Llama-3-8B-Instruct` to `FP8` as an example to elaborate on how to do offline quantization. + +```python Example +from transformers import AutoTokenizer +from llmcompressor.transformers import SparseAutoModelForCausalLM +from llmcompressor.transformers import oneshot +from llmcompressor.modifiers.quantization import QuantizationModifier + +# Step 1: Load the original model. +MODEL_ID = "meta-llama/Meta-Llama-3-8B-Instruct" + +model = SparseAutoModelForCausalLM.from_pretrained( + MODEL_ID, device_map="auto", torch_dtype="auto") +tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) + +# Step 2: Perform offline quantization. +# Step 2.1: Configure the simple PTQ quantization. +recipe = QuantizationModifier( + targets="Linear", scheme="FP8_DYNAMIC", ignore=["lm_head"]) + +# Step 2.2: Apply the quantization algorithm. +oneshot(model=model, recipe=recipe) + +# Step 3: Save the model. +SAVE_DIR = MODEL_ID.split("/")[1] + "-FP8-Dynamic" +model.save_pretrained(SAVE_DIR) +tokenizer.save_pretrained(SAVE_DIR) +``` + +Then, you can directly use the quantized model with `SGLang`, by using the following command: + +```bash Command +python3 -m sglang.launch_server \ + --model-path $PWD/Meta-Llama-3-8B-Instruct-FP8-Dynamic \ + --port 30000 --host 0.0.0.0 +``` + +#### Using [NVIDIA ModelOpt](https://github.com/NVIDIA/Model-Optimizer) + +NVIDIA Model Optimizer (ModelOpt) provides advanced quantization techniques optimized for NVIDIA hardware. SGLang includes a streamlined workflow for quantizing models with ModelOpt and automatically exporting them for deployment. + +##### Installation + +First, install ModelOpt. You can either install it directly or as an optional SGLang dependency: + +```bash Command +# Option 1: Install ModelOpt directly +pip install nvidia-modelopt + +# Option 2: Install SGLang with ModelOpt support (recommended) +pip install sglang[modelopt] +``` + +##### Quantization and Export Workflow + +SGLang provides an example script that demonstrates the complete ModelOpt quantization and export workflow: + +```bash Command +# Quantize and export a model using ModelOpt FP8 quantization +python examples/usage/modelopt_quantize_and_export.py quantize \ + --model-path TinyLlama/TinyLlama-1.1B-Chat-v1.0 \ + --export-dir ./quantized_tinyllama_fp8 \ + --quantization-method modelopt_fp8 + +# For FP4 quantization +python examples/usage/modelopt_quantize_and_export.py quantize \ + --model-path TinyLlama/TinyLlama-1.1B-Chat-v1.0 \ + --export-dir ./quantized_tinyllama_fp4 \ + --quantization-method modelopt_fp4 +``` + +##### Available Quantization Methods + +- `modelopt_fp8`: FP8 quantization with optimal performance on NVIDIA Hopper and Blackwell GPUs +- `modelopt_fp4`: FP4 quantization with optimal performance on Nvidia Blackwell GPUs + +##### Python API Usage + +You can also use ModelOpt quantization programmatically: + +```python Example +import sglang as sgl +from sglang.srt.configs.device_config import DeviceConfig +from sglang.srt.configs.load_config import LoadConfig +from sglang.srt.configs.model_config import ModelConfig +from sglang.srt.model_loader.loader import get_model_loader + +# Configure model with ModelOpt quantization and export +model_config = ModelConfig( + model_path="TinyLlama/TinyLlama-1.1B-Chat-v1.0", + quantization="modelopt_fp8", # or "modelopt_fp4" + trust_remote_code=True, +) + +load_config = LoadConfig( + modelopt_export_path="./exported_model", + modelopt_checkpoint_save_path="./checkpoint.pth", # optional, fake quantized checkpoint +) +device_config = DeviceConfig(device="cuda") + +# Load and quantize the model (export happens automatically) +model_loader = get_model_loader(load_config, model_config) +quantized_model = model_loader.load_model( + model_config=model_config, + device_config=device_config, +) +``` + +##### Deploying Quantized Models + +After quantization and export, you can deploy the model with SGLang: + +```bash Command +# Deploy the exported quantized model +python -m sglang.launch_server \ + --model-path ./quantized_tinyllama_fp8 \ + --quantization modelopt \ + --port 30000 --host 0.0.0.0 +``` + +Or using the Python API: + +```python Example +import sglang as sgl + +# Deploy exported ModelOpt quantized model +llm = sgl.Engine( + model_path="./quantized_tinyllama_fp8", + quantization="modelopt" +) + +# Run inference +prompts = ["Hello, how are you?", "What is the capital of France?"] +sampling_params = {"temperature": 0.8, "top_p": 0.95, "max_new_tokens": 100} +outputs = llm.generate(prompts, sampling_params) + +for i, output in enumerate(outputs): + print(f"Prompt: {prompts[i]}") + print(f"Output: {output.outputs[0].text}") +``` + +##### Advanced Features + +**Checkpoint Management**: Save and restore fake quantized checkpoints for reuse: + +```bash Command +# Save the fake quantized checkpoint during quantization +python examples/usage/modelopt_quantize_and_export.py quantize \ + --model-path meta-llama/Llama-3.2-1B-Instruct \ + --export-dir ./quantized_model \ + --quantization-method modelopt_fp8 \ + --checkpoint-save-path ./my_checkpoint.pth + +# The checkpoint can be reused for future quantization runs and skip calibration +``` + +**Export-only Workflow**: If you have a pre-existing fake quantized ModelOpt checkpoint, you can export it directly: + +```python Example +from sglang.srt.configs.device_config import DeviceConfig +from sglang.srt.configs.load_config import LoadConfig +from sglang.srt.configs.model_config import ModelConfig +from sglang.srt.model_loader.loader import get_model_loader + +model_config = ModelConfig( + model_path="meta-llama/Llama-3.2-1B-Instruct", + quantization="modelopt_fp8", + trust_remote_code=True, +) + +load_config = LoadConfig( + modelopt_checkpoint_restore_path="./my_checkpoint.pth", + modelopt_export_path="./exported_model", +) + +# Load and export the model +model_loader = get_model_loader(load_config, model_config) +model_loader.load_model(model_config=model_config, device_config=DeviceConfig()) +``` + +##### Benefits of ModelOpt + +- **Hardware Optimization**: Specifically optimized for NVIDIA GPU architectures +- **Advanced Quantization**: Supports cutting-edge FP8 and FP4 quantization techniques +- **Seamless Integration**: Automatic export to HuggingFace format for easy deployment +- **Calibration-based**: Uses calibration datasets for optimal quantization quality +- **Production Ready**: Enterprise-grade quantization with NVIDIA support + +## Online Quantization + +To enable online quantization, you can simply specify `--quantization` in the command line. For example, you can launch the server with the following command to enable `FP8` quantization for model `meta-llama/Meta-Llama-3.1-8B-Instruct`: + +```bash Command +python3 -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --quantization fp8 \ + --port 30000 --host 0.0.0.0 +``` + +Our team is working on supporting more online quantization methods. SGLang will soon support methods including but not limited to `["awq", "gptq", "marlin", "gptq_marlin", "awq_marlin", "bitsandbytes", "gguf"]`. + +### torchao online quantization method + +SGLang also supports quantization methods based on [torchao](https://github.com/pytorch/ao). You can simply specify `--torchao-config` in the command line to support this feature. For example, if you want to enable `int4wo-128` for model `meta-llama/Meta-Llama-3.1-8B-Instruct`, you can launch the server with the following command: + +```bash Command +python3 -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --torchao-config int4wo-128 \ + --port 30000 --host 0.0.0.0 +``` + +SGLang supports the following quantization methods based on torchao `["int8dq", "int8wo", "fp8wo", "fp8dq-per_tensor", "fp8dq-per_row", "int4wo-32", "int4wo-64", "int4wo-128", "int4wo-256"]`. + +Note: According to [this issue](https://github.com/sgl-project/sglang/issues/2219#issuecomment-2561890230), `"int8dq"` method currently has some bugs when using together with cuda graph capture. So we suggest to disable cuda graph capture when using `"int8dq"` method. Namely, please use the following command: + +```bash Command +python3 -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --torchao-config int8dq \ + --disable-cuda-graph \ + --port 30000 --host 0.0.0.0 +``` + +### `quark_int4fp8_moe` online quantization method + +SGLang running on AMD GPUs (CDNA3 or CDNA4 architecture) supports the quantization method `--quantization quark_int4fp8_moe`, that will replace [MoE layers](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/moe/fused_moe_triton/layer.py) originally in high precision (bfloat16, float16 or float32) to use weights dynamically quantized to int4, that are upcasted to float8 during inference to run compute in float8 precision with activations dynamically quantized on the fly to float8. + +Other layers (e.g. projections in the attention layers) have their weights quantized online to float8 directly. + +## Reference + +- [GPTQModel](https://github.com/ModelCloud/GPTQModel) +- [LLM Compressor](https://github.com/vllm-project/llm-compressor/) +- [NVIDIA Model Optimizer (ModelOpt)](https://github.com/NVIDIA/Model-Optimizer) +- [Torchao: PyTorch Architecture Optimization](https://github.com/pytorch/ao) +- [vLLM Quantization](https://docs.vllm.ai/en/latest/quantization/) +- [auto-round](https://github.com/intel/auto-round) diff --git a/docs_new/docs/advanced_features/quantized_kv_cache.mdx b/docs_new/docs/advanced_features/quantized_kv_cache.mdx new file mode 100644 index 000000000..034741fe0 --- /dev/null +++ b/docs_new/docs/advanced_features/quantized_kv_cache.mdx @@ -0,0 +1,256 @@ +--- +title: "Quantized KV Cache" +metatags: + description: "SGLang quantized KV cache: FP8 E4M3/E5M2 and FP4 E2M1 formats, memory savings up to 3.56x, scaling factors, accuracy benchmarks." +--- +Quantized KV cache reduces the memory footprint of key-value cache storage by using lower-precision data types (FP8 or FP4) instead of the default model precision in BF16. During autoregressive generation, LLMs cache previously computed key-value pairs to avoid redundant calculations. The KV cache typically consumes a significant portion of GPU memory, especially for long sequences. + +Quantized KV cache is a memory optimization technique that primarily benefits throughput by allowing more tokens to be cached, but may introduce minimal accuracy degradation depending on the quantization format used. + + +**Performance Warning**: When quantized KV cache must be dequantized before use in attention operations, performance can be extremely slow if dequantization is not fused with the attention kernel. Always verify that your chosen attention backend supports quantized KV cache. Backends without fused support may experience significant throughput degradation, potentially negating the memory benefits. + +**Backend Support**: Not all attention backends support quantized KV cache. Refer to [Attention Backend](./attention_backend) for which backends support it. + + +## Supported Formats + +SGLang supports the following quantized KV cache formats: + +### FP8 Format + +[OCP (Open Compute Project)](https://www.opencompute.org) specifies two common 8-bit floating point formats: + +- **E5M2** (5 exponent bits, 2 mantissa bits): Larger dynamic range (±57344.0), lower precision +- **E4M3** (4 exponent bits, 3 mantissa bits): Higher precision, smaller dynamic range (±240.0) + +### FP4 Format + + +FP4 quantization is currently experimental. + + +[OCP (Open Compute Project)](https://www.opencompute.org) specifies MXFP4 (Microscaling FP4), a 4-bit floating-point format: + +- **E2M1** (1 sign bit, 2 exponent bits, 1 mantissa bit): Uses block-based microscaling where tensors are divided into blocks of consecutive elements, with each block sharing a single 8-bit exponential scaling factor. While OCP specifies blocks of 32 elements, SGLang's current implementation uses blocks of 16 elements for KV cache quantization. + +## Usage + +### Enabling Quantized KV Cache + +To enable quantized KV cache, use the `--kv-cache-dtype` argument when launching the server: + +```bash Command +# Enable FP8 E5M2 KV cache +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-R1-0528 \ + --kv-cache-dtype fp8_e5m2 \ + +# Enable FP8 E4M3 KV cache +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-R1-0528 \ + --kv-cache-dtype fp8_e4m3 \ + +# Enable FP4 E2M1 KV cache +python3 -m sglang.launch_server \ + --model-path nvidia/DeepSeek-R1-0528-NVFP4 \ + --kv-cache-dtype fp4_e2m1 \ +``` + +### Scaling Factors + +FP8 quantization requires scaling factors to properly quantize and dequantize the KV cache. + + +Currently, only per-tensor (scalar) scaling factors are supported. + + +Scaling factors can be: + +- **Loaded from checkpoints**: Pre-quantized models (e.g., ModelOpt) may include `k_scale` and `v_scale` parameters that are automatically loaded +- **Provided via JSON**: Supply scaling factors via `--quantization-param-path`. + +The JSON file should follow this format: + +```json Config +{ + "kv_cache": { + "dtype": "float8_e4m3fn", + "scaling_factor": { + "0": { + "0": 1.0, + "1": 1.0 + } + } + } +} +``` + +Where the outer keys in `scaling_factor` are tensor parallel ranks and inner keys are layer indices. + + +If scaling factors are not provided and not found in the checkpoint, it will default to 1.0, which may cause accuracy issues. + + + +**FP4 (MXFP4)**: Unlike FP8, FP4 quantization handles scaling factors automatically on-the-fly during quantization and dequantization. No pre-quantized models or external scaling factor files are required—the block-based scaling factors are computed dynamically as needed. + + +## Performance Considerations + +### Memory Savings + +Quantized KV cache provides significant memory savings: +- **BF16 → FP4**: Supports approximately 3.56× more tokens than BF16 (accounting for scaling factor overhead) + + +FP4 and FP8 quantization require additional memory for block-based scaling factors, which reduces the effective memory savings compared to the raw bit-width reduction. FP4 with block size 16 supports approximately 1.78× more tokens than FP8, and approximately 3.56× more tokens than BF16. The relative token capacity between FP8 and BF16 can be derived from these ratios. + + +This enables longer context lengths or more concurrent requests within the same memory budget. + +### Accuracy Impact + +#### FP8 Accuracy + +FP8 E4M3 quantization typically introduces minimal accuracy degradation. The impact depends on model architecture, sequence length, and quantization format (generally, E4M3 has better accuracy than E5M2). + +#### FP4 Accuracy + +FP4 (MXFP4) quantization provides significant memory savings with varying accuracy impact depending on model size and dataset complexity. Preliminary accuracy test results from [PR #10078](https://github.com/sgl-project/sglang/pull/10078) (MLA) and [PR #12612](https://github.com/sgl-project/sglang/pull/12612) (MHA) show: + +**Large Models (e.g., Qwen3-235B-A22B, DeepSeek-R1-0528)** + +On large-scale models, FP4 maintains accuracy close to FP8/BF16, especially on simpler datasets: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelDatasetKV16KV8 (FP8 E4M3)KV4 (FP4 E2M1)
Qwen3-235B-A22Bgsm8k0.91680.91810.9186
Qwen3-235B-A22Baime250.77330.73330.6000
Qwen3-235B-A22Bgpqa_diamond0.70100.68990.6778
DeepSeek-R1-0528gsm8k0.91570.91540.9124
DeepSeek-R1-0528aime250.50670.49340.4000
DeepSeek-R1-0528gpqa_diamond0.77070.76970.7273
+ +**Smaller Models (e.g., GPT-OSS-120B)** + +On smaller models, FP4 shows more pronounced accuracy drops, particularly on challenging datasets: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelDatasetKV16KV8 (FP8 E4M3)KV4 (FP4 E2M1)
GPT-OSS-120Bgsm8k0.91610.91630.9152
GPT-OSS-120Baime250.75330.76670.3533
GPT-OSS-120Bgpqa_diamond0.50810.54340.3202
+ +**Key Observations:** + +- **Simple datasets (e.g., gsm8k)**: FP4 maintains accuracy close to FP8/BF16 across model sizes +- **Model size matters**: Large models (200B+ parameters) generally tolerate FP4 quantization better than smaller models +- **Context length**: Accuracy degradation may be more pronounced in long-context scenarios, as the accumulation of the quantization error may become significant. + + +Evaluate FP4 accuracy on your specific model and workload. Large models on simpler tasks typically show minimal degradation, while smaller models or complex reasoning tasks may require FP8 or BF16 for acceptable accuracy. + + +## Best Practices + +- **Use pre-quantized models**: Prefer models quantized offline with scaling factors included in the checkpoint. +- **Choose the right format**: Use `fp8_e4m3` for better accuracy (recommended), `fp8_e5m2` for larger dynamic range, or `fp4_e2m1` for maximum memory savings (experimental) +- **Check backend compatibility**: Verify that your chosen attention backend supports quantized KV cache + + +See also: +- [Quantization](./quantization) +- [Attention Backend](./attention_backend) +- [Server Arguments](./server_arguments) + diff --git a/docs_new/docs/advanced_features/rfork.mdx b/docs_new/docs/advanced_features/rfork.mdx new file mode 100644 index 000000000..d14109bc2 --- /dev/null +++ b/docs_new/docs/advanced_features/rfork.mdx @@ -0,0 +1,82 @@ +--- +title: "R-Fork" +metatags: + description: "SGLang R-Fork: zero-copy GPU-to-GPU weight loading, reduce boot-up time from minutes to seconds. NCCL and TransferEngine backends." +--- +R-Fork (Tensor Remote Fork) is a novel weight loading methodology that leverages efficient inter-node GPU-to-GPU data transfer path to load tensors from a running SGLang instance to a new instance with zero-copy. It can significantly optimize the SGLang instance boot-up time by reducing model weights loading from several minutes to mere seconds. + +To learn more details about R-Fork, please check **[R-Fork blog](https://lmsys.org/blog/2025-12-10-rfork/)** + +## Usage + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentUsage
load-formatset to `remote_instance` to enable R-Fork.
remote-instance-weight-loader-backend`nccl` or `transfer_engine`, default value is `nccl`
remote-instance-weight-loader-seed-instance-ipIP address of the seed instance who will provide the model weight
remote-instance-weight-loader-seed-instance-service-portthe port that the seed instance's HTTP server is listening on
remote-instance-weight-loader-send-weights-group-portsthe list of available ports on the seed instance that will be used to build NCCL communication groups between seed and client instance. This argument is only needed by `nccl` backend.
remote-instance-weight-loader-start-seed-via-transfer-engineset to start seed service that supports TransferEngine as backend. It is needed for seed instances when using `transfer_engine` as backend.
+ +### NCCL as backend + +seed instance: +```shell Command +python -m sglang.launch_server [args] +``` + +client instance: +```shell Command +python -m sglang.launch_server [args] \ + --load-format remote_instance \ + --remote-instance-weight-loader-seed-instance-ip [seed_instance_ip] \ + --remote-instance-weight-loader-seed-instance-service-port [seed_instance_service_port] \ + --remote-instance-weight-loader-send-weights-group-ports [send_weights_nccl_group_ports_list] \ + --remote-instance-weight-loader-backend nccl +``` + +### TransferEngine as backend + +seed instance: +```shell Command +python -m sglang.launch_server [args] \ + --remote-instance-weight-loader-start-seed-via-transfer-engine +``` + +```shell Command +python -m sglang.launch_server [args] \ + --load-format remote_instance \ + --remote-instance-weight-loader-seed-instance-ip [seed_instance_ip] \ + --remote-instance-weight-loader-seed-instance-service-port [seed_instance_service_port] \ + --remote-instance-weight-loader-backend transfer_engine +``` diff --git a/docs_new/docs/advanced_features/separate_reasoning.ipynb b/docs_new/docs/advanced_features/separate_reasoning.ipynb new file mode 100644 index 000000000..fde97d8a6 --- /dev/null +++ b/docs_new/docs/advanced_features/separate_reasoning.ipynb @@ -0,0 +1,377 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Reasoning Parser\n", + "\n", + "SGLang supports parsing reasoning content out from \"normal\" content for reasoning models such as [DeepSeek R1](https://huggingface.co/deepseek-ai/DeepSeek-R1).\n", + "\n", + "## Supported Models & Parsers\n", + "\n", + "| Model | Reasoning tags | Parser | Notes |\n", + "|---------|-----------------------------|------------------|-------|\n", + "| [DeepSeek‑R1 series](https://huggingface.co/collections/deepseek-ai/deepseek-r1-678e1e131c0169c0bc89728d) | `` … `` | `deepseek-r1` | Supports all variants (R1, R1-0528, R1-Distill) |\n", + "| [DeepSeek‑V3 series](https://huggingface.co/deepseek-ai/DeepSeek-V3.1) | `` … `` | `deepseek-v3` | Including [DeepSeek‑V3.2](https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Exp). Supports `thinking` parameter |\n", + "| [Standard Qwen3 models](https://huggingface.co/collections/Qwen/qwen3-67dd247413f0e2e4f653967f) | `` … `` | `qwen3` | Supports `enable_thinking` parameter |\n", + "| [Qwen3-Thinking models](https://huggingface.co/Qwen/Qwen3-235B-A22B-Thinking-2507) | `` … `` | `qwen3` or `qwen3-thinking` | Always generates thinking content |\n", + "| [Kimi K2 Thinking](https://huggingface.co/moonshotai/Kimi-K2-Thinking) | `◁think▷` … `◁/think▷` | `kimi_k2` | Uses special thinking delimiters. Also requires `--tool-call-parser kimi_k2` for tool use. |\n", + "| [GPT OSS](https://huggingface.co/openai/gpt-oss-120b) | `<\\|channel\\|>analysis<\\|message\\|>` … `<\\|end\\|>` | `gpt-oss` | N/A |\n", + "### Model-Specific Behaviors\n", + "\n", + "**DeepSeek-R1 Family:**\n", + "- DeepSeek-R1: No `` start tag, jumps directly to thinking content\n", + "- DeepSeek-R1-0528: Generates both `` start and `` end tags\n", + "- Both are handled by the same `deepseek-r1` parser\n", + "\n", + "**DeepSeek-V3 Family:**\n", + "- DeepSeek-V3.1/V3.2: Hybrid model supporting both thinking and non-thinking modes, use the `deepseek-v3` parser and `thinking` parameter (NOTE: not `enable_thinking`)\n", + "\n", + "**Qwen3 Family:**\n", + "- Standard Qwen3 (e.g., Qwen3-2507): Use `qwen3` parser, supports `enable_thinking` in chat templates\n", + "- Qwen3-Thinking (e.g., Qwen3-235B-A22B-Thinking-2507): Use `qwen3` or `qwen3-thinking` parser, always thinks\n", + "\n", + "**Kimi K2:**\n", + "- Kimi K2 Thinking: Uses special `◁think▷` and `◁/think▷` tags. For agentic tool use, also specify `--tool-call-parser kimi_k2`.\n", + "\n", + "**GPT OSS:**\n", + "- GPT OSS: Uses special `<|channel|>analysis<|message|>` and `<|end|>` tags" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Usage\n", + "\n", + "### Launching the Server" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Specify the `--reasoning-parser` option." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "from openai import OpenAI\n", + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "server_process, port = launch_server_cmd(\n", + " \"python3 -m sglang.launch_server --model-path deepseek-ai/DeepSeek-R1-Distill-Qwen-7B --host 0.0.0.0 --reasoning-parser deepseek-r1 --log-level warning\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that `--reasoning-parser` defines the parser used to interpret responses." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### OpenAI Compatible API\n", + "\n", + "Using the OpenAI compatible API, the contract follows the [DeepSeek API design](https://api-docs.deepseek.com/guides/reasoning_model) established with the release of DeepSeek-R1:\n", + "\n", + "- `reasoning_content`: The content of the CoT.\n", + "- `content`: The content of the final answer." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Initialize OpenAI-like client\n", + "client = OpenAI(api_key=\"None\", base_url=f\"http://0.0.0.0:{port}/v1\")\n", + "model_name = client.models.list().data[0].id\n", + "\n", + "messages = [\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"What is 1+3?\",\n", + " }\n", + "]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Non-Streaming Request" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response_non_stream = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0.6,\n", + " top_p=0.95,\n", + " stream=False, # Non-streaming\n", + " extra_body={\"separate_reasoning\": True},\n", + ")\n", + "print_highlight(\"==== Reasoning ====\")\n", + "print_highlight(response_non_stream.choices[0].message.reasoning_content)\n", + "\n", + "print_highlight(\"==== Text ====\")\n", + "print_highlight(response_non_stream.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Streaming Request" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response_stream = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0.6,\n", + " top_p=0.95,\n", + " stream=True, # Non-streaming\n", + " extra_body={\"separate_reasoning\": True},\n", + ")\n", + "\n", + "reasoning_content = \"\"\n", + "content = \"\"\n", + "for chunk in response_stream:\n", + " if chunk.choices[0].delta.content:\n", + " content += chunk.choices[0].delta.content\n", + " if chunk.choices[0].delta.reasoning_content:\n", + " reasoning_content += chunk.choices[0].delta.reasoning_content\n", + "\n", + "print_highlight(\"==== Reasoning ====\")\n", + "print_highlight(reasoning_content)\n", + "\n", + "print_highlight(\"==== Text ====\")\n", + "print_highlight(content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Optionally, you can buffer the reasoning content to the last reasoning chunk (or the first chunk after the reasoning content)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response_stream = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0.6,\n", + " top_p=0.95,\n", + " stream=True, # Non-streaming\n", + " extra_body={\"separate_reasoning\": True, \"stream_reasoning\": False},\n", + ")\n", + "\n", + "reasoning_content = \"\"\n", + "content = \"\"\n", + "for chunk in response_stream:\n", + " if chunk.choices[0].delta.content:\n", + " content += chunk.choices[0].delta.content\n", + " if chunk.choices[0].delta.reasoning_content:\n", + " reasoning_content += chunk.choices[0].delta.reasoning_content\n", + "\n", + "print_highlight(\"==== Reasoning ====\")\n", + "print_highlight(reasoning_content)\n", + "\n", + "print_highlight(\"==== Text ====\")\n", + "print_highlight(content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The reasoning separation is enable by default when specify . \n", + "**To disable it, set the `separate_reasoning` option to `False` in request.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response_non_stream = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0.6,\n", + " top_p=0.95,\n", + " stream=False, # Non-streaming\n", + " extra_body={\"separate_reasoning\": False},\n", + ")\n", + "\n", + "print_highlight(\"==== Original Output ====\")\n", + "print_highlight(response_non_stream.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### SGLang Native API " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import AutoTokenizer\n", + "\n", + "tokenizer = AutoTokenizer.from_pretrained(\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\")\n", + "input = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "\n", + "gen_url = f\"http://localhost:{port}/generate\"\n", + "gen_data = {\n", + " \"text\": input,\n", + " \"sampling_params\": {\n", + " \"skip_special_tokens\": False,\n", + " \"max_new_tokens\": 1024,\n", + " \"temperature\": 0.6,\n", + " \"top_p\": 0.95,\n", + " },\n", + "}\n", + "gen_response = requests.post(gen_url, json=gen_data).json()[\"text\"]\n", + "\n", + "print_highlight(\"==== Original Output ====\")\n", + "print_highlight(gen_response)\n", + "\n", + "parse_url = f\"http://localhost:{port}/separate_reasoning\"\n", + "separate_reasoning_data = {\n", + " \"text\": gen_response,\n", + " \"reasoning_parser\": \"deepseek-r1\",\n", + "}\n", + "separate_reasoning_response_json = requests.post(\n", + " parse_url, json=separate_reasoning_data\n", + ").json()\n", + "print_highlight(\"==== Reasoning ====\")\n", + "print_highlight(separate_reasoning_response_json[\"reasoning_text\"])\n", + "print_highlight(\"==== Text ====\")\n", + "print_highlight(separate_reasoning_response_json[\"text\"])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Offline Engine API" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import sglang as sgl\n", + "from sglang.srt.parser.reasoning_parser import ReasoningParser\n", + "from sglang.utils import print_highlight\n", + "\n", + "llm = sgl.Engine(model_path=\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\")\n", + "tokenizer = AutoTokenizer.from_pretrained(\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\")\n", + "input = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "sampling_params = {\n", + " \"max_new_tokens\": 1024,\n", + " \"skip_special_tokens\": False,\n", + " \"temperature\": 0.6,\n", + " \"top_p\": 0.95,\n", + "}\n", + "result = llm.generate(prompt=input, sampling_params=sampling_params)\n", + "\n", + "generated_text = result[\"text\"] # Assume there is only one prompt\n", + "\n", + "print_highlight(\"==== Original Output ====\")\n", + "print_highlight(generated_text)\n", + "\n", + "parser = ReasoningParser(\"deepseek-r1\")\n", + "reasoning_text, text = parser.parse_non_stream(generated_text)\n", + "print_highlight(\"==== Reasoning ====\")\n", + "print_highlight(reasoning_text)\n", + "print_highlight(\"==== Text ====\")\n", + "print_highlight(text)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "llm.shutdown()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Supporting New Reasoning Model Schemas\n", + "\n", + "For future reasoning models, you can implement the reasoning parser as a subclass of `BaseReasoningFormatDetector` in `python/sglang/srt/reasoning_parser.py` and specify the reasoning parser for new reasoning model schemas accordingly." + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/docs_new/docs/advanced_features/separate_reasoning.mdx b/docs_new/docs/advanced_features/separate_reasoning.mdx new file mode 100644 index 000000000..e0bea35ee --- /dev/null +++ b/docs_new/docs/advanced_features/separate_reasoning.mdx @@ -0,0 +1,317 @@ +--- +title: "Reasoning Parser" +metatags: + description: "SGLang reasoning parser: separate thinking content from output for DeepSeek R1, Qwen3, Kimi K2, GPT-OSS reasoning models." +--- +SGLang supports parsing reasoning content out from "normal" content for reasoning models such as [DeepSeek R1](https://huggingface.co/deepseek-ai/DeepSeek-R1). + +## Supported Models & Parsers + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelReasoning tagsParserNotes
[DeepSeek‑R1 series](https://huggingface.co/collections/deepseek-ai/deepseek-r1-678e1e131c0169c0bc89728d)`` … ```deepseek-r1`Supports all variants (R1, R1-0528, R1-Distill)
[DeepSeek‑V3 series](https://huggingface.co/deepseek-ai/DeepSeek-V3.1)`` … ```deepseek-v3`Including [DeepSeek‑V3.2](https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Exp). Supports `thinking` parameter
[Standard Qwen3 models](https://huggingface.co/collections/Qwen/qwen3-67dd247413f0e2e4f653967f)`` … ```qwen3`Supports `enable_thinking` parameter
[Qwen3-Thinking models](https://huggingface.co/Qwen/Qwen3-235B-A22B-Thinking-2507)`` … ```qwen3` or `qwen3-thinking`Always generates thinking content
[Kimi K2 Thinking](https://huggingface.co/moonshotai/Kimi-K2-Thinking)`◁think▷` … `◁/think▷``kimi_k2`Uses special thinking delimiters. Also requires `--tool-call-parser kimi_k2` for tool use.
[GPT OSS](https://huggingface.co/openai/gpt-oss-120b)`<|channel|>analysis<|message|>` … `<|end|>``gpt-oss`N/A
+### Model-Specific Behaviors + +**DeepSeek-R1 Family:** +- DeepSeek-R1: No `` start tag, jumps directly to thinking content +- DeepSeek-R1-0528: Generates both `` start and `` end tags +- Both are handled by the same `deepseek-r1` parser + +**DeepSeek-V3 Family:** +- DeepSeek-V3.1/V3.2: Hybrid model supporting both thinking and non-thinking modes, use the `deepseek-v3` parser and `thinking` parameter (NOTE: not `enable_thinking`) + +**Qwen3 Family:** +- Standard Qwen3 (e.g., Qwen3-2507): Use `qwen3` parser, supports `enable_thinking` in chat templates +- Qwen3-Thinking (e.g., Qwen3-235B-A22B-Thinking-2507): Use `qwen3` or `qwen3-thinking` parser, always thinks + +**Kimi K2:** +- Kimi K2 Thinking: Uses special `◁think▷` and `◁/think▷` tags. For agentic tool use, also specify `--tool-call-parser kimi_k2`. + +**GPT OSS:** +- GPT OSS: Uses special `<|channel|>analysis<|message|>` and `<|end|>` tags + + +## Usage + +### Launching the Server + + +Specify the `--reasoning-parser` option. + + + +```python Example +import requests +from openai import OpenAI +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process + +server_process, port = launch_server_cmd( + "python3 -m sglang.launch_server --model-path deepseek-ai/DeepSeek-R1-Distill-Qwen-7B --host 0.0.0.0 --reasoning-parser deepseek-r1 --log-level warning" +) + +wait_for_server(f"http://localhost:{port}") +``` + +Note that `--reasoning-parser` defines the parser used to interpret responses. + + +### OpenAI Compatible API + +Using the OpenAI compatible API, the contract follows the [DeepSeek API design](https://api-docs.deepseek.com/guides/reasoning_model) established with the release of DeepSeek-R1: + +- `reasoning_content`: The content of the CoT. +- `content`: The content of the final answer. + + + +```python Example +# Initialize OpenAI-like client +client = OpenAI(api_key="None", base_url=f"http://0.0.0.0:{port}/v1") +model_name = client.models.list().data[0].id + +messages = [ + { + "role": "user", + "content": "What is 1+3?", + } +] +``` + +#### Non-Streaming Request + + + +```python Example +response_non_stream = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0.6, + top_p=0.95, + stream=False, # Non-streaming + extra_body={"separate_reasoning": True}, +) +print_highlight("==== Reasoning ====") +print_highlight(response_non_stream.choices[0].message.reasoning_content) + +print_highlight("==== Text ====") +print_highlight(response_non_stream.choices[0].message.content) +``` + +#### Streaming Request + + + +```python Example +response_stream = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0.6, + top_p=0.95, + stream=True, # Non-streaming + extra_body={"separate_reasoning": True}, +) + +reasoning_content = "" +content = "" +for chunk in response_stream: + if chunk.choices[0].delta.content: + content += chunk.choices[0].delta.content + if chunk.choices[0].delta.reasoning_content: + reasoning_content += chunk.choices[0].delta.reasoning_content + +print_highlight("==== Reasoning ====") +print_highlight(reasoning_content) + +print_highlight("==== Text ====") +print_highlight(content) +``` + +Optionally, you can buffer the reasoning content to the last reasoning chunk (or the first chunk after the reasoning content). + + + +```python Example +response_stream = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0.6, + top_p=0.95, + stream=True, # Non-streaming + extra_body={"separate_reasoning": True, "stream_reasoning": False}, +) + +reasoning_content = "" +content = "" +for chunk in response_stream: + if chunk.choices[0].delta.content: + content += chunk.choices[0].delta.content + if chunk.choices[0].delta.reasoning_content: + reasoning_content += chunk.choices[0].delta.reasoning_content + +print_highlight("==== Reasoning ====") +print_highlight(reasoning_content) + +print_highlight("==== Text ====") +print_highlight(content) +``` + +The reasoning separation is enable by default when specify . +**To disable it, set the `separate_reasoning` option to `False` in request.** + + + +```python Example +response_non_stream = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0.6, + top_p=0.95, + stream=False, # Non-streaming + extra_body={"separate_reasoning": False}, +) + +print_highlight("==== Original Output ====") +print_highlight(response_non_stream.choices[0].message.content) +``` + +### SGLang Native API + + + +```python Example +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-R1-Distill-Qwen-7B") +input = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) + +gen_url = f"http://localhost:{port}/generate" +gen_data = { + "text": input, + "sampling_params": { + "skip_special_tokens": False, + "max_new_tokens": 1024, + "temperature": 0.6, + "top_p": 0.95, + }, +} +gen_response = requests.post(gen_url, json=gen_data).json()["text"] + +print_highlight("==== Original Output ====") +print_highlight(gen_response) + +parse_url = f"http://localhost:{port}/separate_reasoning" +separate_reasoning_data = { + "text": gen_response, + "reasoning_parser": "deepseek-r1", +} +separate_reasoning_response_json = requests.post( + parse_url, json=separate_reasoning_data +).json() +print_highlight("==== Reasoning ====") +print_highlight(separate_reasoning_response_json["reasoning_text"]) +print_highlight("==== Text ====") +print_highlight(separate_reasoning_response_json["text"]) +``` + + +```python Example +terminate_process(server_process) +``` + +### Offline Engine API + + + +```python Example +import sglang as sgl +from sglang.srt.parser.reasoning_parser import ReasoningParser +from sglang.utils import print_highlight + +llm = sgl.Engine(model_path="deepseek-ai/DeepSeek-R1-Distill-Qwen-7B") +tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-R1-Distill-Qwen-7B") +input = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +sampling_params = { + "max_new_tokens": 1024, + "skip_special_tokens": False, + "temperature": 0.6, + "top_p": 0.95, +} +result = llm.generate(prompt=input, sampling_params=sampling_params) + +generated_text = result["text"] # Assume there is only one prompt + +print_highlight("==== Original Output ====") +print_highlight(generated_text) + +parser = ReasoningParser("deepseek-r1") +reasoning_text, text = parser.parse_non_stream(generated_text) +print_highlight("==== Reasoning ====") +print_highlight(reasoning_text) +print_highlight("==== Text ====") +print_highlight(text) +``` + + +```python Example +llm.shutdown() +``` + +## Supporting New Reasoning Model Schemas + +For future reasoning models, you can implement the reasoning parser as a subclass of `BaseReasoningFormatDetector` in `python/sglang/srt/reasoning_parser.py` and specify the reasoning parser for new reasoning model schemas accordingly. diff --git a/docs_new/docs/advanced_features/server_arguments.mdx b/docs_new/docs/advanced_features/server_arguments.mdx new file mode 100644 index 000000000..e183be1ce --- /dev/null +++ b/docs_new/docs/advanced_features/server_arguments.mdx @@ -0,0 +1,2871 @@ +--- +title: "Server Arguments" +metatags: + description: "SGLang server arguments: model selection, TP/DP parallelism, memory management, quantization, logging, and optimization options." +--- +This page provides a list of server arguments used in the command line to configure the behavior +and performance of the language model server during deployment. These arguments enable users to +customize key aspects of the server, including model selection, parallelism policies, +memory management, and optimization techniques. +You can find all arguments by `python3 -m sglang.launch_server --help` + +## Common launch commands + +- To use a configuration file, create a YAML file with your server arguments and specify it with `--config`. CLI arguments will override config file values. + + ```bash Command + # Create config.yaml + cat > config.yaml << EOF + model-path: meta-llama/Meta-Llama-3-8B-Instruct + host: 0.0.0.0 + port: 30000 + tensor-parallel-size: 2 + enable-metrics: true + log-requests: true + EOF + + # Launch server with config file + python -m sglang.launch_server --config config.yaml + ``` + +- To enable multi-GPU tensor parallelism, add `--tp 2`. If it reports the error "peer access is not supported between these two devices", add `--enable-p2p-check` to the server launch command. + + ```bash Command + python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3-8B-Instruct --tp 2 + ``` + +- To enable multi-GPU data parallelism, add `--dp 2`. Data parallelism is better for throughput if there is enough memory. It can also be used together with tensor parallelism. The following command uses 4 GPUs in total. We recommend [SGLang Model Gateway (former Router)](../advanced_features/sgl_model_gateway) for data parallelism. + + ```bash Command + python -m sglang_router.launch_server --model-path meta-llama/Meta-Llama-3-8B-Instruct --dp 2 --tp 2 + ``` + +- If you see out-of-memory errors during serving, try to reduce the memory usage of the KV cache pool by setting a smaller value of `--mem-fraction-static`. The default value is `0.9`. + + ```bash Command + python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3-8B-Instruct --mem-fraction-static 0.7 + ``` + +- See [hyperparameter tuning](./hyperparameter_tuning) on tuning hyperparameters for better performance. +- For docker and Kubernetes runs, you need to set up shared memory which is used for communication between processes. See `--shm-size` for docker and `/dev/shm` size update for Kubernetes manifests. +- If you see out-of-memory errors during prefill for long prompts, try to set a smaller chunked prefill size. + + ```bash Command + python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3-8B-Instruct --chunked-prefill-size 4096 + ``` + +- To enable `torch.compile` acceleration, add `--enable-torch-compile`. It accelerates small models on small batch sizes. By default, the cache path is located at `/tmp/torchinductor_root`, you can customize it using environment variable `TORCHINDUCTOR_CACHE_DIR`. For more details, please refer to [PyTorch official documentation](https://pytorch.org/tutorials/recipes/torch_compile_caching_tutorial.html) and [Enabling cache for torch.compile](../references/torch_compile_cache). +- To enable torchao quantization, add `--torchao-config int4wo-128`. It supports other [quantization strategies (INT8/FP8)](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/server_args.py) as well. +- To enable fp8 weight quantization, add `--quantization fp8` on a fp16 checkpoint or directly load a fp8 checkpoint without specifying any arguments. +- To enable fp8 kv cache quantization, add `--kv-cache-dtype fp8_e5m2`. +- To enable deterministic inference and batch invariant operations, add `--enable-deterministic-inference`. More details can be found in [deterministic inference document](../advanced_features/deterministic_inference). +- If the model does not have a chat template in the Hugging Face tokenizer, you can specify a [custom chat template](../references/custom_chat_template). If the tokenizer has multiple named templates (e.g., 'default', 'tool_use'), you can select one using `--hf-chat-template-name tool_use`. +- To run tensor parallelism on multiple nodes, add `--nnodes 2`. If you have two nodes with two GPUs on each node and want to run TP=4, let `sgl-dev-0` be the hostname of the first node and `50000` be an available port, you can use the following commands. If you meet deadlock, please try to add `--disable-cuda-graph` + + ```bash Command + # Node 0 + python -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3-8B-Instruct \ + --tp 4 \ + --dist-init-addr sgl-dev-0:50000 \ + --nnodes 2 \ + --node-rank 0 + + # Node 1 + python -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3-8B-Instruct \ + --tp 4 \ + --dist-init-addr sgl-dev-0:50000 \ + --nnodes 2 \ + --node-rank 1 + ``` + +Please consult the documentation below and [server_args.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/server_args.py) to learn more about the arguments you may provide when launching a server. + +## Model and tokenizer + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
` --model-path`
`--model`
The path of the model weights. This can be a local folder or a Hugging Face repo ID.` None`Type: str
` --tokenizer-path`The path of the tokenizer.` None`Type: str
` --tokenizer-mode`Tokenizer mode. 'auto' will use the fast tokenizer if available, and 'slow' will always use the slow tokenizer.` auto`` auto`, `slow`
` --tokenizer-worker-num`The worker num of the tokenizer manager.` 1`Type: int
` --skip-tokenizer-init`If set, skip init tokenizer and pass input_ids in generate request.` False`bool flag (set to enable)
` --load-format`The format of the model weights to load. "auto" will try to load the weights in the safetensors format and fall back to the pytorch bin format if safetensors format is not available. "pt" will load the weights in the pytorch bin format. "safetensors" will load the weights in the safetensors format. "npcache" will load the weights in pytorch format and store a numpy cache to speed up the loading. "dummy" will initialize the weights with random values, which is mainly for profiling. "gguf" will load the weights in the gguf format. "bitsandbytes" will load the weights using bitsandbytes quantization. "layered" loads weights layer by layer so that one can quantize a layer before loading another to make the peak memory envelope smaller. "flash_rl" will load the weights in flash_rl format. "fastsafetensors" and "private" are also supported.` auto`` auto`, `pt`, `safetensors`, `npcache`, `dummy`, `sharded_state`, `gguf`, `bitsandbytes`, `layered`, `flash_rl`, `remote`, `remote_instance`, `fastsafetensors`, `private`
` --model-loader-extra-config`Extra config for model loader. This will be passed to the model loader corresponding to the chosen load_format.` {}`Type: str
` --trust-remote-code`Whether or not to allow for custom models defined on the Hub in their own modeling files.` False`bool flag (set to enable)
` --context-length`The model's maximum context length. Defaults to None (will use the value from the model's config.json instead).` None`Type: int
` --is-embedding`Whether to use a CausalLM as an embedding model.` False`bool flag (set to enable)
` --enable-multimodal`Enable the multimodal functionality for the served model. If the model being served is not multimodal, nothing will happen.` None`bool flag (set to enable)
` --revision`The specific model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version.` None`Type: str
` --model-impl`Which implementation of the model to use. "auto" will try to use the SGLang implementation if it exists and fall back to the Transformers implementation if no SGLang implementation is available. "sglang" will use the SGLang model implementation. "transformers" will use the Transformers model implementation.` auto`Type: str
+ +## HTTP server + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--host`The host of the HTTP server.`127.0.0.1`Type: str
`--port`The port of the HTTP server.`30000`Type: int
`--fastapi-root-path`App is behind a path based routing proxy.`""`Type: str
`--grpc-mode`If set, use gRPC server instead of HTTP server.`False`bool flag (set to enable)
`--skip-server-warmup`If set, skip warmup.`False`bool flag (set to enable)
`--warmups`Specify custom warmup functions (csv) to run before server starts eg. --warmups=warmup_name1,warmup_name2 will run the functions `warmup_name1` and `warmup_name2` specified in warmup.py before the server starts listening for requests`None`Type: str
`--nccl-port`The port for NCCL distributed environment setup. Defaults to a random port.`None`Type: int
`--checkpoint-engine-wait-weights-before-ready`If set, the server will wait for initial weights to be loaded via checkpoint-engine or other update methods before serving inference requests.`False`bool flag (set to enable)
+ +## Quantization and data type + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--dtype`Data type for model weights and activations. * "auto" will use FP16 precision for FP32 and FP16 models, and BF16 precision for BF16 models. * "half" for FP16. Recommended for AWQ quantization. * "float16" is the same as "half". * "bfloat16" for a balance between precision and range. * "float" is shorthand for FP32 precision. * "float32" for FP32 precision.`auto``auto`, `half`, `float16`, `bfloat16`, `float`, `float32`
`--quantization`The quantization method.`None``awq`, `fp8`, `gptq`, `marlin`, `gptq_marlin`, `awq_marlin`, `bitsandbytes`, `gguf`, `modelopt`, `modelopt_fp8`, `modelopt_fp4`, `petit_nvfp4`, `w8a8_int8`, `w8a8_fp8`, `moe_wna16`, `qoq`, `w4afp8`, `mxfp4`, `auto-round`, `compressed-tensors`, `modelslim`, `quark_int4fp8_moe`
`--quantization-param-path`Path to the JSON file containing the KV cache scaling factors. This should generally be supplied, when KV cache dtype is FP8. Otherwise, KV cache scaling factors default to 1.0, which may cause accuracy issues.`None`Type: Optional[str]
`--kv-cache-dtype`Data type for kv cache storage. "auto" will use model data type. "bf16" or "bfloat16" for BF16 KV cache. "fp8_e5m2" and "fp8_e4m3" are supported for CUDA 11.8+. "fp4_e2m1" (only mxfp4) is supported for CUDA 12.8+ and PyTorch 2.8.0+`auto``auto`, `fp8_e5m2`, `fp8_e4m3`, `bf16`, `bfloat16`, `fp4_e2m1`
`--enable-fp32-lm-head`If set, the LM head outputs (logits) are in FP32.`False`bool flag (set to enable)
`--modelopt-quant`The ModelOpt quantization configuration. Supported values: 'fp8', 'int4_awq', 'w4a8_awq', 'nvfp4', 'nvfp4_awq'. This requires the NVIDIA Model Optimizer library to be installed: pip install nvidia-modelopt`None`Type: str
`--modelopt-checkpoint-restore-path`Path to restore a previously saved ModelOpt quantized checkpoint. If provided, the quantization process will be skipped and the model will be loaded from this checkpoint.`None`Type: str
`--modelopt-checkpoint-save-path`Path to save the ModelOpt quantized checkpoint after quantization. This allows reusing the quantized model in future runs.`None`Type: str
`--modelopt-export-path`Path to export the quantized model in HuggingFace format after ModelOpt quantization. The exported model can then be used directly with SGLang for inference. If not provided, the model will not be exported.`None`Type: str
`--quantize-and-serve`Quantize the model with ModelOpt and immediately serve it without exporting. This is useful for development and prototyping. For production, it's recommended to use separate quantization and deployment steps.`False`bool flag (set to enable)
`--rl-quant-profile`Path to the FlashRL quantization profile. Required when using --load-format flash_rl.`None`Type: str
+ +## Memory and scheduling + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--mem-fraction-static`The fraction of the memory used for static allocation (model weights and KV cache memory pool). Use a smaller value if you see out-of-memory errors.`None`Type: float
`--max-running-requests`The maximum number of running requests.`None`Type: int
`--max-queued-requests`The maximum number of queued requests. This option is ignored when using disaggregation-mode.`None`Type: int
`--max-total-tokens`The maximum number of tokens in the memory pool. If not specified, it will be automatically calculated based on the memory usage fraction. This option is typically used for development and debugging purposes.`None`Type: int
`--chunked-prefill-size`The maximum number of tokens in a chunk for the chunked prefill. Setting this to -1 means disabling chunked prefill.`None`Type: int
`--prefill-max-requests`The maximum number of requests in a prefill batch. If not specified, there is no limit.`None`Type: int
`--enable-dynamic-chunking`Enable dynamic chunk size adjustment for pipeline parallelism. When enabled, chunk sizes are dynamically calculated based on fitted function to maintain consistent execution time across chunks.`False`bool flag (set to enable)
`--max-prefill-tokens`The maximum number of tokens in a prefill batch. The real bound will be the maximum of this value and the model's maximum context length.`16384`Type: int
`--schedule-policy`The scheduling policy of the requests.`fcfs``lpm`, `random`, `fcfs`, `dfs-weight`, `lof`, `priority`, `routing-key`
`--enable-priority-scheduling`Enable priority scheduling. Requests with higher priority integer values will be scheduled first by default.`False`bool flag (set to enable)
`--abort-on-priority-when-disabled`If set, abort requests that specify a priority when priority scheduling is disabled.`False`bool flag (set to enable)
`--schedule-low-priority-values-first`If specified with --enable-priority-scheduling, the scheduler will schedule requests with lower priority integer values first.`False`bool flag (set to enable)
`--priority-scheduling-preemption-threshold`Minimum difference in priorities for an incoming request to have to preempt running request(s).`10`Type: int
`--schedule-conservativeness`How conservative the schedule policy is. A larger value means more conservative scheduling. Use a larger value if you see requests being retracted frequently.`1.0`Type: float
`--page-size`The number of tokens in a page.`1`Type: int
`--swa-full-tokens-ratio`The ratio of SWA layer KV tokens / full layer KV tokens, regardless of the number of swa:full layers. It should be between 0 and 1. E.g. 0.5 means if each swa layer has 50 tokens, then each full layer has 100 tokens.`0.8`Type: float
`--disable-hybrid-swa-memory`Disable the hybrid SWA memory.`False`bool flag (set to enable)
`--radix-eviction-policy`The eviction policy of radix trees. 'lru' stands for Least Recently Used, 'lfu' stands for Least Frequently Used.`lru``lru`, `lfu`
`--enable-prefill-delayer`Enable prefill delayer for DP attention to reduce idle time.`False`bool flag (set to enable)
`--prefill-delayer-max-delay-passes`Maximum forward passes to delay prefill.`30`Type: int
`--prefill-delayer-token-usage-low-watermark`Token usage low watermark for prefill delayer.`None`Type: float
`--prefill-delayer-forward-passes-buckets`Custom buckets for prefill delayer forward passes histogram. 0 and max_delay_passes-1 will be auto-added.`None`List[float]
`--prefill-delayer-wait-seconds-buckets`Custom buckets for prefill delayer wait seconds histogram. 0 will be auto-added.`None`List[float]
+ +## Runtime options + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--device`The device to use ('cuda', 'xpu', 'hpu', 'npu', 'cpu'). Defaults to auto-detection if not specified.`None`Type: str
`--tensor-parallel-size` `--tp-size`The tensor parallelism size.`1`Type: int
`--pipeline-parallel-size` `--pp-size`The pipeline parallelism size.`1`Type: int
`--pp-max-micro-batch-size`The maximum micro batch size in pipeline parallelism.`None`Type: int
`--pp-async-batch-depth`The async batch depth of pipeline parallelism.`0`Type: int
`--stream-interval`The interval (or buffer size) for streaming in terms of the token length. A smaller value makes streaming smoother, while a larger value makes the throughput higher.`1`Type: int
`--stream-output`Whether to output as a sequence of disjoint segments.`False`bool flag (set to enable)
`--random-seed`The random seed.`None`Type: int
`--constrained-json-whitespace-pattern`{"(outlines and llguidance backends only) Regex pattern for syntactic whitespaces allowed in JSON constrained output. For example, to allow the model to generate consecutive whitespaces, set the pattern to [\\n\\t ]*"}`None`Type: str
`--constrained-json-disable-any-whitespace`{"(xgrammar and llguidance backends only) Enforce compact representation in JSON constrained output."}`False`bool flag (set to enable)
`--watchdog-timeout`Set watchdog timeout in seconds. If a forward batch takes longer than this, the server will crash to prevent hanging.`300`Type: float
`--soft-watchdog-timeout`Set soft watchdog timeout in seconds. If a forward batch takes longer than this, the server will dump information for debugging.`None`Type: float
`--dist-timeout`Set timeout for torch.distributed initialization.`None`Type: int
`--download-dir`Model download directory for huggingface.`None`Type: str
`--model-checksum`Model file integrity verification. If provided without value, uses model-path as HF repo ID. Otherwise, provide checksums JSON file path or HuggingFace repo ID.`None`Type: str
`--base-gpu-id`The base GPU ID to start allocating GPUs from. Useful when running multiple instances on the same machine.`0`Type: int
`--gpu-id-step`The delta between consecutive GPU IDs that are used. For example, setting it to 2 will use GPU 0,2,4,...`1`Type: int
`--sleep-on-idle`Reduce CPU usage when sglang is idle.`False`bool flag (set to enable)
`--custom-sigquit-handler`Register a custom sigquit handler so you can do additional cleanup after the server is shutdown. This is only available for Engine, not for CLI.`None`Type: str
+ +## Logging + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--log-level`The logging level of all loggers.`info`Type: str
`--log-level-http`The logging level of HTTP server. If not set, reuse --log-level by default.`None`Type: str
`--log-requests`Log metadata, inputs, outputs of all requests. The verbosity is decided by --log-requests-level`False`bool flag (set to enable)
`--log-requests-level`0: Log metadata (no sampling parameters). 1: Log metadata and sampling parameters. 2: Log metadata, sampling parameters and partial input/output. 3: Log every input/output.`2``0`, `1`, `2`, `3`
`--log-requests-format`Format for request logging: 'text' (human-readable) or 'json' (structured)`text``text`, `json`
`--log-requests-target`Target(s) for request logging: 'stdout' and/or directory path(s) for file output. Can specify multiple targets, e.g., '--log-requests-target stdout /my/path'.`None`List[str]
`--uvicorn-access-log-exclude-prefixes`Exclude uvicorn access logs whose request path starts with any of these prefixes. Defaults to empty (disabled).`[]`List[str]
`--crash-dump-folder`Folder path to dump requests from the last 5 min before a crash (if any). If not specified, crash dumping is disabled.`None`Type: str
`--show-time-cost`Show time cost of custom marks.`False`bool flag (set to enable)
`--enable-metrics`Enable log prometheus metrics.`False`bool flag (set to enable)
`--enable-metrics-for-all-schedulers`Enable --enable-metrics-for-all-schedulers when you want schedulers on all TP ranks (not just TP 0) to record request metrics separately. This is especially useful when dp_attention is enabled, as otherwise all metrics appear to come from TP 0.`False`bool flag (set to enable)
`--tokenizer-metrics-custom-labels-header`Specify the HTTP header for passing custom labels for tokenizer metrics.`x-custom-labels`Type: str
`--tokenizer-metrics-allowed-custom-labels`The custom labels allowed for tokenizer metrics. The labels are specified via a dict in '--tokenizer-metrics-custom-labels-header' field in HTTP requests, e.g., {'label1': 'value1', 'label2': 'value2'} is allowed if '--tokenizer-metrics-allowed-custom-labels label1 label2' is set.`None`List[str]
`--bucket-time-to-first-token`The buckets of time to first token, specified as a list of floats.`None`List[float]
`--bucket-inter-token-latency`The buckets of inter-token latency, specified as a list of floats.`None`List[float]
`--bucket-e2e-request-latency`The buckets of end-to-end request latency, specified as a list of floats.`None`List[float]
`--collect-tokens-histogram`Collect prompt/generation tokens histogram.`False`bool flag (set to enable)
`--prompt-tokens-buckets`The buckets rule of prompt tokens. Supports 3 rule types: 'default' uses predefined buckets; 'tse <middle> <base> <count>' generates two sides exponential distributed buckets (e.g., 'tse 1000 2 8' generates buckets [984.0, 992.0, 996.0, 998.0, 1000.0, 1002.0, 1004.0, 1008.0, 1016.0]).); 'custom <value1> <value2> ...' uses custom bucket values (e.g., 'custom 10 50 100 500').`None`List[str]
`--generation-tokens-buckets`The buckets rule for generation tokens histogram. Supports 3 rule types: 'default' uses predefined buckets; 'tse <middle> <base> <count>' generates two sides exponential distributed buckets (e.g., 'tse 1000 2 8' generates buckets [984.0, 992.0, 996.0, 998.0, 1000.0, 1002.0, 1004.0, 1008.0, 1016.0]).); 'custom <value1> <value2> ...' uses custom bucket values (e.g., 'custom 10 50 100 500').`None`List[str]
`--gc-warning-threshold-secs`The threshold for long GC warning. If a GC takes longer than this, a warning will be logged. Set to 0 to disable.`0.0`Type: float
`--decode-log-interval`The log interval of decode batch.`40`Type: int
`--enable-request-time-stats-logging`Enable per request time stats logging`False`bool flag (set to enable)
`--kv-events-config`Config in json format for NVIDIA dynamo KV event publishing. Publishing will be enabled if this flag is used.`None`Type: str
`--enable-trace`Enable opentelemetry trace`False`bool flag (set to enable)
`--otlp-traces-endpoint`Config opentelemetry collector endpoint if --enable-trace is set. format: <ip>:<port>`localhost:4317`Type: str
+ +## RequestMetricsExporter configuration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--export-metrics-to-file`Export performance metrics for each request to local file (e.g. for forwarding to external systems).`False`bool flag (set to enable)
`--export-metrics-to-file-dir`Directory path for writing performance metrics files (required when --export-metrics-to-file is enabled).`None`Type: str
+ +## API related + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--api-key`Set API key of the server. It is also used in the OpenAI API compatible server.`None`Type: str
`--admin-api-key`Set **admin API key** for administrative/control endpoints (e.g., weights update, cache flush, `/get_server_info`). Endpoints marked as admin-only require `Authorization: Bearer ` when this is set.`None`Type: str
`--served-model-name`Override the model name returned by the v1/models endpoint in OpenAI API server.`None`Type: str
`--weight-version`Version identifier for the model weights. Defaults to 'default' if not specified.`default`Type: str
`--chat-template`The buliltin chat template name or the path of the chat template file. This is only used for OpenAI-compatible API server.`None`Type: str
`--hf-chat-template-name`When the HuggingFace tokenizer has multiple chat templates (e.g., 'default', 'tool_use', 'rag'), specify which named template to use. If not set, the first available template is used.`None`Type: str
`--completion-template`The buliltin completion template name or the path of the completion template file. This is only used for OpenAI-compatible API server. only for code completion currently.`None`Type: str
`--file-storage-path`The path of the file storage in backend.`sglang_storage`Type: str
`--enable-cache-report`Return number of cached tokens in usage.prompt_tokens_details for each openai request.`False`bool flag (set to enable)
`--reasoning-parser`Specify the parser for reasoning models. Supported parsers: [deepseek-r1, deepseek-v3, glm45, gpt-oss, kimi, qwen3, qwen3-thinking, step3].`None``deepseek-r1`, `deepseek-v3`, `glm45`, `gpt-oss`, `kimi`, `qwen3`, `qwen3-thinking`, `step3`
`--tool-call-parser`Specify the parser for handling tool-call interactions. Supported parsers: [deepseekv3, deepseekv31, glm, glm45, glm47, gpt-oss, kimi_k2, llama3, mistral, pythonic, qwen, qwen25, qwen3_coder, step3].`None``deepseekv3`, `deepseekv31`, `glm`, `glm45`, `glm47`, `gpt-oss`, `kimi_k2`, `llama3`, `mistral`, `pythonic`, `qwen`, `qwen25`, `qwen3_coder`, `step3`
`--tool-server`Either 'demo' or a comma-separated list of tool server urls to use for the model. If not specified, no tool server will be used.`None`Type: str
`--sampling-defaults`Where to get default sampling parameters. 'openai' uses SGLang/OpenAI defaults (temperature=1.0, top_p=1.0, etc.). 'model' uses the model's generation_config.json to get the recommended sampling parameters if available. Default is 'model'.`model``openai`, `model`
+ +## Data parallelism + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
` --data-parallel-size`
`--dp-size`
The data parallelism size.` 1`Type: int
` --load-balance-method`The load balancing strategy for data parallelism. The `total_tokens` algorithm can only be used when DP attention is applied. This algorithm performs load balancing based on the real-time token load of the DP workers.` auto`` auto`, `round_robin`, `follow_bootstrap_room`, `total_requests`, `total_tokens`
+ +## Multi-node distributed serving + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
` --dist-init-addr`
`--nccl-init-addr`
The host address for initializing distributed backend (e.g., `192.168.0.2:25000`).` None`Type: str
` --nnodes`The number of nodes.` 1`Type: int
` --node-rank`The node rank.` 0`Type: int
+ +## Model override args + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--json-model-override-args`A dictionary in JSON string format used to override default model configurations.`{}`Type: str
`--preferred-sampling-params`json-formatted sampling settings that will be returned in /get_model_info`None`Type: str
+ +## LoRA + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--enable-lora`Enable LoRA support for the model. This argument is automatically set to `True` if `--lora-paths` is provided for backward compatibility.`False`Bool flag (set to enable)
`--enable-lora-overlap-loading`Enable asynchronous LoRA weight loading in order to overlap H2D transfers with GPU compute. This should be enabled if you find that your LoRA workloads are bottlenecked by adapter weight loading, for example when frequently loading large LoRA adapters.`False`Bool flag (set to enable)
`--max-lora-rank`The maximum LoRA rank that should be supported. If not specified, it will be automatically inferred from the adapters provided in `--lora-paths`. This argument is needed when you expect to dynamically load adapters of larger LoRA rank after server startup.`None`Type: int
`--lora-target-modules`The union set of all target modules where LoRA should be applied (e.g., `q_proj`, `k_proj`, `gate_proj`). If not specified, it will be automatically inferred from the adapters provided in `--lora-paths`. You can also set it to `all` to enable LoRA for all supported modules; note this may introduce minor performance overhead.`None`{"q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj, qkv_proj, gate_up_proj, all"}
`--lora-paths`{"The list of LoRA adapters to load. Each adapter must be specified in one of the following formats: | = | JSON with schema {\"lora_name\": str, \"lora_path\": str, \"pinned\": bool}."}`None`Type: List[str] / JSON objects
`--max-loras-per-batch`Maximum number of adapters for a running batch, including base-only requests.`8`Type: int
`--max-loaded-loras`If specified, limits the maximum number of LoRA adapters loaded in CPU memory at a time. Must be ≥ `--max-loras-per-batch`.`None`Type: int
`--lora-eviction-policy`LoRA adapter eviction policy when the GPU memory pool is full.`lru`lru, fifo
`--lora-backend`Choose the kernel backend for multi-LoRA serving.`csgmv`triton, csgmv, ascend, torch_native
`--max-lora-chunk-size`Maximum chunk size for the ChunkedSGMV LoRA backend. Only used when `--lora-backend` is `csgmv`. Larger values may improve performance.`16`16, 32, 64, 128
+ +## Kernel Backends (Attention, Sampling, Grammar, GEMM) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--attention-backend`Choose the kernels for attention layers.`None``triton`, `torch_native`, `flex_attention`, `nsa`, `cutlass_mla`, `fa3`, `fa4`, `flashinfer`, `flashmla`, `trtllm_mla`, `trtllm_mha`, `dual_chunk_flash_attn`, `aiter`, `wave`, `intel_amx`, `ascend`
`--prefill-attention-backend`Choose the kernels for prefill attention layers (have priority over --attention-backend).`None``triton`, `torch_native`, `flex_attention`, `nsa`, `cutlass_mla`, `fa3`, `fa4`, `flashinfer`, `flashmla`, `trtllm_mla`, `trtllm_mha`, `dual_chunk_flash_attn`, `aiter`, `wave`, `intel_amx`, `ascend`
`--decode-attention-backend`Choose the kernels for decode attention layers (have priority over --attention-backend).`None``triton`, `torch_native`, `flex_attention`, `nsa`, `cutlass_mla`, `fa3`, `fa4`, `flashinfer`, `flashmla`, `trtllm_mla`, `trtllm_mha`, `dual_chunk_flash_attn`, `aiter`, `wave`, `intel_amx`, `ascend`
`--sampling-backend`Choose the kernels for sampling layers.`None``flashinfer`, `pytorch`, `ascend`
`--grammar-backend`Choose the backend for grammar-guided decoding.`None``xgrammar`, `outlines`, `llguidance`, `none`
`--mm-attention-backend`Set multimodal attention backend.`None``sdpa`, `fa3`, `fa4`, `triton_attn`, `ascend_attn`, `aiter_attn`
`--nsa-prefill-backend`Choose the NSA backend for the prefill stage (overrides `--attention-backend` when running DeepSeek NSA-style attention).`flashmla_sparse``flashmla_sparse`, `flashmla_kv`, `flashmla_auto`, `fa3`, `tilelang`, `aiter`
`--nsa-decode-backend`Choose the NSA backend for the decode stage when running DeepSeek NSA-style attention. Overrides `--attention-backend` for decoding.`fa3``flashmla_sparse`, `flashmla_kv`, `fa3`, `tilelang`, `aiter`
`--fp8-gemm-backend`Choose the runner backend for Blockwise FP8 GEMM operations. Options: 'auto' (default, auto-selects based on hardware), 'deep_gemm' (JIT-compiled; enabled by default on NVIDIA Hopper (SM90) and Blackwell (SM100) when DeepGEMM is installed), 'flashinfer_trtllm' (optimal for Blackwell and low-latency), 'cutlass' (optimal for Hopper/Blackwell GPUs and high-throughput), 'triton' (fallback, widely compatible), 'aiter' (ROCm only). **NOTE**: This replaces the deprecated environment variables SGLANG_ENABLE_FLASHINFER_FP8_GEMM and SGLANG_SUPPORT_CUTLASS_BLOCK_FP8.`auto``auto`, `deep_gemm`, `flashinfer_trtllm`, `cutlass`, `triton`, `aiter`
`--fp4-gemm-backend`Choose the runner backend for NVFP4 GEMM operations. Options: 'auto' (default, auto-selects between flashinfer_cudnn/flashinfer_cutlass based on CUDA/cuDNN version), 'flashinfer_cudnn' (FlashInfer cuDNN backend, optimal on CUDA 13+ with cuDNN 9.15+), 'flashinfer_cutlass' (FlashInfer CUTLASS backend, optimal on CUDA 12), 'flashinfer_trtllm' (FlashInfer TensorRT-LLM backend, requires different weight preparation with shuffling). All backends are from FlashInfer; when FlashInfer is unavailable, sgl-kernel CUTLASS is used as an automatic fallback. **NOTE**: This replaces the deprecated environment variable SGLANG_FLASHINFER_FP4_GEMM_BACKEND.`auto``auto`, `flashinfer_cudnn`, `flashinfer_cutlass`, `flashinfer_trtllm`
`--disable-flashinfer-autotune`Flashinfer autotune is enabled by default. Set this flag to disable the autotune.`False`bool flag (set to enable)
+ +## Speculative decoding + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--speculative-algorithm`Speculative algorithm.`None``EAGLE`, `EAGLE3`, `NEXTN`, `STANDALONE`, `NGRAM`
`--speculative-draft-model-path` `--speculative-draft-model`The path of the draft model weights. This can be a local folder or a Hugging Face repo ID.`None`Type: str
`--speculative-draft-model-revision`The specific draft model version to use. It can be a branch name, a tag name, or a commit id. If unspecified, will use the default version.`None`Type: str
`--speculative-draft-load-format`The format of the draft model weights to load. If not specified, will use the same format as `--load-format`. Use 'dummy' to initialize draft model weights with random values for profiling.`None`Same as `--load-format` options
`--speculative-num-steps`The number of steps sampled from draft model in Speculative Decoding.`None`Type: int
`--speculative-eagle-topk`The number of tokens sampled from the draft model in eagle2 each step.`None`Type: int
`--speculative-num-draft-tokens`The number of tokens sampled from the draft model in Speculative Decoding.`None`Type: int
`--speculative-accept-threshold-single`Accept a draft token if its probability in the target model is greater than this threshold.`1.0`Type: float
`--speculative-accept-threshold-acc`The accept probability of a draft token is raised from its target probability p to min(1, p / threshold_acc).`1.0`Type: float
`--speculative-token-map`The path of the draft model's small vocab table.`None`Type: str
`--speculative-attention-mode`Attention backend for speculative decoding operations (both target verify and draft extend). Can be one of 'prefill' (default) or 'decode'.`prefill`prefill, decode
`--speculative-draft-attention-backend`Attention backend for speculative decoding drafting.`None`Same as attention backend options
`--speculative-moe-runner-backend`MOE backend for EAGLE speculative decoding, see `--moe-runner-backend` for options. Same as moe runner backend if unset.`None`Same as `--moe-runner-backend` options
`--speculative-moe-a2a-backend`MOE A2A backend for EAGLE speculative decoding, see `--moe-a2a-backend` for options. Same as moe a2a backend if unset.`None`Same as `--moe-a2a-backend` options
`--speculative-draft-model-quantization`The quantization method for speculative model.`None`Same as `--quantization` options
+ +## Ngram speculative decoding + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--speculative-ngram-min-match-window-size`The minimum window size for pattern matching in ngram speculative decoding.`1`Type: int
`--speculative-ngram-max-match-window-size`The maximum window size for pattern matching in ngram speculative decoding.`12`Type: int
`--speculative-ngram-min-bfs-breadth`The minimum breadth for BFS (Breadth-First Search) in ngram speculative decoding.`1`Type: int
`--speculative-ngram-max-bfs-breadth`The maximum breadth for BFS (Breadth-First Search) in ngram speculative decoding.`10`Type: int
`--speculative-ngram-match-type`The match type for cache tree.`BFS``BFS`, `PROB`
`--speculative-ngram-branch-length`The branch length for ngram speculative decoding.`18`Type: int
`--speculative-ngram-capacity`The cache capacity for ngram speculative decoding.`10000000`Type: int
+ +## Multi-layer Eagle speculative decoding + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--enable-multi-layer-eagle`Enable multi-layer Eagle speculative decoding.`False`bool flag (set to enable)
+ +## MoE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
` --expert-parallel-size`
`--ep-size`
`--ep`
The expert parallelism size.` 1`Type: int
` --moe-a2a-backend`Select the backend for all-to-all communication for expert parallelism.` none`` none`, `deepep`, `mooncake`, `ascend_fuseep`
` --moe-runner-backend`Choose the runner backend for MoE.` auto`` auto`, `deep_gemm`, `triton`, `triton_kernel`, `flashinfer_trtllm`, `flashinfer_cutlass`, `flashinfer_mxfp4`, `flashinfer_cutedsl`, `cutlass`
` --flashinfer-mxfp4-moe-precision`Choose the computation precision of flashinfer mxfp4 moe.` default`` default`, `bf16`
` --enable-flashinfer-allreduce-fusion`Enable FlashInfer allreduce fusion with Residual RMSNorm.` False`bool flag (set to enable)
` --deepep-mode`Select the mode when enable DeepEP MoE, could be `normal`, `low_latency` or `auto`. Default is `auto`, which means `low_latency` for decode batch and `normal` for prefill batch.` auto`` normal`, `low_latency`, `auto`
` --ep-num-redundant-experts`Allocate this number of redundant experts in expert parallel.` 0`Type: int
` --ep-dispatch-algorithm`The algorithm to choose ranks for redundant experts in expert parallel.` None`Type: str
` --init-expert-location`Initial location of EP experts.` trivial`Type: str
` --enable-eplb`Enable EPLB algorithm.` False`bool flag (set to enable)
` --eplb-algorithm`Chosen EPLB algorithm.` auto`Type: str
` --eplb-rebalance-num-iterations`Number of iterations to automatically trigger a EPLB re-balance.` 1000`Type: int
` --eplb-rebalance-layers-per-chunk`Number of layers to rebalance per forward pass.` None`Type: int
` --eplb-min-rebalancing-utilization-threshold`Minimum threshold for GPU average utilization to trigger EPLB rebalancing. Must be in the range [0.0, 1.0].` 1.0`Type: float
` --expert-distribution-recorder-mode`Mode of expert distribution recorder.` None`Type: str
` --expert-distribution-recorder-buffer-size`Circular buffer size of expert distribution recorder. Set to -1 to denote infinite buffer.` None`Type: int
` --enable-expert-distribution-metrics`Enable logging metrics for expert balancedness.` False`bool flag (set to enable)
` --deepep-config`Tuned DeepEP config suitable for your own cluster. It can be either a string with JSON content or a file path.` None`Type: str
` --moe-dense-tp-size`TP size for MoE dense MLP layers. This flag is useful when, with large TP size, there are errors caused by weights in MLP layers having dimension smaller than the min dimension GEMM supports.` None`Type: int
` --elastic-ep-backend`Specify the collective communication backend for elastic EP. Currently supports 'mooncake'.` none`` none`, `mooncake`
` --mooncake-ib-device`The InfiniBand devices for Mooncake Backend transfer, accepts multiple comma-separated devices (e.g., --mooncake-ib-device mlx5_0,mlx5_1). Default is None, which triggers automatic device detection when Mooncake Backend is enabled.` None`Type: str
+ +## Mamba Cache + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--max-mamba-cache-size`The maximum size of the mamba cache.`None`Type: int
`--mamba-ssm-dtype`The data type of the SSM states in mamba cache.`float32``float32`, `bfloat16`
`--mamba-full-memory-ratio`The ratio of mamba state memory to full kv cache memory.`0.9`Type: float
`--mamba-scheduler-strategy`The strategy to use for mamba scheduler. `auto` currently defaults to `no_buffer`. 1. `no_buffer` does not support overlap scheduler due to not allocating extra mamba state buffers. Branching point caching support is feasible but not implemented. 2. `extra_buffer` supports overlap schedule by allocating extra mamba state buffers to track mamba state for caching (mamba state usage per running req becomes `2x` for non-spec; `1+(1/(2+speculative_num_draft_tokens))x` for spec dec (e.g. 1.16x if speculative_num_draft_tokens==4)). 2a. `extra_buffer` is strictly better for non-KV-cache-bound cases; for KV-cache-bound cases, the tradeoff depends on whether enabling overlap outweighs reduced max running requests. 2b. mamba caching at radix cache branching point is strictly better than non-branch but requires kernel support (currently only FLA backend), currently only extra_buffer supports branching.`auto``auto`, `no_buffer`, `extra_buffer`
`--mamba-track-interval`The interval (in tokens) to track the mamba state during decode. Only used when `--mamba-scheduler-strategy` is `extra_buffer`. Must be divisible by page_size if set, and must be >= speculative_num_draft_tokens when using speculative decoding.`256`Type: int
+ +## Hierarchical cache + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--enable-hierarchical-cache`Enable hierarchical cache`False`bool flag (set to enable)
`--hicache-ratio`The ratio of the size of host KV cache memory pool to the size of device pool.`2.0`Type: float
`--hicache-size`The size of host KV cache memory pool in gigabytes, which will override the hicache_ratio if set.`0`Type: int
`--hicache-write-policy`The write policy of hierarchical cache.`write_through``write_back`, `write_through`, `write_through_selective`
`--hicache-io-backend`The IO backend for KV cache transfer between CPU and GPU`kernel``direct`, `kernel`, `kernel_ascend`
`--hicache-mem-layout`The layout of host memory pool for hierarchical cache.`layer_first``layer_first`, `page_first`, `page_first_direct`, `page_first_kv_split`, `page_head`
`--hicache-storage-backend`The storage backend for hierarchical KV cache. Built-in backends: file, mooncake, hf3fs, nixl, aibrix. For dynamic backend, use --hicache-storage-backend-extra-config to specify: backend_name (custom name), module_path (Python module path), class_name (backend class name).`None``file`, `mooncake`, `hf3fs`, `nixl`, `aibrix`, `dynamic`, `eic`
`--hicache-storage-prefetch-policy`Control when prefetching from the storage backend should stop.`best_effort``best_effort`, `wait_complete`, `timeout`
`--hicache-storage-backend-extra-config`A dictionary in JSON string format, or a string starting with a `@` followed by a config file in JSON/YAML/TOML format, containing extra configuration for the storage backend.`None`Type: str
+ +## Hierarchical sparse attention + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--hierarchical-sparse-attention-extra-config`A dictionary in JSON string format for hierarchical sparse attention configuration. Required fields: `algorithm` (str), `backend` (str). All other fields are algorithm-specific and passed to the algorithm constructor.`None`Type: str
+ +## LMCache + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--enable-lmcache`Using LMCache as an alternative hierarchical cache solution`False`bool flag (set to enable)
+ +## Ktransformers + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--kt-weight-path`[ktransformers parameter] The path of the quantized expert weights for amx kernel. A local folder.`None`Type: str
`--kt-method`[ktransformers parameter] Quantization formats for CPU execution.`AMXINT4`Type: str
`--kt-cpuinfer`[ktransformers parameter] The number of CPUInfer threads.`None`Type: int
`--kt-threadpool-count`[ktransformers parameter] One-to-one with the number of NUMA nodes (one thread pool per NUMA).`2`Type: int
`--kt-num-gpu-experts`[ktransformers parameter] The number of GPU experts.`None`Type: int
`--kt-max-deferred-experts-per-token`[ktransformers parameter] Maximum number of experts deferred to CPU per token. All MoE layers except the final one use this value; the final layer always uses 0.`None`Type: int
+ +## Diffusion LLM + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--dllm-algorithm`The diffusion LLM algorithm, such as LowConfidence.`None`Type: str
`--dllm-algorithm-config`The diffusion LLM algorithm configurations. Must be a YAML file.`None`Type: str
+ +## Double Sparsity + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--enable-double-sparsity`Enable double sparsity attention`False`bool flag (set to enable)
`--ds-channel-config-path`The path of the double sparsity channel config`None`Type: str
`--ds-heavy-channel-num`The number of heavy channels in double sparsity attention`32`Type: int
`--ds-heavy-token-num`The number of heavy tokens in double sparsity attention`256`Type: int
`--ds-heavy-channel-type`The type of heavy channels in double sparsity attention`qk`Type: str
`--ds-sparse-decode-threshold`The minimum decode sequence length required before the double-sparsity backend switches from the dense fallback to the sparse decode kernel.`4096`Type: int
+ +## Offloading + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--cpu-offload-gb`How many GBs of RAM to reserve for CPU offloading.`0`Type: int
`--offload-group-size`Number of layers per group in offloading.`-1`Type: int
`--offload-num-in-group`Number of layers to be offloaded within a group.`1`Type: int
`--offload-prefetch-step`Steps to prefetch in offloading.`1`Type: int
`--offload-mode`Mode of offloading.`cpu`Type: str
+ +## Args for multi-item scoring + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--multi-item-scoring-delimiter`Delimiter token ID for multi-item scoring. Used to combine Query and Items into a single sequence: Query<delimiter>Item1<delimiter>Item2<delimiter>... This enables efficient batch processing of multiple items against a single query.`None`Type: int
+ +## Optimization/debug options + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--disable-radix-cache`Disable RadixAttention for prefix caching.`False`bool flag (set to enable)
`--cuda-graph-max-bs`Set the maximum batch size for cuda graph. It will extend the cuda graph capture batch size to this value.`None`Type: int
`--cuda-graph-bs`Set the list of batch sizes for cuda graph.`None`List[int]
`--disable-cuda-graph`Disable cuda graph.`False`bool flag (set to enable)
`--disable-cuda-graph-padding`Disable cuda graph when padding is needed. Still uses cuda graph when padding is not needed.`False`bool flag (set to enable)
`--enable-profile-cuda-graph`Enable profiling of cuda graph capture.`False`bool flag (set to enable)
`--enable-cudagraph-gc`Enable garbage collection during CUDA graph capture. If disabled (default), GC is frozen during capture to speed up the process.`False`bool flag (set to enable)
`--enable-layerwise-nvtx-marker`Enable layerwise NVTX profiling annotations for the model. This adds NVTX markers to every layer for detailed per-layer performance analysis with Nsight Systems.`False`bool flag (set to enable)
`--enable-nccl-nvls`Enable NCCL NVLS for prefill heavy requests when available.`False`bool flag (set to enable)
`--enable-symm-mem`Enable NCCL symmetric memory for fast collectives.`False`bool flag (set to enable)
`--disable-flashinfer-cutlass-moe-fp4-allgather`Disables quantize before all-gather for flashinfer cutlass moe.`False`bool flag (set to enable)
`--enable-tokenizer-batch-encode`Enable batch tokenization for improved performance when processing multiple text inputs. Do not use with image inputs, pre-tokenized input_ids, or input_embeds.`False`bool flag (set to enable)
`--disable-tokenizer-batch-decode`Disable batch decoding when decoding multiple completions.`False`bool flag (set to enable)
`--disable-outlines-disk-cache`Disable disk cache of outlines to avoid possible crashes related to file system or high concurrency.`False`bool flag (set to enable)
`--disable-custom-all-reduce`Disable the custom all-reduce kernel and fall back to NCCL.`False`bool flag (set to enable)
`--enable-mscclpp`Enable using mscclpp for small messages for all-reduce kernel and fall back to NCCL.`False`bool flag (set to enable)
`--enable-torch-symm-mem`Enable using torch symm mem for all-reduce kernel and fall back to NCCL. Only supports CUDA device SM90 and above. SM90 supports world size 4, 6, 8. SM10 supports world size 6, 8.`False`bool flag (set to enable)
`--disable-overlap-schedule`Disable the overlap scheduler, which overlaps the CPU scheduler with GPU model worker.`False`bool flag (set to enable)
`--enable-mixed-chunk`Enabling mixing prefill and decode in a batch when using chunked prefill.`False`bool flag (set to enable)
`--enable-dp-attention`Enabling data parallelism for attention and tensor parallelism for FFN. The dp size should be equal to the tp size. Currently DeepSeek-V2 and Qwen 2/3 MoE models are supported.`False`bool flag (set to enable)
`--enable-dp-lm-head`Enable vocabulary parallel across the attention TP group to avoid all-gather across DP groups, optimizing performance under DP attention.`False`bool flag (set to enable)
`--enable-two-batch-overlap`Enabling two micro batches to overlap.`False`bool flag (set to enable)
`--enable-single-batch-overlap`Let computation and communication overlap within one micro batch.`False`bool flag (set to enable)
`--tbo-token-distribution-threshold`The threshold of token distribution between two batches in micro-batch-overlap, determines whether to two-batch-overlap or two-chunk-overlap. Set to 0 denote disable two-chunk-overlap.`0.48`Type: float
`--enable-torch-compile`Optimize the model with torch.compile. Experimental feature.`False`bool flag (set to enable)
`--enable-torch-compile-debug-mode`Enable debug mode for torch compile.`False`bool flag (set to enable)
`--enable-piecewise-cuda-graph`Optimize the model with piecewise cuda graph for extend/prefill only. Experimental feature.`False`bool flag (set to enable)
`--piecewise-cuda-graph-tokens`Set the list of tokens when using piecewise cuda graph.`None`Type: JSON list
`--piecewise-cuda-graph-compiler`Set the compiler for piecewise cuda graph. Choices are: eager, inductor.`eager``eager`, `inductor`
`--torch-compile-max-bs`Set the maximum batch size when using torch compile.`32`Type: int
`--piecewise-cuda-graph-max-tokens`Set the maximum tokens when using piecewise cuda graph.`4096`Type: int
`--torchao-config`Optimize the model with torchao. Experimental feature. Current choices are: int8dq, int8wo, int4wo-<group_size>, fp8wo, fp8dq-per_tensor, fp8dq-per_row``Type: str
`--enable-nan-detection`Enable the NaN detection for debugging purposes.`False`bool flag (set to enable)
`--enable-p2p-check`Enable P2P check for GPU access, otherwise the p2p access is allowed by default.`False`bool flag (set to enable)
`--triton-attention-reduce-in-fp32`Cast the intermediate attention results to fp32 to avoid possible crashes related to fp16. This only affects Triton attention kernels.`False`bool flag (set to enable)
`--triton-attention-num-kv-splits`The number of KV splits in flash decoding Triton kernel. Larger value is better in longer context scenarios. The default value is 8.`8`Type: int
`--triton-attention-split-tile-size`The size of split KV tile in flash decoding Triton kernel. Used for deterministic inference.`None`Type: int
`--num-continuous-decode-steps`Run multiple continuous decoding steps to reduce scheduling overhead. This can potentially increase throughput but may also increase time-to-first-token latency. The default value is 1, meaning only run one decoding step at a time.`1`Type: int
`--delete-ckpt-after-loading`Delete the model checkpoint after loading the model.`False`bool flag (set to enable)
`--enable-memory-saver`Allow saving memory using release_memory_occupation and resume_memory_occupation`False`bool flag (set to enable)
`--enable-weights-cpu-backup`Save model weights to CPU memory during release_weights_occupation and resume_weights_occupation`False`bool flag (set to enable)
`--enable-draft-weights-cpu-backup`Save draft model weights to CPU memory during release_weights_occupation and resume_weights_occupation`False`bool flag (set to enable)
`--allow-auto-truncate`Allow automatically truncating requests that exceed the maximum input length instead of returning an error.`False`bool flag (set to enable)
`--enable-custom-logit-processor`Enable users to pass custom logit processors to the server (disabled by default for security)`False`bool flag (set to enable)
`--flashinfer-mla-disable-ragged`Not using ragged prefill wrapper when running flashinfer mla`False`bool flag (set to enable)
`--disable-shared-experts-fusion`Disable shared experts fusion optimization for deepseek v3/r1.`False`bool flag (set to enable)
`--disable-chunked-prefix-cache`Disable chunked prefix cache feature for deepseek, which should save overhead for short sequences.`False`bool flag (set to enable)
`--disable-fast-image-processor`Adopt base image processor instead of fast image processor.`False`bool flag (set to enable)
`--keep-mm-feature-on-device`Keep multimodal feature tensors on device after processing to save D2H copy.`False`bool flag (set to enable)
`--enable-return-hidden-states`Enable returning hidden states with responses.`False`bool flag (set to enable)
`--enable-return-routed-experts`Enable returning routed experts of each layer with responses.`False`bool flag (set to enable)
`--scheduler-recv-interval`The interval to poll requests in scheduler. Can be set to >1 to reduce the overhead of this.`1`Type: int
`--numa-node`Sets the numa node for the subprocesses. i-th element corresponds to i-th subprocess.`None`List[int]
`--enable-deterministic-inference`Enable deterministic inference mode with batch invariant ops.`False`bool flag (set to enable)
`--rl-on-policy-target`The training system that SGLang needs to match for true on-policy.`None``fsdp`
`--enable-attn-tp-input-scattered`Allow input of attention to be scattered when only using tensor parallelism, to reduce the computational load of operations such as qkv latent.`False`bool flag (set to enable)
`--enable-nsa-prefill-context-parallel`Enable context parallelism used in the long sequence prefill phase of DeepSeek v3.2.`False`bool flag (set to enable)
`--nsa-prefill-cp-mode`Token splitting mode for the prefill phase of DeepSeek v3.2 under context parallelism. Optional values: `in-seq-split` (default), `round-robin-split`. `round-robin-split` distributes tokens across ranks based on `token_idx % cp_size`. It supports multi-batch prefill, fused MoE, and FP8 KV cache.`in-seq-split``in-seq-split`, `round-robin-split`
`--enable-fused-qk-norm-rope`Enable fused qk normalization and rope rotary embedding.`False`bool flag (set to enable)
`--enable-precise-embedding-interpolation`Enable corner alignment for resize of embeddings grid to ensure more accurate(but slower) evaluation of interpolated embedding values.`False`bool flag (set to enable)
+ +## Dynamic batch tokenizer + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--enable-dynamic-batch-tokenizer`Enable async dynamic batch tokenizer for improved performance when multiple requests arrive concurrently.`False`bool flag (set to enable)
`--dynamic-batch-tokenizer-batch-size`[Only used if --enable-dynamic-batch-tokenizer is set] Maximum batch size for dynamic batch tokenizer.`32`Type: int
`--dynamic-batch-tokenizer-batch-timeout`[Only used if --enable-dynamic-batch-tokenizer is set] Timeout in seconds for batching tokenization requests.`0.002`Type: float
+ +## Debug tensor dumps + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--debug-tensor-dump-output-folder`The output folder for dumping tensors.`None`Type: str
`--debug-tensor-dump-layers`The layer ids to dump. Dump all layers if not specified.`None`Type: JSON list
`--debug-tensor-dump-input-file`The input filename for dumping tensors`None`Type: str
`--debug-tensor-dump-inject`Inject the outputs from jax as the input of every layer.`False`Type: str
+ +## PD disaggregation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--disaggregation-mode`Only used for PD disaggregation. "prefill" for prefill-only server, and "decode" for decode-only server. If not specified, it is not PD disaggregated`null``null`, `prefill`, `decode`
`--disaggregation-transfer-backend`The backend for disaggregation transfer. Default is mooncake.`mooncake``mooncake`, `nixl`, `ascend`, `fake`
`--disaggregation-bootstrap-port`Bootstrap server port on the prefill server. Default is 8998.`8998`Type: int
`--disaggregation-decode-tp`Decode tp size. If not set, it matches the tp size of the current engine. This is only set on the prefill server.`None`Type: int
`--disaggregation-decode-dp`Decode dp size. If not set, it matches the dp size of the current engine. This is only set on the prefill server.`None`Type: int
`--disaggregation-prefill-pp`Prefill pp size. If not set, it is default to 1. This is only set on the decode server.`1`Type: int
`--disaggregation-ib-device`The InfiniBand devices for disaggregation transfer, accepts single device (e.g., --disaggregation-ib-device mlx5_0) or multiple comma-separated devices (e.g., --disaggregation-ib-device mlx5_0,mlx5_1). Default is None, which triggers automatic device detection when mooncake backend is enabled.`None`Type: str
`--disaggregation-decode-enable-offload-kvcache`Enable async KV cache offloading on decode server (PD mode).`False`bool flag (set to enable)
`--disaggregation-decode-enable-fake-auto`Auto enable FAKE mode for decode node testing, no need to pass bootstrap_host and bootstrap_room in request.`False`bool flag (set to enable)
`--num-reserved-decode-tokens`Number of decode tokens that will have memory reserved when adding new request to the running batch.`512`Type: int
`--disaggregation-decode-polling-interval`The interval to poll requests in decode server. Can be set to >1 to reduce the overhead of this.`1`Type: int
+ +## Encode prefill disaggregation + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--encoder-only`For MLLM with an encoder, launch an encoder-only server`False`bool flag (set to enable)
`--language-only`For VLM, load weights for the language model only.`False`bool flag (set to enable)
`--encoder-transfer-backend`The backend for encoder disaggregation transfer. Default is zmq_to_scheduler.`zmq_to_scheduler``zmq_to_scheduler`, `zmq_to_tokenizer`, `mooncake`
`--encoder-urls`List of encoder server urls.`[]`Type: JSON list
+ +## Custom weight loader + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--custom-weight-loader`The custom dataloader which used to update the model. Should be set with a valid import path, such as my_package.weight_load_func`None`List[str]
`--weight-loader-disable-mmap`Disable mmap while loading weight using safetensors.`False`bool flag (set to enable)
`--remote-instance-weight-loader-seed-instance-ip`The ip of the seed instance for loading weights from remote instance.`None`Type: str
`--remote-instance-weight-loader-seed-instance-service-port`The service port of the seed instance for loading weights from remote instance.`None`Type: int
`--remote-instance-weight-loader-send-weights-group-ports`The communication group ports for loading weights from remote instance.`None`Type: JSON list
`--remote-instance-weight-loader-backend`The backend for loading weights from remote instance. Can be 'transfer_engine' or 'nccl'. Default is 'nccl'.`nccl``transfer_engine`, `nccl`
`--remote-instance-weight-loader-start-seed-via-transfer-engine`Start seed server via transfer engine backend for remote instance weight loader.`False`bool flag (set to enable)
+ +## For PD-Multiplexing + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--enable-pdmux`Enable PD-Multiplexing, PD running on greenctx stream.`False`bool flag (set to enable)
`--pdmux-config-path`The path of the PD-Multiplexing config file.`None`Type: str
`--sm-group-num`Number of sm partition groups.`8`Type: int
+ +## Configuration file support + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--config`Read CLI options from a config file. Must be a YAML file with configuration options.`None`Type: str
+ +## For Multi-Modal + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--mm-max-concurrent-calls`The max concurrent calls for async mm data processing.`32`Type: int
`--mm-per-request-timeout`The timeout for each multi-modal request in seconds.`10.0`Type: int
`--enable-broadcast-mm-inputs-process`Enable broadcast mm-inputs process in scheduler.`False`bool flag (set to enable)
`--mm-process-config`Multimodal preprocessing config, a json config contains keys: `image`, `video`, `audio`.`{}`Type: JSON / Dict
`--mm-enable-dp-encoder`Enabling data parallelism for mm encoder. The dp size will be set to the tp size automatically.`False`bool flag (set to enable)
`--limit-mm-data-per-request`Limit the number of multimodal inputs per request. e.g. '{"image": 1, "video": 1, "audio": 1}'`None`Type: JSON / Dict
+ +## For checkpoint decryption + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--decrypted-config-file`The path of the decrypted config file.`None`Type: str
`--decrypted-draft-config-file`The path of the decrypted draft config file.`None`Type: str
`--enable-prefix-mm-cache`Enable prefix multimodal cache. Currently only supports mm-only.`False`bool flag (set to enable)
+ +## Forward hooks + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--forward-hooks`JSON-formatted list of forward hook specifications. Each element must include `target_modules` (list of glob patterns matched against `model.named_modules()` names) and `hook_factory` (Python import path to a factory, e.g. `my_package.hooks:make_hook`). An optional `name` field is used for logging, and an optional `config` object is passed as a `dict` to the factory.`None`Type: JSON list
+ +## Deprecated arguments + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDescriptionDefaultsOptions
`--enable-ep-moe`NOTE: --enable-ep-moe is deprecated. Please set `--ep-size` to the same value as `--tp-size` instead.`None`N/A
`--enable-deepep-moe`NOTE: --enable-deepep-moe is deprecated. Please set `--moe-a2a-backend` to 'deepep' instead.`None`N/A
`--prefill-round-robin-balance`Note: Note: --prefill-round-robin-balance is deprecated now.`None`N/A
`--enable-flashinfer-cutlass-moe`NOTE: --enable-flashinfer-cutlass-moe is deprecated. Please set `--moe-runner-backend` to 'flashinfer_cutlass' instead.`None`N/A
`--enable-flashinfer-cutedsl-moe`NOTE: --enable-flashinfer-cutedsl-moe is deprecated. Please set `--moe-runner-backend` to 'flashinfer_cutedsl' instead.`None`N/A
`--enable-flashinfer-trtllm-moe`NOTE: --enable-flashinfer-trtllm-moe is deprecated. Please set `--moe-runner-backend` to 'flashinfer_trtllm' instead.`None`N/A
`--enable-triton-kernel-moe`NOTE: --enable-triton-kernel-moe is deprecated. Please set `--moe-runner-backend` to 'triton_kernel' instead.`None`N/A
`--enable-flashinfer-mxfp4-moe`NOTE: --enable-flashinfer-mxfp4-moe is deprecated. Please set `--moe-runner-backend` to 'flashinfer_mxfp4' instead.`None`N/A
`--crash-on-nan`Crash the server on nan logprobs.`False`Type: str
`--hybrid-kvcache-ratio`Mix ratio in [0,1] between uniform and hybrid kv buffers (0.0 = pure uniform: swa_size / full_size = 1)(1.0 = pure hybrid: swa_size / full_size = local_attention_size / context_length)`None`Optional[float]
`--load-watch-interval`The interval of load watching in seconds.`0.1`Type: float
`--nsa-prefill`Choose the NSA backend for the prefill stage (overrides `--attention-backend` when running DeepSeek NSA-style attention).`flashmla_sparse``flashmla_sparse`, `flashmla_decode`, `fa3`, `tilelang`, `aiter`
`--nsa-decode`Choose the NSA backend for the decode stage when running DeepSeek NSA-style attention. Overrides `--attention-backend` for decoding.`flashmla_kv``flashmla_prefill`, `flashmla_kv`, `fa3`, `tilelang`, `aiter`
diff --git a/docs_new/docs/advanced_features/sgl_model_gateway.mdx b/docs_new/docs/advanced_features/sgl_model_gateway.mdx new file mode 100644 index 000000000..1789442de --- /dev/null +++ b/docs_new/docs/advanced_features/sgl_model_gateway.mdx @@ -0,0 +1,2775 @@ +--- +title: "SGLang Model Gateway" +metatags: + description: "SGLang Model Gateway: load balancing, PD disaggregation, multi-model routing, gRPC support, MCP integration, Kubernetes service discovery." +--- +SGLang Model Gateway is a high-performance model-routing gateway for large-scale LLM deployments. It centralizes worker lifecycle management, balances traffic across heterogeneous protocols (HTTP, gRPC, OpenAI-compatible), and provides enterprise-ready control over history storage, MCP tooling, and privacy-sensitive workflows. The gateway is deeply optimized for the SGLang serving runtime, but can route to any OpenAI-compatible backend. + +*** +## Table of Contents + +1. [Overview](#overview) +2. [Architecture](#architecture) + - [Control Plane](#control-plane) + - [Data Plane](#data-plane) + - [Storage and Privacy](#storage-and-privacy) +3. [Installation](#installation) +4. [Quick Start](#quick-start) +5. [Deployment Modes](#deployment-modes) + - [Co-launch Router and Workers](#co-launch-router-and-workers) + - [Separate Launch (HTTP)](#separate-launch-http) + - [gRPC Launch](#grpc-launch) + - [Prefill-Decode Disaggregation](#prefill-decode-disaggregation) + - [OpenAI Backend Proxy](#openai-backend-proxy) + - [Multi-Model Inference Gateway](#multi-model-inference-gateway) +6. [API Reference](#api-reference) + - [Inference Endpoints](#inference-endpoints) + - [Tokenization Endpoints](#tokenization-endpoints) + - [Parser Endpoints](#parser-endpoints) + - [Classification API](#classification-api) + - [Conversation and Response APIs](#conversation-and-response-apis) + - [Worker Management APIs](#worker-management-apis) + - [Admin and Health Endpoints](#admin-and-health-endpoints) +7. [Load Balancing Policies](#load-balancing-policies) +8. [Reliability and Flow Control](#reliability-and-flow-control) + - [Retries](#retries) + - [Circuit Breaker](#circuit-breaker) + - [Rate Limiting and Queuing](#rate-limiting-and-queuing) + - [Health Checks](#health-checks) +9. [Reasoning Parser Integration](#reasoning-parser-integration) +10. [Tool Call Parsing](#tool-call-parsing) +11. [Tokenizer Management](#tokenizer-management) +12. [MCP Integration](#mcp-integration) +13. [Service Discovery (Kubernetes)](#service-discovery-kubernetes) +14. [History and Data Connectors](#history-and-data-connectors) +15. [WASM Middleware](#wasm-middleware) +16. [Language Bindings](#language-bindings) +17. [Security and Authentication](#security-and-authentication) + - [TLS (HTTPS) for Gateway Server](#tls-https-for-gateway-server) + - [mTLS for Worker Communication](#mtls-for-worker-communication) +18. [Observability](#observability) + - [Prometheus Metrics](#prometheus-metrics) + - [OpenTelemetry Tracing](#opentelemetry-tracing) + - [Logging](#logging) +19. [Production Recommendations](#production-recommendations) + - [Security Best Practices](#security-best-practices) + - [High Availability](#high-availability) + - [Performance](#performance) + - [Kubernetes Deployment](#kubernetes-deployment) + - [Monitoring with PromQL](#monitoring-with-promql) +20. [Configuration Reference](#configuration-reference) +21. [Troubleshooting](#troubleshooting) + +*** +## Overview + +- **Unified control plane** for registering, monitoring, and orchestrating regular, prefill, and decode workers across heterogeneous model fleets. +- **Multi-protocol data plane** that routes traffic across HTTP, PD (prefill/decode), gRPC, and OpenAI-compatible backends with shared reliability primitives. +- **Industry-first gRPC pipeline** with native Rust tokenization, reasoning parsers, and tool-call execution for high-throughput, OpenAI-compatible serving; supports both single-stage and PD topologies. +- **Inference Gateway Mode (`--enable-igw`)** dynamically instantiates multiple router stacks (HTTP regular/PD, gRPC) and applies per-model policies for multi-tenant deployments. +- **Conversation & responses connectors** centralize chat history inside the router so the same context can be reused across models and MCP loops without leaking data to upstream vendors (memory, none, Oracle ATP, PostgreSQL). +- **Enterprise privacy**: agentic multi-turn `/v1/responses`, native MCP client (STDIO/HTTP/SSE/Streamable), and history storage all operate within the router boundary. +- **Reliability core**: retries with jitter, worker-scoped circuit breakers, token-bucket rate limiting with queuing, background health checks, and cache-aware load monitoring. +- **Comprehensive observability**: 40+ Prometheus metrics, OpenTelemetry distributed tracing, structured logging, and request ID propagation. + +*** +## Architecture + +### Control Plane + +- **Worker Manager** discovers capabilities (`/get_server_info`, `/get_model_info`), tracks load, and registers/removes workers in the shared registry. +- **Job Queue** serializes add/remove requests and exposes status (`/workers/{worker_id}`) so clients can track onboarding progress. +- **Load Monitor** feeds cache-aware and power-of-two policies with live worker load statistics. +- **Health Checker** continuously probes workers and updates readiness, circuit breaker state, and router metrics. +- **Tokenizer Registry** manages dynamically registered tokenizers with async loading from HuggingFace or local paths. + +### Data Plane + +- **HTTP routers** (regular & PD) implement `/generate`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/embeddings`, `/v1/rerank`, `/v1/classify`, `/v1/tokenize`, `/v1/detokenize`, and associated admin endpoints. +- **gRPC router** streams tokenized requests directly to SRT gRPC workers, running fully in Rust—tokenizer, reasoning parser, and tool parser all reside in-process. Supports both single-stage and PD routing, including embeddings and classification. +- **OpenAI router** proxies OpenAI-compatible endpoints to external vendors (OpenAI, xAI, etc.) while keeping chat history and multi-turn orchestration local. + +### Storage and Privacy + +- Conversation and response history is stored at the router tier (memory, none, Oracle ATP, or PostgreSQL). The same history can power multiple models or MCP loops without sending data to upstream vendors. +- `/v1/responses` agentic flows, MCP sessions, and conversation APIs share the same storage layer, enabling compliance for regulated workloads. + +*** +## Installation + +### Docker + +Pre-built Docker images are available on Docker Hub with multi-architecture support (x86_64 and ARM64): + +```bash Command +docker pull lmsysorg/sgl-model-gateway:latest +``` + +### Prerequisites + +- **Rust and Cargo** + ```bash Command + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + source "$HOME/.cargo/env" + rustc --version + cargo --version + ``` +- **Python** with `pip` and virtualenv tooling available. + +### Rust Binary + +```bash Command +cd sgl-model-gateway +cargo build --release +``` + +### Python Package + +```bash Command +pip install maturin + +# Fast development mode +cd sgl-model-gateway/bindings/python +maturin develop + +# Production build +maturin build --release --out dist --features vendored-openssl +pip install --force-reinstall dist/*.whl +``` + +*** +## Quick Start + +### Regular HTTP Routing + +```bash Command +# Rust binary +./target/release/sgl-model-gateway \ + --worker-urls http://worker1:8000 http://worker2:8000 \ + --policy cache_aware + +# Python launcher +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 http://worker2:8000 \ + --policy cache_aware +``` + +### gRPC Routing + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls grpc://127.0.0.1:20000 \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --reasoning-parser deepseek-r1 \ + --tool-call-parser json \ + --host 0.0.0.0 --port 8080 +``` + +*** +## Deployment Modes + +### Co-launch Router and Workers + +Launch the router and a fleet of SGLang workers in one process: + +```bash Command +python -m sglang_router.launch_server \ + --model meta-llama/Meta-Llama-3.1-8B-Instruct \ + --dp-size 4 \ + --host 0.0.0.0 \ + --port 30000 +``` + +Comprehensive example with router arguments (prefixed with `--router-`): + +```bash Command +python -m sglang_router.launch_server \ + --host 0.0.0.0 \ + --port 8080 \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --tp-size 1 \ + --dp-size 8 \ + --grpc-mode \ + --log-level debug \ + --router-prometheus-port 10001 \ + --router-tool-call-parser llama \ + --router-model-path meta-llama/Llama-3.1-8B-Instruct \ + --router-policy round_robin \ + --router-log-level debug +``` + +### Separate Launch (HTTP) + +Run workers independently and point the router at their HTTP endpoints: + +```bash Command +# Worker nodes +python -m sglang.launch_server --model meta-llama/Meta-Llama-3.1-8B-Instruct --port 8000 +python -m sglang.launch_server --model meta-llama/Meta-Llama-3.1-8B-Instruct --port 8001 + +# Router node +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 http://worker2:8001 \ + --policy cache_aware \ + --host 0.0.0.0 --port 30000 +``` + +### gRPC Launch + +Use SRT gRPC workers to unlock the highest throughput and access native reasoning/tool pipelines: + +```bash Command +# Workers expose gRPC endpoints +python -m sglang.launch_server \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --grpc-mode \ + --port 20000 + +# Router +python -m sglang_router.launch_router \ + --worker-urls grpc://127.0.0.1:20000 \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --reasoning-parser deepseek-r1 \ + --tool-call-parser json \ + --host 0.0.0.0 --port 8080 +``` + +The gRPC router supports both regular HTTP-equivalent serving and PD (prefill/decode) serving. Provide `--tokenizer-path` or `--model-path` (HuggingFace ID or local directory) whenever connection mode resolves to gRPC. + +### Prefill-Decode Disaggregation + +Split prefill and decode workers for PD-aware caching and balancing: + +```bash Command +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --prefill http://prefill1:30001 9001 \ + --decode http://decode1:30011 \ + --prefill-policy cache_aware \ + --decode-policy power_of_two +``` + +Prefill entries accept an optional bootstrap port. PD mode merges prefill metadata with decode outputs and streams results back to the client. + +### OpenAI Backend Proxy + +Proxy OpenAI-compatible endpoints while keeping history and MCP sessions local: + +```bash Command +python -m sglang_router.launch_router \ + --backend openai \ + --worker-urls https://api.openai.com \ + --history-backend memory +``` + +OpenAI backend mode expects exactly one `--worker-urls` entry per router instance. + +### Multi-Model Inference Gateway + +Enable IGW mode to route multiple models through a single router: + +```bash Command +./target/release/sgl-model-gateway \ + --enable-igw \ + --policy cache_aware \ + --max-concurrent-requests 512 + +# Register workers dynamically +curl -X POST http://localhost:30000/workers \ + -H "Content-Type: application/json" \ + -d '{ + "url": "http://worker-a:8000", + "model_id": "mistral", + "priority": 10, + "labels": {"tier": "gold"} + }' +``` + +*** +## API Reference + +### Inference Endpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodPathDescription
`POST``/generate`SGLang generate API
`POST``/v1/chat/completions`OpenAI-compatible chat completions (streaming/tool calls)
`POST``/v1/completions`OpenAI-compatible text completions
`POST``/v1/embeddings`Embedding generation (HTTP and gRPC)
`POST``/v1/rerank`, `/rerank`Reranking requests
`POST``/v1/classify`Text classification
+ +### Tokenization Endpoints + +The gateway provides HTTP endpoints for text tokenization with batch support, designed to mirror the SGLang Python tokenization API. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodPathDescription
`POST``/v1/tokenize`Tokenize text to token IDs (single or batch)
`POST``/v1/detokenize`Convert token IDs back to text (single or batch)
`POST``/v1/tokenizers`Register a new tokenizer (async, returns job status)
`GET``/v1/tokenizers`List all registered tokenizers
`GET``/v1/tokenizers/{id}`Get tokenizer info by UUID
`GET``/v1/tokenizers/{id}/status`Check async tokenizer loading status
`DELETE``/v1/tokenizers/{id}`Remove a tokenizer from the registry
+ +#### Tokenize Request + +```json Config +{ + "model": "meta-llama/Llama-3.1-8B-Instruct", + "prompt": "Hello, world!" +} +``` + +#### Batch Tokenize Request + +```json Config +{ + "model": "meta-llama/Llama-3.1-8B-Instruct", + "prompt": ["Hello", "World", "How are you?"] +} +``` + +#### Tokenize Response + +```json Config +{ + "tokens": [15339, 11, 1917, 0], + "count": 4, + "char_count": 13 +} +``` + +#### Detokenize Request + +```json Config +{ + "model": "meta-llama/Llama-3.1-8B-Instruct", + "tokens": [15339, 11, 1917, 0], + "skip_special_tokens": true +} +``` + +#### Detokenize Response + +```json Config +{ + "text": "Hello, world!" +} +``` + +#### Add Tokenizer (Async) + +```bash Command +curl -X POST http://localhost:30000/v1/tokenizers \ + -H "Content-Type: application/json" \ + -d '{"name": "llama3", "source": "meta-llama/Llama-3.1-8B-Instruct"}' +``` + +Response: +```json Config +{ + "id": "550e8400-e29b-41d4-a716-446655440000", + "status": "pending", + "message": "Tokenizer registration queued" +} +``` + +Check status: +```bash Command +curl http://localhost:30000/v1/tokenizers/550e8400-e29b-41d4-a716-446655440000/status +``` + +### Parser Endpoints + +The gateway provides admin endpoints for parsing reasoning content and function calls from LLM outputs. + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodPathDescription
`POST``/parse/reasoning`Separate reasoning (`<think>`) from normal text
`POST``/parse/function_call`Parse function/tool calls from text
+ +#### Separate Reasoning Request + +```json Config +{ + "text": "<think>Let me analyze this step by step...</think>The answer is 42.", + "parser": "deepseek-r1" +} +``` + +#### Response + +```json Config +{ + "normal_text": "The answer is 42.", + "reasoning_text": "Let me analyze this step by step..." +} +``` + +#### Function Call Parsing + +```json Config +{ + "text": "{\"name\": \"get_weather\", \"arguments\": {\"city\": \"NYC\"}}", + "parser": "json" +} +``` + +### Classification API + +The `/v1/classify` endpoint provides text classification using sequence classification models (e.g., `Qwen2ForSequenceClassification`, `BertForSequenceClassification`). + +#### Request + +```bash Command +curl http://localhost:30000/v1/classify \ + -H "Content-Type: application/json" \ + -d '{ + "model": "jason9693/Qwen2.5-1.5B-apeach", + "input": "I love this product!" + }' +``` + +#### Response + +```json Config +{ + "id": "classify-a1b2c3d4-5678-90ab-cdef-1234567890ab", + "object": "list", + "created": 1767034308, + "model": "jason9693/Qwen2.5-1.5B-apeach", + "data": [ + { + "index": 0, + "label": "positive", + "probs": [0.12, 0.88], + "num_classes": 2 + } + ], + "usage": { + "prompt_tokens": 6, + "completion_tokens": 0, + "total_tokens": 6 + } +} +``` + +#### Response Fields + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescription
`label`Predicted class label (from model's `id2label` config, or `LABEL_N` fallback)
`probs`Probability distribution over all classes (softmax of logits)
`num_classes`Number of classification classes
+ +#### Notes + +- Classification reuses the embedding backend—the scheduler returns logits which are converted to probabilities via softmax +- Labels come from the model's HuggingFace config (`id2label` field); models without this mapping use generic labels (`LABEL_0`, `LABEL_1`, etc.) +- Both HTTP and gRPC routers support classification + +### Conversation and Response APIs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodPathDescription
`POST``/v1/responses`Create background responses (agentic loops)
`GET``/v1/responses/{id}`Retrieve stored response
`POST``/v1/responses/{id}/cancel`Cancel background response
`DELETE``/v1/responses/{id}`Delete response
`GET``/v1/responses/{id}/input_items`List response input items
`POST``/v1/conversations`Create conversation
`GET``/v1/conversations/{id}`Get conversation
`POST``/v1/conversations/{id}`Update conversation
`DELETE``/v1/conversations/{id}`Delete conversation
`GET``/v1/conversations/{id}/items`List conversation items
`POST``/v1/conversations/{id}/items`Add items to conversation
`GET``/v1/conversations/{id}/items/{item_id}`Get conversation item
`DELETE``/v1/conversations/{id}/items/{item_id}`Delete conversation item
+ +### Worker Management APIs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodPathDescription
`POST``/workers`Queue worker registration (returns 202 Accepted)
`GET``/workers`List workers with health, load, and policy metadata
`GET``/workers/{worker_id}`Inspect specific worker or job queue entry
`PUT``/workers/{worker_id}`Queue worker update
`DELETE``/workers/{worker_id}`Queue worker removal
+ +#### Add Worker + +```bash Command +curl -X POST http://localhost:30000/workers \ + -H "Content-Type: application/json" \ + -d '{"url":"grpc://0.0.0.0:31000","worker_type":"regular"}' +``` + +#### List Workers + +```bash Command +curl http://localhost:30000/workers +``` + +Response: +```json Config +{ + "workers": [ + { + "id": "2f3a0c3e-3a7b-4c3f-8c70-1b7d4c3a6e1f", + "url": "http://0.0.0.0:31378", + "model_id": "mistral", + "priority": 50, + "cost": 1.0, + "worker_type": "regular", + "is_healthy": true, + "load": 0, + "connection_mode": "Http" + } + ], + "total": 1, + "stats": { + "prefill_count": 0, + "decode_count": 0, + "regular_count": 1 + } +} +``` + +### Admin and Health Endpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodPathDescription
`GET``/liveness`Health check (always returns OK)
`GET``/readiness`Readiness check (checks healthy worker availability)
`GET``/health`Alias for liveness
`GET``/health_generate`Health generate test
`GET``/engine_metrics`Engine-level metrics from workers
`GET``/v1/models`List available models
`GET``/get_model_info`Get model information
`GET``/get_server_info`Get server information
`POST``/flush_cache`Clear all caches
`GET``/get_loads`Get all worker loads
`POST``/wasm`Upload WASM module
`GET``/wasm`List WASM modules
`DELETE``/wasm/{module_uuid}`Remove WASM module
+ +*** +## Load Balancing Policies + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PolicyDescriptionUsage
`random`Uniform random selection`--policy random`
`round_robin`Cycles through workers in order`--policy round_robin`
`power_of_two`Samples two workers and picks the lighter one`--policy power_of_two`
`cache_aware`Combines cache locality with load balancing (default)`--policy cache_aware`
`bucket`Divides workers into load buckets with dynamic boundaries`--policy bucket`
+ +### Cache-Aware Policy Tuning + +```bash Command +--cache-threshold 0.5 \ +--balance-abs-threshold 32 \ +--balance-rel-threshold 1.5 \ +--eviction-interval-secs 120 \ +--max-tree-size 67108864 +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDefaultDescription
`--cache-threshold`0.3Minimum prefix match ratio for cache hit
`--balance-abs-threshold`64Absolute load difference before rebalancing
`--balance-rel-threshold`1.5Relative load ratio before rebalancing
`--eviction-interval-secs`120Cache eviction cadence in seconds
`--max-tree-size`67108864Maximum nodes in cache tree
+ +*** +## Reliability and Flow Control + +### Retries + +Configure exponential backoff retries: + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 http://worker2:8001 \ + --retry-max-retries 5 \ + --retry-initial-backoff-ms 50 \ + --retry-max-backoff-ms 30000 \ + --retry-backoff-multiplier 1.5 \ + --retry-jitter-factor 0.2 +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDefaultDescription
`--retry-max-retries`5Maximum retry attempts
`--retry-initial-backoff-ms`50Initial backoff duration (ms)
`--retry-max-backoff-ms`5000Maximum backoff duration (ms)
`--retry-backoff-multiplier`2.0Exponential backoff multiplier
`--retry-jitter-factor`0.1Random jitter factor (0.0-1.0)
`--disable-retries`falseDisable retries entirely
+ +**Retryable Status Codes:** 408, 429, 500, 502, 503, 504 + +### Circuit Breaker + +Per-worker circuit breakers prevent cascading failures: + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 http://worker2:8001 \ + --cb-failure-threshold 5 \ + --cb-success-threshold 2 \ + --cb-timeout-duration-secs 30 \ + --cb-window-duration-secs 60 +``` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDefaultDescription
`--cb-failure-threshold`5Consecutive failures to open circuit
`--cb-success-threshold`2Successes to close from half-open
`--cb-timeout-duration-secs`30Time before half-open attempt
`--cb-window-duration-secs`60Failure counting window
`--disable-circuit-breaker`falseDisable circuit breaker
+ +**Circuit Breaker States:** +- **Closed**: Normal operation, requests allowed +- **Open**: Failing, requests rejected immediately +- **Half-Open**: Testing recovery, limited requests allowed + +### Rate Limiting and Queuing + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 http://worker2:8001 \ + --max-concurrent-requests 256 \ + --rate-limit-tokens-per-second 512 \ + --queue-size 128 \ + --queue-timeout-secs 30 +``` + +Requests beyond the concurrency limit wait in a FIFO queue. Returns: +- `429 Too Many Requests` when queue is full +- `408 Request Timeout` when queue timeout expires + +### Health Checks + +```bash Command +--health-check-interval-secs 30 \ +--health-check-timeout-secs 10 \ +--health-success-threshold 2 \ +--health-failure-threshold 3 \ +--health-check-endpoint /health +``` + +*** +## Reasoning Parser Integration + +The gateway includes built-in reasoning parsers for models that use Chain-of-Thought (CoT) reasoning with explicit thinking blocks. + +### Supported Parsers + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Parser IDModel FamilyThink Tokens
`deepseek-r1`DeepSeek-R1`<think>...</think>` (initial reasoning)
`qwen3`Qwen-3`<think>...</think>`
`qwen3-thinking`Qwen-3 Thinking`<think>...</think>` (initial reasoning)
`kimi`Kimi K2Unicode think tokens
`glm45`GLM-4.5/4.6/4.7`<think>...</think>`
`step3`Step-3`<think>...</think>`
`minimax`MiniMax`<think>...</think>`
+ +### Usage + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls grpc://127.0.0.1:20000 \ + --model-path deepseek-ai/DeepSeek-R1 \ + --reasoning-parser deepseek-r1 +``` + +The gRPC router automatically: +1. Detects reasoning blocks in streaming output +2. Separates reasoning content from normal text +3. Applies incremental streaming parsing with buffer management +4. Handles partial token detection for correct streaming behavior + +*** +## Tool Call Parsing + +The gateway supports parsing function/tool calls from LLM outputs in multiple formats. + +### Supported Formats + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParserFormatDescription
`json`JSONStandard JSON tool calls
`python`PythonicPython function call syntax
`xml`XMLXML-formatted tool calls
+ +### Usage + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls grpc://127.0.0.1:20000 \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --tool-call-parser json +``` + +*** +## Tokenizer Management + +### Tokenizer Sources + +The gateway supports multiple tokenizer backends: +- **HuggingFace**: Load from HuggingFace Hub by model ID +- **Local**: Load from local `tokenizer.json` or directory +- **Tiktoken**: Auto-detect OpenAI GPT models (gpt-4, davinci, etc.) + +### Configuration + +```bash Command +# HuggingFace model +--model-path meta-llama/Llama-3.1-8B-Instruct + +# Local tokenizer +--tokenizer-path /path/to/tokenizer.json + +# With chat template override +--chat-template /path/to/template.jinja +``` + +### Tokenizer Caching + +Two-level caching for optimal performance: + + + + + + + + + + + + + + + + + + + + + + + + + + +
CacheTypeDescription
L0Exact matchWhole-string caching for repeated prompts
L1Prefix matchPrefix boundary matching for incremental prompts
+ +```bash Command +--enable-l0-cache \ +--l0-max-entries 10000 \ +--enable-l1-cache \ +--l1-max-memory 52428800 # 50MB +``` + +*** +## MCP Integration + +The gateway provides native Model Context Protocol (MCP) client integration for tool execution. + +### Supported Transports + + + + + + + + + + + + + + + + + + + + + + + + + + +
TransportDescription
STDIOLocal process execution
SSEServer-Sent Events (HTTP)
StreamableBidirectional streaming
+ +### Configuration + +```bash Command +python -m sglang_router.launch_router \ + --mcp-config-path /path/to/mcp-config.yaml \ + --worker-urls http://worker1:8000 +``` + +### MCP Configuration File + +```yaml Config +servers: + - name: "filesystem" + command: "npx" + args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"] + protocol: "stdio" + required: false + + - name: "github" + url: "https://api.github.com/mcp" + token: "ghp_xxxxx" + protocol: "sse" + required: false + + - name: "custom-tools" + url: "https://tools.example.com/mcp" + protocol: "streamable" + required: true + +pool: + max_connections: 100 + idle_timeout: 300 + +proxy: + http: "http://proxy.internal:8080" + https: "https://proxy.internal:8443" + no_proxy: "localhost,127.0.0.1,*.internal" + +inventory: + enable_refresh: true + tool_ttl: 300 + refresh_interval: 300 +``` + +*** +## Service Discovery (Kubernetes) + +Enable automatic worker discovery via Kubernetes pod selectors: + +```bash Command +python -m sglang_router.launch_router \ + --service-discovery \ + --selector app=sglang-worker role=inference \ + --service-discovery-namespace production \ + --service-discovery-port 8000 +``` + +### PD Mode Discovery + +```bash Command +--pd-disaggregation \ +--prefill-selector app=sglang component=prefill \ +--decode-selector app=sglang component=decode \ +--service-discovery +``` + +Prefill pods can expose bootstrap ports via the `sglang.ai/bootstrap-port` annotation. RBAC must allow `get`, `list`, and `watch` on pods. + +*** +## History and Data Connectors + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BackendDescriptionUsage
`memory`In-memory storage (default)`--history-backend memory`
`none`No persistence`--history-backend none`
`oracle`Oracle Autonomous Database`--history-backend oracle`
`postgres`PostgreSQL Database`--history-backend postgres`
`redis`Redis`--history-backend redis`
+ +### Oracle Configuration + +```bash Command +# Connection descriptor +export ATP_DSN="(description=(address=(protocol=tcps)(port=1522)(host=adb.region.oraclecloud.com))(connect_data=(service_name=service_name)))" + +# Or TNS alias (requires wallet) +export ATP_TNS_ALIAS="sglroutertestatp_high" +export ATP_WALLET_PATH="/path/to/wallet" + +# Credentials +export ATP_USER="admin" +export ATP_PASSWORD="secret" +export ATP_POOL_MIN=4 +export ATP_POOL_MAX=32 + +python -m sglang_router.launch_router \ + --backend openai \ + --worker-urls https://api.openai.com \ + --history-backend oracle +``` + +### PostgreSQL Configuration + +```bash Command +export POSTGRES_DB_URL="postgres://user:password@host:5432/dbname" + +python -m sglang_router.launch_router \ + --backend openai \ + --worker-urls https://api.openai.com \ + --history-backend postgres +``` + +### Redis Configuration + +```bash Command +export REDIS_URL="redis://localhost:6379" +export REDIS_POOL_MAX=16 +export REDIS_RETENTION_DAYS=30 + +python -m sglang_router.launch_router \ + --backend openai \ + --worker-urls https://api.openai.com \ + --history-backend redis \ + --redis-retention-days 30 +``` + +Use `--redis-retention-days -1` for persistent storage (default is 30 days). + +*** +## WASM Middleware + +The gateway supports WebAssembly (WASM) middleware modules for custom request/response processing. This enables organization-specific logic for authentication, rate limiting, billing, logging, and more—without modifying or recompiling the gateway. + +### Overview + +WASM middleware runs in a sandboxed environment with memory isolation, no network/filesystem access, and configurable resource limits. + + + + + + + + + + + + + + + + + + + + + + + + + + +
Attach PointWhen ExecutedUse Cases
`OnRequest`Before forwarding to workersAuth, rate limiting, request modification
`OnResponse`After receiving worker responseLogging, response modification, error handling
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ActionDescription
`Continue`Proceed without modification
`Reject(status)`Reject request with HTTP status code
`Modify(...)`Modify headers, body, or status
+ +### Examples + +Complete working examples are available in `examples/wasm/`: + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
`auth/`API key authentication for protected routes
`rate_limit/`Per-client rate limiting (requests/minute)
`logging/`Request tracking headers and response modification
+ +The interface definition is located at `src/wasm/interface`. + +### Building Modules + +```bash Command +# Prerequisites +rustup target add wasm32-wasip2 +cargo install wasm-tools + +# Build +cargo build --target wasm32-wasip2 --release + +# Convert to component format +wasm-tools component new \ + target/wasm32-wasip2/release/my_middleware.wasm \ + -o my_middleware.component.wasm +``` + +### Deploying Modules + +```bash Command +# Enable WASM support +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 \ + --enable-wasm + +# Upload module +curl -X POST http://localhost:30000/wasm \ + -H "Content-Type: application/json" \ + -d '{ + "modules": [{ + "name": "auth-middleware", + "file_path": "/absolute/path/to/auth.component.wasm", + "module_type": "Middleware", + "attach_points": [{"Middleware": "OnRequest"}] + }] + }' + +# List modules +curl http://localhost:30000/wasm + +# Remove module +curl -X DELETE http://localhost:30000/wasm/{module_uuid} +``` + +### Runtime Configuration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDefaultDescription
`max_memory_pages`1024 (64MB)Maximum WASM memory
`max_execution_time_ms`1000Execution timeout
`max_stack_size`1MBStack size limit
`module_cache_size`10Cached modules per worker
+ +**Note:** Rate limiting state is per-worker thread and not shared across gateway replicas. For production, consider implementing rate limiting at a shared layer (e.g., Redis) + +*** +## Language Bindings + +SGLang Model Gateway provides official language bindings for Python and Go, enabling integration with different technology stacks and organizational requirements. + +### Python Bindings + +The Python bindings provide a PyO3-based wrapper around the Rust gateway library. This is a straightforward binding that calls the gateway server startup from Python. + +#### Installation + +```bash Command +# From PyPI +pip install sglang-router + +# Development build +cd sgl-model-gateway/bindings/python +pip install maturin && maturin develop --features vendored-openssl +``` + +#### Usage + +The Python bindings are used throughout this documentation. See the [Quick Start](#quick-start) and [Deployment Modes](#deployment-modes) sections for detailed examples. + +Key components: +- `RouterArgs` dataclass with 50+ configuration options +- `Router.from_args()` for programmatic startup +- CLI commands: `smg launch`, `smg server`, `python -m sglang_router.launch_router` + +### Go Bindings + +The Go bindings provide a high-performance gRPC client library for organizations with Go-based infrastructure. This is ideal for: + +- Integration with internal Go services and tooling +- High-performance client applications +- Building custom OpenAI-compatible proxy servers + +#### Architecture + +```text Output ++-------------------------------------------+ +| High-Level Go API | +| (client.go - OpenAI-style interface) | ++-------------------------------------------+ +| gRPC Layer | ++-------------------------------------------+ +| Rust FFI Layer | +| (Tokenization, Parsing, Conversion) | ++-------------------------------------------+ +``` + +**Key Features:** +- Native Rust tokenization via FFI (thread-safe, lock-free) +- Full streaming support with context cancellation +- Configurable channel buffer sizes for high concurrency +- Built-in tool call parsing and chat template application + +#### Installation + +```bash Command +# Build the FFI library first +cd sgl-model-gateway/bindings/golang +make build && make lib + +# Then use in your Go project +go get github.com/sgl-project/sgl-go-sdk +``` + +**Requirements:** Go 1.24+, Rust toolchain + +#### Examples + +Complete working examples are available in `bindings/golang/examples/`: + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExampleDescription
`simple/`Non-streaming chat completion
`streaming/`Streaming chat completion with SSE
`oai_server/`Full OpenAI-compatible HTTP server
+ +```bash Command +# Run examples +cd sgl-model-gateway/bindings/golang/examples/simple && ./run.sh +cd sgl-model-gateway/bindings/golang/examples/streaming && ./run.sh +cd sgl-model-gateway/bindings/golang/examples/oai_server && ./run.sh +``` + +#### Testing + +```bash Command +cd sgl-model-gateway/bindings/golang + +# Unit tests +go test -v ./... + +# Integration tests (requires running SGLang server) +export SGL_GRPC_ENDPOINT=grpc://localhost:20000 +export SGL_TOKENIZER_PATH=/path/to/tokenizer +go test -tags=integration -v ./... +``` + +### Comparison + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeaturePythonGo
**Primary Use**Gateway server launchergRPC client library
**CLI Support**Full CLI (smg, sglang-router)Library only
**K8s Discovery**Native supportN/A (client library)
**PD Mode**Built-inN/A (client library)
+ +**When to Use Python:** Launching and managing the gateway server, service discovery, PD disaggregation. + +**When to Use Go:** Building custom client applications, integration with Go microservices, OpenAI-compatible proxy servers + +*** +## Security and Authentication + +### Router API Key + +```bash Command +python -m sglang_router.launch_router \ + --api-key "your-router-api-key" \ + --worker-urls http://worker1:8000 +``` + +Clients must supply `Authorization: Bearer ` for protected endpoints. + +### Worker API Keys + +```bash Command +# Add worker with explicit key +curl -H "Authorization: Bearer router-key" \ + -X POST http://localhost:8080/workers \ + -H "Content-Type: application/json" \ + -d '{"url":"http://worker:8000","api_key":"worker-key"}' +``` + +### Security Configurations + +1. **No Authentication** (default): Use only in trusted environments +2. **Router-only Authentication**: Clients authenticate to router +3. **Worker-only Authentication**: Router open, workers require keys +4. **Full Authentication**: Both router and workers protected + +### TLS (HTTPS) for Gateway Server + +Enable TLS to serve the gateway over HTTPS: + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 \ + --tls-cert-path /path/to/server.crt \ + --tls-key-path /path/to/server.key +``` + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescription
`--tls-cert-path`Path to server certificate (PEM format)
`--tls-key-path`Path to server private key (PEM format)
+ +Both parameters must be provided together. The gateway uses rustls with the ring crypto provider for TLS termination. If TLS is not configured, the gateway falls back to plain HTTP. + +### mTLS for Worker Communication + +Enable mutual TLS (mTLS) for secure communication with workers in HTTP mode: + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls https://worker1:8443 https://worker2:8443 \ + --client-cert-path /path/to/client.crt \ + --client-key-path /path/to/client.key \ + --ca-cert-path /path/to/ca.crt +``` + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterDescription
`--client-cert-path`Path to client certificate for mTLS (PEM format)
`--client-key-path`Path to client private key for mTLS (PEM format)
`--ca-cert-path`Path to CA certificate for verifying worker TLS (PEM format, repeatable)
+ +**Key Points:** +- Client certificate and key must be provided together +- Multiple CA certificates can be added with multiple `--ca-cert-path` flags +- Uses rustls backend when TLS is configured +- Single HTTP client is created for all workers (assumes single security domain) +- TCP keepalive (30 seconds) is enabled for long-lived connections + +### Full TLS Configuration Example + +Gateway HTTPS + Worker mTLS + API Key authentication: + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls https://worker1:8443 https://worker2:8443 \ + --tls-cert-path /etc/certs/server.crt \ + --tls-key-path /etc/certs/server.key \ + --client-cert-path /etc/certs/client.crt \ + --client-key-path /etc/certs/client.key \ + --ca-cert-path /etc/certs/ca.crt \ + --api-key "secure-api-key" \ + --policy cache_aware +``` + +*** +## Observability + +### Prometheus Metrics + +Enable with `--prometheus-host`/`--prometheus-port` (defaults to `0.0.0.0:29000`). + +#### Metric Categories (40+ metrics) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
LayerPrefixMetrics
HTTP`smg_http_*``requests_total`, `request_duration_seconds`, `responses_total`, `connections_active`, `rate_limit_total`
Router`smg_router_*``requests_total`, `request_duration_seconds`, `request_errors_total`, `stage_duration_seconds`, `upstream_responses_total`
Inference`smg_router_*``ttft_seconds`, `tpot_seconds`, `tokens_total`, `generation_duration_seconds`
Worker`smg_worker_*``pool_size`, `connections_active`, `requests_active`, `health_checks_total`, `selection_total`, `errors_total`
Circuit Breaker`smg_worker_cb_*``state`, `transitions_total`, `outcomes_total`, `consecutive_failures`, `consecutive_successes`
Retry`smg_worker_*``retries_total`, `retries_exhausted_total`, `retry_backoff_seconds`
Discovery`smg_discovery_*``registrations_total`, `deregistrations_total`, `sync_duration_seconds`, `workers_discovered`
MCP`smg_mcp_*``tool_calls_total`, `tool_duration_seconds`, `servers_active`, `tool_iterations_total`
Database`smg_db_*``operations_total`, `operation_duration_seconds`, `connections_active`, `items_stored`
+ +#### Key Inference Metrics (gRPC mode) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MetricTypeDescription
`smg_router_ttft_seconds`HistogramTime to first token
`smg_router_tpot_seconds`HistogramTime per output token
`smg_router_tokens_total`CounterTotal tokens (input/output)
`smg_router_generation_duration_seconds`HistogramEnd-to-end generation time
+ +#### Duration Buckets + +1ms, 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, 2.5s, 5s, 10s, 15s, 30s, 45s, 60s, 90s, 120s, 180s, 240s + +### OpenTelemetry Tracing + +Enable distributed tracing with OTLP export: + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 \ + --enable-trace \ + --otlp-traces-endpoint localhost:4317 +``` + +#### Features + +- OTLP/gRPC exporter (default port 4317) +- W3C Trace Context propagation for HTTP and gRPC +- Batch span processing (500ms delay, 64 span batch size) +- Custom filtering to reduce noise +- Trace context injection into upstream worker requests +- Service name: `sgl-router` + +### Logging + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 \ + --log-level debug \ + --log-dir ./router_logs +``` + +Structured tracing with optional file sink. Log levels: `debug`, `info`, `warn`, `error`. + +### Request ID Propagation + +```bash Command +--request-id-headers x-request-id x-trace-id x-correlation-id +``` + +Responses include `x-request-id` header for correlation. + +*** +## Production Recommendations + +This section provides guidance for deploying SGLang Model Gateway in production environments. + +### Security Best Practices + +**Always enable TLS in production:** + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls https://worker1:8443 https://worker2:8443 \ + --tls-cert-path /etc/certs/server.crt \ + --tls-key-path /etc/certs/server.key \ + --client-cert-path /etc/certs/client.crt \ + --client-key-path /etc/certs/client.key \ + --ca-cert-path /etc/certs/ca.crt \ + --api-key "${ROUTER_API_KEY}" +``` + +**Security Checklist:** +- Enable TLS for gateway HTTPS termination +- Enable mTLS for worker communication when workers are on untrusted networks +- Set `--api-key` to protect router endpoints +- Use Kubernetes Secrets or a secrets manager for credentials +- Rotate certificates and API keys periodically +- Restrict network access with firewalls or network policies + +### High Availability + +**Scaling Strategy:** + +The gateway supports running multiple replicas behind a load balancer for high availability. However, there are important considerations: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComponentShared Across ReplicasImpact
Worker RegistryNo (independent)Each replica discovers workers independently
Radix Cache TreeNo (independent)Cache hits may decrease by 10-20%
Circuit Breaker StateNo (independent)Each replica tracks failures independently
Rate LimitingNo (independent)Limits apply per-replica, not globally
+ +**Recommendations:** + +1. **Prefer horizontal scaling over vertical scaling**: Deploy multiple smaller gateway replicas rather than one large instance with excessive CPU and memory. This provides: + - Better fault tolerance (single replica failure doesn't take down the gateway) + - More predictable resource usage + - Easier capacity planning + +2. **Use Kubernetes Service Discovery**: Let the gateway automatically discover and manage workers: + ```bash Command + python -m sglang_router.launch_router \ + --service-discovery \ + --selector app=sglang-worker \ + --service-discovery-namespace production + ``` + +3. **Accept cache efficiency trade-off**: With multiple replicas, the cache-aware routing policy's radix tree is not synchronized across replicas. This means: + - Each replica builds its own cache tree + - Requests from the same user may hit different replicas + - Expected cache hit rate reduction: **10-20%** + - This is often acceptable given the HA benefits + +4. **Configure session affinity (optional)**: If cache efficiency is critical, configure your load balancer for session affinity based on a consistent hash of the request (e.g., user ID or API key). + +**Example HA Architecture:** +```text Output + +-------------------+ + | Load Balancer | + | (L4/L7) | + +---------+---------+ + | + +-------------------+-------------------+ + | | | + v v v + +-----------+ +-----------+ +-----------+ + | Gateway | | Gateway | | Gateway | + | Replica 1 | | Replica 2 | | Replica 3 | + +-----+-----+ +-----+-----+ +-----+-----+ + | | | + +-------------------+-------------------+ + | + +-------------------+-------------------+ + | | | + v v v + +-----------+ +-----------+ +-----------+ + | Worker | | Worker | | Worker | + | Pod 1 | | Pod 2 | | Pod N | + +-----------+ +-----------+ +-----------+ +``` + +### Performance + +**Use gRPC mode for high throughput:** + +gRPC mode provides the highest performance for SGLang workers: + +```bash Command +# Start workers in gRPC mode +python -m sglang.launch_server \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --grpc-mode \ + --port 20000 + +# Configure gateway for gRPC +python -m sglang_router.launch_router \ + --worker-urls grpc://worker1:20000 grpc://worker2:20000 \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --policy cache_aware +``` + +**Performance Benefits of gRPC:** +- Native Rust tokenization (no Python overhead) +- Streaming with lower latency +- Built-in reasoning parser execution +- Tool call parsing in the gateway +- Reduced serialization overhead + +**Tuning Recommendations:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterRecommendationReason
`--policy``cache_aware`Best for repeated prompts, ~30% latency reduction
`--max-concurrent-requests`2-4x worker countPrevent overload while maximizing throughput
`--queue-size`2x max-concurrentBuffer for burst traffic
`--request-timeout-secs`Based on max generation lengthPrevent stuck requests
+ +### Kubernetes Deployment + +**Pod Labeling for Service Discovery:** + +For the gateway to discover workers automatically, label your worker pods consistently: + +```yaml Config +# Worker Deployment (Regular Mode) +apiVersion: apps/v1 +kind: Deployment +metadata: + name: sglang-worker + namespace: production +spec: + replicas: 4 + selector: + matchLabels: + app: sglang-worker + component: inference + template: + metadata: + labels: + app: sglang-worker + component: inference + model: llama-3-8b + spec: + containers: + - name: worker + image: lmsysorg/sglang:latest + ports: + - containerPort: 8000 + name: http + - containerPort: 20000 + name: grpc +``` + +**Gateway configuration for discovery:** +```bash Command +python -m sglang_router.launch_router \ + --service-discovery \ + --selector app=sglang-worker component=inference \ + --service-discovery-namespace production \ + --service-discovery-port 8000 +``` + +**PD (Prefill/Decode) Mode Labeling:** + +```yaml Config +# Prefill Worker +metadata: + labels: + app: sglang-worker + component: prefill + annotations: + sglang.ai/bootstrap-port: "9001" + +# Decode Worker +metadata: + labels: + app: sglang-worker + component: decode +``` + +**Gateway configuration for PD discovery:** +```bash Command +python -m sglang_router.launch_router \ + --service-discovery \ + --pd-disaggregation \ + --prefill-selector app=sglang-worker component=prefill \ + --decode-selector app=sglang-worker component=decode \ + --service-discovery-namespace production +``` + +**RBAC Requirements:** + +The gateway needs permissions to watch pods: + +```yaml Config +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: sglang-gateway + namespace: production +rules: +- apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list", "watch"] +*** +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: sglang-gateway + namespace: production +subjects: +- kind: ServiceAccount + name: sglang-gateway + namespace: production +roleRef: + kind: Role + name: sglang-gateway + apiGroup: rbac.authorization.k8s.io +``` + +### Monitoring with PromQL + +Configure Prometheus to scrape the gateway metrics endpoint (default: `:29000/metrics`). + +**Essential Dashboards:** + +**1. Request Rate and Latency:** +```sql Example +# Request rate by endpoint +sum(rate(smg_http_requests_total[5m])) by (path, method) + +# P50 latency +histogram_quantile(0.50, sum(rate(smg_http_request_duration_seconds_bucket[5m])) by (le)) + +# P99 latency +histogram_quantile(0.99, sum(rate(smg_http_request_duration_seconds_bucket[5m])) by (le)) + +# Error rate +sum(rate(smg_http_responses_total{status=~"5.."}[5m])) / sum(rate(smg_http_responses_total[5m])) +``` + +**2. Worker Health:** +```sql Example +# Healthy workers +sum(smg_worker_pool_size) + +# Active connections per worker +smg_worker_connections_active + +# Worker health check failures +sum(rate(smg_worker_health_checks_total{result="failure"}[5m])) by (worker_id) +``` + +**3. Circuit Breaker Status:** +```sql Example +# Circuit breaker states (0=closed, 1=open, 2=half-open) +smg_worker_cb_state + +# Circuit breaker transitions +sum(rate(smg_worker_cb_transitions_total[5m])) by (worker_id, from_state, to_state) + +# Workers with open circuits +count(smg_worker_cb_state == 1) +``` + +**4. Inference Performance (gRPC mode):** +```sql Example +# Time to first token (P50) +histogram_quantile(0.50, sum(rate(smg_router_ttft_seconds_bucket[5m])) by (le, model)) + +# Time per output token (P99) +histogram_quantile(0.99, sum(rate(smg_router_tpot_seconds_bucket[5m])) by (le, model)) + +# Token throughput +sum(rate(smg_router_tokens_total[5m])) by (model, direction) + +# Generation duration P95 +histogram_quantile(0.95, sum(rate(smg_router_generation_duration_seconds_bucket[5m])) by (le)) +``` + +**5. Rate Limiting and Queuing:** +```sql Example +# Rate limit rejections +sum(rate(smg_http_rate_limit_total{decision="rejected"}[5m])) + +# Queue depth (if using concurrency limiting) +smg_worker_requests_active + +# Retry attempts +sum(rate(smg_worker_retries_total[5m])) by (worker_id) + +# Exhausted retries (failures after all retries) +sum(rate(smg_worker_retries_exhausted_total[5m])) +``` + +**6. MCP Tool Execution:** +```sql Example +# Tool call rate +sum(rate(smg_mcp_tool_calls_total[5m])) by (server, tool) + +# Tool latency P95 +histogram_quantile(0.95, sum(rate(smg_mcp_tool_duration_seconds_bucket[5m])) by (le, tool)) + +# Active MCP server connections +smg_mcp_servers_active +``` + +**Alerting Rules Example:** + +```yaml Config +groups: +- name: sglang-gateway + rules: + - alert: HighErrorRate + expr: | + sum(rate(smg_http_responses_total{status=~"5.."}[5m])) + / sum(rate(smg_http_responses_total[5m])) > 0.05 + for: 5m + labels: + severity: critical + annotations: + summary: "High error rate on SGLang Gateway" + + - alert: CircuitBreakerOpen + expr: count(smg_worker_cb_state == 1) > 0 + for: 2m + labels: + severity: warning + annotations: + summary: "Worker circuit breaker is open" + + - alert: HighLatency + expr: | + histogram_quantile(0.99, sum(rate(smg_http_request_duration_seconds_bucket[5m])) by (le)) > 30 + for: 5m + labels: + severity: warning + annotations: + summary: "P99 latency exceeds 30 seconds" + + - alert: NoHealthyWorkers + expr: sum(smg_worker_pool_size) == 0 + for: 1m + labels: + severity: critical + annotations: + summary: "No healthy workers available" +``` + +*** +## Configuration Reference + +### Core Settings + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDefaultDescription
`--host`str127.0.0.1Router host
`--port`int30000Router port
`--worker-urls`list[]Worker URLs (HTTP or gRPC)
`--policy`strcache_awareRouting policy
`--max-concurrent-requests`int-1Concurrency limit (-1 disables)
`--request-timeout-secs`int600Request timeout
`--max-payload-size`int256MBMaximum request payload
+ +### Prefill/Decode + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDefaultDescription
`--pd-disaggregation`flagfalseEnable PD mode
`--prefill`list[]Prefill URLs + optional bootstrap ports
`--decode`list[]Decode URLs
`--prefill-policy`strNoneOverride policy for prefill nodes
`--decode-policy`strNoneOverride policy for decode nodes
`--worker-startup-timeout-secs`int600Worker init timeout
+ +### Kubernetes Discovery + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
`--service-discovery`flagEnable discovery
`--selector`listLabel selectors (key=value)
`--prefill-selector` / `--decode-selector`listPD mode selectors
`--service-discovery-namespace`strNamespace to watch
`--service-discovery-port`intWorker port (default 80)
`--bootstrap-port-annotation`strAnnotation for bootstrap ports
+ +### TLS Configuration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
`--tls-cert-path`strServer certificate for gateway HTTPS (PEM)
`--tls-key-path`strServer private key for gateway HTTPS (PEM)
`--client-cert-path`strClient certificate for worker mTLS (PEM)
`--client-key-path`strClient private key for worker mTLS (PEM)
`--ca-cert-path`strCA certificate for verifying workers (PEM, repeatable)
+ +*** +## Troubleshooting + +### Workers Never Ready + +Increase `--worker-startup-timeout-secs` or ensure health probes respond before router startup. + +### Load Imbalance / Hot Workers + +Inspect `smg_router_requests_total` by worker and tune cache-aware thresholds (`--balance-*`, `--cache-threshold`). + +### Circuit Breaker Flapping + +Increase `--cb-failure-threshold` or extend the timeout/window durations. Consider temporarily disabling retries. + +### Queue Overflow (429) + +Increase `--queue-size` or reduce client concurrency. Ensure `--max-concurrent-requests` matches downstream capacity. + +### Memory Growth + +Reduce `--max-tree-size` or lower `--eviction-interval-secs` for more aggressive cache pruning. + +### Debugging + +```bash Command +python -m sglang_router.launch_router \ + --worker-urls http://worker1:8000 \ + --log-level debug \ + --log-dir ./router_logs +``` + +### gRPC Connection Issues + +Ensure workers are started with `--grpc-mode` and verify `--model-path` or `--tokenizer-path` is provided to the router. + +### Tokenizer Loading Failures + +Check HuggingFace Hub credentials (`HF_TOKEN` environment variable) for private models. Verify local paths are accessible. + +*** +SGLang Model Gateway continues to evolve alongside the SGLang runtime. Keep CLI flags, integrations, and documentation aligned when adopting new features or contributing improvements. diff --git a/docs_new/docs/advanced_features/sglang_for_rl.mdx b/docs_new/docs/advanced_features/sglang_for_rl.mdx new file mode 100644 index 000000000..31898d34c --- /dev/null +++ b/docs_new/docs/advanced_features/sglang_for_rl.mdx @@ -0,0 +1,575 @@ +--- +title: "SGLang for RL Systems" +metatags: + description: "SGLang for RL: engine sleep/wake, weight refit, partial rollout, deterministic inference, cache-aware load balancing for RLHF." +--- +This document is a practical guide for infrastructure teams integrating SGLang into RL and post-training systems. It focuses on the operational pain points in the loop (rollout, evaluation, training, weight sync) and maps them to concrete SGLang APIs, flags, and integration patterns. The focus is on maximizing rollout efficiency, accuracy and stability while keeping rollout-serving behavior aligned in production environments. + +## Why SGLang for RL Lifecycle? + +Let's embrace a guiding principle from early DeepMind's RL engineering: + +**Be a library, not a framework.** + +This philosophy empowers innovation by providing SGLang as flexible tools, not rigid structures. Here are five reasons to use SGLang for your RL lifecycle: + +* **Fine-Grained Engine Sleep and Wake Up**: facilitate maximum-powered rollout and training +* **Open-To-Use Refit Functionality**: diverse methods for co-location or disaggregation +* **Easy To Postpone Generation**: enable partial rollout and dedicated rollout control +* **Deterministic Inference**: achieve deterministic inference to enable zero training-inference mismatch +* **Load Balancing Router**: cache-aware load-balancing for high-throughput rollout + +The following sections cover these aspects in detail. + +## Fine-Grained Engine Sleep and Wake Up + +Rollout and training are both memory-intensive, and co-locating them on the same GPUs often leads to memory pressure and slow handoffs. SGLang provides a memory-aware sleep/wake mechanism that releases KV cache and weights while keeping the server process alive, then resumes them for rollout without a full restart. This avoids repeated disk I/O and CUDA graph recapture during each RL step. + +Under the hood, the RL team uses CUDA-graph-aware weight offload via [torch_memory_saver](https://github.com/fzyzcjy/torch_memory_saver) to preserve virtual memory addresses for graph replay. For details, see: [Efficient RL Training - Optimizing Memory Usage in verl](https://hebiao064.github.io/rl-memory-management). + +### Server flag + +Enable memory saver support when launching the server: + +```text Output +--enable-memory-saver +``` + +### Release Memory + +**Endpoint:** `POST /release_memory_occupation` + +**Request body:** + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`tags`Which memory regions to release. If omitted, all are released.`None`Type: list[str], values: `kv_cache`, `weights`
+{/* python/sglang/srt/managers/io_struct.py#L1381 currently only supports `kv_cache`, `weights` */} +**Behavior notes:** + +- This call asserts there are no ongoing requests. Ensure the engine is idle before calling it. +- If `kv_cache` is released, SGLang flushes cache; subsequent requests will rebuild KV cache as needed. + +### Resume Memory + +**Endpoint:** `POST /resume_memory_occupation` + +**Request body:** + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`tags`Which memory regions to resume. If omitted, all are resumed.`None`Type: list[str], values: `kv_cache`, `weights`
+{/* python/sglang/srt/managers/io_struct.py#L1393 currently only supports `kv_cache`, `weights` */} + +## Open-To-Use Refit Functionality + +After training completes each step, rollout engines must be refit with new weights. SGLang supports three refit strategies so you can match your infrastructure style (co-located vs disaggregated) and scaling needs. Each strategy maps to a concrete API with clear request schemas. For a deeper dive into SGLang's weight update utilities, see [RL System Deep Thinking: Weight Update Mechanisms](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/sys-design/readme-1-EN). + +**How to choose:** + +- **From disk** is simplest and best for elastic rollout scaling and checkpointing. +- **From tensor** is best for co-located training/rollout when you can pass in-memory tensors. +- **From distributed** is best for disaggregated training/rollout with dedicated communication groups (NCCL/IB). + +### Update Weights from Disk + +**When to use:** + +- Save checkpoint to disk and update weights from disk +- Dynamic scaling (new rollout instances can load from the same checkpoint) + +**Why it works well:** + +This path trades some I/O overhead for simplicity and flexibility. It integrates naturally with checkpointing and makes it trivial to add new rollout engines: point them at the same checkpoint and call the API. It is also the safest option for high availability because the checkpoint itself is the source of truth. + +**Endpoint:** `POST /update_weights_from_disk` + +**Request body:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`model_path`The model path with the new weights.RequiredType: str
`load_format`The format to load the weights.`None`Type: str
`abort_all_requests`Abort all running requests before update.`False`Type: bool
`weight_version`Optional weight version label tracked by the server.`None`Type: str
`is_async`Perform weight load asynchronously.`False`Type: bool
`torch_empty_cache`Empty torch cache.`False`Type: bool
`keep_pause`Keep scheduler paused after update.`False`Type: bool
`recapture_cuda_graph`Recapture CUDA graphs after update.`False`Type: bool
`token_step`Trainer step id for rollout bookkeeping.`0`Type: int
`flush_cache`Flush KV cache after update.`True`Type: bool
+ +**Response body:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`success`Whether the update succeeded.-Type: bool
`message`Status / error message.-Type: str
`num_paused_requests`Number of paused requests during update.`0`Type: int
+ +**Python Engine API:** `engine.update_weights_from_disk(model_path, load_format=None)` + +### Update Weights from Tensor + +**When to use:** + +- Co-located training and rollout, where training can provide tensors directly +- Fast in-memory updates + +**Important constraints:** + +This strategy requires the training process and rollout engine to share access to the tensors. Co-located setups must keep the model on GPU; moving tensors to CPU will break the update path. For high-performance MoE or specialized attention kernels, co-location may limit some optimizations compared to disaggregated rollouts. + +**Endpoint:** `POST /update_weights_from_tensor` + +**Request body:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`serialized_named_tensors`Per-TP serialized tensor payloads.RequiredType: list[str
`load_format`Optional load format selector.`None``None`, `direct`, `flattened_bucket`, or a custom loader path string
`flush_cache`Flush KV cache after update.`True`Type: bool
`abort_all_requests`Abort all running requests before update.`False`Type: bool
`weight_version`Optional version label tracked by the server.`None`Type: str
+ +**Note:** The serialized tensor payloads must be created with `MultiprocessingSerializer.serialize(...)` and should be base64-safe strings. + +**Python Engine API:** `engine.update_weights_from_tensor(named_tensors, load_format=None, flush_cache=True)` + +### Update Weights from Distributed Group + +**When to use:** + +- Disaggregated training and rollout +- NCCL or IB-backed weight broadcast from training workers to rollout workers + +**How it works:** + +Training workers gather weights (typically on TP rank 0), broadcast them to the rollout group, and each rollout TP shard loads the parameters it needs. This avoids disk I/O and keeps training and rollout decoupled, at the cost of managing a dedicated communication group. + +**Initialize weight update group** + +**Endpoint:** `POST /init_weights_update_group` + +**Request body:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`master_address`Group master address.RequiredType: str
`master_port`Group master port.RequiredType: int
`rank_offset`Offset for local rank mapping.RequiredType: int
`world_size`Total world size.RequiredType: int
`group_name`Group name.`weight_update_group`Type: str
`backend`Communication backend.`nccl`Type: str
+ +**Update weight** + +**Endpoint:** `POST /update_weights_from_distributed` + +**Request body:** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`names`Parameter names to update.RequiredType: list[str]
`dtypes`Dtype strings for each parameter.RequiredType: list[str]
`shapes`Tensor shapes.RequiredType: list[list[int]]
`group_name`Group name.`weight_update_group`Type: str
`flush_cache`Flush KV cache after update.`True`Type: bool
`abort_all_requests`Abort all running requests before update.`False`Type: bool
`weight_version`Optional version label.`None`Type: str
`load_format`Optional format selector.`None``None` or `flattened_bucket`
+ +**Destroy weights update group** + +**Endpoint:** `POST /destroy_weights_update_group` + +**Request body:** + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`group_name`Group name.`weight_update_group`Type: str
+ +**Python Engine APIs:** + +- `engine.init_weights_update_group(...)` +- `engine.update_weights_from_distributed(names, dtypes, shapes, ...)` +- `engine.destroy_weights_update_group(group_name)` + +## Easy To Postpone Generation + +Multi-turn RL rollouts often suffer from long-tail requests that block the entire batch. A small number of slow interactions can stall all GPUs, and the long-tail behavior makes profiling and monitoring difficult. + +SGLang exposes explicit pause/resume APIs so you can pause slow requests and continue them later. This pattern matches systems like [APRIL](https://arxiv.org/abs/2509.18521), terminate once enough responses are collected, and recycle incomplete responses in the next step. The result is higher GPU utilization without discarding partial work. + +`pause_generation` --- update weights --- `continue_generation` is the correct execution flow when updating weights from training. An update can only happen when SGLang is not actively processing inference tasks. + +### Pause Generation + +**Endpoint:** `POST /pause_generation` + +**Request body:** + + + + + + + + + + + + + + + + + + + + + + + + +
FieldDescriptionDefaultsOptions
`mode`Pause mode.`abort``abort`, `retract`, `in_place`
+ +**Modes:** + +- `abort`: Default behavior, identical to `abort` endpoint with `abort_all` set. Pending requests from `waiting_queue` and `running_queue` will be returned immediately to the caller. +- `retract`: Put engine in "paused" state. Move running requests back to waiting queue. KV cache can be flushed and recomputed later. +- `in_place`: Put engine in "paused" state without changing states of the requests. Running requests rely on availability of KV caches to continue, so any subsequent `flush_cache` call will be unsuccessful. + +### Continue Generation + +**Endpoint:** `POST /continue_generation` + +## Deterministic Inference + +In many RL stacks, rollout and training are implemented with different kernels or batching behavior. Even when weights are identical, token probabilities can drift, silently breaking the on-policy assumption. This is the training–inference mismatch problem. + +SGLang supports a deterministic inference mode that reduces non-determinism across batch shapes. This mitigates variance introduced by runtime batching and kernel selection. To further achieve true on-policy training, you need to modify the training engine to use the same deterministic kernels. For implementation details, see these miles examples: [True On-Policy](https://github.com/radixark/miles/tree/main/examples/true_on_policy) and [True On-Policy for VLM](https://github.com/radixark/miles/tree/main/examples/true_on_policy_vlm). For additional context, see the blog post [Let Speed Be With Stability: All-In-One Solution to Training-Inference Mismatch with Miles](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/blob/main/rlhf/slime/mismatch/blog-en). + +**Server flag:** + +```text Output +--enable-deterministic-inference +``` + +For more details, see [Deterministic Inference](./deterministic_inference) + +## Load Balancing Router + +SGLang Model Gateway is the recommended control plane for large‑scale RL rollouts. It provides async, non‑blocking request handling, cache‑aware load balancing, and fault‑tolerant routing across rollout and reward servers. This lets you keep GPUs saturated while avoiding long‑tail stalls and brittle, engine‑local concurrency logic. It has been deployed in the training of GLM 4.5+ models and proven to be highly efficient in production-level large-scale RL workloads. + +Key benefits for RL infrastructure: + +- **Async non-blocking efficiency**: SGLang’s native async server/router architecture (HTTPS/gRPC) manages concurrency automatically. This guarantees maximum GPU saturation and effective continuous batching without requiring complex, manual implementation by engineers. +- **Elasticity and fault tolerance**: By encapsulating the reward model and rollout as independent servers, SGLang decouples them logically and physically. This architecture provides robust disaster recovery for large-scale distributed training; if a server fails, the router automatically redirects traffic to healthy nodes, ensuring the training process continues without interruption. +- **Training–Inference alignment**: Using the SGLang Model Gateway for both training and inference ensures "What You See Is What You Get." This eliminates score discrepancies and the painful backend alignment issues often caused by using different engines for training versus deployment. +- **Dynamic load balancing and long-tail mitigation**: Unlike static partitioning, the SGLang Model Gateway enables request-level dynamic dispatching for multi-turn RL. It can distribute different turns of a conversation across different servers to balance workloads and eliminate long-tail latency caused by varying sequence lengths. + +For deployment and configuration, see: [SGLang Model Gateway](./sgl_model_gateway) diff --git a/docs_new/docs/advanced_features/speculative_decoding.ipynb b/docs_new/docs/advanced_features/speculative_decoding.ipynb new file mode 100644 index 000000000..c24cac402 --- /dev/null +++ b/docs_new/docs/advanced_features/speculative_decoding.ipynb @@ -0,0 +1,360 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Speculative Decoding\n", + "\n", + "SGLang now provides an EAGLE-based (EAGLE-2/EAGLE-3) speculative decoding option. Our implementation aims to maximize speed and efficiency and is considered to be among the fastest in open-source LLM engines.\n", + "\n", + "### Performance Highlights\n", + "\n", + "Please see below for the huge improvements on throughput for LLaMA-Instruct 3.1 8B tested on MT bench that can be achieved via EAGLE3 decoding.\n", + "For further details please see the [EAGLE3 paper](https://arxiv.org/pdf/2503.01840).\n", + "\n", + "| Method | Throughput (tokens/s) |\n", + "|--------|----------------|\n", + "| SGLang (w/o speculative, 1x H100) | 158.34 tokens/s |\n", + "| SGLang + EAGLE-2 (1x H100) | 244.10 tokens/s |\n", + "| SGLang + EAGLE-3 (1x H100) | 373.25 tokens/s |" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## EAGLE Decoding\n", + "\n", + "To enable EAGLE speculative decoding the following parameters are relevant:\n", + "* `speculative_draft_model_path`: Specifies draft model. This parameter is required.\n", + "* `speculative_num_steps`: Depth of autoregressive drafting. Increases speculation range but risks rejection cascades. Default is 5.\n", + "* `speculative_eagle_topk`: Branching factor per step. Improves candidate diversity, will lead to higher acceptance rate, but more lead to higher memory/compute consumption. Default is 4.\n", + "* `speculative_num_draft_tokens`: Maximum parallel verification capacity. Allows deeper tree evaluation but will lead to higher GPU memory usage. Default is 8.\n", + "\n", + "These parameters are the same for EAGLE-2 and EAGLE-3.\n", + "\n", + "You can find the best combinations of these parameters with [bench_speculative.py](https://github.com/sgl-project/sglang/blob/main/scripts/playground/bench_speculative.py).\n", + "\n", + "In the documentation below, we set `--cuda-graph-max-bs` to be a small value for faster engine startup. For your own workloads, please tune the above parameters together with `--cuda-graph-max-bs`, `--max-running-requests`, `--mem-fraction-static` for the best performance. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EAGLE-2 decoding\n", + "\n", + "You can enable EAGLE-2 decoding by setting `--speculative-algorithm EAGLE` and choosing an appropriate model." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "import openai" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model meta-llama/Llama-2-7b-chat-hf --speculative-algorithm EAGLE \\\n", + " --speculative-draft-model-path lmsys/sglang-EAGLE-llama2-chat-7B --speculative-num-steps 3 \\\n", + " --speculative-eagle-topk 4 --speculative-num-draft-tokens 16 --cuda-graph-max-bs 8 --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Llama-2-7b-chat-hf\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=64,\n", + ")\n", + "\n", + "print_highlight(f\"Response: {response}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EAGLE-2 Decoding with `torch.compile`\n", + "\n", + "You can also enable `torch.compile` for further optimizations and optionally set `--torch-compile-max-bs`:\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model meta-llama/Llama-2-7b-chat-hf --speculative-algorithm EAGLE \\\n", + " --speculative-draft-model-path lmsys/sglang-EAGLE-llama2-chat-7B --speculative-num-steps 5 \\\n", + " --speculative-eagle-topk 8 --speculative-num-draft-tokens 64 --mem-fraction 0.6 \\\n", + " --enable-torch-compile --torch-compile-max-bs 2 --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Llama-2-7b-chat-hf\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=64,\n", + ")\n", + "\n", + "print_highlight(f\"Response: {response}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EAGLE-2 Decoding via Frequency-Ranked Speculative Sampling\n", + "\n", + "By employing a truncated high-frequency token vocabulary in the draft model, Eagle speculative decoding reduces `lm_head` computational overhead while accelerating the pipeline without quality degradation. For more details, checkout [the paper](https://arxiv.org/pdf/arXiv:2502.14856).\n", + "\n", + "In our implementation, set `--speculative-token-map` to enable the optimization. You can get the high-frequency token in FR-Spec from [this model](https://huggingface.co/thunlp/LLaMA3-Instruct-8B-FR-Spec). Or you can obtain high-frequency token by directly downloading these token from [this repo](https://github.com/thunlp/FR-Spec/tree/main?tab=readme-ov-file#prepare-fr-spec-vocabulary-subset).\n", + "\n", + "Thanks for the contribution from [Weilin Zhao](https://github.com/Achazwl) and [Zhousx](https://github.com/Zhou-sx). " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model meta-llama/Meta-Llama-3-8B-Instruct --speculative-algorithm EAGLE \\\n", + " --speculative-draft-model-path lmsys/sglang-EAGLE-LLaMA3-Instruct-8B --speculative-num-steps 5 \\\n", + " --speculative-eagle-topk 8 --speculative-num-draft-tokens 64 --speculative-token-map thunlp/LLaMA3-Instruct-8B-FR-Spec/freq_32768.pt \\\n", + " --mem-fraction 0.7 --cuda-graph-max-bs 2 --dtype float16 --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Meta-Llama-3-8B-Instruct\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=64,\n", + ")\n", + "\n", + "print_highlight(f\"Response: {response}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EAGLE-3 Decoding\n", + "\n", + "You can enable EAGLE-3 decoding by setting `--speculative-algorithm EAGLE3` and choosing an appropriate model." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model meta-llama/Llama-3.1-8B-Instruct --speculative-algorithm EAGLE3 \\\n", + " --speculative-draft-model-path jamesliu1/sglang-EAGLE3-Llama-3.1-Instruct-8B --speculative-num-steps 5 \\\n", + " --speculative-eagle-topk 8 --speculative-num-draft-tokens 32 --mem-fraction 0.6 \\\n", + " --cuda-graph-max-bs 2 --dtype float16 --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=64,\n", + ")\n", + "\n", + "print_highlight(f\"Response: {response}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Multi Token Prediction\n", + "\n", + "We support [MTP(Multi-Token Prediction)](https://arxiv.org/pdf/2404.19737) in SGLang by using speculative decoding. We use Xiaomi/MiMo-7B-RL model as example here (deepseek mtp usage refer to [deepseek doc](../basic_usage/deepseek.md#multi-token-prediction))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\"\"\"\n", + " python3 -m sglang.launch_server --model-path XiaomiMiMo/MiMo-7B-RL --host 0.0.0.0 --trust-remote-code \\\n", + " --speculative-algorithm EAGLE --speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2 \\\n", + " --mem-fraction 0.5 --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "url = f\"http://localhost:{port}/v1/chat/completions\"\n", + "\n", + "data = {\n", + " \"model\": \"XiaomiMiMo/MiMo-7B-RL\",\n", + " \"messages\": [{\"role\": \"user\", \"content\": \"What is the capital of France?\"}],\n", + "}\n", + "\n", + "response = requests.post(url, json=data)\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## References\n", + "\n", + "EAGLE process is as follows:\n", + "\n", + "- Within EAGLE the draft model predicts the next feature vector, i.e. the last hidden state of the original LLM, using the feature sequence $(f_1, ..., f_k)$ and the token sequence $(t_2, ..., t_{k+1})$. \n", + "- The next token is then sampled from $p_{k+2}=\\text{LMHead}(f_{k+1})$. Afterwards, the two sequences are extended in a tree style—branching out multiple potential continuations, with the branching factor per step controlled by the `speculative_eagle_topk` parameter—to ensure a more coherent connection of context, and are given as input again.\n", + "- EAGLE-2 additionally uses the draft model to evaluate how probable certain branches in the draft tree are, dynamically stopping the expansion of unlikely branches. After the expansion phase, reranking is employed to select only the top `speculative_num_draft_tokens` final nodes as draft tokens.\n", + "- EAGLE-3 removes the feature prediction objective, incorporates low and mid-layer features, and is trained in an on-policy manner.\n", + "\n", + "This enhances drafting accuracy by operating on the features instead of tokens for more regular inputs and passing the tokens from the next timestep additionally to minimize randomness effects from sampling. Furthermore the dynamic adjustment of the draft tree and selection of reranked final nodes increases acceptance rate of draft tokens further. For more details see [EAGLE-2](https://arxiv.org/abs/2406.16858) and [EAGLE-3](https://arxiv.org/abs/2503.01840) paper.\n", + "\n", + "\n", + "For guidance how to train your own EAGLE model please see the [EAGLE repo](https://github.com/SafeAILab/EAGLE/tree/main?tab=readme-ov-file#train)." + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/advanced_features/speculative_decoding.mdx b/docs_new/docs/advanced_features/speculative_decoding.mdx new file mode 100644 index 000000000..b5f4f1158 --- /dev/null +++ b/docs_new/docs/advanced_features/speculative_decoding.mdx @@ -0,0 +1,278 @@ +--- +title: "Speculative Decoding" +metatags: + description: "SGLang EAGLE speculative decoding: EAGLE-2/EAGLE-3, up to 2.4x throughput improvement, draft model configuration, MTP for DeepSeek." +--- +SGLang now provides an EAGLE-based (EAGLE-2/EAGLE-3) speculative decoding option. Our implementation aims to maximize speed and efficiency and is considered to be among the fastest in open-source LLM engines. + +### Performance Highlights + +Please see below for the huge improvements on throughput for LLaMA-Instruct 3.1 8B tested on MT bench that can be achieved via EAGLE3 decoding. +For further details please see the [EAGLE3 paper](https://arxiv.org/pdf/2503.01840). + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodThroughput (tokens/s)
SGLang (w/o speculative, 1x H100)158.34 tokens/s
SGLang + EAGLE-2 (1x H100)244.10 tokens/s
SGLang + EAGLE-3 (1x H100)373.25 tokens/s
+ + +## EAGLE Decoding + +To enable EAGLE speculative decoding the following parameters are relevant: +* `speculative_draft_model_path`: Specifies draft model. This parameter is required. +* `speculative_num_steps`: Depth of autoregressive drafting. Increases speculation range but risks rejection cascades. Default is 5. +* `speculative_eagle_topk`: Branching factor per step. Improves candidate diversity, will lead to higher acceptance rate, but more lead to higher memory/compute consumption. Default is 4. +* `speculative_num_draft_tokens`: Maximum parallel verification capacity. Allows deeper tree evaluation but will lead to higher GPU memory usage. Default is 8. + +These parameters are the same for EAGLE-2 and EAGLE-3. + +You can find the best combinations of these parameters with [bench_speculative.py](https://github.com/sgl-project/sglang/blob/main/scripts/playground/bench_speculative.py). + +In the documentation below, we set `--cuda-graph-max-bs` to be a small value for faster engine startup. For your own workloads, please tune the above parameters together with `--cuda-graph-max-bs`, `--max-running-requests`, `--mem-fraction-static` for the best performance. + + +### EAGLE-2 decoding + +You can enable EAGLE-2 decoding by setting `--speculative-algorithm EAGLE` and choosing an appropriate model. + + + +```python Example +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process + +import openai +``` + + +```python Example +server_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model meta-llama/Llama-2-7b-chat-hf --speculative-algorithm EAGLE \ + --speculative-draft-model-path lmsys/sglang-EAGLE-llama2-chat-7B --speculative-num-steps 3 \ + --speculative-eagle-topk 4 --speculative-num-draft-tokens 16 --cuda-graph-max-bs 8 --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + + +```python Example +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") + +response = client.chat.completions.create( + model="meta-llama/Llama-2-7b-chat-hf", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, +) + +print_highlight(f"Response: {response}") +``` + + +```python Example +terminate_process(server_process) +``` + +### EAGLE-2 Decoding with `torch.compile` + +You can also enable `torch.compile` for further optimizations and optionally set `--torch-compile-max-bs`: + + + + +```python Example +server_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model meta-llama/Llama-2-7b-chat-hf --speculative-algorithm EAGLE \ + --speculative-draft-model-path lmsys/sglang-EAGLE-llama2-chat-7B --speculative-num-steps 5 \ + --speculative-eagle-topk 8 --speculative-num-draft-tokens 64 --mem-fraction 0.6 \ + --enable-torch-compile --torch-compile-max-bs 2 --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + + +```python Example +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") + +response = client.chat.completions.create( + model="meta-llama/Llama-2-7b-chat-hf", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, +) + +print_highlight(f"Response: {response}") +``` + + +```python Example +terminate_process(server_process) +``` + +### EAGLE-2 Decoding via Frequency-Ranked Speculative Sampling + +By employing a truncated high-frequency token vocabulary in the draft model, Eagle speculative decoding reduces `lm_head` computational overhead while accelerating the pipeline without quality degradation. For more details, checkout [the paper](https://arxiv.org/pdf/arXiv:2502.14856). + +In our implementation, set `--speculative-token-map` to enable the optimization. You can get the high-frequency token in FR-Spec from [this model](https://huggingface.co/thunlp/LLaMA3-Instruct-8B-FR-Spec). Or you can obtain high-frequency token by directly downloading these token from [this repo](https://github.com/thunlp/FR-Spec/tree/main?tab=readme-ov-file#prepare-fr-spec-vocabulary-subset). + +Thanks for the contribution from [Weilin Zhao](https://github.com/Achazwl) and [Zhousx](https://github.com/Zhou-sx). + + + +```python Example +server_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model meta-llama/Meta-Llama-3-8B-Instruct --speculative-algorithm EAGLE \ + --speculative-draft-model-path lmsys/sglang-EAGLE-LLaMA3-Instruct-8B --speculative-num-steps 5 \ + --speculative-eagle-topk 8 --speculative-num-draft-tokens 64 --speculative-token-map thunlp/LLaMA3-Instruct-8B-FR-Spec/freq_32768.pt \ + --mem-fraction 0.7 --cuda-graph-max-bs 2 --dtype float16 --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + + +```python Example +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") + +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3-8B-Instruct", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, +) + +print_highlight(f"Response: {response}") +``` + + +```python Example +terminate_process(server_process) +``` + +### EAGLE-3 Decoding + +You can enable EAGLE-3 decoding by setting `--speculative-algorithm EAGLE3` and choosing an appropriate model. + + + +```python Example +server_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model meta-llama/Llama-3.1-8B-Instruct --speculative-algorithm EAGLE3 \ + --speculative-draft-model-path jamesliu1/sglang-EAGLE3-Llama-3.1-Instruct-8B --speculative-num-steps 5 \ + --speculative-eagle-topk 8 --speculative-num-draft-tokens 32 --mem-fraction 0.6 \ + --cuda-graph-max-bs 2 --dtype float16 --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + + +```python Example +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") + +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3.1-8B-Instruct", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, +) + +print_highlight(f"Response: {response}") +``` + + +```python Example +terminate_process(server_process) +``` + +## Multi Token Prediction + +We support [MTP(Multi-Token Prediction)](https://arxiv.org/pdf/2404.19737) in SGLang by using speculative decoding. We use Xiaomi/MiMo-7B-RL model as example here (deepseek mtp usage refer to [deepseek doc](../basic_usage/deepseek_v3#multi-token-prediction)) + + + +```python Example +server_process, port = launch_server_cmd( + """ + python3 -m sglang.launch_server --model-path XiaomiMiMo/MiMo-7B-RL --host 0.0.0.0 --trust-remote-code \ + --speculative-algorithm EAGLE --speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2 \ + --mem-fraction 0.5 --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + + +```python Example +import requests + +url = f"http://localhost:{port}/v1/chat/completions" + +data = { + "model": "XiaomiMiMo/MiMo-7B-RL", + "messages": [{"role": "user", "content": "What is the capital of France?"}], +} + +response = requests.post(url, json=data) +print_highlight(response.json()) +``` + + +```python Example +terminate_process(server_process) +``` + +## References + +EAGLE process is as follows: + +- Within EAGLE the draft model predicts the next feature vector, i.e. the last hidden state of the original LLM, using the feature sequence $(f_1, ..., f_k)$ and the token sequence $(t_2, ..., t_{k+1})$. +- The next token is then sampled from $p_{k+2}=\text{LMHead}(f_{k+1})$. Afterwards, the two sequences are extended in a tree style—branching out multiple potential continuations, with the branching factor per step controlled by the `speculative_eagle_topk` parameter—to ensure a more coherent connection of context, and are given as input again. +- EAGLE-2 additionally uses the draft model to evaluate how probable certain branches in the draft tree are, dynamically stopping the expansion of unlikely branches. After the expansion phase, reranking is employed to select only the top `speculative_num_draft_tokens` final nodes as draft tokens. +- EAGLE-3 removes the feature prediction objective, incorporates low and mid-layer features, and is trained in an on-policy manner. + +This enhances drafting accuracy by operating on the features instead of tokens for more regular inputs and passing the tokens from the next timestep additionally to minimize randomness effects from sampling. Furthermore the dynamic adjustment of the draft tree and selection of reranked final nodes increases acceptance rate of draft tokens further. For more details see [EAGLE-2](https://arxiv.org/abs/2406.16858) and [EAGLE-3](https://arxiv.org/abs/2503.01840) paper. + + +For guidance how to train your own EAGLE model please see the [EAGLE repo](https://github.com/SafeAILab/EAGLE/tree/main?tab=readme-ov-file#train). diff --git a/docs_new/docs/advanced_features/structured_outputs.ipynb b/docs_new/docs/advanced_features/structured_outputs.ipynb new file mode 100644 index 000000000..bd29a0b3e --- /dev/null +++ b/docs_new/docs/advanced_features/structured_outputs.ipynb @@ -0,0 +1,997 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Structured Outputs" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can specify a JSON schema, [regular expression](https://en.wikipedia.org/wiki/Regular_expression) or [EBNF](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) to constrain the model output. The model output will be guaranteed to follow the given constraints. Only one constraint parameter (`json_schema`, `regex`, or `ebnf`) can be specified for a request.\n", + "\n", + "SGLang supports three grammar backends:\n", + "\n", + "- [XGrammar](https://github.com/mlc-ai/xgrammar)(default): Supports JSON schema, regular expression, and EBNF constraints.\n", + "- [Outlines](https://github.com/dottxt-ai/outlines): Supports JSON schema and regular expression constraints.\n", + "- [Llguidance](https://github.com/guidance-ai/llguidance): Supports JSON schema, regular expression, and EBNF constraints.\n", + "\n", + "We suggest using XGrammar for its better performance and utility. XGrammar currently uses the [GGML BNF format](https://github.com/ggerganov/llama.cpp/blob/master/grammars/README). For more details, see [XGrammar technical overview](https://blog.mlc.ai/2024/11/22/achieving-efficient-flexible-portable-structured-generation-with-xgrammar).\n", + "\n", + "To use Outlines, simply add `--grammar-backend outlines` when launching the server.\n", + "To use llguidance, add `--grammar-backend llguidance` when launching the server.\n", + "If no backend is specified, XGrammar will be used as the default.\n", + "\n", + "For better output quality, **It's advisable to explicitly include instructions in the prompt to guide the model to generate the desired format.** For example, you can specify, 'Please generate the output in the following JSON format: ...'.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## OpenAI Compatible API" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import openai\n", + "import os\n", + "\n", + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n", + "\n", + "\n", + "server_process, port = launch_server_cmd(\n", + " \"python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --host 0.0.0.0 --log-level warning\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")\n", + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### JSON\n", + "\n", + "you can directly define a JSON schema or use [Pydantic](https://docs.pydantic.dev/latest/) to define and validate the response." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Using Pydantic**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from pydantic import BaseModel, Field\n", + "\n", + "\n", + "# Define the schema using Pydantic\n", + "class CapitalInfo(BaseModel):\n", + " name: str = Field(..., pattern=r\"^\\w+$\", description=\"Name of the capital city\")\n", + " population: int = Field(..., description=\"Population of the capital city\")\n", + "\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n", + " messages=[\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"Please generate the information of the capital of France in the JSON format.\",\n", + " },\n", + " ],\n", + " temperature=0,\n", + " max_tokens=128,\n", + " response_format={\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": {\n", + " \"name\": \"foo\",\n", + " # convert the pydantic model to json schema\n", + " \"schema\": CapitalInfo.model_json_schema(),\n", + " },\n", + " },\n", + ")\n", + "\n", + "response_content = response.choices[0].message.content\n", + "# validate the JSON response by the pydantic model\n", + "capital_info = CapitalInfo.model_validate_json(response_content)\n", + "print_highlight(f\"Validated response: {capital_info.model_dump_json()}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**JSON Schema Directly**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "json_schema = json.dumps(\n", + " {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"name\": {\"type\": \"string\", \"pattern\": \"^[\\\\w]+$\"},\n", + " \"population\": {\"type\": \"integer\"},\n", + " },\n", + " \"required\": [\"name\", \"population\"],\n", + " }\n", + ")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n", + " messages=[\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"Give me the information of the capital of France in the JSON format.\",\n", + " },\n", + " ],\n", + " temperature=0,\n", + " max_tokens=128,\n", + " response_format={\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": {\"name\": \"foo\", \"schema\": json.loads(json_schema)},\n", + " },\n", + ")\n", + "\n", + "print_highlight(response.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EBNF" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ebnf_grammar = \"\"\"\n", + "root ::= city | description\n", + "city ::= \"London\" | \"Paris\" | \"Berlin\" | \"Rome\"\n", + "description ::= city \" is \" status\n", + "status ::= \"the capital of \" country\n", + "country ::= \"England\" | \"France\" | \"Germany\" | \"Italy\"\n", + "\"\"\"\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n", + " messages=[\n", + " {\"role\": \"system\", \"content\": \"You are a helpful geography bot.\"},\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"Give me the information of the capital of France.\",\n", + " },\n", + " ],\n", + " temperature=0,\n", + " max_tokens=32,\n", + " extra_body={\"ebnf\": ebnf_grammar},\n", + ")\n", + "\n", + "print_highlight(response.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Regular expression" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"What is the capital of France?\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=128,\n", + " extra_body={\"regex\": \"(Paris|London)\"},\n", + ")\n", + "\n", + "print_highlight(response.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Structural Tag" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tool_get_current_weather = {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"get_current_weather\",\n", + " \"description\": \"Get the current weather in a given location\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"city\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The city to find the weather for, e.g. 'San Francisco'\",\n", + " },\n", + " \"state\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"the two-letter abbreviation for the state that the city is\"\n", + " \" in, e.g. 'CA' which would mean 'California'\",\n", + " },\n", + " \"unit\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The unit to fetch the temperature in\",\n", + " \"enum\": [\"celsius\", \"fahrenheit\"],\n", + " },\n", + " },\n", + " \"required\": [\"city\", \"state\", \"unit\"],\n", + " },\n", + " },\n", + "}\n", + "\n", + "tool_get_current_date = {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"get_current_date\",\n", + " \"description\": \"Get the current date and time for a given timezone\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"timezone\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The timezone to fetch the current date and time for, e.g. 'America/New_York'\",\n", + " }\n", + " },\n", + " \"required\": [\"timezone\"],\n", + " },\n", + " },\n", + "}\n", + "\n", + "schema_get_current_weather = tool_get_current_weather[\"function\"][\"parameters\"]\n", + "schema_get_current_date = tool_get_current_date[\"function\"][\"parameters\"]\n", + "\n", + "\n", + "def get_messages():\n", + " return [\n", + " {\n", + " \"role\": \"system\",\n", + " \"content\": f\"\"\"\n", + "# Tool Instructions\n", + "- Always execute python code in messages that you share.\n", + "- When looking for real time information use relevant functions if available else fallback to brave_search\n", + "You have access to the following functions:\n", + "Use the function 'get_current_weather' to: Get the current weather in a given location\n", + "{tool_get_current_weather[\"function\"]}\n", + "Use the function 'get_current_date' to: Get the current date and time for a given timezone\n", + "{tool_get_current_date[\"function\"]}\n", + "If a you choose to call a function ONLY reply in the following format:\n", + "<{{start_tag}}={{function_name}}>{{parameters}}{{end_tag}}\n", + "where\n", + "start_tag => ` a JSON dict with the function argument name as key and function argument value as value.\n", + "end_tag => ``\n", + "Here is an example,\n", + "{{\"example_name\": \"example_value\"}}\n", + "Reminder:\n", + "- Function calls MUST follow the specified format\n", + "- Required parameters MUST be specified\n", + "- Only call one function at a time\n", + "- Put the entire function call reply on one line\n", + "- Always add your sources when using search results to answer the user query\n", + "You are a helpful assistant.\"\"\",\n", + " },\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"You are in New York. Please get the current date and time, and the weather.\",\n", + " },\n", + " ]\n", + "\n", + "\n", + "messages = get_messages()\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"meta-llama/Meta-Llama-3.1-8B-Instruct\",\n", + " messages=messages,\n", + " response_format={\n", + " \"type\": \"structural_tag\",\n", + " \"structures\": [\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_weather,\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_date,\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"triggers\": [\"\",\n", + " \"content\": {\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": schema_get_current_weather,\n", + " },\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"content\": {\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": schema_get_current_date,\n", + " },\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"at_least_one\": False,\n", + " \"stop_after_first\": False,\n", + " },\n", + " },\n", + ")\n", + "\n", + "print_highlight(response.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Native API and SGLang Runtime (SRT)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### JSON" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Using Pydantic**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "import json\n", + "from pydantic import BaseModel, Field\n", + "\n", + "from transformers import AutoTokenizer\n", + "\n", + "tokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Meta-Llama-3.1-8B-Instruct\")\n", + "\n", + "\n", + "# Define the schema using Pydantic\n", + "class CapitalInfo(BaseModel):\n", + " name: str = Field(..., pattern=r\"^\\w+$\", description=\"Name of the capital city\")\n", + " population: int = Field(..., description=\"Population of the capital city\")\n", + "\n", + "\n", + "# Make API request\n", + "messages = [\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"Here is the information of the capital of France in the JSON format.\\n\",\n", + " }\n", + "]\n", + "text = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": text,\n", + " \"sampling_params\": {\n", + " \"temperature\": 0,\n", + " \"max_new_tokens\": 64,\n", + " \"json_schema\": json.dumps(CapitalInfo.model_json_schema()),\n", + " },\n", + " },\n", + ")\n", + "print_highlight(response.json())\n", + "\n", + "\n", + "response_data = json.loads(response.json()[\"text\"])\n", + "# validate the response by the pydantic model\n", + "capital_info = CapitalInfo.model_validate(response_data)\n", + "print_highlight(f\"Validated response: {capital_info.model_dump_json()}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**JSON Schema Directly**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "json_schema = json.dumps(\n", + " {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"name\": {\"type\": \"string\", \"pattern\": \"^[\\\\w]+$\"},\n", + " \"population\": {\"type\": \"integer\"},\n", + " },\n", + " \"required\": [\"name\", \"population\"],\n", + " }\n", + ")\n", + "\n", + "# JSON\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": text,\n", + " \"sampling_params\": {\n", + " \"temperature\": 0,\n", + " \"max_new_tokens\": 64,\n", + " \"json_schema\": json_schema,\n", + " },\n", + " },\n", + ")\n", + "\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EBNF" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "messages = [\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"Give me the information of the capital of France.\",\n", + " }\n", + "]\n", + "text = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": text,\n", + " \"sampling_params\": {\n", + " \"max_new_tokens\": 128,\n", + " \"temperature\": 0,\n", + " \"n\": 3,\n", + " \"ebnf\": (\n", + " \"root ::= city | description\\n\"\n", + " 'city ::= \"London\" | \"Paris\" | \"Berlin\" | \"Rome\"\\n'\n", + " 'description ::= city \" is \" status\\n'\n", + " 'status ::= \"the capital of \" country\\n'\n", + " 'country ::= \"England\" | \"France\" | \"Germany\" | \"Italy\"'\n", + " ),\n", + " },\n", + " \"stream\": False,\n", + " \"return_logprob\": False,\n", + " },\n", + ")\n", + "\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Regular expression" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "messages = [\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"Paris is the capital of\",\n", + " }\n", + "]\n", + "text = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": text,\n", + " \"sampling_params\": {\n", + " \"temperature\": 0,\n", + " \"max_new_tokens\": 64,\n", + " \"regex\": \"(France|England)\",\n", + " },\n", + " },\n", + ")\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Structural Tag" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import AutoTokenizer\n", + "\n", + "# generate an answer\n", + "tokenizer = AutoTokenizer.from_pretrained(\"meta-llama/Meta-Llama-3.1-8B-Instruct\")\n", + "\n", + "text = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "payload = {\n", + " \"text\": text,\n", + " \"sampling_params\": {\n", + " \"structural_tag\": json.dumps(\n", + " {\n", + " \"type\": \"structural_tag\",\n", + " \"structures\": [\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_weather,\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_date,\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"triggers\": [\"\",\n", + " \"content\": {\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": schema_get_current_weather,\n", + " },\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"content\": {\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": schema_get_current_date,\n", + " },\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"at_least_one\": False,\n", + " \"stop_after_first\": False,\n", + " },\n", + " }\n", + " )\n", + " },\n", + "}\n", + "\n", + "\n", + "# Send POST request to the API endpoint\n", + "response = requests.post(f\"http://localhost:{port}/generate\", json=payload)\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Offline Engine API" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import sglang as sgl\n", + "\n", + "llm = sgl.Engine(\n", + " model_path=\"meta-llama/Meta-Llama-3.1-8B-Instruct\", grammar_backend=\"xgrammar\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### JSON" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Using Pydantic**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "from pydantic import BaseModel, Field\n", + "\n", + "prompts = [\n", + " \"Give me the information of the capital of China in the JSON format.\",\n", + " \"Give me the information of the capital of France in the JSON format.\",\n", + " \"Give me the information of the capital of Ireland in the JSON format.\",\n", + "]\n", + "\n", + "\n", + "# Define the schema using Pydantic\n", + "class CapitalInfo(BaseModel):\n", + " name: str = Field(..., pattern=r\"^\\w+$\", description=\"Name of the capital city\")\n", + " population: int = Field(..., description=\"Population of the capital city\")\n", + "\n", + "\n", + "sampling_params = {\n", + " \"temperature\": 0.1,\n", + " \"top_p\": 0.95,\n", + " \"json_schema\": json.dumps(CapitalInfo.model_json_schema()),\n", + "}\n", + "\n", + "outputs = llm.generate(prompts, sampling_params)\n", + "for prompt, output in zip(prompts, outputs):\n", + " print_highlight(\"===============================\")\n", + " print_highlight(f\"Prompt: {prompt}\") # validate the output by the pydantic model\n", + " capital_info = CapitalInfo.model_validate_json(output[\"text\"])\n", + " print_highlight(f\"Validated output: {capital_info.model_dump_json()}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**JSON Schema Directly**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prompts = [\n", + " \"Give me the information of the capital of China in the JSON format.\",\n", + " \"Give me the information of the capital of France in the JSON format.\",\n", + " \"Give me the information of the capital of Ireland in the JSON format.\",\n", + "]\n", + "\n", + "json_schema = json.dumps(\n", + " {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"name\": {\"type\": \"string\", \"pattern\": \"^[\\\\w]+$\"},\n", + " \"population\": {\"type\": \"integer\"},\n", + " },\n", + " \"required\": [\"name\", \"population\"],\n", + " }\n", + ")\n", + "\n", + "sampling_params = {\"temperature\": 0.1, \"top_p\": 0.95, \"json_schema\": json_schema}\n", + "\n", + "outputs = llm.generate(prompts, sampling_params)\n", + "for prompt, output in zip(prompts, outputs):\n", + " print_highlight(\"===============================\")\n", + " print_highlight(f\"Prompt: {prompt}\\nGenerated text: {output['text']}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EBNF\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prompts = [\n", + " \"Give me the information of the capital of France.\",\n", + " \"Give me the information of the capital of Germany.\",\n", + " \"Give me the information of the capital of Italy.\",\n", + "]\n", + "\n", + "sampling_params = {\n", + " \"temperature\": 0.8,\n", + " \"top_p\": 0.95,\n", + " \"ebnf\": (\n", + " \"root ::= city | description\\n\"\n", + " 'city ::= \"London\" | \"Paris\" | \"Berlin\" | \"Rome\"\\n'\n", + " 'description ::= city \" is \" status\\n'\n", + " 'status ::= \"the capital of \" country\\n'\n", + " 'country ::= \"England\" | \"France\" | \"Germany\" | \"Italy\"'\n", + " ),\n", + "}\n", + "\n", + "outputs = llm.generate(prompts, sampling_params)\n", + "for prompt, output in zip(prompts, outputs):\n", + " print_highlight(\"===============================\")\n", + " print_highlight(f\"Prompt: {prompt}\\nGenerated text: {output['text']}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Regular expression" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prompts = [\n", + " \"Please provide information about London as a major global city:\",\n", + " \"Please provide information about Paris as a major global city:\",\n", + "]\n", + "\n", + "sampling_params = {\"temperature\": 0.8, \"top_p\": 0.95, \"regex\": \"(France|England)\"}\n", + "\n", + "outputs = llm.generate(prompts, sampling_params)\n", + "for prompt, output in zip(prompts, outputs):\n", + " print_highlight(\"===============================\")\n", + " print_highlight(f\"Prompt: {prompt}\\nGenerated text: {output['text']}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Structural Tag" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "text = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "prompts = [text]\n", + "\n", + "\n", + "sampling_params = {\n", + " \"temperature\": 0.8,\n", + " \"top_p\": 0.95,\n", + " \"structural_tag\": json.dumps(\n", + " {\n", + " \"type\": \"structural_tag\",\n", + " \"structures\": [\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_weather,\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_date,\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"triggers\": [\"\",\n", + " \"content\": {\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": schema_get_current_weather,\n", + " },\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"content\": {\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": schema_get_current_date,\n", + " },\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"at_least_one\": False,\n", + " \"stop_after_first\": False,\n", + " },\n", + " }\n", + " ),\n", + "}\n", + "\n", + "\n", + "# Send POST request to the API endpoint\n", + "outputs = llm.generate(prompts, sampling_params)\n", + "for prompt, output in zip(prompts, outputs):\n", + " print_highlight(\"===============================\")\n", + " print_highlight(f\"Prompt: {prompt}\\nGenerated text: {output['text']}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "llm.shutdown()" + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/advanced_features/structured_outputs.mdx b/docs_new/docs/advanced_features/structured_outputs.mdx new file mode 100644 index 000000000..cb9b0b464 --- /dev/null +++ b/docs_new/docs/advanced_features/structured_outputs.mdx @@ -0,0 +1,803 @@ +--- +title: "Structured Outputs" +metatags: + description: "SGLang structured outputs: JSON schema, regex, EBNF constraints. XGrammar, Outlines, Llguidance backends for guaranteed output format." +--- +You can specify a JSON schema, [regular expression](https://en.wikipedia.org/wiki/Regular_expression) or [EBNF](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) to constrain the model output. The model output will be guaranteed to follow the given constraints. Only one constraint parameter (`json_schema`, `regex`, or `ebnf`) can be specified for a request. + +SGLang supports three grammar backends: + +- [XGrammar](https://github.com/mlc-ai/xgrammar)(default): Supports JSON schema, regular expression, and EBNF constraints. +- [Outlines](https://github.com/dottxt-ai/outlines): Supports JSON schema and regular expression constraints. +- [Llguidance](https://github.com/guidance-ai/llguidance): Supports JSON schema, regular expression, and EBNF constraints. + +We suggest using XGrammar for its better performance and utility. XGrammar currently uses the [GGML BNF format](https://github.com/ggerganov/llama.cpp/blob/master/grammars/README). For more details, see [XGrammar technical overview](https://blog.mlc.ai/2024/11/22/achieving-efficient-flexible-portable-structured-generation-with-xgrammar). + +To use Outlines, simply add `--grammar-backend outlines` when launching the server. +To use llguidance, add `--grammar-backend llguidance` when launching the server. +If no backend is specified, XGrammar will be used as the default. + +For better output quality, **It's advisable to explicitly include instructions in the prompt to guide the model to generate the desired format.** For example, you can specify, 'Please generate the output in the following JSON format: ...'. + + + +## OpenAI Compatible API + + + +```python Example +import openai +import os + +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process + +os.environ["TOKENIZERS_PARALLELISM"] = "false" + + +server_process, port = launch_server_cmd( + "python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --host 0.0.0.0 --log-level warning" +) + +wait_for_server(f"http://localhost:{port}") +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") +``` + +### JSON + +you can directly define a JSON schema or use [Pydantic](https://docs.pydantic.dev/latest/) to define and validate the response. + + +**Using Pydantic** + + + +```python Example +from pydantic import BaseModel, Field + + +# Define the schema using Pydantic +class CapitalInfo(BaseModel): + name: str = Field(..., pattern=r"^\w+$", description="Name of the capital city") + population: int = Field(..., description="Population of the capital city") + + +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3.1-8B-Instruct", + messages=[ + { + "role": "user", + "content": "Please generate the information of the capital of France in the JSON format.", + }, + ], + temperature=0, + max_tokens=128, + response_format={ + "type": "json_schema", + "json_schema": { + "name": "foo", + # convert the pydantic model to json schema + "schema": CapitalInfo.model_json_schema(), + }, + }, +) + +response_content = response.choices[0].message.content +# validate the JSON response by the pydantic model +capital_info = CapitalInfo.model_validate_json(response_content) +print_highlight(f"Validated response: {capital_info.model_dump_json()}") +``` + +**JSON Schema Directly** + + + + +```python Example +import json + +json_schema = json.dumps( + { + "type": "object", + "properties": { + "name": {"type": "string", "pattern": "^[\\w]+$"}, + "population": {"type": "integer"}, + }, + "required": ["name", "population"], + } +) + +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3.1-8B-Instruct", + messages=[ + { + "role": "user", + "content": "Give me the information of the capital of France in the JSON format.", + }, + ], + temperature=0, + max_tokens=128, + response_format={ + "type": "json_schema", + "json_schema": {"name": "foo", "schema": json.loads(json_schema)}, + }, +) + +print_highlight(response.choices[0].message.content) +``` + +### EBNF + + + +```python Example +ebnf_grammar = """ +root ::= city | description +city ::= "London" | "Paris" | "Berlin" | "Rome" +description ::= city " is " status +status ::= "the capital of " country +country ::= "England" | "France" | "Germany" | "Italy" +""" + +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3.1-8B-Instruct", + messages=[ + {"role": "system", "content": "You are a helpful geography bot."}, + { + "role": "user", + "content": "Give me the information of the capital of France.", + }, + ], + temperature=0, + max_tokens=32, + extra_body={"ebnf": ebnf_grammar}, +) + +print_highlight(response.choices[0].message.content) +``` + +### Regular expression + + + +```python Example +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3.1-8B-Instruct", + messages=[ + {"role": "user", "content": "What is the capital of France?"}, + ], + temperature=0, + max_tokens=128, + extra_body={"regex": "(Paris|London)"}, +) + +print_highlight(response.choices[0].message.content) +``` + +### Structural Tag + + + +```python Example +tool_get_current_weather = { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "The city to find the weather for, e.g. 'San Francisco'", + }, + "state": { + "type": "string", + "description": "the two-letter abbreviation for the state that the city is" + " in, e.g. 'CA' which would mean 'California'", + }, + "unit": { + "type": "string", + "description": "The unit to fetch the temperature in", + "enum": ["celsius", "fahrenheit"], + }, + }, + "required": ["city", "state", "unit"], + }, + }, +} + +tool_get_current_date = { + "type": "function", + "function": { + "name": "get_current_date", + "description": "Get the current date and time for a given timezone", + "parameters": { + "type": "object", + "properties": { + "timezone": { + "type": "string", + "description": "The timezone to fetch the current date and time for, e.g. 'America/New_York'", + } + }, + "required": ["timezone"], + }, + }, +} + +schema_get_current_weather = tool_get_current_weather["function"]["parameters"] +schema_get_current_date = tool_get_current_date["function"]["parameters"] + + +def get_messages(): + return [ + { + "role": "system", + "content": f""" +# Tool Instructions +- Always execute python code in messages that you share. +- When looking for real time information use relevant functions if available else fallback to brave_search +You have access to the following functions: +Use the function 'get_current_weather' to: Get the current weather in a given location +{tool_get_current_weather["function"]} +Use the function 'get_current_date' to: Get the current date and time for a given timezone +{tool_get_current_date["function"]} +If a you choose to call a function ONLY reply in the following format: +<{{start_tag}}={{function_name}}>{{parameters}}{{end_tag}} +where +start_tag => ` a JSON dict with the function argument name as key and function argument value as value. +end_tag => `</function>` +Here is an example, +<function=example_function_name>{{"example_name": "example_value"}}</function> +Reminder: +- Function calls MUST follow the specified format +- Required parameters MUST be specified +- Only call one function at a time +- Put the entire function call reply on one line +- Always add your sources when using search results to answer the user query +You are a helpful assistant.""", + }, + { + "role": "user", + "content": "You are in New York. Please get the current date and time, and the weather.", + }, + ] + + +messages = get_messages() + +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3.1-8B-Instruct", + messages=messages, + response_format={ + "type": "structural_tag", + "structures": [ + { + "begin": "<function=get_current_weather>", + "schema": schema_get_current_weather, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "schema": schema_get_current_date, + "end": "</function>", + }, + ], + "triggers": ["<function="], + }, +) + +print_highlight(response.choices[0].message.content) +``` + + +```python Example +# Support for XGrammar latest structural tag format +# https://xgrammar.mlc.ai/docs/tutorials/structural_tag.html + +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3.1-8B-Instruct", + messages=messages, + response_format={ + "type": "structural_tag", + "format": { + "type": "triggered_tags", + "triggers": ["<function="], + "tags": [ + { + "begin": "<function=get_current_weather>", + "content": { + "type": "json_schema", + "json_schema": schema_get_current_weather, + }, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "content": { + "type": "json_schema", + "json_schema": schema_get_current_date, + }, + "end": "</function>", + }, + ], + "at_least_one": False, + "stop_after_first": False, + }, + }, +) + +print_highlight(response.choices[0].message.content) +``` + +## Native API and SGLang Runtime (SRT) + + +### JSON + + +**Using Pydantic** + + + +```python Example +import requests +import json +from pydantic import BaseModel, Field + +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct") + + +# Define the schema using Pydantic +class CapitalInfo(BaseModel): + name: str = Field(..., pattern=r"^\w+$", description="Name of the capital city") + population: int = Field(..., description="Population of the capital city") + + +# Make API request +messages = [ + { + "role": "user", + "content": "Here is the information of the capital of France in the JSON format.\n", + } +] +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": text, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 64, + "json_schema": json.dumps(CapitalInfo.model_json_schema()), + }, + }, +) +print_highlight(response.json()) + + +response_data = json.loads(response.json()["text"]) +# validate the response by the pydantic model +capital_info = CapitalInfo.model_validate(response_data) +print_highlight(f"Validated response: {capital_info.model_dump_json()}") +``` + +**JSON Schema Directly** + + + +```python Example +json_schema = json.dumps( + { + "type": "object", + "properties": { + "name": {"type": "string", "pattern": "^[\\w]+$"}, + "population": {"type": "integer"}, + }, + "required": ["name", "population"], + } +) + +# JSON +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": text, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 64, + "json_schema": json_schema, + }, + }, +) + +print_highlight(response.json()) +``` + +### EBNF + + + +```python Example +messages = [ + { + "role": "user", + "content": "Give me the information of the capital of France.", + } +] +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": text, + "sampling_params": { + "max_new_tokens": 128, + "temperature": 0, + "n": 3, + "ebnf": ( + "root ::= city | description\n" + 'city ::= "London" | "Paris" | "Berlin" | "Rome"\n' + 'description ::= city " is " status\n' + 'status ::= "the capital of " country\n' + 'country ::= "England" | "France" | "Germany" | "Italy"' + ), + }, + "stream": False, + "return_logprob": False, + }, +) + +print_highlight(response.json()) +``` + +### Regular expression + + + +```python Example +messages = [ + { + "role": "user", + "content": "Paris is the capital of", + } +] +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": text, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 64, + "regex": "(France|England)", + }, + }, +) +print_highlight(response.json()) +``` + +### Structural Tag + + + +```python Example +from transformers import AutoTokenizer + +# generate an answer +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct") + +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +payload = { + "text": text, + "sampling_params": { + "structural_tag": json.dumps( + { + "type": "structural_tag", + "structures": [ + { + "begin": "<function=get_current_weather>", + "schema": schema_get_current_weather, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "schema": schema_get_current_date, + "end": "</function>", + }, + ], + "triggers": ["<function="], + } + ) + }, +} + + +# Send POST request to the API endpoint +response = requests.post(f"http://localhost:{port}/generate", json=payload) +print_highlight(response.json()) +``` + + +```python Example +# Support for XGrammar latest structural tag format +# https://xgrammar.mlc.ai/docs/tutorials/structural_tag.html + +payload = { + "text": text, + "sampling_params": { + "structural_tag": json.dumps( + { + "type": "structural_tag", + "format": { + "type": "triggered_tags", + "triggers": ["<function="], + "tags": [ + { + "begin": "<function=get_current_weather>", + "content": { + "type": "json_schema", + "json_schema": schema_get_current_weather, + }, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "content": { + "type": "json_schema", + "json_schema": schema_get_current_date, + }, + "end": "</function>", + }, + ], + "at_least_one": False, + "stop_after_first": False, + }, + } + ) + }, +} + + +# Send POST request to the API endpoint +response = requests.post(f"http://localhost:{port}/generate", json=payload) +print_highlight(response.json()) +``` + + +```python Example +terminate_process(server_process) +``` + +## Offline Engine API + + + +```python Example +import sglang as sgl + +llm = sgl.Engine( + model_path="meta-llama/Meta-Llama-3.1-8B-Instruct", grammar_backend="xgrammar" +) +``` + +### JSON + + +**Using Pydantic** + + + +```python Example +import json +from pydantic import BaseModel, Field + + +prompts = [ + "Give me the information of the capital of China in the JSON format.", + "Give me the information of the capital of France in the JSON format.", + "Give me the information of the capital of Ireland in the JSON format.", +] + + +# Define the schema using Pydantic +class CapitalInfo(BaseModel): + name: str = Field(..., pattern=r"^\w+$", description="Name of the capital city") + population: int = Field(..., description="Population of the capital city") + + +sampling_params = { + "temperature": 0.1, + "top_p": 0.95, + "json_schema": json.dumps(CapitalInfo.model_json_schema()), +} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print_highlight("===============================") + print_highlight(f"Prompt: {prompt}") # validate the output by the pydantic model + capital_info = CapitalInfo.model_validate_json(output["text"]) + print_highlight(f"Validated output: {capital_info.model_dump_json()}") +``` + +**JSON Schema Directly** + + + +```python Example +prompts = [ + "Give me the information of the capital of China in the JSON format.", + "Give me the information of the capital of France in the JSON format.", + "Give me the information of the capital of Ireland in the JSON format.", +] + +json_schema = json.dumps( + { + "type": "object", + "properties": { + "name": {"type": "string", "pattern": "^[\\w]+$"}, + "population": {"type": "integer"}, + }, + "required": ["name", "population"], + } +) + +sampling_params = {"temperature": 0.1, "top_p": 0.95, "json_schema": json_schema} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print_highlight("===============================") + print_highlight(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + +### EBNF + + + + +```python Example +prompts = [ + "Give me the information of the capital of France.", + "Give me the information of the capital of Germany.", + "Give me the information of the capital of Italy.", +] + +sampling_params = { + "temperature": 0.8, + "top_p": 0.95, + "ebnf": ( + "root ::= city | description\n" + 'city ::= "London" | "Paris" | "Berlin" | "Rome"\n' + 'description ::= city " is " status\n' + 'status ::= "the capital of " country\n' + 'country ::= "England" | "France" | "Germany" | "Italy"' + ), +} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print_highlight("===============================") + print_highlight(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + +### Regular expression + + + +```python Example +prompts = [ + "Please provide information about London as a major global city:", + "Please provide information about Paris as a major global city:", +] + +sampling_params = {"temperature": 0.8, "top_p": 0.95, "regex": "(France|England)"} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print_highlight("===============================") + print_highlight(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + +### Structural Tag + + + +```python Example +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +prompts = [text] + + +sampling_params = { + "temperature": 0.8, + "top_p": 0.95, + "structural_tag": json.dumps( + { + "type": "structural_tag", + "structures": [ + { + "begin": "<function=get_current_weather>", + "schema": schema_get_current_weather, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "schema": schema_get_current_date, + "end": "</function>", + }, + ], + "triggers": ["<function="], + } + ), +} + + +# Send POST request to the API endpoint +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print_highlight("===============================") + print_highlight(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + + +```python Example +# Support for XGrammar latest structural tag format +# https://xgrammar.mlc.ai/docs/tutorials/structural_tag.html + +sampling_params = { + "temperature": 0.8, + "top_p": 0.95, + "structural_tag": json.dumps( + { + "type": "structural_tag", + "format": { + "type": "triggered_tags", + "triggers": ["<function="], + "tags": [ + { + "begin": "<function=get_current_weather>", + "content": { + "type": "json_schema", + "json_schema": schema_get_current_weather, + }, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "content": { + "type": "json_schema", + "json_schema": schema_get_current_date, + }, + "end": "</function>", + }, + ], + "at_least_one": False, + "stop_after_first": False, + }, + } + ), +} + + +# Send POST request to the API endpoint +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print_highlight("===============================") + print_highlight(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + + +```python Example +llm.shutdown() +``` diff --git a/docs_new/docs/advanced_features/structured_outputs_for_reasoning_models.ipynb b/docs_new/docs/advanced_features/structured_outputs_for_reasoning_models.ipynb new file mode 100644 index 000000000..d05f9e950 --- /dev/null +++ b/docs_new/docs/advanced_features/structured_outputs_for_reasoning_models.ipynb @@ -0,0 +1,841 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Structured Outputs For Reasoning Models\n", + "\n", + "When working with reasoning models that use special tokens like `...` to denote reasoning sections, you might want to allow free-form text within these sections while still enforcing grammar constraints on the rest of the output.\n", + "\n", + "SGLang provides a feature to disable grammar restrictions within reasoning sections. This is particularly useful for models that need to perform complex reasoning steps before providing a structured output.\n", + "\n", + "To enable this feature, use the `--reasoning-parser` flag which decide the think_end_token, such as `
`, when launching the server. You can also specify the reasoning parser using the `--reasoning-parser` flag.\n", + "\n", + "## Supported Models\n", + "\n", + "Currently, SGLang supports the following reasoning models:\n", + "- [DeepSeek R1 series](https://huggingface.co/collections/deepseek-ai/deepseek-r1-678e1e131c0169c0bc89728d): The reasoning content is wrapped with `` and `` tags.\n", + "- [QwQ](https://huggingface.co/Qwen/QwQ-32B): The reasoning content is wrapped with `` and `` tags.\n", + "\n", + "\n", + "## Usage\n", + "\n", + "## OpenAI Compatible API" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Specify the `--grammar-backend`, `--reasoning-parser` option." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import openai\n", + "import os\n", + "\n", + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n", + "\n", + "\n", + "server_process, port = launch_server_cmd(\n", + " \"python -m sglang.launch_server --model-path deepseek-ai/DeepSeek-R1-Distill-Qwen-7B --host 0.0.0.0 --reasoning-parser deepseek-r1 --log-level warning\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")\n", + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### JSON\n", + "\n", + "you can directly define a JSON schema or use [Pydantic](https://docs.pydantic.dev/latest/) to define and validate the response." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Using Pydantic**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from pydantic import BaseModel, Field\n", + "\n", + "\n", + "# Define the schema using Pydantic\n", + "class CapitalInfo(BaseModel):\n", + " name: str = Field(..., pattern=r\"^\\w+$\", description=\"Name of the capital city\")\n", + " population: int = Field(..., description=\"Population of the capital city\")\n", + "\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\",\n", + " messages=[\n", + " {\n", + " \"role\": \"assistant\",\n", + " \"content\": \"Give me the information and population of the capital of France in the JSON format.\",\n", + " },\n", + " ],\n", + " temperature=0,\n", + " max_tokens=2048,\n", + " response_format={\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": {\n", + " \"name\": \"foo\",\n", + " # convert the pydantic model to json schema\n", + " \"schema\": CapitalInfo.model_json_schema(),\n", + " },\n", + " },\n", + ")\n", + "\n", + "print_highlight(\n", + " f\"reasoing_content: {response.choices[0].message.reasoning_content}\\n\\ncontent: {response.choices[0].message.content}\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**JSON Schema Directly**\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "json_schema = json.dumps(\n", + " {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"name\": {\"type\": \"string\", \"pattern\": \"^[\\\\w]+$\"},\n", + " \"population\": {\"type\": \"integer\"},\n", + " },\n", + " \"required\": [\"name\", \"population\"],\n", + " }\n", + ")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\",\n", + " messages=[\n", + " {\n", + " \"role\": \"assistant\",\n", + " \"content\": \"Give me the information and population of the capital of France in the JSON format.\",\n", + " },\n", + " ],\n", + " temperature=0,\n", + " max_tokens=2048,\n", + " response_format={\n", + " \"type\": \"json_schema\",\n", + " \"json_schema\": {\"name\": \"foo\", \"schema\": json.loads(json_schema)},\n", + " },\n", + ")\n", + "\n", + "print_highlight(\n", + " f\"reasoing_content: {response.choices[0].message.reasoning_content}\\n\\ncontent: {response.choices[0].message.content}\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EBNF" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "ebnf_grammar = \"\"\"\n", + "root ::= city | description\n", + "city ::= \"London\" | \"Paris\" | \"Berlin\" | \"Rome\"\n", + "description ::= city \" is \" status\n", + "status ::= \"the capital of \" country\n", + "country ::= \"England\" | \"France\" | \"Germany\" | \"Italy\"\n", + "\"\"\"\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\",\n", + " messages=[\n", + " {\"role\": \"system\", \"content\": \"You are a helpful geography bot.\"},\n", + " {\n", + " \"role\": \"assistant\",\n", + " \"content\": \"Give me the information and population of the capital of France in the JSON format.\",\n", + " },\n", + " ],\n", + " temperature=0,\n", + " max_tokens=2048,\n", + " extra_body={\"ebnf\": ebnf_grammar},\n", + ")\n", + "\n", + "print_highlight(\n", + " f\"reasoing_content: {response.choices[0].message.reasoning_content}\\n\\ncontent: {response.choices[0].message.content}\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Regular expression" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = client.chat.completions.create(\n", + " model=\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\",\n", + " messages=[\n", + " {\"role\": \"assistant\", \"content\": \"What is the capital of France?\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=2048,\n", + " extra_body={\"regex\": \"(Paris|London)\"},\n", + ")\n", + "\n", + "print_highlight(\n", + " f\"reasoing_content: {response.choices[0].message.reasoning_content}\\n\\ncontent: {response.choices[0].message.content}\"\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Structural Tag" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tool_get_current_weather = {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"get_current_weather\",\n", + " \"description\": \"Get the current weather in a given location\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"city\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The city to find the weather for, e.g. 'San Francisco'\",\n", + " },\n", + " \"state\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"the two-letter abbreviation for the state that the city is\"\n", + " \" in, e.g. 'CA' which would mean 'California'\",\n", + " },\n", + " \"unit\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The unit to fetch the temperature in\",\n", + " \"enum\": [\"celsius\", \"fahrenheit\"],\n", + " },\n", + " },\n", + " \"required\": [\"city\", \"state\", \"unit\"],\n", + " },\n", + " },\n", + "}\n", + "\n", + "tool_get_current_date = {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"get_current_date\",\n", + " \"description\": \"Get the current date and time for a given timezone\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"timezone\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The timezone to fetch the current date and time for, e.g. 'America/New_York'\",\n", + " }\n", + " },\n", + " \"required\": [\"timezone\"],\n", + " },\n", + " },\n", + "}\n", + "\n", + "schema_get_current_weather = tool_get_current_weather[\"function\"][\"parameters\"]\n", + "schema_get_current_date = tool_get_current_date[\"function\"][\"parameters\"]\n", + "\n", + "\n", + "def get_messages():\n", + " return [\n", + " {\n", + " \"role\": \"system\",\n", + " \"content\": f\"\"\"\n", + "# Tool Instructions\n", + "- Always execute python code in messages that you share.\n", + "- When looking for real time information use relevant functions if available else fallback to brave_search\n", + "You have access to the following functions:\n", + "Use the function 'get_current_weather' to: Get the current weather in a given location\n", + "{tool_get_current_weather[\"function\"]}\n", + "Use the function 'get_current_date' to: Get the current date and time for a given timezone\n", + "{tool_get_current_date[\"function\"]}\n", + "If a you choose to call a function ONLY reply in the following format:\n", + "<{{start_tag}}={{function_name}}>{{parameters}}{{end_tag}}\n", + "where\n", + "start_tag => ` a JSON dict with the function argument name as key and function argument value as value.\n", + "end_tag => ``\n", + "Here is an example,\n", + "{{\"example_name\": \"example_value\"}}\n", + "Reminder:\n", + "- Function calls MUST follow the specified format\n", + "- Required parameters MUST be specified\n", + "- Only call one function at a time\n", + "- Put the entire function call reply on one line\n", + "- Always add your sources when using search results to answer the user query\n", + "You are a helpful assistant.\"\"\",\n", + " },\n", + " {\n", + " \"role\": \"assistant\",\n", + " \"content\": \"You are in New York. Please get the current date and time, and the weather.\",\n", + " },\n", + " ]\n", + "\n", + "\n", + "messages = get_messages()\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\",\n", + " messages=messages,\n", + " response_format={\n", + " \"type\": \"structural_tag\",\n", + " \"max_new_tokens\": 2048,\n", + " \"structures\": [\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_weather,\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_date,\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"triggers\": [\" Note: For native API, as a work-around, you need to set `require_reasoning` argument to `True` to ensure the model will think before generating the structured output. It's not required for chat-completion API." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### JSON" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Using Pydantic**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "from pydantic import BaseModel, Field\n", + "from transformers import AutoTokenizer\n", + "\n", + "tokenizer = AutoTokenizer.from_pretrained(\"deepseek-ai/DeepSeek-R1-Distill-Qwen-7B\")\n", + "\n", + "\n", + "# Define the schema using Pydantic\n", + "class CapitalInfo(BaseModel):\n", + " name: str = Field(..., pattern=r\"^\\w+$\", description=\"Name of the capital city\")\n", + " population: int = Field(..., description=\"Population of the capital city\")\n", + "\n", + "\n", + "messages = [\n", + " {\n", + " \"role\": \"assistant\",\n", + " \"content\": \"Give me the information and population of the capital of France in the JSON format.\",\n", + " },\n", + "]\n", + "text = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "# Make API request\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": text,\n", + " \"require_reasoning\": True,\n", + " \"sampling_params\": {\n", + " \"temperature\": 0,\n", + " \"max_new_tokens\": 2048,\n", + " \"json_schema\": json.dumps(CapitalInfo.model_json_schema()),\n", + " },\n", + " },\n", + ")\n", + "print(response.json())\n", + "\n", + "\n", + "reasoing_content = response.json()[\"text\"].split(\"
\")[0]\n", + "content = response.json()[\"text\"].split(\"
\")[1]\n", + "print_highlight(f\"reasoing_content: {reasoing_content}\\n\\ncontent: {content}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**JSON Schema Directly**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "json_schema = json.dumps(\n", + " {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"name\": {\"type\": \"string\", \"pattern\": \"^[\\\\w]+$\"},\n", + " \"population\": {\"type\": \"integer\"},\n", + " },\n", + " \"required\": [\"name\", \"population\"],\n", + " }\n", + ")\n", + "\n", + "# JSON\n", + "text = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": text,\n", + " \"require_reasoning\": True,\n", + " \"sampling_params\": {\n", + " \"temperature\": 0,\n", + " \"max_new_tokens\": 2048,\n", + " \"json_schema\": json_schema,\n", + " },\n", + " },\n", + ")\n", + "\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### EBNF" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": \"Give me the information of the capital of France.\",\n", + " \"require_reasoning\": True,\n", + " \"sampling_params\": {\n", + " \"max_new_tokens\": 2048,\n", + " \"temperature\": 0,\n", + " \"n\": 3,\n", + " \"ebnf\": (\n", + " \"root ::= city | description\\n\"\n", + " 'city ::= \"London\" | \"Paris\" | \"Berlin\" | \"Rome\"\\n'\n", + " 'description ::= city \" is \" status\\n'\n", + " 'status ::= \"the capital of \" country\\n'\n", + " 'country ::= \"England\" | \"France\" | \"Germany\" | \"Italy\"'\n", + " ),\n", + " },\n", + " \"stream\": False,\n", + " \"return_logprob\": False,\n", + " },\n", + ")\n", + "\n", + "print(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Regular expression" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": \"Paris is the capital of\",\n", + " \"require_reasoning\": True,\n", + " \"sampling_params\": {\n", + " \"temperature\": 0,\n", + " \"max_new_tokens\": 2048,\n", + " \"regex\": \"(France|England)\",\n", + " },\n", + " },\n", + ")\n", + "print(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Structural Tag" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "text = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, return_dict=False\n", + ")\n", + "payload = {\n", + " \"text\": text,\n", + " \"require_reasoning\": True,\n", + " \"sampling_params\": {\n", + " \"max_new_tokens\": 2048,\n", + " \"structural_tag\": json.dumps(\n", + " {\n", + " \"type\": \"structural_tag\",\n", + " \"structures\": [\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_weather,\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_date,\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"triggers\": [\"\",\n", + " \"schema\": schema_get_current_weather,\n", + " \"end\": \"\",\n", + " },\n", + " {\n", + " \"begin\": \"\",\n", + " \"schema\": schema_get_current_date,\n", + " \"end\": \"\",\n", + " },\n", + " ],\n", + " \"triggers\": [\"{{parameters}}{{end_tag}} +where +start_tag => ` a JSON dict with the function argument name as key and function argument value as value. +end_tag => `</function>` +Here is an example, +<function=example_function_name>{{"example_name": "example_value"}}</function> +Reminder: +- Function calls MUST follow the specified format +- Required parameters MUST be specified +- Only call one function at a time +- Put the entire function call reply on one line +- Always add your sources when using search results to answer the user query +You are a helpful assistant.""", + }, + { + "role": "assistant", + "content": "You are in New York. Please get the current date and time, and the weather.", + }, + ] + + +messages = get_messages() + +response = client.chat.completions.create( + model="deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", + messages=messages, + response_format={ + "type": "structural_tag", + "max_new_tokens": 2048, + "structures": [ + { + "begin": "<function=get_current_weather>", + "schema": schema_get_current_weather, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "schema": schema_get_current_date, + "end": "</function>", + }, + ], + "triggers": ["<function="], + }, +) + +print_highlight( + f"reasoing_content: {response.choices[0].message.reasoning_content}\n\ncontent: {response.choices[0].message.content}" +) +``` + +## Native API and SGLang Runtime (SRT) + + +> Note: For native API, as a work-around, you need to set `require_reasoning` argument to `True` to ensure the model will think before generating the structured output. It's not required for chat-completion API. + + +### JSON + + +**Using Pydantic** + + + +```python Example +import requests +from pydantic import BaseModel, Field +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-R1-Distill-Qwen-7B") + + +# Define the schema using Pydantic +class CapitalInfo(BaseModel): + name: str = Field(..., pattern=r"^\w+$", description="Name of the capital city") + population: int = Field(..., description="Population of the capital city") + + +messages = [ + { + "role": "assistant", + "content": "Give me the information and population of the capital of France in the JSON format.", + }, +] +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +# Make API request +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": text, + "require_reasoning": True, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 2048, + "json_schema": json.dumps(CapitalInfo.model_json_schema()), + }, + }, +) +print(response.json()) + + +reasoing_content = response.json()["text"].split("</think>")[0] +content = response.json()["text"].split("</think>")[1] +print_highlight(f"reasoing_content: {reasoing_content}\n\ncontent: {content}") +``` + +**JSON Schema Directly** + + + +```python Example +json_schema = json.dumps( + { + "type": "object", + "properties": { + "name": {"type": "string", "pattern": "^[\\w]+$"}, + "population": {"type": "integer"}, + }, + "required": ["name", "population"], + } +) + +# JSON +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": text, + "require_reasoning": True, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 2048, + "json_schema": json_schema, + }, + }, +) + +print_highlight(response.json()) +``` + +### EBNF + + + +```python Example +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": "Give me the information of the capital of France.", + "require_reasoning": True, + "sampling_params": { + "max_new_tokens": 2048, + "temperature": 0, + "n": 3, + "ebnf": ( + "root ::= city | description\n" + 'city ::= "London" | "Paris" | "Berlin" | "Rome"\n' + 'description ::= city " is " status\n' + 'status ::= "the capital of " country\n' + 'country ::= "England" | "France" | "Germany" | "Italy"' + ), + }, + "stream": False, + "return_logprob": False, + }, +) + +print(response.json()) +``` + +### Regular expression + + + +```python Example +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": "Paris is the capital of", + "require_reasoning": True, + "sampling_params": { + "temperature": 0, + "max_new_tokens": 2048, + "regex": "(France|England)", + }, + }, +) +print(response.json()) +``` + +### Structural Tag + + + +```python Example +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +payload = { + "text": text, + "require_reasoning": True, + "sampling_params": { + "max_new_tokens": 2048, + "structural_tag": json.dumps( + { + "type": "structural_tag", + "structures": [ + { + "begin": "<function=get_current_weather>", + "schema": schema_get_current_weather, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "schema": schema_get_current_date, + "end": "</function>", + }, + ], + "triggers": ["<function="], + } + ), + }, +} + + +# Send POST request to the API endpoint +response = requests.post(f"http://localhost:{port}/generate", json=payload) +print_highlight(response.json()) +``` + + +```python Example +terminate_process(server_process) +``` + +## Offline Engine API + + + +```python Example +import sglang as sgl + +llm = sgl.Engine( + model_path="deepseek-ai/DeepSeek-R1-Distill-Qwen-7B", + reasoning_parser="deepseek-r1", + grammar_backend="xgrammar", +) +``` + +### JSON + + +**Using Pydantic** + + + +```python Example +import json +from pydantic import BaseModel, Field + + +prompts = [ + "Give me the information of the capital of China in the JSON format.", + "Give me the information of the capital of France in the JSON format.", + "Give me the information of the capital of Ireland in the JSON format.", +] + + +# Define the schema using Pydantic +class CapitalInfo(BaseModel): + name: str = Field(..., pattern=r"^\w+$", description="Name of the capital city") + population: int = Field(..., description="Population of the capital city") + + +sampling_params = { + "temperature": 0, + "top_p": 0.95, + "max_new_tokens": 2048, + "json_schema": json.dumps(CapitalInfo.model_json_schema()), +} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print("===============================") + print(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + +**JSON Schema Directly** + + + +```python Example +prompts = [ + "Give me the information of the capital of China in the JSON format.", + "Give me the information of the capital of France in the JSON format.", + "Give me the information of the capital of Ireland in the JSON format.", +] + +json_schema = json.dumps( + { + "type": "object", + "properties": { + "name": {"type": "string", "pattern": "^[\\w]+$"}, + "population": {"type": "integer"}, + }, + "required": ["name", "population"], + } +) + +sampling_params = {"temperature": 0, "max_new_tokens": 2048, "json_schema": json_schema} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print("===============================") + print(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + +### EBNF + + + + +```python Example +prompts = [ + "Give me the information of the capital of France.", + "Give me the information of the capital of Germany.", + "Give me the information of the capital of Italy.", +] + +sampling_params = { + "temperature": 0.8, + "top_p": 0.95, + "ebnf": ( + "root ::= city | description\n" + 'city ::= "London" | "Paris" | "Berlin" | "Rome"\n' + 'description ::= city " is " status\n' + 'status ::= "the capital of " country\n' + 'country ::= "England" | "France" | "Germany" | "Italy"' + ), +} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print("===============================") + print(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + +### Regular expression + + + +```python Example +prompts = [ + "Please provide information about London as a major global city:", + "Please provide information about Paris as a major global city:", +] + +sampling_params = {"temperature": 0.8, "top_p": 0.95, "regex": "(France|England)"} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print("===============================") + print(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + + +```python Example +text = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, return_dict=False +) +prompts = [text] + + +sampling_params = { + "temperature": 0.8, + "top_p": 0.95, + "max_new_tokens": 2048, + "structural_tag": json.dumps( + { + "type": "structural_tag", + "structures": [ + { + "begin": "<function=get_current_weather>", + "schema": schema_get_current_weather, + "end": "</function>", + }, + { + "begin": "<function=get_current_date>", + "schema": schema_get_current_date, + "end": "</function>", + }, + ], + "triggers": ["<function="], + } + ), +} + + +# Send POST request to the API endpoint +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print("===============================") + print(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + + +```python Example +llm.shutdown() +``` diff --git a/docs_new/docs/advanced_features/tool_parser.ipynb b/docs_new/docs/advanced_features/tool_parser.ipynb new file mode 100644 index 000000000..df1bc4bc7 --- /dev/null +++ b/docs_new/docs/advanced_features/tool_parser.ipynb @@ -0,0 +1,854 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Tool Parser\n", + "\n", + "This guide demonstrates how to use SGLang’s [Function calling](https://platform.openai.com/docs/guides/function-calling) functionality." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Currently supported parsers:\n", + "\n", + "| Parser | Supported Models | Notes |\n", + "|---|---|---|\n", + "| `deepseekv3` | DeepSeek-v3 (e.g., `deepseek-ai/DeepSeek-V3-0324`) | Recommend adding `--chat-template ./examples/chat_template/tool_chat_template_deepseekv3.jinja` to launch command. |\n", + "| `deepseekv31` | DeepSeek-V3.1 and DeepSeek-V3.2-Exp (e.g. `deepseek-ai/DeepSeek-V3.1`, `deepseek-ai/DeepSeek-V3.2-Exp`) | Recommend adding `--chat-template ./examples/chat_template/tool_chat_template_deepseekv31.jinja` (Or ..deepseekv32.jinja for DeepSeek-V3.2) to launch command. |\n", + "| `deepseekv32` | DeepSeek-V3.2 (`deepseek-ai/DeepSeek-V3.2`) | |\n", + "| `glm` | GLM series (e.g. `zai-org/GLM-4.6`) | |\n", + "| `gpt-oss` | GPT-OSS (e.g., `openai/gpt-oss-120b`, `openai/gpt-oss-20b`, `lmsys/gpt-oss-120b-bf16`, `lmsys/gpt-oss-20b-bf16`) | The gpt-oss tool parser filters out analysis channel events and only preserves normal text. This can cause the content to be empty when explanations are in the analysis channel. To work around this, complete the tool round by returning tool results as `role=\"tool\"` messages, which enables the model to generate the final content. |\n", + "| `kimi_k2` | `moonshotai/Kimi-K2-Instruct` | |\n", + "| `llama3` | Llama 3.1 / 3.2 / 3.3 (e.g. `meta-llama/Llama-3.1-8B-Instruct`, `meta-llama/Llama-3.2-1B-Instruct`, `meta-llama/Llama-3.3-70B-Instruct`) | |\n", + "| `llama4` | Llama 4 (e.g. `meta-llama/Llama-4-Scout-17B-16E-Instruct`) | |\n", + "| `mistral` | Mistral (e.g. `mistralai/Mistral-7B-Instruct-v0.3`, `mistralai/Mistral-Nemo-Instruct-2407`, `mistralai/Mistral-7B-v0.3`) | |\n", + "| `pythonic` | Llama-3.2 / Llama-3.3 / Llama-4 | Model outputs function calls as Python code. Requires `--tool-call-parser pythonic` and is recommended to use with a specific chat template. |\n", + "| `qwen` | Qwen series (e.g. `Qwen/Qwen3-Next-80B-A3B-Instruct`, `Qwen/Qwen3-VL-30B-A3B-Thinking`) except Qwen3-Coder| |\n", + "| `qwen3_coder` | Qwen3-Coder (e.g. `Qwen/Qwen3-Coder-30B-A3B-Instruct`) | |\n", + "| `step3` | Step-3 | |\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## OpenAI Compatible API" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Launching the Server" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "from openai import OpenAI\n", + "\n", + "server_process, port = launch_server_cmd(\n", + " \"python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --tool-call-parser qwen25 --host 0.0.0.0 --log-level warning\" # qwen25\n", + ")\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that `--tool-call-parser` defines the parser used to interpret responses." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Define Tools for Function Call\n", + "Below is a Python snippet that shows how to define a tool as a dictionary. The dictionary includes a tool name, a description, and property defined Parameters." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Define tools\n", + "tools = [\n", + " {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"get_current_weather\",\n", + " \"description\": \"Get the current weather in a given location\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"city\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The city to find the weather for, e.g. 'San Francisco'\",\n", + " },\n", + " \"state\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"the two-letter abbreviation for the state that the city is\"\n", + " \" in, e.g. 'CA' which would mean 'California'\",\n", + " },\n", + " \"unit\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The unit to fetch the temperature in\",\n", + " \"enum\": [\"celsius\", \"fahrenheit\"],\n", + " },\n", + " },\n", + " \"required\": [\"city\", \"state\", \"unit\"],\n", + " },\n", + " },\n", + " }\n", + "]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Define Messages" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def get_messages():\n", + " return [\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": \"What's the weather like in Boston today? Output a reasoning before act, then use the tools to help you.\",\n", + " }\n", + " ]\n", + "\n", + "\n", + "messages = get_messages()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Initialize the Client" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Initialize OpenAI-like client\n", + "client = OpenAI(api_key=\"None\", base_url=f\"http://0.0.0.0:{port}/v1\")\n", + "model_name = client.models.list().data[0].id" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Non-Streaming Request" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Non-streaming mode test\n", + "response_non_stream = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0,\n", + " top_p=0.95,\n", + " max_tokens=1024,\n", + " stream=False, # Non-streaming\n", + " tools=tools,\n", + ")\n", + "print_highlight(\"Non-stream response:\")\n", + "print_highlight(response_non_stream)\n", + "print_highlight(\"==== content ====\")\n", + "print_highlight(response_non_stream.choices[0].message.content)\n", + "print_highlight(\"==== tool_calls ====\")\n", + "print_highlight(response_non_stream.choices[0].message.tool_calls)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Handle Tools\n", + "When the engine determines it should call a particular tool, it will return arguments or partial arguments through the response. You can parse these arguments and later invoke the tool accordingly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "name_non_stream = response_non_stream.choices[0].message.tool_calls[0].function.name\n", + "arguments_non_stream = (\n", + " response_non_stream.choices[0].message.tool_calls[0].function.arguments\n", + ")\n", + "\n", + "print_highlight(f\"Final streamed function call name: {name_non_stream}\")\n", + "print_highlight(f\"Final streamed function call arguments: {arguments_non_stream}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Streaming Request" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Streaming mode test\n", + "print_highlight(\"Streaming response:\")\n", + "response_stream = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0,\n", + " top_p=0.95,\n", + " max_tokens=1024,\n", + " stream=True, # Enable streaming\n", + " tools=tools,\n", + ")\n", + "\n", + "texts = \"\"\n", + "tool_calls = []\n", + "name = \"\"\n", + "arguments = \"\"\n", + "for chunk in response_stream:\n", + " if chunk.choices[0].delta.content:\n", + " texts += chunk.choices[0].delta.content\n", + " if chunk.choices[0].delta.tool_calls:\n", + " tool_calls.append(chunk.choices[0].delta.tool_calls[0])\n", + "print_highlight(\"==== Text ====\")\n", + "print_highlight(texts)\n", + "\n", + "print_highlight(\"==== Tool Call ====\")\n", + "for tool_call in tool_calls:\n", + " print_highlight(tool_call)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Handle Tools\n", + "When the engine determines it should call a particular tool, it will return arguments or partial arguments through the response. You can parse these arguments and later invoke the tool accordingly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Parse and combine function call arguments\n", + "arguments = []\n", + "for tool_call in tool_calls:\n", + " if tool_call.function.name:\n", + " print_highlight(f\"Streamed function call name: {tool_call.function.name}\")\n", + "\n", + " if tool_call.function.arguments:\n", + " arguments.append(tool_call.function.arguments)\n", + "\n", + "# Combine all fragments into a single JSON string\n", + "full_arguments = \"\".join(arguments)\n", + "print_highlight(f\"streamed function call arguments: {full_arguments}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Define a Tool Function" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# This is a demonstration, define real function according to your usage.\n", + "def get_current_weather(city: str, state: str, unit: \"str\"):\n", + " return (\n", + " f\"The weather in {city}, {state} is 85 degrees {unit}. It is \"\n", + " \"partly cloudly, with highs in the 90's.\"\n", + " )\n", + "\n", + "\n", + "available_tools = {\"get_current_weather\": get_current_weather}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "### Execute the Tool" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "messages.append(response_non_stream.choices[0].message)\n", + "\n", + "# Call the corresponding tool function\n", + "tool_call = messages[-1].tool_calls[0]\n", + "tool_name = tool_call.function.name\n", + "tool_to_call = available_tools[tool_name]\n", + "result = tool_to_call(**(json.loads(tool_call.function.arguments)))\n", + "print_highlight(f\"Function call result: {result}\")\n", + "# messages.append({\"role\": \"tool\", \"content\": result, \"name\": tool_name})\n", + "messages.append(\n", + " {\n", + " \"role\": \"tool\",\n", + " \"tool_call_id\": tool_call.id,\n", + " \"content\": str(result),\n", + " \"name\": tool_name,\n", + " }\n", + ")\n", + "\n", + "print_highlight(f\"Updated message history: {messages}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Send Results Back to Model" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "final_response = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0,\n", + " top_p=0.95,\n", + " stream=False,\n", + " tools=tools,\n", + ")\n", + "print_highlight(\"Non-stream response:\")\n", + "print_highlight(final_response)\n", + "\n", + "print_highlight(\"==== Text ====\")\n", + "print_highlight(final_response.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Native API and SGLang Runtime (SRT)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import AutoTokenizer\n", + "import requests\n", + "\n", + "# generate an answer\n", + "tokenizer = AutoTokenizer.from_pretrained(\"Qwen/Qwen2.5-7B-Instruct\")\n", + "\n", + "messages = get_messages()\n", + "\n", + "input = tokenizer.apply_chat_template(\n", + " messages, tokenize=False, add_generation_prompt=True, tools=tools, return_dict=False\n", + ")\n", + "\n", + "gen_url = f\"http://localhost:{port}/generate\"\n", + "gen_data = {\n", + " \"text\": input,\n", + " \"sampling_params\": {\n", + " \"skip_special_tokens\": False,\n", + " \"max_new_tokens\": 1024,\n", + " \"temperature\": 0,\n", + " \"top_p\": 0.95,\n", + " },\n", + "}\n", + "gen_response = requests.post(gen_url, json=gen_data).json()[\"text\"]\n", + "print_highlight(\"==== Response ====\")\n", + "print_highlight(gen_response)\n", + "\n", + "# parse the response\n", + "parse_url = f\"http://localhost:{port}/parse_function_call\"\n", + "\n", + "function_call_input = {\n", + " \"text\": gen_response,\n", + " \"tool_call_parser\": \"qwen25\",\n", + " \"tools\": tools,\n", + "}\n", + "\n", + "function_call_response = requests.post(parse_url, json=function_call_input)\n", + "function_call_response_json = function_call_response.json()\n", + "\n", + "print_highlight(\"==== Text ====\")\n", + "print(function_call_response_json[\"normal_text\"])\n", + "print_highlight(\"==== Calls ====\")\n", + "print(\"function name: \", function_call_response_json[\"calls\"][0][\"name\"])\n", + "print(\"function arguments: \", function_call_response_json[\"calls\"][0][\"parameters\"])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Offline Engine API" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import sglang as sgl\n", + "from sglang.srt.function_call.function_call_parser import FunctionCallParser\n", + "from sglang.srt.managers.io_struct import Tool, Function\n", + "\n", + "llm = sgl.Engine(model_path=\"Qwen/Qwen2.5-7B-Instruct\")\n", + "tokenizer = llm.tokenizer_manager.tokenizer\n", + "input_ids = tokenizer.apply_chat_template(\n", + " messages, tokenize=True, add_generation_prompt=True, tools=tools, return_dict=False\n", + ")\n", + "\n", + "# Note that for gpt-oss tool parser, adding \"no_stop_trim\": True\n", + "# to make sure the tool call token is not trimmed.\n", + "\n", + "sampling_params = {\n", + " \"max_new_tokens\": 1024,\n", + " \"temperature\": 0,\n", + " \"top_p\": 0.95,\n", + " \"skip_special_tokens\": False,\n", + "}\n", + "\n", + "# 1) Offline generation\n", + "result = llm.generate(input_ids=input_ids, sampling_params=sampling_params)\n", + "generated_text = result[\"text\"] # Assume there is only one prompt\n", + "\n", + "print_highlight(\"=== Offline Engine Output Text ===\")\n", + "print_highlight(generated_text)\n", + "\n", + "\n", + "# 2) Parse using FunctionCallParser\n", + "def convert_dict_to_tool(tool_dict: dict) -> Tool:\n", + " function_dict = tool_dict.get(\"function\", {})\n", + " return Tool(\n", + " type=tool_dict.get(\"type\", \"function\"),\n", + " function=Function(\n", + " name=function_dict.get(\"name\"),\n", + " description=function_dict.get(\"description\"),\n", + " parameters=function_dict.get(\"parameters\"),\n", + " ),\n", + " )\n", + "\n", + "\n", + "tools = [convert_dict_to_tool(raw_tool) for raw_tool in tools]\n", + "\n", + "parser = FunctionCallParser(tools=tools, tool_call_parser=\"qwen25\")\n", + "normal_text, calls = parser.parse_non_stream(generated_text)\n", + "\n", + "print_highlight(\"=== Parsing Result ===\")\n", + "print(\"Normal text portion:\", normal_text)\n", + "print_highlight(\"Function call portion:\")\n", + "for call in calls:\n", + " # call: ToolCallItem\n", + " print_highlight(f\" - tool name: {call.name}\")\n", + " print_highlight(f\" parameters: {call.parameters}\")\n", + "\n", + "# 3) If needed, perform additional logic on the parsed functions, such as automatically calling the corresponding function to obtain a return value, etc." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "llm.shutdown()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Tool Choice Mode\n", + "\n", + "SGLang supports OpenAI's `tool_choice` parameter to control when and which tools the model should call. This feature is implemented using EBNF (Extended Backus-Naur Form) grammar to ensure reliable tool calling behavior.\n", + "\n", + "### Supported Tool Choice Options\n", + "\n", + "- **`tool_choice=\"required\"`**: Forces the model to call at least one tool\n", + "- **`tool_choice={\"type\": \"function\", \"function\": {\"name\": \"specific_function\"}}`**: Forces the model to call a specific function\n", + "\n", + "### Backend Compatibility\n", + "\n", + "Tool choice is fully supported with the **Xgrammar backend**, which is the default grammar backend (`--grammar-backend xgrammar`). However, it may not be fully supported with other backends such as `outlines`.\n", + "\n", + "### Example: Required Tool Choice" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from openai import OpenAI\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "from sglang.test.doc_patch import launch_server_cmd\n", + "\n", + "# Start a new server session for tool choice examples\n", + "server_process_tool_choice, port_tool_choice = launch_server_cmd(\n", + " \"python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --tool-call-parser qwen25 --host 0.0.0.0 --log-level warning\"\n", + ")\n", + "wait_for_server(f\"http://localhost:{port_tool_choice}\")\n", + "\n", + "# Initialize client for tool choice examples\n", + "client_tool_choice = OpenAI(\n", + " api_key=\"None\", base_url=f\"http://0.0.0.0:{port_tool_choice}/v1\"\n", + ")\n", + "model_name_tool_choice = client_tool_choice.models.list().data[0].id\n", + "\n", + "# Example with tool_choice=\"required\" - forces the model to call a tool\n", + "messages_required = [\n", + " {\"role\": \"user\", \"content\": \"Hello, what is the capital of France?\"}\n", + "]\n", + "\n", + "# Define tools\n", + "tools = [\n", + " {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"get_current_weather\",\n", + " \"description\": \"Get the current weather in a given location\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"city\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The city to find the weather for, e.g. 'San Francisco'\",\n", + " },\n", + " \"unit\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The unit to fetch the temperature in\",\n", + " \"enum\": [\"celsius\", \"fahrenheit\"],\n", + " },\n", + " },\n", + " \"required\": [\"city\", \"unit\"],\n", + " },\n", + " },\n", + " }\n", + "]\n", + "\n", + "response_required = client_tool_choice.chat.completions.create(\n", + " model=model_name_tool_choice,\n", + " messages=messages_required,\n", + " temperature=0,\n", + " max_tokens=1024,\n", + " tools=tools,\n", + " tool_choice=\"required\", # Force the model to call a tool\n", + ")\n", + "\n", + "print_highlight(\"Response with tool_choice='required':\")\n", + "print(\"Content:\", response_required.choices[0].message.content)\n", + "print(\"Tool calls:\", response_required.choices[0].message.tool_calls)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Example: Specific Function Choice\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Example with specific function choice - forces the model to call a specific function\n", + "messages_specific = [\n", + " {\"role\": \"user\", \"content\": \"What are the most attactive places in France?\"}\n", + "]\n", + "\n", + "response_specific = client_tool_choice.chat.completions.create(\n", + " model=model_name_tool_choice,\n", + " messages=messages_specific,\n", + " temperature=0,\n", + " max_tokens=1024,\n", + " tools=tools,\n", + " tool_choice={\n", + " \"type\": \"function\",\n", + " \"function\": {\"name\": \"get_current_weather\"},\n", + " }, # Force the model to call the specific get_current_weather function\n", + ")\n", + "\n", + "print_highlight(\"Response with specific function choice:\")\n", + "print(\"Content:\", response_specific.choices[0].message.content)\n", + "print(\"Tool calls:\", response_specific.choices[0].message.tool_calls)\n", + "\n", + "if response_specific.choices[0].message.tool_calls:\n", + " tool_call = response_specific.choices[0].message.tool_calls[0]\n", + " print_highlight(f\"Called function: {tool_call.function.name}\")\n", + " print_highlight(f\"Arguments: {tool_call.function.arguments}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process_tool_choice)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Pythonic Tool Call Format (Llama-3.2 / Llama-3.3 / Llama-4)\n", + "\n", + "Some Llama models (such as Llama-3.2-1B, Llama-3.2-3B, Llama-3.3-70B, and Llama-4) support a \"pythonic\" tool call format, where the model outputs function calls as Python code, e.g.:\n", + "\n", + "```python\n", + "[get_current_weather(city=\"San Francisco\", state=\"CA\", unit=\"celsius\")]\n", + "```\n", + "\n", + "- The output is a Python list of function calls, with arguments as Python literals (not JSON).\n", + "- Multiple tool calls can be returned in the same list:\n", + "```python\n", + "[get_current_weather(city=\"San Francisco\", state=\"CA\", unit=\"celsius\"),\n", + " get_current_weather(city=\"New York\", state=\"NY\", unit=\"fahrenheit\")]\n", + "```\n", + "\n", + "For more information, refer to Meta’s documentation on [Zero shot function calling](https://github.com/meta-llama/llama-models/blob/main/models/llama4/prompt_format.md#zero-shot-function-calling---system-message).\n", + "\n", + "Note that this feature is still under development on Blackwell.\n", + "\n", + "### How to enable\n", + "- Launch the server with `--tool-call-parser pythonic`\n", + "- You may also specify --chat-template with the improved template for the model (e.g., `--chat-template=examples/chat_template/tool_chat_template_llama4_pythonic.jinja`).\n", + "This is recommended because the model expects a special prompt format to reliably produce valid pythonic tool call outputs. The template ensures that the prompt structure (e.g., special tokens, message boundaries like `<|eom|>`, and function call delimiters) matches what the model was trained or fine-tuned on. If you do not use the correct chat template, tool calling may fail or produce inconsistent results.\n", + "\n", + "#### Forcing Pythonic Tool Call Output Without a Chat Template\n", + "If you don't want to specify a chat template, you must give the model extremely explicit instructions in your messages to enforce pythonic output. For example, for `Llama-3.2-1B-Instruct`, you need:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import openai\n", + "\n", + "server_process, port = launch_server_cmd(\n", + " \" python3 -m sglang.launch_server --model-path meta-llama/Llama-3.2-1B-Instruct --tool-call-parser pythonic --tp 1 --log-level warning\" # llama-3.2-1b-instruct\n", + ")\n", + "wait_for_server(f\"http://localhost:{port}\")\n", + "\n", + "tools = [\n", + " {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"get_weather\",\n", + " \"description\": \"Get the current weather for a given location.\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"location\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The name of the city or location.\",\n", + " }\n", + " },\n", + " \"required\": [\"location\"],\n", + " },\n", + " },\n", + " },\n", + " {\n", + " \"type\": \"function\",\n", + " \"function\": {\n", + " \"name\": \"get_tourist_attractions\",\n", + " \"description\": \"Get a list of top tourist attractions for a given city.\",\n", + " \"parameters\": {\n", + " \"type\": \"object\",\n", + " \"properties\": {\n", + " \"city\": {\n", + " \"type\": \"string\",\n", + " \"description\": \"The name of the city to find attractions for.\",\n", + " }\n", + " },\n", + " \"required\": [\"city\"],\n", + " },\n", + " },\n", + " },\n", + "]\n", + "\n", + "\n", + "def get_messages():\n", + " return [\n", + " {\n", + " \"role\": \"system\",\n", + " \"content\": (\n", + " \"You are a travel assistant. \"\n", + " \"When asked to call functions, ALWAYS respond ONLY with a python list of function calls, \"\n", + " \"using this format: [func_name1(param1=value1, param2=value2), func_name2(param=value)]. \"\n", + " \"Do NOT use JSON, do NOT use variables, do NOT use any other format. \"\n", + " \"Here is an example:\\n\"\n", + " '[get_weather(location=\"Paris\"), get_tourist_attractions(city=\"Paris\")]'\n", + " ),\n", + " },\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": (\n", + " \"I'm planning a trip to Tokyo next week. What's the weather like and what are some top tourist attractions? \"\n", + " \"Propose parallel tool calls at once, using the python list of function calls format as shown above.\"\n", + " ),\n", + " },\n", + " ]\n", + "\n", + "\n", + "messages = get_messages()\n", + "\n", + "client = openai.Client(base_url=f\"http://localhost:{port}/v1\", api_key=\"xxxxxx\")\n", + "model_name = client.models.list().data[0].id\n", + "\n", + "\n", + "response_non_stream = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0,\n", + " top_p=0.9,\n", + " stream=False, # Non-streaming\n", + " tools=tools,\n", + ")\n", + "print_highlight(\"Non-stream response:\")\n", + "print_highlight(response_non_stream)\n", + "\n", + "response_stream = client.chat.completions.create(\n", + " model=model_name,\n", + " messages=messages,\n", + " temperature=0,\n", + " top_p=0.9,\n", + " stream=True,\n", + " tools=tools,\n", + ")\n", + "texts = \"\"\n", + "tool_calls = []\n", + "name = \"\"\n", + "arguments = \"\"\n", + "\n", + "for chunk in response_stream:\n", + " if chunk.choices[0].delta.content:\n", + " texts += chunk.choices[0].delta.content\n", + " if chunk.choices[0].delta.tool_calls:\n", + " tool_calls.append(chunk.choices[0].delta.tool_calls[0])\n", + "\n", + "print_highlight(\"Streaming Response:\")\n", + "print_highlight(\"==== Text ====\")\n", + "print_highlight(texts)\n", + "\n", + "print_highlight(\"==== Tool Call ====\")\n", + "for tool_call in tool_calls:\n", + " print_highlight(tool_call)\n", + "\n", + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "> **Note:** \n", + "> The model may still default to JSON if it was heavily finetuned on that format. Prompt engineering (including examples) is the only way to increase the chance of pythonic output if you are not using a chat template." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## How to support a new model?\n", + "1. Update the TOOLS_TAG_LIST in sglang/srt/function_call_parser.py with the model’s tool tags. Currently supported tags include:\n", + "```\n", + "\tTOOLS_TAG_LIST = [\n", + "\t “<|plugin|>“,\n", + "\t ““,\n", + "\t “<|python_tag|>“,\n", + "\t “[TOOL_CALLS]”\n", + "\t]\n", + "```\n", + "2. Create a new detector class in sglang/srt/function_call_parser.py that inherits from BaseFormatDetector. The detector should handle the model’s specific function call format. For example:\n", + "```\n", + " class NewModelDetector(BaseFormatDetector):\n", + "```\n", + "3. Add the new detector to the MultiFormatParser class that manages all the format detectors." + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/docs_new/docs/advanced_features/tool_parser.mdx b/docs_new/docs/advanced_features/tool_parser.mdx new file mode 100644 index 000000000..a5fcc169b --- /dev/null +++ b/docs_new/docs/advanced_features/tool_parser.mdx @@ -0,0 +1,740 @@ +--- +title: "Tool Parser" +metatags: + description: "SGLang function calling: tool parsers for DeepSeek, Llama, Qwen, Mistral, GLM, Kimi K2. OpenAI-compatible tool use API." +--- +This guide demonstrates how to use SGLang’s [Function calling](https://platform.openai.com/docs/guides/function-calling) functionality. + + +## Currently supported parsers: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParserSupported ModelsNotes
`deepseekv3`DeepSeek-v3 (e.g., `deepseek-ai/DeepSeek-V3-0324`)Recommend adding `--chat-template ./examples/chat_template/tool_chat_template_deepseekv3.jinja` to launch command.
`deepseekv31`DeepSeek-V3.1 and DeepSeek-V3.2-Exp (e.g. `deepseek-ai/DeepSeek-V3.1`, `deepseek-ai/DeepSeek-V3.2-Exp`)Recommend adding `--chat-template ./examples/chat_template/tool_chat_template_deepseekv31.jinja` (Or ..deepseekv32.jinja for DeepSeek-V3.2) to launch command.
`deepseekv32`DeepSeek-V3.2 (`deepseek-ai/DeepSeek-V3.2`)
`glm`GLM series (e.g. `zai-org/GLM-4.6`)
`gpt-oss`GPT-OSS (e.g., `openai/gpt-oss-120b`, `openai/gpt-oss-20b`, `lmsys/gpt-oss-120b-bf16`, `lmsys/gpt-oss-20b-bf16`)The gpt-oss tool parser filters out analysis channel events and only preserves normal text. This can cause the content to be empty when explanations are in the analysis channel. To work around this, complete the tool round by returning tool results as `role="tool"` messages, which enables the model to generate the final content.
`kimi_k2``moonshotai/Kimi-K2-Instruct`
`llama3`Llama 3.1 / 3.2 / 3.3 (e.g. `meta-llama/Llama-3.1-8B-Instruct`, `meta-llama/Llama-3.2-1B-Instruct`, `meta-llama/Llama-3.3-70B-Instruct`)
`llama4`Llama 4 (e.g. `meta-llama/Llama-4-Scout-17B-16E-Instruct`)
`mistral`Mistral (e.g. `mistralai/Mistral-7B-Instruct-v0.3`, `mistralai/Mistral-Nemo-Instruct-2407`, `mistralai/Mistral-7B-v0.3`)
`pythonic`Llama-3.2 / Llama-3.3 / Llama-4Model outputs function calls as Python code. Requires `--tool-call-parser pythonic` and is recommended to use with a specific chat template.
`qwen`Qwen series (e.g. `Qwen/Qwen3-Next-80B-A3B-Instruct`, `Qwen/Qwen3-VL-30B-A3B-Thinking`) except Qwen3-Coder
`qwen3_coder`Qwen3-Coder (e.g. `Qwen/Qwen3-Coder-30B-A3B-Instruct`)
`step3`Step-3
+ + + +## OpenAI Compatible API + + +### Launching the Server + + + +```python Example +import json +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process +from openai import OpenAI + +server_process, port = launch_server_cmd( + "python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --tool-call-parser qwen25 --host 0.0.0.0 --log-level warning" # qwen25 +) +wait_for_server(f"http://localhost:{port}") +``` + +Note that `--tool-call-parser` defines the parser used to interpret responses. + + +### Define Tools for Function Call +Below is a Python snippet that shows how to define a tool as a dictionary. The dictionary includes a tool name, a description, and property defined Parameters. + + + +```python Example +# Define tools +tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "The city to find the weather for, e.g. 'San Francisco'", + }, + "state": { + "type": "string", + "description": "the two-letter abbreviation for the state that the city is" + " in, e.g. 'CA' which would mean 'California'", + }, + "unit": { + "type": "string", + "description": "The unit to fetch the temperature in", + "enum": ["celsius", "fahrenheit"], + }, + }, + "required": ["city", "state", "unit"], + }, + }, + } +] +``` + +### Define Messages + + + +```python Example +def get_messages(): + return [ + { + "role": "user", + "content": "What's the weather like in Boston today? Output a reasoning before act, then use the tools to help you.", + } + ] + + +messages = get_messages() +``` + +### Initialize the Client + + + +```python Example +# Initialize OpenAI-like client +client = OpenAI(api_key="None", base_url=f"http://0.0.0.0:{port}/v1") +model_name = client.models.list().data[0].id +``` + +### Non-Streaming Request + + + +```python Example +# Non-streaming mode test +response_non_stream = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0, + top_p=0.95, + max_tokens=1024, + stream=False, # Non-streaming + tools=tools, +) +print_highlight("Non-stream response:") +print_highlight(response_non_stream) +print_highlight("==== content ====") +print_highlight(response_non_stream.choices[0].message.content) +print_highlight("==== tool_calls ====") +print_highlight(response_non_stream.choices[0].message.tool_calls) +``` + +#### Handle Tools +When the engine determines it should call a particular tool, it will return arguments or partial arguments through the response. You can parse these arguments and later invoke the tool accordingly. + + + +```python Example +name_non_stream = response_non_stream.choices[0].message.tool_calls[0].function.name +arguments_non_stream = ( + response_non_stream.choices[0].message.tool_calls[0].function.arguments +) + +print_highlight(f"Final streamed function call name: {name_non_stream}") +print_highlight(f"Final streamed function call arguments: {arguments_non_stream}") +``` + +### Streaming Request + + + +```python Example +# Streaming mode test +print_highlight("Streaming response:") +response_stream = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0, + top_p=0.95, + max_tokens=1024, + stream=True, # Enable streaming + tools=tools, +) + +texts = "" +tool_calls = [] +name = "" +arguments = "" +for chunk in response_stream: + if chunk.choices[0].delta.content: + texts += chunk.choices[0].delta.content + if chunk.choices[0].delta.tool_calls: + tool_calls.append(chunk.choices[0].delta.tool_calls[0]) +print_highlight("==== Text ====") +print_highlight(texts) + +print_highlight("==== Tool Call ====") +for tool_call in tool_calls: + print_highlight(tool_call) +``` + +#### Handle Tools +When the engine determines it should call a particular tool, it will return arguments or partial arguments through the response. You can parse these arguments and later invoke the tool accordingly. + + + +```python Example +# Parse and combine function call arguments +arguments = [] +for tool_call in tool_calls: + if tool_call.function.name: + print_highlight(f"Streamed function call name: {tool_call.function.name}") + + if tool_call.function.arguments: + arguments.append(tool_call.function.arguments) + +# Combine all fragments into a single JSON string +full_arguments = "".join(arguments) +print_highlight(f"streamed function call arguments: {full_arguments}") +``` + +### Define a Tool Function + + + +```python Example +# This is a demonstration, define real function according to your usage. +def get_current_weather(city: str, state: str, unit: "str"): + return ( + f"The weather in {city}, {state} is 85 degrees {unit}. It is " + "partly cloudly, with highs in the 90's." + ) + + +available_tools = {"get_current_weather": get_current_weather} +``` + + +### Execute the Tool + + + +```python Example +messages.append(response_non_stream.choices[0].message) + +# Call the corresponding tool function +tool_call = messages[-1].tool_calls[0] +tool_name = tool_call.function.name +tool_to_call = available_tools[tool_name] +result = tool_to_call(**(json.loads(tool_call.function.arguments))) +print_highlight(f"Function call result: {result}") +# messages.append({"role": "tool", "content": result, "name": tool_name}) +messages.append( + { + "role": "tool", + "tool_call_id": tool_call.id, + "content": str(result), + "name": tool_name, + } +) + +print_highlight(f"Updated message history: {messages}") +``` + +### Send Results Back to Model + + + +```python Example +final_response = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0, + top_p=0.95, + stream=False, + tools=tools, +) +print_highlight("Non-stream response:") +print_highlight(final_response) + +print_highlight("==== Text ====") +print_highlight(final_response.choices[0].message.content) +``` + +## Native API and SGLang Runtime (SRT) + + + +```python Example +from transformers import AutoTokenizer +import requests + +# generate an answer +tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct") + +messages = get_messages() + +input = tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=True, tools=tools, return_dict=False +) + +gen_url = f"http://localhost:{port}/generate" +gen_data = { + "text": input, + "sampling_params": { + "skip_special_tokens": False, + "max_new_tokens": 1024, + "temperature": 0, + "top_p": 0.95, + }, +} +gen_response = requests.post(gen_url, json=gen_data).json()["text"] +print_highlight("==== Response ====") +print_highlight(gen_response) + +# parse the response +parse_url = f"http://localhost:{port}/parse_function_call" + +function_call_input = { + "text": gen_response, + "tool_call_parser": "qwen25", + "tools": tools, +} + +function_call_response = requests.post(parse_url, json=function_call_input) +function_call_response_json = function_call_response.json() + +print_highlight("==== Text ====") +print(function_call_response_json["normal_text"]) +print_highlight("==== Calls ====") +print("function name: ", function_call_response_json["calls"][0]["name"]) +print("function arguments: ", function_call_response_json["calls"][0]["parameters"]) +``` + + +```python Example +terminate_process(server_process) +``` + +## Offline Engine API + + + +```python Example +import sglang as sgl +from sglang.srt.function_call.function_call_parser import FunctionCallParser +from sglang.srt.managers.io_struct import Tool, Function + +llm = sgl.Engine(model_path="Qwen/Qwen2.5-7B-Instruct") +tokenizer = llm.tokenizer_manager.tokenizer +input_ids = tokenizer.apply_chat_template( + messages, tokenize=True, add_generation_prompt=True, tools=tools, return_dict=False +) + +# Note that for gpt-oss tool parser, adding "no_stop_trim": True +# to make sure the tool call token is not trimmed. + +sampling_params = { + "max_new_tokens": 1024, + "temperature": 0, + "top_p": 0.95, + "skip_special_tokens": False, +} + +# 1) Offline generation +result = llm.generate(input_ids=input_ids, sampling_params=sampling_params) +generated_text = result["text"] # Assume there is only one prompt + +print_highlight("=== Offline Engine Output Text ===") +print_highlight(generated_text) + + +# 2) Parse using FunctionCallParser +def convert_dict_to_tool(tool_dict: dict) -> Tool: + function_dict = tool_dict.get("function", {}) + return Tool( + type=tool_dict.get("type", "function"), + function=Function( + name=function_dict.get("name"), + description=function_dict.get("description"), + parameters=function_dict.get("parameters"), + ), + ) + + +tools = [convert_dict_to_tool(raw_tool) for raw_tool in tools] + +parser = FunctionCallParser(tools=tools, tool_call_parser="qwen25") +normal_text, calls = parser.parse_non_stream(generated_text) + +print_highlight("=== Parsing Result ===") +print("Normal text portion:", normal_text) +print_highlight("Function call portion:") +for call in calls: + # call: ToolCallItem + print_highlight(f" - tool name: {call.name}") + print_highlight(f" parameters: {call.parameters}") + +# 3) If needed, perform additional logic on the parsed functions, such as automatically calling the corresponding function to obtain a return value, etc. +``` + + +```python Example +llm.shutdown() +``` + +## Tool Choice Mode + +SGLang supports OpenAI's `tool_choice` parameter to control when and which tools the model should call. This feature is implemented using EBNF (Extended Backus-Naur Form) grammar to ensure reliable tool calling behavior. + +### Supported Tool Choice Options + +- **`tool_choice="required"`**: Forces the model to call at least one tool +- **`tool_choice={"type": "function", "function": {"name": "specific_function"}}`**: Forces the model to call a specific function + +### Backend Compatibility + +Tool choice is fully supported with the **Xgrammar backend**, which is the default grammar backend (`--grammar-backend xgrammar`). However, it may not be fully supported with other backends such as `outlines`. + +### Example: Required Tool Choice + + + +```python Example +from openai import OpenAI +from sglang.utils import wait_for_server, print_highlight, terminate_process +from sglang.test.doc_patch import launch_server_cmd + +# Start a new server session for tool choice examples +server_process_tool_choice, port_tool_choice = launch_server_cmd( + "python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --tool-call-parser qwen25 --host 0.0.0.0 --log-level warning" +) +wait_for_server(f"http://localhost:{port_tool_choice}") + +# Initialize client for tool choice examples +client_tool_choice = OpenAI( + api_key="None", base_url=f"http://0.0.0.0:{port_tool_choice}/v1" +) +model_name_tool_choice = client_tool_choice.models.list().data[0].id + +# Example with tool_choice="required" - forces the model to call a tool +messages_required = [ + {"role": "user", "content": "Hello, what is the capital of France?"} +] + +# Define tools +tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current 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_required = client_tool_choice.chat.completions.create( + model=model_name_tool_choice, + messages=messages_required, + temperature=0, + max_tokens=1024, + tools=tools, + tool_choice="required", # Force the model to call a tool +) + +print_highlight("Response with tool_choice='required':") +print("Content:", response_required.choices[0].message.content) +print("Tool calls:", response_required.choices[0].message.tool_calls) +``` + +### Example: Specific Function Choice + + + + +```python Example +# Example with specific function choice - forces the model to call a specific function +messages_specific = [ + {"role": "user", "content": "What are the most attactive places in France?"} +] + +response_specific = client_tool_choice.chat.completions.create( + model=model_name_tool_choice, + messages=messages_specific, + temperature=0, + max_tokens=1024, + tools=tools, + tool_choice={ + "type": "function", + "function": {"name": "get_current_weather"}, + }, # Force the model to call the specific get_current_weather function +) + +print_highlight("Response with specific function choice:") +print("Content:", response_specific.choices[0].message.content) +print("Tool calls:", response_specific.choices[0].message.tool_calls) + +if response_specific.choices[0].message.tool_calls: + tool_call = response_specific.choices[0].message.tool_calls[0] + print_highlight(f"Called function: {tool_call.function.name}") + print_highlight(f"Arguments: {tool_call.function.arguments}") +``` + + +```python Example +terminate_process(server_process_tool_choice) +``` + +## Pythonic Tool Call Format (Llama-3.2 / Llama-3.3 / Llama-4) + +Some Llama models (such as Llama-3.2-1B, Llama-3.2-3B, Llama-3.3-70B, and Llama-4) support a "pythonic" tool call format, where the model outputs function calls as Python code, e.g.: + +```python Example +[get_current_weather(city="San Francisco", state="CA", unit="celsius")] +``` + +- The output is a Python list of function calls, with arguments as Python literals (not JSON). +- Multiple tool calls can be returned in the same list: +```python Example +[get_current_weather(city="San Francisco", state="CA", unit="celsius"), + get_current_weather(city="New York", state="NY", unit="fahrenheit")] +``` + +For more information, refer to Meta’s documentation on [Zero shot function calling](https://github.com/meta-llama/llama-models/blob/main/models/llama4/prompt_format.md#zero-shot-function-calling---system-message). + +Note that this feature is still under development on Blackwell. + +### How to enable +- Launch the server with `--tool-call-parser pythonic` +- You may also specify --chat-template with the improved template for the model (e.g., `--chat-template=examples/chat_template/tool_chat_template_llama4_pythonic.jinja`). +This is recommended because the model expects a special prompt format to reliably produce valid pythonic tool call outputs. The template ensures that the prompt structure (e.g., special tokens, message boundaries like `<|eom|>`, and function call delimiters) matches what the model was trained or fine-tuned on. If you do not use the correct chat template, tool calling may fail or produce inconsistent results. + +#### Forcing Pythonic Tool Call Output Without a Chat Template +If you don't want to specify a chat template, you must give the model extremely explicit instructions in your messages to enforce pythonic output. For example, for `Llama-3.2-1B-Instruct`, you need: + + + +```python Example +import openai + +server_process, port = launch_server_cmd( + " python3 -m sglang.launch_server --model-path meta-llama/Llama-3.2-1B-Instruct --tool-call-parser pythonic --tp 1 --log-level warning" # llama-3.2-1b-instruct +) +wait_for_server(f"http://localhost:{port}") + +tools = [ + { + "type": "function", + "function": { + "name": "get_weather", + "description": "Get the current weather for a given location.", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The name of the city or location.", + } + }, + "required": ["location"], + }, + }, + }, + { + "type": "function", + "function": { + "name": "get_tourist_attractions", + "description": "Get a list of top tourist attractions for a given city.", + "parameters": { + "type": "object", + "properties": { + "city": { + "type": "string", + "description": "The name of the city to find attractions for.", + } + }, + "required": ["city"], + }, + }, + }, +] + + +def get_messages(): + return [ + { + "role": "system", + "content": ( + "You are a travel assistant. " + "When asked to call functions, ALWAYS respond ONLY with a python list of function calls, " + "using this format: [func_name1(param1=value1, param2=value2), func_name2(param=value)]. " + "Do NOT use JSON, do NOT use variables, do NOT use any other format. " + "Here is an example:\n" + '[get_weather(location="Paris"), get_tourist_attractions(city="Paris")]' + ), + }, + { + "role": "user", + "content": ( + "I'm planning a trip to Tokyo next week. What's the weather like and what are some top tourist attractions? " + "Propose parallel tool calls at once, using the python list of function calls format as shown above." + ), + }, + ] + + +messages = get_messages() + +client = openai.Client(base_url=f"http://localhost:{port}/v1", api_key="xxxxxx") +model_name = client.models.list().data[0].id + + +response_non_stream = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0, + top_p=0.9, + stream=False, # Non-streaming + tools=tools, +) +print_highlight("Non-stream response:") +print_highlight(response_non_stream) + +response_stream = client.chat.completions.create( + model=model_name, + messages=messages, + temperature=0, + top_p=0.9, + stream=True, + tools=tools, +) +texts = "" +tool_calls = [] +name = "" +arguments = "" + +for chunk in response_stream: + if chunk.choices[0].delta.content: + texts += chunk.choices[0].delta.content + if chunk.choices[0].delta.tool_calls: + tool_calls.append(chunk.choices[0].delta.tool_calls[0]) + +print_highlight("Streaming Response:") +print_highlight("==== Text ====") +print_highlight(texts) + +print_highlight("==== Tool Call ====") +for tool_call in tool_calls: + print_highlight(tool_call) + +terminate_process(server_process) +``` + +> **Note:** +> The model may still default to JSON if it was heavily finetuned on that format. Prompt engineering (including examples) is the only way to increase the chance of pythonic output if you are not using a chat template. + + +## How to support a new model? +1. Update the TOOLS_TAG_LIST in sglang/srt/function_call_parser.py with the model’s tool tags. Currently supported tags include: +```text Output + TOOLS_TAG_LIST = [ + “<|plugin|>“, + ““, + “<|python_tag|>“, + “[TOOL_CALLS]” + ] +``` +2. Create a new detector class in sglang/srt/function_call_parser.py that inherits from BaseFormatDetector. The detector should handle the model’s specific function call format. For example: +```text Output + class NewModelDetector(BaseFormatDetector): +``` +3. Add the new detector to the MultiFormatParser class that manages all the format detectors. diff --git a/docs_new/docs/advanced_features/vlm_query.ipynb b/docs_new/docs/advanced_features/vlm_query.ipynb new file mode 100644 index 000000000..13491d1b9 --- /dev/null +++ b/docs_new/docs/advanced_features/vlm_query.ipynb @@ -0,0 +1,388 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "0", + "metadata": {}, + "source": [ + "# Query VLM with Offline Engine\n", + "\n", + "This tutorial demonstrates how to use SGLang's **offline Engine API** to query VLMs. We will demonstrate usage with Qwen2.5-VL and Llama 4. This section demonstrates three different calling approaches:\n", + "\n", + "1. **Basic Call**: Directly pass images and text.\n", + "2. **Processor Output**: Use HuggingFace processor for data preprocessing.\n", + "3. **Precomputed Embeddings**: Pre-calculate image features to improve inference efficiency." + ] + }, + { + "cell_type": "markdown", + "id": "1", + "metadata": {}, + "source": [ + "## Understanding the Three Input Formats\n", + "\n", + "SGLang supports three ways to pass visual data, each optimized for different scenarios:\n", + "\n", + "### 1. **Raw Images** - Simplest approach\n", + "- Pass PIL Images, file paths, URLs, or base64 strings directly\n", + "- SGLang handles all preprocessing automatically\n", + "- Best for: Quick prototyping, simple applications\n", + "\n", + "### 2. **Processor Output** - For custom preprocessing\n", + "- Pre-process images with HuggingFace processor\n", + "- Pass the complete processor output dict with `format: \"processor_output\"`\n", + "- Best for: Custom image transformations, integration with existing pipelines\n", + "- Requirement: Must use `input_ids` instead of text prompt\n", + "\n", + "### 3. **Precomputed Embeddings** - For maximum performance\n", + "- Pre-calculate visual embeddings using the vision encoder\n", + "- Pass embeddings with `format: \"precomputed_embedding\"`\n", + "- Best for: Repeated queries on same images, caching, high-throughput serving\n", + "- Performance gain: Avoids redundant vision encoder computation (30-50% speedup)\n", + "\n", + "**Key Rule**: Within a single request, use only one format for all images. Don't mix formats.\n", + "\n", + "The examples below demonstrate all three approaches with both Qwen2.5-VL and Llama 4 models." + ] + }, + { + "cell_type": "markdown", + "id": "2", + "metadata": {}, + "source": [ + "## Querying Qwen2.5-VL Model" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3", + "metadata": {}, + "outputs": [], + "source": [ + "import nest_asyncio\n", + "\n", + "nest_asyncio.apply()\n", + "\n", + "model_path = \"Qwen/Qwen2.5-VL-3B-Instruct\"\n", + "chat_template = \"qwen2-vl\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4", + "metadata": {}, + "outputs": [], + "source": [ + "from io import BytesIO\n", + "import requests\n", + "from PIL import Image\n", + "\n", + "from sglang.srt.parser.conversation import chat_templates\n", + "\n", + "image = Image.open(\n", + " BytesIO(\n", + " requests.get(\n", + " \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\"\n", + " ).content\n", + " )\n", + ")\n", + "\n", + "conv = chat_templates[chat_template].copy()\n", + "conv.append_message(conv.roles[0], f\"What's shown here: {conv.image_token}?\")\n", + "conv.append_message(conv.roles[1], \"\")\n", + "conv.image_data = [image]\n", + "\n", + "print(\"Generated prompt text:\")\n", + "print(conv.get_prompt())\n", + "print(f\"\\nImage size: {image.size}\")\n", + "image" + ] + }, + { + "cell_type": "markdown", + "id": "5", + "metadata": {}, + "source": [ + "### Basic Offline Engine API Call" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6", + "metadata": {}, + "outputs": [], + "source": [ + "from sglang import Engine\n", + "\n", + "llm = Engine(model_path=model_path, chat_template=chat_template, log_level=\"warning\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7", + "metadata": {}, + "outputs": [], + "source": [ + "out = llm.generate(prompt=conv.get_prompt(), image_data=[image])\n", + "print(\"Model response:\")\n", + "print(out[\"text\"])" + ] + }, + { + "cell_type": "markdown", + "id": "8", + "metadata": {}, + "source": [ + "### Call with Processor Output\n", + "\n", + "Using a HuggingFace processor to preprocess text and images, and passing the `processor_output` directly into `Engine.generate`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9", + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import AutoProcessor\n", + "\n", + "processor = AutoProcessor.from_pretrained(model_path, use_fast=True)\n", + "processor_output = processor(\n", + " images=[image], text=conv.get_prompt(), return_tensors=\"pt\"\n", + ")\n", + "\n", + "out = llm.generate(\n", + " input_ids=processor_output[\"input_ids\"][0].detach().cpu().tolist(),\n", + " image_data=[dict(processor_output, format=\"processor_output\")],\n", + ")\n", + "print(\"Response using processor output:\")\n", + "print(out[\"text\"])" + ] + }, + { + "cell_type": "markdown", + "id": "10", + "metadata": {}, + "source": [ + "### Call with Precomputed Embeddings\n", + "\n", + "You can pre-calculate image features to avoid repeated visual encoding processes." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "11", + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import AutoProcessor\n", + "from transformers import Qwen2_5_VLForConditionalGeneration\n", + "\n", + "processor = AutoProcessor.from_pretrained(model_path, use_fast=True)\n", + "vision = (\n", + " Qwen2_5_VLForConditionalGeneration.from_pretrained(model_path).eval().visual.cuda()\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "12", + "metadata": {}, + "outputs": [], + "source": [ + "processor_output = processor(\n", + " images=[image], text=conv.get_prompt(), return_tensors=\"pt\"\n", + ")\n", + "\n", + "input_ids = processor_output[\"input_ids\"][0].detach().cpu().tolist()\n", + "\n", + "precomputed_embeddings = vision(\n", + " processor_output[\"pixel_values\"].cuda(), processor_output[\"image_grid_thw\"].cuda()\n", + ")\n", + "\n", + "multi_modal_item = dict(\n", + " processor_output,\n", + " format=\"precomputed_embedding\",\n", + " feature=precomputed_embeddings,\n", + ")\n", + "\n", + "out = llm.generate(input_ids=input_ids, image_data=[multi_modal_item])\n", + "print(\"Response using precomputed embeddings:\")\n", + "print(out[\"text\"])\n", + "\n", + "llm.shutdown()" + ] + }, + { + "cell_type": "markdown", + "id": "13", + "metadata": {}, + "source": [ + "## Querying Llama 4 Vision Model\n", + "\n", + "```python\n", + "model_path = \"meta-llama/Llama-4-Scout-17B-16E-Instruct\"\n", + "chat_template = \"llama-4\"\n", + "\n", + "from io import BytesIO\n", + "import requests\n", + "from PIL import Image\n", + "\n", + "from sglang.srt.parser.conversation import chat_templates\n", + "\n", + "# Download the same example image\n", + "image = Image.open(\n", + " BytesIO(\n", + " requests.get(\n", + " \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\"\n", + " ).content\n", + " )\n", + ")\n", + "\n", + "conv = chat_templates[chat_template].copy()\n", + "conv.append_message(conv.roles[0], f\"What's shown here: {conv.image_token}?\")\n", + "conv.append_message(conv.roles[1], \"\")\n", + "conv.image_data = [image]\n", + "\n", + "print(\"Llama 4 generated prompt text:\")\n", + "print(conv.get_prompt())\n", + "print(f\"Image size: {image.size}\")\n", + "\n", + "image\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "14", + "metadata": {}, + "source": [ + "### Llama 4 Basic Call\n", + "\n", + "Llama 4 requires more computational resources, so it's configured with multi-GPU parallelism (tp_size=4) and larger context length.\n", + "\n", + "```python\n", + "llm = Engine(\n", + " model_path=model_path,\n", + " enable_multimodal=True,\n", + " attention_backend=\"fa3\",\n", + " tp_size=4,\n", + " context_length=65536,\n", + ")\n", + "\n", + "out = llm.generate(prompt=conv.get_prompt(), image_data=[image])\n", + "print(\"Llama 4 response:\")\n", + "print(out[\"text\"])\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "15", + "metadata": {}, + "source": [ + "### Call with Processor Output\n", + "\n", + "Using HuggingFace processor to preprocess data can reduce computational overhead during inference.\n", + "\n", + "```python\n", + "from transformers import AutoProcessor\n", + "\n", + "processor = AutoProcessor.from_pretrained(model_path, use_fast=True)\n", + "processor_output = processor(\n", + " images=[image], text=conv.get_prompt(), return_tensors=\"pt\"\n", + ")\n", + "\n", + "out = llm.generate(\n", + " input_ids=processor_output[\"input_ids\"][0].detach().cpu().tolist(),\n", + " image_data=[dict(processor_output, format=\"processor_output\")],\n", + ")\n", + "print(\"Response using processor output:\")\n", + "print(out)\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "16", + "metadata": {}, + "source": [ + "### Call with Precomputed Embeddings\n", + "\n", + "```python\n", + "from transformers import AutoProcessor\n", + "from transformers import Llama4ForConditionalGeneration\n", + "\n", + "processor = AutoProcessor.from_pretrained(model_path, use_fast=True)\n", + "model = Llama4ForConditionalGeneration.from_pretrained(\n", + " model_path, torch_dtype=\"auto\"\n", + ").eval()\n", + "\n", + "vision = model.vision_model.cuda()\n", + "multi_modal_projector = model.multi_modal_projector.cuda()\n", + "\n", + "print(f'Image pixel values shape: {processor_output[\"pixel_values\"].shape}')\n", + "input_ids = processor_output[\"input_ids\"][0].detach().cpu().tolist()\n", + "\n", + "# Process image through vision encoder\n", + "image_outputs = vision(\n", + " processor_output[\"pixel_values\"].to(\"cuda\"), \n", + " aspect_ratio_ids=processor_output[\"aspect_ratio_ids\"].to(\"cuda\"),\n", + " aspect_ratio_mask=processor_output[\"aspect_ratio_mask\"].to(\"cuda\"),\n", + " output_hidden_states=False\n", + ")\n", + "image_features = image_outputs.last_hidden_state\n", + "\n", + "# Flatten image features and pass through multimodal projector\n", + "vision_flat = image_features.view(-1, image_features.size(-1))\n", + "precomputed_embeddings = multi_modal_projector(vision_flat)\n", + "\n", + "# Build precomputed embedding data item\n", + "mm_item = dict(\n", + " processor_output, \n", + " format=\"precomputed_embedding\", \n", + " feature=precomputed_embeddings\n", + ")\n", + "\n", + "# Use precomputed embeddings for efficient inference\n", + "out = llm.generate(input_ids=input_ids, image_data=[mm_item])\n", + "print(\"Llama 4 precomputed embedding response:\")\n", + "print(out[\"text\"])\n", + "```" + ] + } + ], + "metadata": { + "jupytext": { + "cell_metadata_filter": "-all", + "custom_cell_magics": "kql", + "encoding": "# -*- coding: utf-8 -*-", + "text_representation": { + "extension": ".py", + "format_name": "light", + "format_version": "1.5", + "jupytext_version": "1.16.1" + } + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs_new/docs/advanced_features/vlm_query.mdx b/docs_new/docs/advanced_features/vlm_query.mdx new file mode 100644 index 000000000..47d8ff9a6 --- /dev/null +++ b/docs_new/docs/advanced_features/vlm_query.mdx @@ -0,0 +1,275 @@ +--- +title: "Query VLM with Offline Engine" +metatags: + description: "SGLang VLM offline engine: raw images, processor output, precomputed embeddings. Qwen2.5-VL and Llama 4 examples." +--- +This tutorial demonstrates how to use SGLang's **offline Engine API** to query VLMs. We will demonstrate usage with Qwen2.5-VL and Llama 4. This section demonstrates three different calling approaches: + +1. **Basic Call**: Directly pass images and text. +2. **Processor Output**: Use HuggingFace processor for data preprocessing. +3. **Precomputed Embeddings**: Pre-calculate image features to improve inference efficiency. + + +## Understanding the Three Input Formats + +SGLang supports three ways to pass visual data, each optimized for different scenarios: + +### 1. **Raw Images** - Simplest approach +- Pass PIL Images, file paths, URLs, or base64 strings directly +- SGLang handles all preprocessing automatically +- Best for: Quick prototyping, simple applications + +### 2. **Processor Output** - For custom preprocessing +- Pre-process images with HuggingFace processor +- Pass the complete processor output dict with `format: "processor_output"` +- Best for: Custom image transformations, integration with existing pipelines +- Requirement: Must use `input_ids` instead of text prompt + +### 3. **Precomputed Embeddings** - For maximum performance +- Pre-calculate visual embeddings using the vision encoder +- Pass embeddings with `format: "precomputed_embedding"` +- Best for: Repeated queries on same images, caching, high-throughput serving +- Performance gain: Avoids redundant vision encoder computation (30-50% speedup) + +**Key Rule**: Within a single request, use only one format for all images. Don't mix formats. + +The examples below demonstrate all three approaches with both Qwen2.5-VL and Llama 4 models. + + +## Querying Qwen2.5-VL Model + + + +```python Example +import nest_asyncio + +nest_asyncio.apply() + +model_path = "Qwen/Qwen2.5-VL-3B-Instruct" +chat_template = "qwen2-vl" +``` + + +```python Example +from io import BytesIO +import requests +from PIL import Image + +from sglang.srt.parser.conversation import chat_templates + +image = Image.open( + BytesIO( + requests.get( + "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" + ).content + ) +) + +conv = chat_templates[chat_template].copy() +conv.append_message(conv.roles[0], f"What's shown here: {conv.image_token}?") +conv.append_message(conv.roles[1], "") +conv.image_data = [image] + +print("Generated prompt text:") +print(conv.get_prompt()) +print(f"\nImage size: {image.size}") +image +``` + +### Basic Offline Engine API Call + + + +```python Example +from sglang import Engine + + +llm = Engine(model_path=model_path, chat_template=chat_template, log_level="warning") +``` + + +```python Example +out = llm.generate(prompt=conv.get_prompt(), image_data=[image]) +print("Model response:") +print(out["text"]) +``` + +### Call with Processor Output + +Using a HuggingFace processor to preprocess text and images, and passing the `processor_output` directly into `Engine.generate`. + + + +```python Example +from transformers import AutoProcessor + +processor = AutoProcessor.from_pretrained(model_path, use_fast=True) +processor_output = processor( + images=[image], text=conv.get_prompt(), return_tensors="pt" +) + +out = llm.generate( + input_ids=processor_output["input_ids"][0].detach().cpu().tolist(), + image_data=[dict(processor_output, format="processor_output")], +) +print("Response using processor output:") +print(out["text"]) +``` + +### Call with Precomputed Embeddings + +You can pre-calculate image features to avoid repeated visual encoding processes. + + + +```python Example +from transformers import AutoProcessor +from transformers import Qwen2_5_VLForConditionalGeneration + +processor = AutoProcessor.from_pretrained(model_path, use_fast=True) +vision = ( + Qwen2_5_VLForConditionalGeneration.from_pretrained(model_path).eval().visual.cuda() +) +``` + + +```python Example +processor_output = processor( + images=[image], text=conv.get_prompt(), return_tensors="pt" +) + +input_ids = processor_output["input_ids"][0].detach().cpu().tolist() + +precomputed_embeddings = vision( + processor_output["pixel_values"].cuda(), processor_output["image_grid_thw"].cuda() +) + +multi_modal_item = dict( + processor_output, + format="precomputed_embedding", + feature=precomputed_embeddings, +) + +out = llm.generate(input_ids=input_ids, image_data=[multi_modal_item]) +print("Response using precomputed embeddings:") +print(out["text"]) + +llm.shutdown() +``` + +## Querying Llama 4 Vision Model + +```python Example +model_path = "meta-llama/Llama-4-Scout-17B-16E-Instruct" +chat_template = "llama-4" + +from io import BytesIO +import requests +from PIL import Image + +from sglang.srt.parser.conversation import chat_templates + +# Download the same example image +image = Image.open( + BytesIO( + requests.get( + "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" + ).content + ) +) + +conv = chat_templates[chat_template].copy() +conv.append_message(conv.roles[0], f"What's shown here: {conv.image_token}?") +conv.append_message(conv.roles[1], "") +conv.image_data = [image] + +print("Llama 4 generated prompt text:") +print(conv.get_prompt()) +print(f"Image size: {image.size}") + +image +``` + + +### Llama 4 Basic Call + +Llama 4 requires more computational resources, so it's configured with multi-GPU parallelism (tp_size=4) and larger context length. + +```python Example +llm = Engine( + model_path=model_path, + enable_multimodal=True, + attention_backend="fa3", + tp_size=4, + context_length=65536, +) + +out = llm.generate(prompt=conv.get_prompt(), image_data=[image]) +print("Llama 4 response:") +print(out["text"]) +``` + + +### Call with Processor Output + +Using HuggingFace processor to preprocess data can reduce computational overhead during inference. + +```python Example +from transformers import AutoProcessor + +processor = AutoProcessor.from_pretrained(model_path, use_fast=True) +processor_output = processor( + images=[image], text=conv.get_prompt(), return_tensors="pt" +) + +out = llm.generate( + input_ids=processor_output["input_ids"][0].detach().cpu().tolist(), + image_data=[dict(processor_output, format="processor_output")], +) +print("Response using processor output:") +print(out) +``` + + +### Call with Precomputed Embeddings + +```python Example +from transformers import AutoProcessor +from transformers import Llama4ForConditionalGeneration + +processor = AutoProcessor.from_pretrained(model_path, use_fast=True) +model = Llama4ForConditionalGeneration.from_pretrained( + model_path, torch_dtype="auto" +).eval() + +vision = model.vision_model.cuda() +multi_modal_projector = model.multi_modal_projector.cuda() + +print(f'Image pixel values shape: {processor_output["pixel_values"].shape}') +input_ids = processor_output["input_ids"][0].detach().cpu().tolist() + +# Process image through vision encoder +image_outputs = vision( + processor_output["pixel_values"].to("cuda"), + aspect_ratio_ids=processor_output["aspect_ratio_ids"].to("cuda"), + aspect_ratio_mask=processor_output["aspect_ratio_mask"].to("cuda"), + output_hidden_states=False +) +image_features = image_outputs.last_hidden_state + +# Flatten image features and pass through multimodal projector +vision_flat = image_features.view(-1, image_features.size(-1)) +precomputed_embeddings = multi_modal_projector(vision_flat) + +# Build precomputed embedding data item +mm_item = dict( + processor_output, + format="precomputed_embedding", + feature=precomputed_embeddings +) + +# Use precomputed embeddings for efficient inference +out = llm.generate(input_ids=input_ids, image_data=[mm_item]) +print("Llama 4 precomputed embedding response:") +print(out["text"]) +``` diff --git a/docs_new/docs/basic_usage/deepseek_v3.mdx b/docs_new/docs/basic_usage/deepseek_v3.mdx new file mode 100644 index 000000000..78fd62d91 --- /dev/null +++ b/docs_new/docs/basic_usage/deepseek_v3.mdx @@ -0,0 +1,337 @@ +--- +title: "DeepSeek V3/V3.1/R1 Usage" +metatags: + description: "Deploy DeepSeek V3/R1 with SGLang: MLA optimization, FP8 quantization, multi-node TP, DP attention, MTP speculative decoding. Supports H200, B200, MI300X, A100." +--- +SGLang provides many optimizations specifically designed for the DeepSeek models, making it the inference engine recommended by the official [DeepSeek team](https://github.com/deepseek-ai/DeepSeek-V3/tree/main?tab=readme-ov-file#62-inference-with-sglang-recommended) from Day 0. + +This document outlines current optimizations for DeepSeek. +For an overview of the implemented features see the completed [Roadmap](https://github.com/sgl-project/sglang/issues/2591). + +## Launch DeepSeek V3.1/V3/R1 with SGLang + +To run DeepSeek V3.1/V3/R1 models, the recommended settings are as follows: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Weight TypeConfiguration
**Full precision [FP8](https://huggingface.co/deepseek-ai/DeepSeek-R1-0528)** *(recommended)*8 x H200
8 x B200
8 x MI300X
2 x 8 x H100/800/20
Xeon 6980P CPU
**Full precision ([BF16](https://huggingface.co/unsloth/DeepSeek-R1-0528-BF16))** (upcast from original FP8)2 x 8 x H200
2 x 8 x MI300X
4 x 8 x H100/800/20
4 x 8 x A100/A800
**Quantized weights ([INT8](https://huggingface.co/meituan/DeepSeek-R1-Channel-INT8))**16 x A100/800
32 x L40S
Xeon 6980P CPU
4 x Atlas 800I A3
**Quantized weights ([W4A8](https://huggingface.co/novita/Deepseek-R1-0528-W4AFP8))**8 x H20/100, 4 x H200
**Quantized weights ([AWQ](https://huggingface.co/QuixiAI/DeepSeek-R1-0528-AWQ))**8 x H100/800/20
8 x A100/A800
**Quantized weights ([MXFP4](https://huggingface.co/amd/DeepSeek-R1-MXFP4-Preview))**8, 4 x MI355X/350X
**Quantized weights ([NVFP4](https://huggingface.co/nvidia/DeepSeek-R1-0528-NVFP4-v2))**8, 4 x B200
+ + + +The official DeepSeek V3 is already in FP8 format, so you should not run it with any quantization arguments like `--quantization fp8`. + + +Detailed commands for reference: + +- [8 x H200](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#using-docker-recommended) +- [4 x B200, 8 x B200](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-one-b200-node) +- [8 x MI300X](../hardware-platforms/amd-gpus#running-deepseek-v3) +- [2 x 8 x H200](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-two-h208-nodes) +- [4 x 8 x A100](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-four-a1008-nodes) +- [8 x A100 (AWQ)](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-8-a100a800-with-awq-quantization) +- [16 x A100 (INT8)](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-16-a100a800-with-int8-quantization) +- [32 x L40S (INT8)](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-32-l40s-with-int8-quantization) +- [Xeon 6980P CPU](../hardware-platforms/cpu-server#example-running-deepseek-v31-terminus) +- [4 x Atlas 800I A3 (int8)](../hardware-platforms/ascend-npus/DeepSeek-Examples#running-deepseek-with-pd-disaggregation-on-4-x-atlas-800i-a3) + +### Download Weights +If you encounter errors when starting the server, ensure the weights have finished downloading. It's recommended to download them beforehand or restart multiple times until all weights are downloaded. Please refer to [DeepSeek V3](https://huggingface.co/deepseek-ai/DeepSeek-V3-Base#61-inference-with-deepseek-infer-demo-example-only) official guide to download the weights. + +### Launch with one node of 8 x H200 +Please refer to [the example](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#installation--launch). + +### Running examples on Multi-Node + +- [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/)) - Comprehensive guide on GB200 optimizations. + +- [Deploying DeepSeek with PD Disaggregation and Large-Scale Expert Parallelism on 96 H100 GPUs](https://lmsys.org/blog/2025-05-05-deepseek-pd-ep/) - Guide on PD disaggregation and large-scale EP. + +- [Serving with two H20*8 nodes](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-two-h208-nodes). + +- [Best Practices for Serving DeepSeek-R1 on H20](https://lmsys.org/blog/2025-09-26-sglang-ant-group/) - Comprehensive guide on H20 optimizations, deployment and performance. + +- [Serving with two H200*8 nodes and docker](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-two-h2008-nodes-and-docker). + +- [Serving with four A100*8 nodes](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-four-a1008-nodes). + +## Optimizations + +### Multi-head Latent Attention (MLA) Throughput Optimizations + +**Description**: [MLA](https://arxiv.org/pdf/2405.04434) is an innovative attention mechanism introduced by the DeepSeek team, aimed at improving inference efficiency. SGLang has implemented specific optimizations for this, including: + +- **Weight Absorption**: By applying the associative law of matrix multiplication to reorder computation steps, this method balances computation and memory access and improves efficiency in the decoding phase. + +- **MLA Attention Backends**: Currently SGLang supports different optimized MLA attention backends, including [FlashAttention3](https://github.com/Dao-AILab/flash-attention), [Flashinfer](https://docs.flashinfer.ai/api/attention.html#flashinfer-mla), [FlashMLA](https://github.com/deepseek-ai/FlashMLA), [CutlassMLA](https://github.com/sgl-project/sglang/pull/5390), **TRTLLM MLA** (optimized for Blackwell architecture), and [Triton](https://github.com/triton-lang/triton) backends. The default FA3 provides good performance across wide workloads. + +- **FP8 Quantization**: W8A8 FP8 and KV Cache FP8 quantization enables efficient FP8 inference. Additionally, we have implemented Batched Matrix Multiplication (BMM) operator to facilitate FP8 inference in MLA with weight absorption. + +- **CUDA Graph & Torch.compile**: Both MLA and Mixture of Experts (MoE) are compatible with CUDA Graph and Torch.compile, which reduces latency and accelerates decoding speed for small batch sizes. + +- **Chunked Prefix Cache**: Chunked prefix cache optimization can increase throughput by cutting prefix cache into chunks, processing them with multi-head attention and merging their states. Its improvement can be significant when doing chunked prefill on long sequences. Currently this optimization is only available for FlashAttention3 backend. + +Overall, with these optimizations, we have achieved up to **7x** acceleration in output throughput compared to the previous version. + + + Multi-head Latent Attention for DeepSeek Series Models + + +**Usage**: MLA optimization is enabled by default. + +**Reference**: Check [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 more details. + +### Data Parallelism Attention + +**Description**: This optimization involves data parallelism (DP) for the MLA attention mechanism of DeepSeek Series Models, which allows for a significant reduction in the KV cache size, enabling larger batch sizes. Each DP worker independently handles different types of batches (prefill, decode, idle), which are then synchronized before and after processing through the Mixture-of-Experts (MoE) layer. If you do not use DP attention, KV cache will be duplicated among all TP ranks. + + + Data Parallelism Attention for DeepSeek Series Models + + +With data parallelism attention enabled, we have achieved up to **1.9x** decoding throughput improvement compared to the previous version. + + + Data Parallelism Attention Performance Comparison + + +**Usage**: +- Append `--enable-dp-attention --tp 8 --dp 8` to the server arguments when using 8 H200 GPUs. This optimization improves peak throughput in high batch size scenarios where the server is limited by KV cache capacity. +- DP and TP attention can be flexibly combined. For example, to deploy DeepSeek-V3/R1 on 2 nodes with 8 H100 GPUs each, you can specify `--enable-dp-attention --tp 16 --dp 2`. This configuration runs attention with 2 DP groups, each containing 8 TP GPUs. + + +Data parallelism attention is not recommended for low-latency, small-batch use cases. It is optimized for high-throughput scenarios with large batch sizes. + + +**Reference**: Check [Blog](https://lmsys.org/blog/2024-12-04-sglang-v0-4/#data-parallelism-attention-for-deepseek-models). + +### Multi-Node Tensor Parallelism + +**Description**: For users with limited memory on a single node, SGLang supports serving DeepSeek Series Models, including DeepSeek V3, across multiple nodes using tensor parallelism. This approach partitions the model parameters across multiple GPUs or nodes to handle models that are too large for one node's memory. + +**Usage**: Check [here](https://github.com/sgl-project/sglang/tree/main/benchmark/deepseek_v3#example-serving-with-2-h208) for usage examples. + +### Block-wise FP8 + +**Description**: SGLang implements block-wise FP8 quantization with two key optimizations: + +- **Activation**: E4M3 format using per-token-per-128-channel sub-vector scales with online casting. + +- **Weight**: Per-128x128-block quantization for better numerical stability. + +- **DeepGEMM**: The [DeepGEMM](https://github.com/deepseek-ai/DeepGEMM) kernel library optimized for FP8 matrix multiplications. + +**Usage**: The activation and weight optimization above are turned on by default for DeepSeek V3 models. DeepGEMM is enabled by default on NVIDIA Hopper/Blackwell GPUs and disabled by default on other devices. DeepGEMM can also be manually turned off by setting the environment variable `SGLANG_ENABLE_JIT_DEEPGEMM=0`. + + +Before serving the DeepSeek model, precompile the DeepGEMM kernels to improve first-run performance. The precompilation process typically takes around 10 minutes to complete. + + +```bash Command +python3 -m sglang.compile_deep_gemm --model deepseek-ai/DeepSeek-V3 --tp 8 --trust-remote-code +``` + +### Multi-token Prediction +**Description**: SGLang implements DeepSeek V3 Multi-Token Prediction (MTP) based on [EAGLE speculative decoding](../advanced_features/speculative_decoding#EAGLE-Decoding). With this optimization, the decoding speed can be improved by **1.8x** for batch size 1 and **1.5x** for batch size 32 respectively on H200 TP8 setting. + +**Usage**: +Add `--speculative-algorithm EAGLE`. Other flags, like `--speculative-num-steps`, `--speculative-eagle-topk` and `--speculative-num-draft-tokens` are optional. For example: +```text Output +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3-0324 \ + --speculative-algorithm EAGLE \ + --trust-remote-code \ + --tp 8 +``` +- The default configuration for DeepSeek models is `--speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4`. The best configuration for `--speculative-num-steps`, `--speculative-eagle-topk` and `--speculative-num-draft-tokens` can be searched with [bench_speculative.py](https://github.com/sgl-project/sglang/blob/main/scripts/playground/bench_speculative.py) script for given batch size. The minimum configuration is `--speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2`, which can achieve speedup for larger batch sizes. +- Most MLA attention backends fully support MTP usage. See [MLA Backends](../advanced_features/attention_backend.md#mla-backends) for details. + + +To enable DeepSeek MTP for large batch sizes (>48), you need to adjust some parameters (Reference [this discussion](https://github.com/sgl-project/sglang/issues/4543#issuecomment-2737413756)): +- Adjust `--max-running-requests` to a larger number. The default value is `48` for MTP. For larger batch sizes, you should increase this value beyond the default value. +- Set `--cuda-graph-bs`. It's a list of batch sizes for cuda graph capture. The [default captured batch sizes for speculative decoding](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/server_args.py#L888-L895) is 48. You can customize this by including more batch sizes. + + + +To enable the experimental overlap scheduler for EAGLE speculative decoding, set the environment variable `SGLANG_ENABLE_SPEC_V2=1`. This can improve performance by enabling overlap scheduling between draft and verification stages. + + + +### Reasoning Content for DeepSeek R1 & V3.1 + +See [Reasoning Parser](../advanced_features/separate_reasoning) and [Thinking Parameter for DeepSeek V3.1](./openai_api_completions#Example:-DeepSeek-V3-Models). + + +### Function calling for DeepSeek Models + +Add arguments `--tool-call-parser deepseekv3` and `--chat-template ./examples/chat_template/tool_chat_template_deepseekv3.jinja`(recommended) to enable this feature. For example (running on 1 * H20 node): + +```text Output +python3 -m sglang.launch_server \ + --model deepseek-ai/DeepSeek-V3-0324 \ + --tp 8 \ + --port 30000 \ + --host 0.0.0.0 \ + --mem-fraction-static 0.9 \ + --tool-call-parser deepseekv3 \ + --chat-template ./examples/chat_template/tool_chat_template_deepseekv3.jinja +``` + +Sample Request: + +```text Output +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-0324", "tools": [{"type": "function", "function": {"name": "query_weather", "description": "Get weather of an city, the user should supply a city first", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "The city, e.g. Beijing"}}, "required": ["city"]}}}], "messages": [{"role": "user", "content": "Hows the weather like in Qingdao today"}]}' +``` + +Expected Response + +```text Output +{"id":"6501ef8e2d874006bf555bc80cddc7c5","object":"chat.completion","created":1745993638,"model":"deepseek-ai/DeepSeek-V3-0324","choices":[{"index":0,"message":{"role":"assistant","content":null,"reasoning_content":null,"tool_calls":[{"id":"0","index":null,"type":"function","function":{"name":"query_weather","arguments":"{\"city\": \"Qingdao\"}"}}]},"logprobs":null,"finish_reason":"tool_calls","matched_stop":null}],"usage":{"prompt_tokens":116,"total_tokens":138,"completion_tokens":22,"prompt_tokens_details":null}} + +``` +Sample Streaming Request: +```text Output +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-0324","stream":true,"tools": [{"type": "function", "function": {"name": "query_weather", "description": "Get weather of an city, the user should supply a city first", "parameters": {"type": "object", "properties": {"city": {"type": "string", "description": "The city, e.g. Beijing"}}, "required": ["city"]}}}], "messages": [{"role": "user", "content": "Hows the weather like in Qingdao today"}]}' +``` +Expected Streamed Chunks (simplified for clarity): +```text Output +data: {"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"{\""}}]}}]} +data: {"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"city"}}]}}]} +data: {"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"\":\""}}]}}]} +data: {"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"Q"}}]}}]} +data: {"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"ing"}}]}}]} +data: {"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"dao"}}]}}]} +data: {"choices":[{"delta":{"tool_calls":[{"function":{"arguments":"\"}"}}]}}]} +data: {"choices":[{"delta":{"tool_calls":null}}], "finish_reason": "tool_calls"} +data: [DONE] +``` +The client needs to concatenate all arguments fragments to reconstruct the complete tool call: +```text Output +{"city": "Qingdao"} +``` + +1. Use a lower `"temperature"` value for better results. +2. To receive more consistent tool call results, it is recommended to use `--chat-template examples/chat_template/tool_chat_template_deepseekv3.jinja`. It provides an improved unified prompt. + + + +### Thinking Budget for DeepSeek R1 + +In SGLang, we can implement thinking budget with `CustomLogitProcessor`. + +Launch a server with `--enable-custom-logit-processor` flag on. + +```text Output +python3 -m sglang.launch_server --model deepseek-ai/DeepSeek-R1 --tp 8 --port 30000 --host 0.0.0.0 --mem-fraction-static 0.9 --disable-cuda-graph --reasoning-parser deepseek-r1 --enable-custom-logit-processor +``` + +Sample Request: + + +```python Sample Request +import openai +from rich.pretty import pprint +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": "Question: Is Paris the Capital of France?", + } + ], + max_tokens=1024, + extra_body={ + "custom_logit_processor": DeepSeekR1ThinkingBudgetLogitProcessor().to_str(), + "custom_params": { + "thinking_budget": 512, + }, + }, +) +pprint(response) +``` + + +## FAQ + +**Q: Model loading is taking too long, and I'm encountering an NCCL timeout. What should I do?** + +A: If you're experiencing extended model loading times and an NCCL timeout, you can try increasing the timeout duration. Add the argument `--dist-timeout 3600` when launching your model. This will set the timeout to one hour, which often resolves the issue. diff --git a/docs_new/docs/basic_usage/deepseek_v32.mdx b/docs_new/docs/basic_usage/deepseek_v32.mdx new file mode 100644 index 000000000..3a9b1643b --- /dev/null +++ b/docs_new/docs/basic_usage/deepseek_v32.mdx @@ -0,0 +1,575 @@ +--- +title: "DeepSeek V3.2 Usage" +metatags: + description: "Deploy DeepSeek V3.2 with SGLang: DeepSeek Sparse Attention (DSA), long-context optimization, MTP speculative decoding, function calling. Supports H200, B200, MI300X, MI350." +--- +DeepSeek-V3.2 model family equips DeepSeek-V3.1-Terminus with DeepSeek Sparse Attention (DSA) through continued training. With DSA, a fine-grained sparse attention mechanism powered by a lightning indexer, DeepSeek-V3.2 achieves efficiency improvements in long-context scenarios. + +For reporting issues or tracking upcoming features, please refer to this [Roadmap](https://github.com/sgl-project/sglang/issues/11060). + +Note: This document is originally written for the usage of [DeepSeek-V3.2-Exp](https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Exp) model. The usage of [DeepSeek-V3.2](https://huggingface.co/deepseek-ai/DeepSeek-V3.2) or [DeepSeek-V3.2-Speciale](https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Speciale) is the same as DeepSeek-V3.2-Exp except for the tool call parser. + + +## Installation + +### Docker + +```bash Command +# H200/B200 +docker pull lmsysorg/sglang:latest + +# MI350/MI355 +docker pull lmsysorg/sglang:v0.5.8-rocm700-mi35x + +# MI300 +# 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 (below). +docker pull lmsysorg/sglang:v0.5.8-rocm700-mi30x + + +# NPUs +docker pull lmsysorg/sglang:dsv32-a2 +docker pull lmsysorg/sglang:dsv32-a3 +``` + +### Build From Source + +```bash Command +# Install SGLang +git clone https://github.com/sgl-project/sglang +cd sglang +pip3 install pip --upgrade +pip3 install -e "python" +``` +## Launch DeepSeek V3.2 with SGLang + +To serve [DeepSeek-V3.2-Exp](https://huggingface.co/deepseek-ai/DeepSeek-V3.2-Exp) on 8xH200/B200 GPUs: + +```bash Command +# Launch with TP + DP (Recommended) +python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 --dp 8 --enable-dp-attention + +# Launch with EP + DP +python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 --ep 8 --dp 8 --enable-dp-attention + +# Launch with Pure TP +python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 + +# Launch with TP on MI30x/MI35x +python3 -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 --nsa-prefill-backend tilelang --nsa-decode-backend tilelang +``` + +### Configuration Tips +- **DP Attention (Recommended)**: For DeepSeek V3.2 model, the kernels are customized for the use case of `dp_size=8`, so DP attention (`--dp 8 --enable-dp-attention`) is the recommended configuration for better stability and performance. All test cases use this configuration by default. +- **Pure TP Mode**: Launching with pure TP (without `--dp` and `--enable-dp-attention`) is also supported. Note that this mode has not been fully validated in PD disaggregation scenarios. +- **Short-sequence MHA prefill (adaptive)**: For short prefill sequences (default threshold: **2048 tokens**), the NSA backend uses standard MHA automatically (no extra flags). On H200 (SM90) this path uses the FlashAttention variable-length kernel; on B200 (SM100) it uses TRT-LLM ragged MHA. MHA uses `MHA_ONE_SHOT` for best performance. `MHA_ONE_SHOT` computes multi-head attention over all tokens (both cached prefix and newly extended tokens) in a single kernel invocation, avoiding the overhead of chunked KV cache processing. This achieves optimal throughput for short sequences where total sequence length fits within the chunk capacity limit. +- **Choices of Attention Kernels**: The attention backend is automatically set to `nsa` attention backend for DeepSeek V3.2 model. In this backend, different kernels for sparse prefilling/decoding are implemented, which can be specified by `--nsa-prefill-backend` and `--nsa-decode-backend` server arguments. The choices of nsa prefill/decode attention kernels include: + - `flashmla_sparse`: `flash_mla_sparse_fwd` kernel from `flash_mla` library. Can run on both Hopper and Blackwell GPUs. It requires bf16 q, kv inputs. + - `flashmla_kv`: `flash_mla_with_kvcache` kernel from `flash_mla` library. Can run on both Hopper and Blackwell GPUs. It requires bf16 q, fp8 k_cache inputs. + - `fa3`: `flash_attn_with_kvcache` kernel from `flash_attn` library. Can only run on Hopper GPUs. It requires bf16 q, kv inputs. + - `tilelang`: `tilelang` implementation that can run on GPU, HPU and NPU. + - `aiter`: Aiter kernel on AMD HPUs. Can only be used as decode kernel. +- On the basis of performance benchmarks, the default configuration on H200 and B200 are set as follows : + - H200: `flashmla_sparse` prefill attention (short-seq prefill uses MHA via FlashAttention varlen), `fa3` decode attention, `bf16` kv cache dtype. + - B200: `flashmla_auto` prefill attention (short-seq prefill uses MHA via TRT-LLM ragged), `flashmla_kv` decode attention, `fp8_e4m3` kv cache dtype. `flashmla_auto` enables automatic selection of either `flashmla_sparse` or `flashmla_kv` kernel for prefill based on KV cache dtype, hardware, and heuristics. When FP8 KV cache is enabled and `total_kv_tokens < total_q_tokens * 512`, it uses the `flashmla_sparse` kernel; otherwise, it falls back to the `flashmla_kv` kernel. The heuristics may need to be tuned if the performance of either the `flashmla_sparse` or `flashmla_kv` kernel changes significantly. + +## Multi-token Prediction +SGLang implements Multi-Token Prediction (MTP) for DeepSeek V3.2 based on [EAGLE speculative decoding](../advanced_features/speculative_decoding#EAGLE-Decoding). With this optimization, the decoding speed can be improved significantly on small batch sizes. Please look at [this PR](https://github.com/sgl-project/sglang/pull/11652) for more information. + +Example usage with DP Attention: +```bash Command +python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 --dp 8 --enable-dp-attention --speculative-algorithm EAGLE --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 +``` + +Example usage with Pure TP: +```bash Command +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 +``` + +- The best configuration for `--speculative-num-steps`, `--speculative-eagle-topk` and `--speculative-num-draft-tokens` can be searched with [bench_speculative.py](https://github.com/sgl-project/sglang/blob/main/scripts/playground/bench_speculative.py) script for given batch size. The minimum configuration is `--speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2`, which can achieve speedup for larger batch sizes. +- The default value of `--max-running-requests` is set to `48` for MTP. For larger batch sizes, this value should be increased beyond the default value. + + +To enable the experimental overlap scheduler for EAGLE speculative decoding, set the environment variable `SGLANG_ENABLE_SPEC_V2=1`. This can improve performance by enabling overlap scheduling between draft and verification stages. + + + +## Function Calling and Reasoning Parser +The usage of function calling and reasoning parser is the same as DeepSeek V3.1. Please refer to [Reasoning Parser](../advanced_features/separate_reasoning) and [Tool Parser](../advanced_features/tool_parser) documents. + +To launch `DeepSeek-V3.2-Exp` with function calling and reasoning parser: + +It is recommended to specify the chat-template, ensuring that you are within the sglang's root directory. + + +```bash Command +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2-Exp \ + --trust-remote-code \ + --tp-size 8 --dp-size 8 --enable-dp-attention \ + --tool-call-parser deepseekv31 \ + --reasoning-parser deepseek-v3 \ + --chat-template ./examples/chat_template/tool_chat_template_deepseekv32.jinja +``` + +To launch `DeepSeek-V3.2` with function calling and reasoning parser: +```bash Command +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2 \ + --trust-remote-code \ + --tp-size 8 --dp-size 8 --enable-dp-attention \ + --tool-call-parser deepseekv32 \ + --reasoning-parser deepseek-v3 +``` + +`DeepSeek-V3.2-Speciale` doesn't support tool calling, so can only be launched with reasoning parser: +```bash Command +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2-Speciale \ + --trust-remote-code \ + --tp-size 8 --dp-size 8 --enable-dp-attention \ + --reasoning-parser deepseek-v3 +``` + + +## PD Disaggregation + +Prefill Command: +```bash Command +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2-Exp \ + --disaggregation-mode prefill \ + --host $LOCAL_IP \ + --port $PORT \ + --tp 8 \ + --dp 8 \ + --enable-dp-attention \ + --dist-init-addr ${HOST}:${DIST_PORT} \ + --trust-remote-code \ + --disaggregation-bootstrap-port 8998 \ + --mem-fraction-static 0.9 \ +``` + +Decode command: +```bash Command +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2-Exp \ + --disaggregation-mode decode \ + --host $LOCAL_IP \ + --port $PORT \ + --tp 8 \ + --dp 8 \ + --enable-dp-attention \ + --dist-init-addr ${HOST}:${DIST_PORT} \ + --trust-remote-code \ + --mem-fraction-static 0.9 \ +``` + +Router command: +```bash Command +python -m sglang_router.launch_router --pd-disaggregation \ + --prefill $PREFILL_ADDR 8998 \ + --decode $DECODE_ADDR \ + --host 127.0.0.1 \ + --port 8000 \ +``` + +If you need more advanced deployment methods or production-ready deployment methods, such as RBG or LWS-based deployment, please refer to [references/multi_node_deployment/rbg_pd/deepseekv32_pd](../references/multi_node_deployment/rbg_pd/deepseekv32_pd). Additionally, you can also find startup commands for DeepEP-based EP parallelism in the aforementioned documentation. + + +## Benchmarking Results + +### Accuracy Test with `gsm8k` +A simple accuracy benchmark can be tested with `gsm8k` dataset: +```bash Command +python3 benchmark/gsm8k/bench_sglang.py --num-shots 8 --num-questions 1319 --parallel 1319 +``` + +The result is 0.956, which matches our expectation: +```bash Command +Accuracy: 0.956 +Invalid: 0.000 +Latency: 25.109 s +Output throughput: 5226.235 token/s +``` + +To test long-context accuracy, run gsm8k with `--num-shots 20`. The results are very close to the 8 shots results: +```text Output +Accuracy: 0.956 +Invalid: 0.000 +Latency: 29.545 s +Output throughput: 4418.617 token/s +``` + + +### Accuracy Test with `gpqa-diamond` + +Accuracy benchmark on long context can be tested on GPQA-diamond dataset with long output tokens and thinking enabled: +```bash Command +python3 -m sglang.test.run_eval --port 30000 --eval-name gpqa --num-examples 198 --max-tokens 128000 --repeat 8 --thinking-mode deepseek-v3 +``` + +The mean accuracy over 8 runs shows 0.797, which matches the number 0.799 in official tech report. +```bash Command +Repeat: 8, mean: 0.797 +Scores: ['0.808', '0.798', '0.808', '0.798', '0.783', '0.788', '0.803', '0.793'] +``` + +For Deepseek V3.2, Deepseek recommends setting the sampling parameters to temperature = 1.0, top_p = 0.95: + +```bash Command +python3 -m sglang.test.run_eval --port 30000 --eval-name gpqa --num-examples 198 --max-tokens 128000 --repeat 8 --top-p 0.95 --temperature 1.0 --thinking-mode deepseek-v3 + +Repeat: 8, mean: 0.840 +Scores: ['0.848', '0.808', '0.848', '0.838', '0.879', '0.813', '0.838', '0.848'] +``` +which matches the official score, 0.824, as reported in the [Deepseek-V3.2 technical report](https://huggingface.co/deepseek-ai/DeepSeek-V3.2/blob/main/assets/paper.pdf). + +### Accuracy Test with `aime 2025` + +Prepare the environment by installing NeMo-Skills in the docker or your own virtual environment: + + ```text Output + pip install git+https://github.com/NVIDIA/NeMo-Skills.git --ignore-installed blinker + ``` + +Then launch the SGLang server: +```text Output +python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 --dp 8 --enable-dp-attention +``` + +**For `DeepSeek-V3.2` and `DeepSeek-V3.2-Speciale`**: + +```text Output +python3 -m sglang.launch_server --model-path deepseek-ai/DeepSeek-V3.2 --trust-remote-code --tp-size 8 --dp-size 8 --enable-dp-attention --tool-call-parser deepseekv32 --reasoning-parser deepseek-v3 +``` + +Run the following script to evaluate AIME 2025: +```text Output +#! /bin/bash +export NEMO_SKILLS_DISABLE_UNCOMMITTED_CHANGES_CHECK=1 + +ns prepare_data aime25 + +PORT=30000 +BACKEND=sglang +MODEL="deepseek-ai/DeepSeek-V3.2-Exp" # Should be changed to the model name +MODEL_NAME="dsv32-fp8" + +echo "Starting AIME25 evaluation with model $MODEL on port $PORT using backend $BACKEND..." +ns eval \ + --benchmarks=aime25:4 \ + --server_type=$BACKEND \ + --model=$MODEL \ + --server_address=http://localhost:${PORT}/v1 \ + --output_dir=nemo_skills_aime25_${MODEL_NAME}_output_${BACKEND}_$(date +%Y%m%d_%H%M%S) \ + ++chat_template_kwargs.thinking=true \ + ++inference.temperature=1.0 \ + ++inference.top_p=0.95 \ + ++inference.tokens_to_generate=64000 + # ++inference.tokens_to_generate=120000 for Speciale model +``` + +Test results (8*B200): + +DeepSeek-V3.2-Exp: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
evaluation_modenum_entriesavg_tokensgen_secondssymbolic_correctno_answer
pass@1[avg-of-4]3015040167387.50% ± 1.67%0.00%
majority@43015040167390.00%0.00%
pass@43015040167390.00%0.00%
+ + +DeepSeek-V3.2: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
evaluation_modenum_entriesavg_tokensgen_secondssymbolic_correctno_answer
pass@1[avg-of-4]3013550163292.50% ± 1.67%0.00%
majority@43013550163294.71%0.00%
pass@43013550163296.67%0.00%
+ + +DeepSeek-V3.2-Speciale: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
evaluation_modenum_entriesavg_tokensgen_secondssymbolic_correctno_answer
pass@1[avg-of-4]3024155358395.00% ± 1.92%0.00%
majority@43024155358395.83%0.00%
pass@430241553583100.00%0.00%
+ + + +## DSA long sequence context parallel optimization(experimental) + +**Note: This feature is only verified on Hopper machines** + +For context parallel in DeepSeek V3.2 model, we provide two different modes of splitting tokens, which can be controlled with argument `--nsa-prefill-cp-mode`. + +### In sequence splitting (default setting) + +The first mode can be enabled by `--nsa-prefill-cp-mode in-seq-split`. This mode implements context parallel for DSA by splitting the sequence uniformly between context parallel ranks. At attention stage, each cp rank computes the indexer results of sharded sequence, and collects the whole kv cache through all gather operator. + +The communication group for context parallel reuses the one for attention tp, thus `cp_size` equals `atten_tp_size = tp_size / dp_size`. + +Note that in sequence splitting mode has the following restrictions: +- The batch size is restricted to 1 for prefill batches +- Multi-node/PD disaggregation is still not supported +- `moe_dense_tp_size=1`, `kv_cache_dtype = "bf16"`, `moe_a2a_backend = "deepep"` +- To ensure `cp_size > 1`, the passed in `tp_size` must be larger than `dp_size` + +For more details, please refer to PR https://github.com/sgl-project/sglang/pull/12065. + +Example: +```bash Command +# In-seq splitting mode launched with EP + DP +python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 --ep 8 --dp 2 --enable-dp-attention --enable-nsa-prefill-context-parallel --nsa-prefill-cp-mode in-seq-split --max-running-requests 32 +``` + +### Round robin splitting + +This mode can be enabled by specifying the parameter `--nsa-prefill-cp-mode round-robin-split`, which distributes tokens across ranks based on `token_idx % cp_size`. + +In this scenario, compared with the aforementioned method, it additionally supports the fused MoE backend (the fused MoE backend may deliver better performance than DeepEP in single-machine scenarios), FP8 KV-cache, and multi-batch prefill inference. But it cannot be enabled with dp attention together. + +For more details, please refer to PR https://github.com/sgl-project/sglang/pull/13959. + +Example usage: +```bash Command +# Launch with FusedMoe + CP8 +python -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.2-Exp --tp 8 --enable-nsa-prefill-context-parallel --nsa-prefill-cp-mode round-robin-split --max-running-requests 32 +``` +### Pipeline Parallel + Context Parallel (PP + CP) + +This mode combines Pipeline Parallelism (PP) and Context Parallelism (CP) to scale across multiple nodes, which can achieve better throughput and Time To First Token (TTFT). Note that this method has only been tested on H20 96G. + +#### Standard Usage + +To launch with PP=2 and CP (via `round-robin-split` mode) on 2 nodes. This configuration uses the fused MoE kernel by default, which generally provides better performance. + +For related development details, please refer to: +- Fused MoE + CP support: [PR #13959](https://github.com/sgl-project/sglang/pull/13959) +- PP + CP support: [Issue #15358](https://github.com/sgl-project/sglang/issues/15358) and [PR #16380](https://github.com/sgl-project/sglang/pull/16380) + +Node 0: +```bash Command +export SGLANG_PP_LAYER_PARTITION=30,31 +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2-Exp \ + --nnodes 2 --node-rank 0 \ + --dist-init-addr :62001 \ + --tp 8 --pp-size 2 \ + --dp-size 1 --moe-dense-tp-size 1 \ + --enable-nsa-prefill-context-parallel \ + --nsa-prefill-cp-mode round-robin-split \ + --trust-remote-code \ + --disable-radix-cache \ + --mem-fraction-static 0.8 \ + --max-running-requests 128 \ + --chunked-prefill-size 16384 \ + --cuda-graph-max-bs 8 \ + --page-size 64 \ + --watchdog-timeout 3600 \ + --host 0.0.0.0 --port 8000 \ + --tool-call-parser deepseekv32 +``` + +Node 1: +```bash Command +export SGLANG_PP_LAYER_PARTITION=30,31 +python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2-Exp \ + --nnodes 2 --node-rank 1 \ + --dist-init-addr :62001 \ + --tp 8 --pp-size 2 \ + --dp-size 1 --moe-dense-tp-size 1 \ + --enable-nsa-prefill-context-parallel \ + --nsa-prefill-cp-mode round-robin-split \ + --trust-remote-code \ + --disable-radix-cache \ + --mem-fraction-static 0.8 \ + --max-running-requests 128 \ + --chunked-prefill-size 16384 \ + --cuda-graph-max-bs 8 \ + --page-size 64 \ + --watchdog-timeout 3600 \ + --host 0.0.0.0 --port 8000 \ + --tool-call-parser deepseekv32 +``` + +#### PD Disaggregation with PP + CP + +If using PD (Prefill-Decode) Disaggregation, the Prefill nodes can be configured with PP + CP as follows. + +Prefill Node 0: +```bash Command +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2-Exp \ + --served-model-name deepseek-v32 \ + --nnodes 2 --node-rank 0 \ + --dist-init-addr :20102 \ + --tp 8 --pp-size 2 \ + --dp-size 1 --moe-dense-tp-size 1 \ + --enable-nsa-prefill-context-parallel \ + --nsa-prefill-cp-mode round-robin-split \ + --disaggregation-ib-device mlx5_bond_0,mlx5_bond_1,mlx5_bond_2,mlx5_bond_3 \ + --trust-remote-code \ + --disable-radix-cache \ + --max-running-requests 512 \ + --chunked-prefill-size 4096 \ + --context-length 131072 \ + --mem-fraction-static 0.9 \ + --page-size 64 \ + --enable-metrics \ + --collect-tokens-histogram \ + --tokenizer-worker-num 8 \ + --host 0.0.0.0 --port 30000 +``` + +Prefill Node 1: +```bash Command +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3.2-Exp \ + --served-model-name deepseek-v32-prefill \ + --nnodes 2 --node-rank 1 \ + --dist-init-addr :20102 \ + --tp 8 --pp-size 2 \ + --dp-size 1 --moe-dense-tp-size 1 \ + --enable-nsa-prefill-context-parallel \ + --nsa-prefill-cp-mode round-robin-split \ + --disaggregation-ib-device mlx5_bond_0,mlx5_bond_1,mlx5_bond_2,mlx5_bond_3 \ + --trust-remote-code \ + --disable-radix-cache \ + --max-running-requests 512 \ + --chunked-prefill-size 4096 \ + --context-length 131072 \ + --mem-fraction-static 0.9 \ + --page-size 64 \ + --enable-metrics \ + --collect-tokens-histogram \ + --tokenizer-worker-num 8 \ + --host 0.0.0.0 --port 30000 +``` + +For the Decode nodes, it is recommended to use the **EP mode**. diff --git a/docs_new/docs/basic_usage/glm45.mdx b/docs_new/docs/basic_usage/glm45.mdx new file mode 100644 index 000000000..8ccb41492 --- /dev/null +++ b/docs_new/docs/basic_usage/glm45.mdx @@ -0,0 +1,76 @@ +--- +title: "Launch GLM-4.5 / GLM-4.6 / GLM-4.7 with SGLang" +metatags: + description: "Deploy GLM-4.5/4.6/4.7 models with SGLang: FP8 inference, EAGLE speculative decoding, function calling support. Optimized for H100/H200 GPUs." +--- + +## Launch GLM-4.5 / GLM-4.6 / GLM-4.7 with SGLang + +To serve GLM-4.5 / GLM-4.6 FP8 models on 8xH100/H200 GPUs: + +```bash Command +python3 -m sglang.launch_server --model zai-org/GLM-4.6-FP8 --tp 8 +``` + +### EAGLE Speculative Decoding + +**Description**: SGLang has supported GLM-4.5 / GLM-4.6 models +with [EAGLE speculative decoding](../advanced_features/speculative_decoding#EAGLE-Decoding). + +**Usage**: +Add arguments `--speculative-algorithm`, `--speculative-num-steps`, `--speculative-eagle-topk` and +`--speculative-num-draft-tokens` to enable this feature. For example: + +```bash Command +python3 -m sglang.launch_server \ + --model-path zai-org/GLM-4.6-FP8 \ + --tp-size 8 \ + --tool-call-parser glm45 \ + --reasoning-parser glm45 \ + --speculative-algorithm EAGLE \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 \ + --mem-fraction-static 0.9 \ + --served-model-name glm-4.6-fp8 \ + --enable-custom-logit-processor +``` + + +To enable the experimental overlap scheduler for EAGLE speculative decoding, set the environment variable `SGLANG_ENABLE_SPEC_V2=1`. This can improve performance by enabling overlap scheduling between draft and verification stages. + + +### Thinking Budget for GLM-4.5 / GLM-4.6 +**Note**: For GLM-4.7, `--tool-call-parser` should be set to `glm47`, for GLM-4.5 and GLM-4.6, it should be set to `glm45`. + +In SGLang, we can implement thinking budget with `CustomLogitProcessor`. + +Launch a server with `--enable-custom-logit-processor` flag on. + +Sample Request: + +```python Example +import openai +from rich.pretty import pprint +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": "Question: Is Paris the Capital of France?", + } + ], + max_tokens=1024, + extra_body={ + "custom_logit_processor": Glm4MoeThinkingBudgetLogitProcessor().to_str(), + "custom_params": { + "thinking_budget": 512, + }, + }, +) +pprint(response) +``` diff --git a/docs_new/docs/basic_usage/glmv.mdx b/docs_new/docs/basic_usage/glmv.mdx new file mode 100644 index 000000000..0427a4ad0 --- /dev/null +++ b/docs_new/docs/basic_usage/glmv.mdx @@ -0,0 +1,139 @@ +--- +title: "GLM-4.6V / GLM-4.5V Usage" +metatags: + description: "Deploy GLM-4.6V/4.5V vision models with SGLang: FP8 and BF16 modes, expert parallelism, video understanding. Supports H100, H200, A100 GPUs." +--- +## Launch commands for SGLang + +Below are suggested launch commands tailored for different hardware / precision modes + +### FP8 (quantised) mode + +For high memory-efficiency and latency optimized deployments (e.g., on H100, H200) where FP8 checkpoint is supported: + +```bash Command +python3 -m sglang.launch_server \ + --model-path zai-org/GLM-4.6V-FP8 \ + --tp 2 \ + --ep 2 \ + --host 0.0.0.0 \ + --port 30000 \ + --keep-mm-feature-on-device +``` + +### Non-FP8 (BF16 / full precision) mode +For deployments on A100/H100 where BF16 is used (or FP8 snapshot not used): +```bash Command +python3 -m sglang.launch_server \ + --model-path zai-org/GLM-4.6V \ + --tp 4 \ + --ep 4 \ + --host 0.0.0.0 \ + --port 30000 +``` + +## Hardware-specific notes / recommendations + +- On H100 with FP8: Use the FP8 checkpoint for best memory efficiency. +- On A100 / H100 with BF16 (non-FP8): It’s recommended to use `--mm-max-concurrent-calls` to control parallel throughput and GPU memory usage during image/video inference. +- On H200 & B200: The model can be run “out of the box”, supporting full context length plus concurrent image + video processing. + +## Sending Image/Video Requests + +### Image input: + +```python Example +import requests + +url = f"http://localhost:30000/v1/chat/completions" + +data = { + "model": "zai-org/GLM-4.6V", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What’s in this image?"}, + { + "type": "image_url", + "image_url": { + "url": "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" + }, + }, + ], + } + ], + "max_tokens": 300, +} + +response = requests.post(url, json=data) +print(response.text) +``` + +### Video Input: + +```python Example +import requests + +url = f"http://localhost:30000/v1/chat/completions" + +data = { + "model": "zai-org/GLM-4.6V", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What’s happening in this video?"}, + { + "type": "video_url", + "video_url": { + "url": "https://github.com/sgl-project/sgl-test-files/raw/refs/heads/main/videos/jobs_presenting_ipod.mp4" + }, + }, + ], + } + ], + "max_tokens": 300, +} + +response = requests.post(url, json=data) +print(response.text) +``` + +## Important Server Parameters and Flags + +When launching the model server for **multimodal support**, you can use the following command-line arguments to fine-tune performance and behavior: + +- `--mm-attention-backend`: Specify multimodal attention backend. Eg. `fa3`(Flash Attention 3) +- `--mm-max-concurrent-calls `: Specifies the **maximum number of concurrent asynchronous multimodal data processing calls** allowed on the server. Use this to control parallel throughput and GPU memory usage during image/video inference. +- `--mm-per-request-timeout `: Defines the **timeout duration (in seconds)** for each multimodal request. If a request exceeds this time limit (e.g., for very large video inputs), it will be automatically terminated. +- `--keep-mm-feature-on-device`: Instructs the server to **retain multimodal feature tensors on the GPU** after processing. This avoids device-to-host (D2H) memory copies and improves performance for repeated or high-frequency inference workloads. +- `--mm-enable-dp-encoder`: Placing the ViT in data parallel while keeping the LLM in tensor parallel consistently lowers TTFT and boosts end-to-end throughput. +- `SGLANG_USE_CUDA_IPC_TRANSPORT=1`: Shared memory pool based CUDA IPC for multi-modal data transport. For significantly improving e2e latency. + +### Example usage with the above optimizations: +```bash Command +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 +``` + +### Thinking Budget for GLM-4.5V / GLM-4.6V + +In SGLang, we can implement thinking budget with `CustomLogitProcessor`. + +Launch a server with `--enable-custom-logit-processor` flag on. and using `Glm4MoeThinkingBudgetLogitProcessor` in the request likes `GLM-4.6` example in [glm45](./glm45). diff --git a/docs_new/docs/basic_usage/gpt_oss.mdx b/docs_new/docs/basic_usage/gpt_oss.mdx new file mode 100644 index 000000000..25c656e91 --- /dev/null +++ b/docs_new/docs/basic_usage/gpt_oss.mdx @@ -0,0 +1,181 @@ +--- +title: "GPT OSS Usage" +metatags: + description: "Deploy GPT-OSS with SGLang: OpenAI Responses API compatible, built-in tools for web search and Python execution, reasoning levels, MCP tool server support." +--- +Please refer to [#8833](https://github.com/sgl-project/sglang/issues/8833). + +## Responses API & Built-in Tools + +### Responses API + +GPT‑OSS is compatible with the OpenAI Responses API. Use `client.responses.create(...)` with `model`, `instructions`, `input`, and optional `tools` to enable built‑in tool use. You can set reasoning level via `instructions`, e.g., "Reasoning: high" (also supports "medium" and "low") — levels: low (fast), medium (balanced), high (deep). + +### Built-in Tools + +GPT‑OSS can call built‑in tools for web search and Python execution. You can use the demo tool server or connect to external MCP tool servers. + +#### Python Tool + +- Executes short Python snippets for calculations, parsing, and quick scripts. +- By default runs in a Docker-based sandbox. To run on the host, set `PYTHON_EXECUTION_BACKEND=UV` (this executes model-generated code locally; use with care). +- Ensure Docker is available if you are not using the UV backend. It is recommended to run `docker pull python:3.11` in advance. + +#### Web Search Tool + +- Uses the Exa backend for web search. +- Requires an Exa API key; set `EXA_API_KEY` in your environment. Create a key at `https://exa.ai`. + +### Tool & Reasoning Parser + +- We support OpenAI Reasoning and Tool Call parser, as well as our SGLang native api for tool call and reasoning. Refer to [reasoning parser](../advanced_features/separate_reasoning) and [tool call parser](../advanced_features/tool_parser) for more details. + + +## Notes + +- Use **Python 3.12** for the demo tools. And install the required `gpt-oss` packages. +- The default demo integrates the web search tool (Exa backend) and a demo Python interpreter via Docker. +- For search, set `EXA_API_KEY`. For Python execution, either have Docker available or set `PYTHON_EXECUTION_BACKEND=UV`. + +Examples: +```bash Command +export EXA_API_KEY=YOUR_EXA_KEY +# Optional: run Python tool locally instead of Docker (use with care) +export PYTHON_EXECUTION_BACKEND=UV +``` + +Launch the server with the demo tool server: + +```bash Command +python3 -m sglang.launch_server \ + --model-path openai/gpt-oss-120b \ + --tool-server demo \ + --tp 2 +``` + +For production usage, sglang can act as an MCP client for multiple services. An [example tool server](https://github.com/openai/gpt-oss/tree/main/gpt-oss-mcp-server) is provided. Start the servers and point sglang to them: +```bash Command +mcp run -t sse browser_server.py:mcp +mcp run -t sse python_server.py:mcp + +python -m sglang.launch_server ... --tool-server ip-1:port-1,ip-2:port-2 +``` +The URLs should be MCP SSE servers that expose server information and well-documented tools. These tools are added to the system prompt so the model can use them. + +## Speculative Decoding + +SGLang supports speculative decoding for GPT-OSS models using EAGLE3 algorithm. This can significantly improve decoding speed, especially for small batch sizes. + +**Usage**: +Add `--speculative-algorithm EAGLE3` along with the draft model path. +```bash Command +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 +``` + + +To enable the experimental overlap scheduler for EAGLE3 speculative decoding, set the environment variable `SGLANG_ENABLE_SPEC_V2=1`. This can improve performance by enabling overlap scheduling between draft and verification stages. + + +### Quick Demo + +```python Example +from openai import OpenAI + +client = OpenAI( + base_url="http://localhost:30000/v1", + api_key="sk-123456" +) + +tools = [ + {"type": "code_interpreter"}, + {"type": "web_search_preview"}, +] + +# Reasoning level example +response = client.responses.create( + model="openai/gpt-oss-120b", + instructions="You are a helpful assistant." + reasoning_effort="high" # Supports high, medium, or low + input="In one sentence, explain the transformer architecture.", +) +print("====== reasoning: high ======") +print(response.output_text) + +# Test python tool +response = client.responses.create( + model="openai/gpt-oss-120b", + instructions="You are a helfpul assistant, you could use python tool to execute code.", + input="Use python tool to calculate the sum of 29138749187 and 29138749187", # 58,277,498,374 + tools=tools +) +print("====== test python tool ======") +print(response.output_text) + +# Test browser tool +response = client.responses.create( + model="openai/gpt-oss-120b", + instructions="You are a helfpul assistant, you could use browser to search the web", + input="Search the web for the latest news about Nvidia stock price", + tools=tools +) +print("====== test browser tool ======") +print(response.output_text) +``` + +Example output: +```text Output +====== test python tool ====== +The sum of 29,138,749,187 and 29,138,749,187 is **58,277,498,374**. +====== test browser tool ====== +**Recent headlines on Nvidia (NVDA) stock** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Date (2025)SourceKey news pointsStock‑price detail
**May 13**ReutersThe market data page shows Nvidia trading “higher” at **$116.61** with no change from the previous close.**$116.61** – latest trade (delayed ≈ 15 min)【14†L34-L38】
**Aug 18**CNBCMorgan Stanley kept an **overweight** rating and lifted its price target to **$206** (up from $200), implying a 14 % upside from the Friday close. The firm notes Nvidia shares have already **jumped 34 % this year**.No exact price quoted, but the article signals strong upside expectations【9†L27-L31】
**Aug 20**The Motley FoolNvidia is set to release its Q2 earnings on Aug 27. The article lists the **current price of $175.36**, down 0.16 % on the day (as of 3:58 p.m. ET).**$175.36** – current price on Aug 20【10†L12-L15】【10†L53-L57】
+ +**What the news tells us** + +* Nvidia’s share price has risen sharply this year – up roughly a third according to Morgan Stanley – and analysts are still raising targets (now $206). +* The most recent market quote (Reuters, May 13) was **$116.61**, but the stock has surged since then, reaching **$175.36** by mid‑August. +* Upcoming earnings on **Aug 27** are a focal point; both the Motley Fool and Morgan Stanley expect the results could keep the rally going. + +**Bottom line:** Nvidia’s stock is on a strong upward trajectory in 2025, with price targets climbing toward $200‑$210 and the market price already near $175 as of late August. + +``` diff --git a/docs_new/docs/basic_usage/kimi_k2_5.mdx b/docs_new/docs/basic_usage/kimi_k2_5.mdx new file mode 100644 index 000000000..d87920198 --- /dev/null +++ b/docs_new/docs/basic_usage/kimi_k2_5.mdx @@ -0,0 +1,106 @@ +--- +title: "Kimi-K2.5 Usage" +metatags: + description: "Deploy Kimi-K2.5 with SGLang: 1T-parameter multimodal MoE model, 256K context, MLA attention, MoonViT vision encoder, thinking and instant modes, tool calling support." +--- +[Kimi-K2.5](https://huggingface.co/moonshotai/Kimi-K2.5) is Moonshot AI's open-source, native multimodal, agentic MoE. It is a 1T-parameter model (32B active) with 256K context, MLA attention, and a MoonViT vision encoder, supporting both thinking and instant modes. + +In SGLang, Kimi-K2.5 uses the `kimi_k2` reasoning and tool-call parsers for correct thinking and tool handling. + +```{note} Example +Kimi-K2.5 support is in SGLang main and will land in the next release. Use the latest main or a nightly image until then. +``` + +Official deployment guide: [Kimi-K2.5 deployment guide](https://huggingface.co/moonshotai/Kimi-K2.5/blob/main/docs/deploy_guidance) + +## Install (Latest Main) + +```bash Command +uv pip install "sglang @ git+https://github.com/sgl-project/sglang.git#subdirectory=python" +# For CUDA 12: +uv pip install "nvidia-cudnn-cu12==9.16.0.29" +# For CUDA 13: +uv pip install "nvidia-cudnn-cu13==9.16.0.29" +``` + +## Launch Kimi-K2.5 with SGLang + +Example: single node, TP8 on H200. + +```bash Command +python3 -m sglang.launch_server \ + --model-path moonshotai/Kimi-K2.5 \ + --tp 8 \ + --trust-remote-code \ + --tool-call-parser kimi_k2 \ + --reasoning-parser kimi_k2 +``` + +### Parser Requirements + +- `--tool-call-parser kimi_k2`: Required for tool calling. +- `--reasoning-parser kimi_k2`: Required to parse thinking content; thinking mode is enabled by default. + +## Test the Deployment + +Thinking mode is enabled by default. To disable thinking (instant mode), pass `extra_body.chat_template_kwargs.thinking=false`. + +```bash Command +# Thinking mode (default) +curl http://localhost:30000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "moonshotai/Kimi-K2.5", + "messages": [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Explain mixture-of-experts in one sentence."} + ], + "max_tokens": 256 + }' +``` + +```bash Command +# Instant mode (thinking disabled) +curl http://localhost:30000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "moonshotai/Kimi-K2.5", + "messages": [ + {"role": "user", "content": "Give one sentence on MoE models."} + ], + "max_tokens": 128, + "extra_body": {"chat_template_kwargs": {"thinking": false}} + }' +``` + +## Multimodal Inputs (Image/Video) + +Kimi-K2.5 is multimodal. Image inputs are supported via the OpenAI-compatible vision API. For more details, see `openai_api_vision.ipynb`. + +```bash Command +# Image input (SGLang) +curl http://localhost:30000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "moonshotai/Kimi-K2.5", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "Describe this image."}, + { + "type": "image_url", + "image_url": { + "url": "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" + } + } + ] + } + ], + "max_tokens": 256 + }' +``` + + +Video chat is experimental and is only supported in the official Moonshot API for now. + diff --git a/docs_new/docs/basic_usage/llama4.mdx b/docs_new/docs/basic_usage/llama4.mdx new file mode 100644 index 000000000..c68ea27c7 --- /dev/null +++ b/docs_new/docs/basic_usage/llama4.mdx @@ -0,0 +1,117 @@ +--- +title: "Llama4 Usage" +metatags: + description: "Deploy Llama 4 Scout (109B) and Maverick (400B) with SGLang: up to 10M context, hybrid KV cache, vision support. Optimized for H100/H200 GPUs." +--- +[Llama 4](https://github.com/meta-llama/llama-models/blob/main/models/llama4/MODEL_CARD) 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). + +## Launch Llama 4 with SGLang + +To serve Llama 4 models on 8xH100/H200 GPUs: + +```bash Command +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-4-Scout-17B-16E-Instruct \ + --tp 8 \ + --context-length 1000000 +``` + +### Configuration Tips + +- **OOM Mitigation**: Adjust `--context-length` to avoid a GPU out-of-memory issue. For the Scout model, we recommend setting this value up to 1M on 8\*H100 and up to 2.5M on 8\*H200. For the Maverick model, we don't need to set context length on 8\*H200. When hybrid kv cache is enabled, `--context-length` can be set up to 5M on 8\*H100 and up to 10M on 8\*H200 for the Scout model. + +- **Attention Backend Auto-Selection**: SGLang automatically selects the optimal attention backend for Llama 4 based on your hardware. You typically don't need to specify `--attention-backend` manually: + - **Blackwell GPUs (B200/GB200)**: `trtllm_mha` + - **Hopper GPUs (H100/H200)**: `fa3` + - **AMD GPUs**: `aiter` + - **Intel XPU**: `intel_xpu` + - **Other platforms**: `triton` (fallback) + + To override the auto-selection, explicitly specify `--attention-backend` with one of the supported backends: `fa3`, `aiter`, `triton`, `trtllm_mha`, or `intel_xpu`. + +- **Chat Template**: Add `--chat-template llama-4` for chat completion tasks. +- **Enable Multi-Modal**: Add `--enable-multimodal` for multi-modal capabilities. +- **Enable Hybrid-KVCache**: Set `--swa-full-tokens-ratio` to adjust the ratio of SWA layer (for Llama4, it's local attention layer) KV tokens / full layer KV tokens. (default: 0.8, range: 0-1) + + +### EAGLE Speculative Decoding +**Description**: SGLang has supported Llama 4 Maverick (400B) with [EAGLE speculative decoding](../advanced_features/speculative_decoding#EAGLE-Decoding). + +**Usage**: +Add arguments `--speculative-draft-model-path`, `--speculative-algorithm`, `--speculative-num-steps`, `--speculative-eagle-topk` and `--speculative-num-draft-tokens` to enable this feature. For example: +```text Output +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-4-Maverick-17B-128E-Instruct \ + --speculative-algorithm EAGLE3 \ + --speculative-draft-model-path nvidia/Llama-4-Maverick-17B-128E-Eagle3 \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 \ + --trust-remote-code \ + --tp 8 \ + --context-length 1000000 +``` + +- **Note** The Llama 4 draft model *nvidia/Llama-4-Maverick-17B-128E-Eagle3* can only recognize conversations in chat mode. + +## Benchmarking Results + +### Accuracy Test with `lm_eval` + +The accuracy on SGLang for both Llama4 Scout and Llama4 Maverick can match the [official benchmark numbers](https://ai.meta.com/blog/llama-4-multimodal-intelligence/). + +Benchmark results on MMLU Pro dataset with 8*H100: + + + + + + + + + + + + + + + + + + + + + + + + + +
Llama-4-Scout-17B-16E-InstructLlama-4-Maverick-17B-128E-Instruct
Official Benchmark74.380.5
SGLang75.280.7
+ +Commands: + +```bash Command +# Llama-4-Scout-17B-16E-Instruct model +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 +lm_eval --model local-chat-completions --model_args model=meta-llama/Llama-4-Scout-17B-16E-Instruct,base_url=http://localhost:30000/v1/chat/completions,num_concurrent=128,timeout=999999,max_gen_toks=2048 --tasks mmlu_pro --batch_size 128 --apply_chat_template --num_fewshot 0 + +# Llama-4-Maverick-17B-128E-Instruct +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 +lm_eval --model local-chat-completions --model_args model=meta-llama/Llama-4-Maverick-17B-128E-Instruct,base_url=http://localhost:30000/v1/chat/completions,num_concurrent=128,timeout=999999,max_gen_toks=2048 --tasks mmlu_pro --batch_size 128 --apply_chat_template --num_fewshot 0 +``` + +Details can be seen in [this PR](https://github.com/sgl-project/sglang/pull/5092). diff --git a/docs_new/docs/basic_usage/minimax_m2.mdx b/docs_new/docs/basic_usage/minimax_m2.mdx new file mode 100644 index 000000000..14da7051d --- /dev/null +++ b/docs_new/docs/basic_usage/minimax_m2.mdx @@ -0,0 +1,69 @@ +--- +title: "MiniMax M2.1/M2 Usage" +metatags: + description: "Deploy MiniMax M2.1/M2 with SGLang: 230B MoE model (10B active), up to 3M context, optimized for coding and agentic tasks, tool use support." +--- +[MiniMax-M2.1](https://huggingface.co/MiniMaxAI/MiniMax-M2.1) and [MiniMax-M2](https://huggingface.co/MiniMaxAI/MiniMax-M2) are advanced large language models created by [MiniMax](https://www.minimax.io/). + +MiniMax-M2 series redefines efficiency for agents. It's 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. With just 10 billion activated parameters, MiniMax-M2 provides the sophisticated, end-to-end tool use performance expected from today's leading models, but in a streamlined form factor that makes deployment and scaling easier than ever. + +## Supported Models + +This guide applies to the following models. You only need to update the model name during deployment. The following examples use **MiniMax-M2**: + +- [MiniMaxAI/MiniMax-M2.1](https://huggingface.co/MiniMaxAI/MiniMax-M2.1) +- [MiniMaxAI/MiniMax-M2](https://huggingface.co/MiniMaxAI/MiniMax-M2) + +## System Requirements + +The following are recommended configurations; actual requirements should be adjusted based on your use case: + +- 4x 96GB GPUs: Supported context length of up to 400K tokens. +- 8x 144GB GPUs: Supported context length of up to 3M tokens. + +## Deployment with Python + +4-GPU deployment command: + +```bash Command +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 8000 \ + --mem-fraction-static 0.85 +``` + +8-GPU deployment command: + +```bash Command +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 8000 \ + --mem-fraction-static 0.85 +``` + +## Testing Deployment + +After startup, you can test the SGLang OpenAI-compatible API with the following command: + +```bash Command +curl http://localhost:8000/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?"}]} + ] + }' +``` diff --git a/docs_new/docs/basic_usage/native_api.ipynb b/docs_new/docs/basic_usage/native_api.ipynb new file mode 100644 index 000000000..59ac6ee3a --- /dev/null +++ b/docs_new/docs/basic_usage/native_api.ipynb @@ -0,0 +1,667 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# SGLang Native APIs\n", + "\n", + "Apart from the OpenAI compatible APIs, the SGLang Runtime also provides its native server APIs. We introduce the following APIs:\n", + "\n", + "- `/generate` (text generation model)\n", + "- `/get_model_info`\n", + "- `/get_server_info`\n", + "- `/health`\n", + "- `/health_generate`\n", + "- `/flush_cache`\n", + "- `/update_weights`\n", + "- `/encode`(embedding model)\n", + "- `/v1/rerank`(cross encoder rerank model)\n", + "- `/v1/score`(decoder-only scoring)\n", + "- `/classify`(reward model)\n", + "- `/start_expert_distribution_record`\n", + "- `/stop_expert_distribution_record`\n", + "- `/dump_expert_distribution_record`\n", + "- `/tokenize`\n", + "- `/detokenize`\n", + "- A full list of these APIs can be found at [http_server.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/entrypoints/http_server.py)\n", + "\n", + "We mainly use `requests` to test these APIs in the following examples. You can also use `curl`.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Launch A Server" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "server_process, port = launch_server_cmd(\n", + " \"python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 --log-level warning\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Generate (text generation model)\n", + "Generate completions. This is similar to the `/v1/completions` in OpenAI API. Detailed parameters can be found in the [sampling parameters](sampling_params)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "url = f\"http://localhost:{port}/generate\"\n", + "data = {\"text\": \"What is the capital of France?\"}\n", + "\n", + "response = requests.post(url, json=data)\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Get Model Info\n", + "\n", + "Get the information of the model.\n", + "\n", + "- `model_path`: The path/name of the model.\n", + "- `is_generation`: Whether the model is used as generation model or embedding model.\n", + "- `tokenizer_path`: The path/name of the tokenizer.\n", + "- `preferred_sampling_params`: The default sampling params specified via `--preferred-sampling-params`. `None` is returned in this example as we did not explicitly configure it in server args.\n", + "- `weight_version`: This field contains the version of the model weights. This is often used to track changes or updates to the model’s trained parameters.\n", + "- `has_image_understanding`: Whether the model has image-understanding capability.\n", + "- `has_audio_understanding`: Whether the model has audio-understanding capability.\n", + "- `model_type`: The model type from the HuggingFace config (e.g., \"qwen2\", \"llama\").\n", + "- `architectures`: The model architectures from the HuggingFace config (e.g., [\"Qwen2ForCausalLM\"])." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://localhost:{port}/get_model_info\"\n", + "\n", + "response = requests.get(url)\n", + "response_json = response.json()\n", + "print_highlight(response_json)\n", + "assert response_json[\"model_path\"] == \"qwen/qwen2.5-0.5b-instruct\"\n", + "assert response_json[\"is_generation\"] is True\n", + "assert response_json[\"tokenizer_path\"] == \"qwen/qwen2.5-0.5b-instruct\"\n", + "assert response_json[\"preferred_sampling_params\"] is None\n", + "assert response_json.keys() == {\n", + " \"model_path\",\n", + " \"is_generation\",\n", + " \"tokenizer_path\",\n", + " \"preferred_sampling_params\",\n", + " \"weight_version\",\n", + " \"has_image_understanding\",\n", + " \"has_audio_understanding\",\n", + " \"model_type\",\n", + " \"architectures\",\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Get Server Info\n", + "Gets the server information including CLI arguments, token limits, and memory pool sizes.\n", + "- Note: `get_server_info` merges the following deprecated endpoints:\n", + " - `get_server_args`\n", + " - `get_memory_pool_size`\n", + " - `get_max_total_num_tokens`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://localhost:{port}/get_server_info\"\n", + "\n", + "response = requests.get(url)\n", + "print_highlight(response.text)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Health Check\n", + "- `/health`: Check the health of the server.\n", + "- `/health_generate`: Check the health of the server by generating one token." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://localhost:{port}/health_generate\"\n", + "\n", + "response = requests.get(url)\n", + "print_highlight(response.text)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://localhost:{port}/health\"\n", + "\n", + "response = requests.get(url)\n", + "print_highlight(response.text)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Flush Cache\n", + "\n", + "Flush the radix cache. It will be automatically triggered when the model weights are updated by the `/update_weights` API." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "url = f\"http://localhost:{port}/flush_cache\"\n", + "\n", + "response = requests.post(url)\n", + "print_highlight(response.text)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Update Weights From Disk\n", + "\n", + "Update model weights from disk without restarting the server. Only applicable for models with the same architecture and parameter size.\n", + "\n", + "SGLang support `update_weights_from_disk` API for continuous evaluation during training (save checkpoint to disk and update weights from disk).\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# successful update with same architecture and size\n", + "\n", + "url = f\"http://localhost:{port}/update_weights_from_disk\"\n", + "data = {\"model_path\": \"qwen/qwen2.5-0.5b-instruct\"}\n", + "\n", + "response = requests.post(url, json=data)\n", + "print_highlight(response.text)\n", + "assert response.json()[\"success\"] is True\n", + "assert response.json()[\"message\"] == \"Succeeded to update model weights.\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# failed update with different parameter size or wrong name\n", + "\n", + "url = f\"http://localhost:{port}/update_weights_from_disk\"\n", + "data = {\"model_path\": \"qwen/qwen2.5-0.5b-instruct-wrong\"}\n", + "\n", + "response = requests.post(url, json=data)\n", + "response_json = response.json()\n", + "print_highlight(response_json)\n", + "assert response_json[\"success\"] is False\n", + "assert response_json[\"message\"] == (\n", + " \"Failed to get weights iterator: \"\n", + " \"qwen/qwen2.5-0.5b-instruct-wrong\"\n", + " \" (repository not found).\"\n", + ")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Encode (embedding model)\n", + "\n", + "Encode text into embeddings. Note that this API is only available for [embedding models](openai_api_embeddings) and will raise an error for generation models.\n", + "Therefore, we launch a new server to server an embedding model." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "embedding_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-1.5B-instruct \\\n", + " --host 0.0.0.0 --is-embedding --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# successful encode for embedding model\n", + "\n", + "url = f\"http://localhost:{port}/encode\"\n", + "data = {\"model\": \"Alibaba-NLP/gte-Qwen2-1.5B-instruct\", \"text\": \"Once upon a time\"}\n", + "\n", + "response = requests.post(url, json=data)\n", + "response_json = response.json()\n", + "print_highlight(f\"Text embedding (first 10): {response_json['embedding'][:10]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(embedding_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## v1/rerank (cross encoder rerank model)\n", + "Rerank a list of documents given a query using a cross-encoder model. Note that this API is only available for cross encoder model like [BAAI/bge-reranker-v2-m3](https://huggingface.co/BAAI/bge-reranker-v2-m3) with `attention-backend` `triton` and `torch_native`.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "reranker_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path BAAI/bge-reranker-v2-m3 \\\n", + " --host 0.0.0.0 --disable-radix-cache --chunked-prefill-size -1 --attention-backend triton --is-embedding --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# compute rerank scores for query and documents\n", + "\n", + "url = f\"http://localhost:{port}/v1/rerank\"\n", + "data = {\n", + " \"model\": \"BAAI/bge-reranker-v2-m3\",\n", + " \"query\": \"what is panda?\",\n", + " \"documents\": [\n", + " \"hi\",\n", + " \"The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China.\",\n", + " ],\n", + "}\n", + "\n", + "response = requests.post(url, json=data)\n", + "response_json = response.json()\n", + "for item in response_json:\n", + " print_highlight(f\"Score: {item['score']:.2f} - Document: '{item['document']}'\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(reranker_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## v1/score (decoder-only scoring)\n", + "\n", + "Compute token probabilities for specified tokens given a query and items. This is useful for classification tasks, scoring responses, or computing log-probabilities.\n", + "\n", + "Parameters:\n", + "- `query`: Query text\n", + "- `items`: Item text(s) to score\n", + "- `label_token_ids`: Token IDs to compute probabilities for\n", + "- `apply_softmax`: Whether to apply softmax to get normalized probabilities (default: False)\n", + "- `item_first`: Whether items come first in concatenation order (default: False)\n", + "- `model`: Model name\n", + "\n", + "The response contains `scores` - a list of probability lists, one per item, each in the order of `label_token_ids`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "score_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct \\\n", + " --host 0.0.0.0 --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Score the probability of different completions given a query\n", + "query = \"The capital of France is\"\n", + "items = [\"Paris\", \"London\", \"Berlin\"]\n", + "\n", + "url = f\"http://localhost:{port}/v1/score\"\n", + "data = {\n", + " \"model\": \"qwen/qwen2.5-0.5b-instruct\",\n", + " \"query\": query,\n", + " \"items\": items,\n", + " \"label_token_ids\": [9454, 2753], # e.g. \"Yes\" and \"No\" token ids\n", + " \"apply_softmax\": True, # Normalize probabilities to sum to 1\n", + "}\n", + "\n", + "response = requests.post(url, json=data)\n", + "response_json = response.json()\n", + "\n", + "# Display scores for each item\n", + "for item, scores in zip(items, response_json[\"scores\"]):\n", + " print_highlight(f\"Item '{item}': probabilities = {[f'{s:.4f}' for s in scores]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(score_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Classify (reward model)\n", + "\n", + "SGLang Runtime also supports reward models. Here we use a reward model to classify the quality of pairwise generations." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Note that SGLang now treats embedding models and reward models as the same type of models.\n", + "# This will be updated in the future.\n", + "\n", + "reward_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path Skywork/Skywork-Reward-Llama-3.1-8B-v0.2 --host 0.0.0.0 --is-embedding --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from transformers import AutoTokenizer\n", + "\n", + "PROMPT = (\n", + " \"What is the range of the numeric output of a sigmoid node in a neural network?\"\n", + ")\n", + "\n", + "RESPONSE1 = \"The output of a sigmoid node is bounded between -1 and 1.\"\n", + "RESPONSE2 = \"The output of a sigmoid node is bounded between 0 and 1.\"\n", + "\n", + "CONVS = [\n", + " [{\"role\": \"user\", \"content\": PROMPT}, {\"role\": \"assistant\", \"content\": RESPONSE1}],\n", + " [{\"role\": \"user\", \"content\": PROMPT}, {\"role\": \"assistant\", \"content\": RESPONSE2}],\n", + "]\n", + "\n", + "tokenizer = AutoTokenizer.from_pretrained(\"Skywork/Skywork-Reward-Llama-3.1-8B-v0.2\")\n", + "prompts = tokenizer.apply_chat_template(CONVS, tokenize=False, return_dict=False)\n", + "\n", + "url = f\"http://localhost:{port}/classify\"\n", + "data = {\"model\": \"Skywork/Skywork-Reward-Llama-3.1-8B-v0.2\", \"text\": prompts}\n", + "\n", + "responses = requests.post(url, json=data).json()\n", + "for response in responses:\n", + " print_highlight(f\"reward: {response['embedding'][0]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(reward_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Capture expert selection distribution in MoE models\n", + "\n", + "SGLang Runtime supports recording the number of times an expert is selected in a MoE model run for each expert in the model. This is useful when analyzing the throughput of the model and plan for optimization.\n", + "\n", + "*Note: We only print out the first 10 lines of the csv below for better readability. Please adjust accordingly if you want to analyze the results more deeply.*" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "expert_record_server_process, port = launch_server_cmd(\n", + " \"python3 -m sglang.launch_server --model-path Qwen/Qwen1.5-MoE-A2.7B --host 0.0.0.0 --expert-distribution-recorder-mode stat --log-level warning\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = requests.post(f\"http://localhost:{port}/start_expert_distribution_record\")\n", + "print_highlight(response)\n", + "\n", + "url = f\"http://localhost:{port}/generate\"\n", + "data = {\"text\": \"What is the capital of France?\"}\n", + "\n", + "response = requests.post(url, json=data)\n", + "print_highlight(response.json())\n", + "\n", + "response = requests.post(f\"http://localhost:{port}/stop_expert_distribution_record\")\n", + "print_highlight(response)\n", + "\n", + "response = requests.post(f\"http://localhost:{port}/dump_expert_distribution_record\")\n", + "print_highlight(response)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(expert_record_server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Tokenize/Detokenize Example (Round Trip)\n", + "\n", + "This example demonstrates how to use the /tokenize and /detokenize endpoints together. We first tokenize a string, then detokenize the resulting IDs to reconstruct the original text. This workflow is useful when you need to handle tokenization externally but still leverage the server for detokenization." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "tokenizer_free_server_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "from sglang.utils import print_highlight\n", + "\n", + "base_url = f\"http://localhost:{port}\"\n", + "tokenize_url = f\"{base_url}/tokenize\"\n", + "detokenize_url = f\"{base_url}/detokenize\"\n", + "\n", + "model_name = \"qwen/qwen2.5-0.5b-instruct\"\n", + "input_text = \"SGLang provides efficient tokenization endpoints.\"\n", + "print_highlight(f\"Original Input Text:\\n'{input_text}'\")\n", + "\n", + "# --- tokenize the input text ---\n", + "tokenize_payload = {\n", + " \"model\": model_name,\n", + " \"prompt\": input_text,\n", + " \"add_special_tokens\": False,\n", + "}\n", + "try:\n", + " tokenize_response = requests.post(tokenize_url, json=tokenize_payload)\n", + " tokenize_response.raise_for_status()\n", + " tokenization_result = tokenize_response.json()\n", + " token_ids = tokenization_result.get(\"tokens\")\n", + "\n", + " if not token_ids:\n", + " raise ValueError(\"Tokenization returned empty tokens.\")\n", + "\n", + " print_highlight(f\"\\nTokenized Output (IDs):\\n{token_ids}\")\n", + " print_highlight(f\"Token Count: {tokenization_result.get('count')}\")\n", + " print_highlight(f\"Max Model Length: {tokenization_result.get('max_model_len')}\")\n", + "\n", + " # --- detokenize the obtained token IDs ---\n", + " detokenize_payload = {\n", + " \"model\": model_name,\n", + " \"tokens\": token_ids,\n", + " \"skip_special_tokens\": True,\n", + " }\n", + "\n", + " detokenize_response = requests.post(detokenize_url, json=detokenize_payload)\n", + " detokenize_response.raise_for_status()\n", + " detokenization_result = detokenize_response.json()\n", + " reconstructed_text = detokenization_result.get(\"text\")\n", + "\n", + " print_highlight(f\"\\nDetokenized Output (Text):\\n'{reconstructed_text}'\")\n", + "\n", + " if input_text == reconstructed_text:\n", + " print_highlight(\n", + " \"\\nRound Trip Successful: Original and reconstructed text match.\"\n", + " )\n", + " else:\n", + " print_highlight(\n", + " \"\\nRound Trip Mismatch: Original and reconstructed text differ.\"\n", + " )\n", + "\n", + "except requests.exceptions.RequestException as e:\n", + " print_highlight(f\"\\nHTTP Request Error: {e}\")\n", + "except Exception as e:\n", + " print_highlight(f\"\\nAn error occurred: {e}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(tokenizer_free_server_process)" + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/docs_new/docs/basic_usage/native_api.mdx b/docs_new/docs/basic_usage/native_api.mdx new file mode 100644 index 000000000..af4c76ce9 --- /dev/null +++ b/docs_new/docs/basic_usage/native_api.mdx @@ -0,0 +1,450 @@ +--- +title: "SGLang Native APIs" +metatags: + description: "SGLang native server APIs for text generation, embedding, reranking, model info, cache management, and more." +--- +Apart from the OpenAI compatible APIs, the SGLang Runtime also provides its native server APIs. We introduce the following APIs: + +- `/generate` (text generation model) +- `/get_model_info` +- `/get_server_info` +- `/health` +- `/health_generate` +- `/flush_cache` +- `/update_weights` +- `/encode`(embedding model) +- `/v1/rerank`(cross encoder rerank model) +- `/v1/score`(decoder-only scoring) +- `/classify`(reward model) +- `/start_expert_distribution_record` +- `/stop_expert_distribution_record` +- `/dump_expert_distribution_record` +- `/tokenize` +- `/detokenize` +- A full list of these APIs can be found at [http_server.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/entrypoints/http_server.py) + +We mainly use `requests` to test these APIs in the following examples. You can also use `curl`. + +## Launch A Server + +```python Example +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process + +server_process, port = launch_server_cmd( + "python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 --log-level warning" +) + +wait_for_server(f"http://localhost:{port}") +``` + +## Generate (text generation model) +Generate completions. This is similar to the `/v1/completions` in OpenAI API. Detailed parameters can be found in the [sampling parameters](./sampling_params). + +```python Example +import requests + +url = f"http://localhost:{port}/generate" +data = {"text": "What is the capital of France?"} + +response = requests.post(url, json=data) +print_highlight(response.json()) +``` + +## Get Model Info + +Get the information of the model. + +- `model_path`: The path/name of the model. +- `is_generation`: Whether the model is used as generation model or embedding model. +- `tokenizer_path`: The path/name of the tokenizer. +- `preferred_sampling_params`: The default sampling params specified via `--preferred-sampling-params`. `None` is returned in this example as we did not explicitly configure it in server args. +- `weight_version`: This field contains the version of the model weights. This is often used to track changes or updates to the model’s trained parameters. +- `has_image_understanding`: Whether the model has image-understanding capability. +- `has_audio_understanding`: Whether the model has audio-understanding capability. +- `model_type`: The model type from the HuggingFace config (e.g., "qwen2", "llama"). +- `architectures`: The model architectures from the HuggingFace config (e.g., ["Qwen2ForCausalLM"]). + +```python Example +url = f"http://localhost:{port}/get_model_info" + +response = requests.get(url) +response_json = response.json() +print_highlight(response_json) +assert response_json["model_path"] == "qwen/qwen2.5-0.5b-instruct" +assert response_json["is_generation"] is True +assert response_json["tokenizer_path"] == "qwen/qwen2.5-0.5b-instruct" +assert response_json["preferred_sampling_params"] is None +assert response_json.keys() == { + "model_path", + "is_generation", + "tokenizer_path", + "preferred_sampling_params", + "weight_version", + "has_image_understanding", + "has_audio_understanding", + "model_type", + "architectures", +} +``` + +## Get Server Info +Gets the server information including CLI arguments, token limits, and memory pool sizes. +- Note: `get_server_info` merges the following deprecated endpoints: + - `get_server_args` + - `get_memory_pool_size` + - `get_max_total_num_tokens` + +```python Example +url = f"http://localhost:{port}/get_server_info" + +response = requests.get(url) +print_highlight(response.text) +``` + +## Health Check +- `/health`: Check the health of the server. +- `/health_generate`: Check the health of the server by generating one token. + +```python Example +url = f"http://localhost:{port}/health_generate" + +response = requests.get(url) +print_highlight(response.text) +``` + +```python Example +url = f"http://localhost:{port}/health" + +response = requests.get(url) +print_highlight(response.text) +``` + +## Flush Cache + +Flush the radix cache. It will be automatically triggered when the model weights are updated by the `/update_weights` API. + +```python Example +url = f"http://localhost:{port}/flush_cache" + +response = requests.post(url) +print_highlight(response.text) +``` + +## Update Weights From Disk + +Update model weights from disk without restarting the server. Only applicable for models with the same architecture and parameter size. + +SGLang support `update_weights_from_disk` API for continuous evaluation during training (save checkpoint to disk and update weights from disk). + +```python Example +# successful update with same architecture and size + +url = f"http://localhost:{port}/update_weights_from_disk" +data = {"model_path": "qwen/qwen2.5-0.5b-instruct"} + +response = requests.post(url, json=data) +print_highlight(response.text) +assert response.json()["success"] is True +assert response.json()["message"] == "Succeeded to update model weights." +``` + +```python Example +# failed update with different parameter size or wrong name + +url = f"http://localhost:{port}/update_weights_from_disk" +data = {"model_path": "qwen/qwen2.5-0.5b-instruct-wrong"} + +response = requests.post(url, json=data) +response_json = response.json() +print_highlight(response_json) +assert response_json["success"] is False +assert response_json["message"] == ( + "Failed to get weights iterator: " + "qwen/qwen2.5-0.5b-instruct-wrong" + " (repository not found)." +) +``` + +```python Example +terminate_process(server_process) +``` + +## Encode (embedding model) + +Encode text into embeddings. Note that this API is only available for [embedding models](./openai_api_embeddings) and will raise an error for generation models. +Therefore, we launch a new server to server an embedding model. + +```python Example +embedding_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-1.5B-instruct \ + --host 0.0.0.0 --is-embedding --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + +```python Example +# successful encode for embedding model + +url = f"http://localhost:{port}/encode" +data = {"model": "Alibaba-NLP/gte-Qwen2-1.5B-instruct", "text": "Once upon a time"} + +response = requests.post(url, json=data) +response_json = response.json() +print_highlight(f"Text embedding (first 10): {response_json['embedding'][:10]}") +``` + +```python Example +terminate_process(embedding_process) +``` + +## v1/rerank (cross encoder rerank model) +Rerank a list of documents given a query using a cross-encoder model. Note that this API is only available for cross encoder model like [BAAI/bge-reranker-v2-m3](https://huggingface.co/BAAI/bge-reranker-v2-m3) with `attention-backend` `triton` and `torch_native`. + +```python Example +reranker_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path BAAI/bge-reranker-v2-m3 \ + --host 0.0.0.0 --disable-radix-cache --chunked-prefill-size -1 --attention-backend triton --is-embedding --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + +```python Example +# compute rerank scores for query and documents + +url = f"http://localhost:{port}/v1/rerank" +data = { + "model": "BAAI/bge-reranker-v2-m3", + "query": "what is panda?", + "documents": [ + "hi", + "The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China.", + ], +} + +response = requests.post(url, json=data) +response_json = response.json() +for item in response_json: + print_highlight(f"Score: {item['score']:.2f} - Document: '{item['document']}'") +``` + +```python Example +terminate_process(reranker_process) +``` + +## v1/score (decoder-only scoring) + +Compute token probabilities for specified tokens given a query and items. This is useful for classification tasks, scoring responses, or computing log-probabilities. + +Parameters: +- `query`: Query text +- `items`: Item text(s) to score +- `label_token_ids`: Token IDs to compute probabilities for +- `apply_softmax`: Whether to apply softmax to get normalized probabilities (default: False) +- `item_first`: Whether items come first in concatenation order (default: False) +- `model`: Model name + +The response contains `scores` - a list of probability lists, one per item, each in the order of `label_token_ids`. + +```python Example +score_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct \ + --host 0.0.0.0 --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + +```python Example +# Score the probability of different completions given a query +query = "The capital of France is" +items = ["Paris", "London", "Berlin"] + +url = f"http://localhost:{port}/v1/score" +data = { + "model": "qwen/qwen2.5-0.5b-instruct", + "query": query, + "items": items, + "label_token_ids": [9454, 2753], # e.g. "Yes" and "No" token ids + "apply_softmax": True, # Normalize probabilities to sum to 1 +} + +response = requests.post(url, json=data) +response_json = response.json() + +# Display scores for each item +for item, scores in zip(items, response_json["scores"]): + print_highlight(f"Item '{item}': probabilities = {[f'{s:.4f}' for s in scores]}") +``` + +```python Example +terminate_process(score_process) +``` + +## Classify (reward model) + +SGLang Runtime also supports reward models. Here we use a reward model to classify the quality of pairwise generations. + +```python Example +# Note that SGLang now treats embedding models and reward models as the same type of models. +# This will be updated in the future. + +reward_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path Skywork/Skywork-Reward-Llama-3.1-8B-v0.2 --host 0.0.0.0 --is-embedding --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + +```python Example +from transformers import AutoTokenizer + +PROMPT = ( + "What is the range of the numeric output of a sigmoid node in a neural network?" +) + +RESPONSE1 = "The output of a sigmoid node is bounded between -1 and 1." +RESPONSE2 = "The output of a sigmoid node is bounded between 0 and 1." + +CONVS = [ + [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE1}], + [{"role": "user", "content": PROMPT}, {"role": "assistant", "content": RESPONSE2}], +] + +tokenizer = AutoTokenizer.from_pretrained("Skywork/Skywork-Reward-Llama-3.1-8B-v0.2") +prompts = tokenizer.apply_chat_template(CONVS, tokenize=False, return_dict=False) + +url = f"http://localhost:{port}/classify" +data = {"model": "Skywork/Skywork-Reward-Llama-3.1-8B-v0.2", "text": prompts} + +responses = requests.post(url, json=data).json() +for response in responses: + print_highlight(f"reward: {response['embedding'][0]}") +``` + +```python Example +terminate_process(reward_process) +``` + +## Capture expert selection distribution in MoE models + +SGLang Runtime supports recording the number of times an expert is selected in a MoE model run for each expert in the model. This is useful when analyzing the throughput of the model and plan for optimization. + +*Note: We only print out the first 10 lines of the csv below for better readability. Please adjust accordingly if you want to analyze the results more deeply.* + +```python Example +expert_record_server_process, port = launch_server_cmd( + "python3 -m sglang.launch_server --model-path Qwen/Qwen1.5-MoE-A2.7B --host 0.0.0.0 --expert-distribution-recorder-mode stat --log-level warning" +) + +wait_for_server(f"http://localhost:{port}") +``` + +```python Example +response = requests.post(f"http://localhost:{port}/start_expert_distribution_record") +print_highlight(response) + +url = f"http://localhost:{port}/generate" +data = {"text": "What is the capital of France?"} + +response = requests.post(url, json=data) +print_highlight(response.json()) + +response = requests.post(f"http://localhost:{port}/stop_expert_distribution_record") +print_highlight(response) + +response = requests.post(f"http://localhost:{port}/dump_expert_distribution_record") +print_highlight(response) +``` + +```python Example +terminate_process(expert_record_server_process) +``` + +## Tokenize/Detokenize Example (Round Trip) + +This example demonstrates how to use the /tokenize and /detokenize endpoints together. We first tokenize a string, then detokenize the resulting IDs to reconstruct the original text. This workflow is useful when you need to handle tokenization externally but still leverage the server for detokenization. + +```python Example +tokenizer_free_server_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + +```python Example +import requests +from sglang.utils import print_highlight + +base_url = f"http://localhost:{port}" +tokenize_url = f"{base_url}/tokenize" +detokenize_url = f"{base_url}/detokenize" + +model_name = "qwen/qwen2.5-0.5b-instruct" +input_text = "SGLang provides efficient tokenization endpoints." +print_highlight(f"Original Input Text:\n'{input_text}'") + +# --- tokenize the input text --- +tokenize_payload = { + "model": model_name, + "prompt": input_text, + "add_special_tokens": False, +} +try: + tokenize_response = requests.post(tokenize_url, json=tokenize_payload) + tokenize_response.raise_for_status() + tokenization_result = tokenize_response.json() + token_ids = tokenization_result.get("tokens") + + if not token_ids: + raise ValueError("Tokenization returned empty tokens.") + + print_highlight(f"\nTokenized Output (IDs):\n{token_ids}") + print_highlight(f"Token Count: {tokenization_result.get('count')}") + print_highlight(f"Max Model Length: {tokenization_result.get('max_model_len')}") + + # --- detokenize the obtained token IDs --- + detokenize_payload = { + "model": model_name, + "tokens": token_ids, + "skip_special_tokens": True, + } + + detokenize_response = requests.post(detokenize_url, json=detokenize_payload) + detokenize_response.raise_for_status() + detokenization_result = detokenize_response.json() + reconstructed_text = detokenization_result.get("text") + + print_highlight(f"\nDetokenized Output (Text):\n'{reconstructed_text}'") + + if input_text == reconstructed_text: + print_highlight( + "\nRound Trip Successful: Original and reconstructed text match." + ) + else: + print_highlight( + "\nRound Trip Mismatch: Original and reconstructed text differ." + ) + +except requests.exceptions.RequestException as e: + print_highlight(f"\nHTTP Request Error: {e}") +except Exception as e: + print_highlight(f"\nAn error occurred: {e}") +``` + +```python Example +terminate_process(tokenizer_free_server_process) +``` diff --git a/docs_new/docs/basic_usage/offline_engine_api.ipynb b/docs_new/docs/basic_usage/offline_engine_api.ipynb new file mode 100644 index 000000000..9c03e90a7 --- /dev/null +++ b/docs_new/docs/basic_usage/offline_engine_api.ipynb @@ -0,0 +1,235 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Offline Engine API\n", + "\n", + "SGLang provides a direct inference engine without the need for an HTTP server, especially for use cases where additional HTTP server adds unnecessary complexity or overhead. Here are two general use cases:\n", + "\n", + "- Offline Batch Inference\n", + "- Custom Server on Top of the Engine\n", + "\n", + "This document focuses on the offline batch inference, demonstrating four different inference modes:\n", + "\n", + "- Non-streaming synchronous generation\n", + "- Streaming synchronous generation\n", + "- Non-streaming asynchronous generation\n", + "- Streaming asynchronous generation\n", + "\n", + "Additionally, you can easily build a custom server on top of the SGLang offline engine. A detailed example working in a python script can be found in [custom_server](https://github.com/sgl-project/sglang/blob/main/examples/runtime/engine/custom_server.py).\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nest Asyncio\n", + "Note that if you want to use **Offline Engine** in ipython or some other nested loop code, you need to add the following code:\n", + "```python\n", + "import nest_asyncio\n", + "\n", + "nest_asyncio.apply()\n", + "\n", + "```" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Advanced Usage\n", + "\n", + "The engine supports [vlm inference](https://github.com/sgl-project/sglang/blob/main/examples/runtime/engine/offline_batch_inference_vlm.py) as well as [extracting hidden states](https://github.com/sgl-project/sglang/blob/main/examples/runtime/hidden_states). \n", + "\n", + "Please see [the examples](https://github.com/sgl-project/sglang/tree/main/examples/runtime/engine) for further use cases." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Offline Batch Inference\n", + "\n", + "SGLang offline engine supports batch inference with efficient scheduling." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# launch the offline engine\n", + "import asyncio\n", + "\n", + "import sglang as sgl\n", + "import sglang.test.doc_patch\n", + "from sglang.utils import async_stream_and_merge, stream_and_merge\n", + "\n", + "llm = sgl.Engine(model_path=\"qwen/qwen2.5-0.5b-instruct\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Non-streaming Synchronous Generation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prompts = [\n", + " \"Hello, my name is\",\n", + " \"The president of the United States is\",\n", + " \"The capital of France is\",\n", + " \"The future of AI is\",\n", + "]\n", + "\n", + "sampling_params = {\"temperature\": 0.8, \"top_p\": 0.95}\n", + "\n", + "outputs = llm.generate(prompts, sampling_params)\n", + "for prompt, output in zip(prompts, outputs):\n", + " print(\"===============================\")\n", + " print(f\"Prompt: {prompt}\\nGenerated text: {output['text']}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Streaming Synchronous Generation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prompts = [\n", + " \"Write a short, neutral self-introduction for a fictional character. Hello, my name is\",\n", + " \"Provide a concise factual statement about France’s capital city. The capital of France is\",\n", + " \"Explain possible future trends in artificial intelligence. The future of AI is\",\n", + "]\n", + "\n", + "sampling_params = {\n", + " \"temperature\": 0.2,\n", + " \"top_p\": 0.9,\n", + "}\n", + "\n", + "print(\"\\n=== Testing synchronous streaming generation with overlap removal ===\\n\")\n", + "\n", + "for prompt in prompts:\n", + " print(f\"Prompt: {prompt}\")\n", + " merged_output = stream_and_merge(llm, prompt, sampling_params)\n", + " print(\"Generated text:\", merged_output)\n", + " print()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Non-streaming Asynchronous Generation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prompts = [\n", + " \"Write a short, neutral self-introduction for a fictional character. Hello, my name is\",\n", + " \"Provide a concise factual statement about France’s capital city. The capital of France is\",\n", + " \"Explain possible future trends in artificial intelligence. The future of AI is\",\n", + "]\n", + "\n", + "sampling_params = {\"temperature\": 0.8, \"top_p\": 0.95}\n", + "\n", + "print(\"\\n=== Testing asynchronous batch generation ===\")\n", + "\n", + "\n", + "async def main():\n", + " outputs = await llm.async_generate(prompts, sampling_params)\n", + "\n", + " for prompt, output in zip(prompts, outputs):\n", + " print(f\"\\nPrompt: {prompt}\")\n", + " print(f\"Generated text: {output['text']}\")\n", + "\n", + "\n", + "asyncio.run(main())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Streaming Asynchronous Generation" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "prompts = [\n", + " \"Write a short, neutral self-introduction for a fictional character. Hello, my name is\",\n", + " \"Provide a concise factual statement about France’s capital city. The capital of France is\",\n", + " \"Explain possible future trends in artificial intelligence. The future of AI is\",\n", + "]\n", + "\n", + "sampling_params = {\"temperature\": 0.8, \"top_p\": 0.95}\n", + "\n", + "print(\"\\n=== Testing asynchronous streaming generation (no repeats) ===\")\n", + "\n", + "\n", + "async def main():\n", + " for prompt in prompts:\n", + " print(f\"\\nPrompt: {prompt}\")\n", + " print(\"Generated text: \", end=\"\", flush=True)\n", + "\n", + " # Replace direct calls to async_generate with our custom overlap-aware version\n", + " async for cleaned_chunk in async_stream_and_merge(llm, prompt, sampling_params):\n", + " print(cleaned_chunk, end=\"\", flush=True)\n", + "\n", + " print() # New line after each prompt\n", + "\n", + "\n", + "asyncio.run(main())" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "llm.shutdown()" + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/basic_usage/offline_engine_api.mdx b/docs_new/docs/basic_usage/offline_engine_api.mdx new file mode 100644 index 000000000..4a814b319 --- /dev/null +++ b/docs_new/docs/basic_usage/offline_engine_api.mdx @@ -0,0 +1,143 @@ +--- +title: "Offline Engine API" +metatags: + description: "Use SGLang's offline engine for direct batch inference without HTTP server overhead. Supports sync/async and streaming modes." +--- +SGLang provides a direct inference engine without the need for an HTTP server, especially for use cases where additional HTTP server adds unnecessary complexity or overhead. Here are two general use cases: + +- Offline Batch Inference +- Custom Server on Top of the Engine + +This document focuses on the offline batch inference, demonstrating four different inference modes: + +- Non-streaming synchronous generation +- Streaming synchronous generation +- Non-streaming asynchronous generation +- Streaming asynchronous generation + +Additionally, you can easily build a custom server on top of the SGLang offline engine. A detailed example working in a python script can be found in [custom_server](https://github.com/sgl-project/sglang/blob/main/examples/runtime/engine/custom_server.py). + +## Nest Asyncio +Note that if you want to use **Offline Engine** in ipython or some other nested loop code, you need to add the following code: +```python Example +import nest_asyncio + +nest_asyncio.apply() + +``` + +## Advanced Usage + +The engine supports [vlm inference](https://github.com/sgl-project/sglang/blob/main/examples/runtime/engine/offline_batch_inference_vlm.py) as well as [extracting hidden states](https://github.com/sgl-project/sglang/tree/main/examples/runtime/hidden_states). + +Please see [the examples](https://github.com/sgl-project/sglang/tree/main/examples/runtime/engine) for further use cases. + +## Offline Batch Inference + +SGLang offline engine supports batch inference with efficient scheduling. + +```python Example +# launch the offline engine +import asyncio + +import sglang as sgl +import sglang.test.doc_patch +from sglang.utils import async_stream_and_merge, stream_and_merge + +llm = sgl.Engine(model_path="qwen/qwen2.5-0.5b-instruct") +``` + +### Non-streaming Synchronous Generation + +```python Example +prompts = [ + "Hello, my name is", + "The president of the United States is", + "The capital of France is", + "The future of AI is", +] + +sampling_params = {"temperature": 0.8, "top_p": 0.95} + +outputs = llm.generate(prompts, sampling_params) +for prompt, output in zip(prompts, outputs): + print("===============================") + print(f"Prompt: {prompt}\nGenerated text: {output['text']}") +``` + +### Streaming Synchronous Generation + +```python Example +prompts = [ + "Write a short, neutral self-introduction for a fictional character. Hello, my name is", + "Provide a concise factual statement about France’s capital city. The capital of France is", + "Explain possible future trends in artificial intelligence. The future of AI is", +] + +sampling_params = { + "temperature": 0.2, + "top_p": 0.9, +} + +print("\n=== Testing synchronous streaming generation with overlap removal ===\n") + +for prompt in prompts: + print(f"Prompt: {prompt}") + merged_output = stream_and_merge(llm, prompt, sampling_params) + print("Generated text:", merged_output) + print() +``` + +### Non-streaming Asynchronous Generation + +```python Example +prompts = [ + "Write a short, neutral self-introduction for a fictional character. Hello, my name is", + "Provide a concise factual statement about France’s capital city. The capital of France is", + "Explain possible future trends in artificial intelligence. The future of AI is", +] + +sampling_params = {"temperature": 0.8, "top_p": 0.95} + +print("\n=== Testing asynchronous batch generation ===") + +async def main(): + outputs = await llm.async_generate(prompts, sampling_params) + + for prompt, output in zip(prompts, outputs): + print(f"\nPrompt: {prompt}") + print(f"Generated text: {output['text']}") + +asyncio.run(main()) +``` + +### Streaming Asynchronous Generation + +```python Example +prompts = [ + "Write a short, neutral self-introduction for a fictional character. Hello, my name is", + "Provide a concise factual statement about France’s capital city. The capital of France is", + "Explain possible future trends in artificial intelligence. The future of AI is", +] + +sampling_params = {"temperature": 0.8, "top_p": 0.95} + +print("\n=== Testing asynchronous streaming generation (no repeats) ===") + +async def main(): + for prompt in prompts: + print(f"\nPrompt: {prompt}") + print("Generated text: ", end="", flush=True) + + # Replace direct calls to async_generate with our custom overlap-aware version + async for cleaned_chunk in async_stream_and_merge(llm, prompt, sampling_params): + print(cleaned_chunk, end="", flush=True) + + print() # New line after each prompt + +asyncio.run(main()) +``` + +```python Example +llm.shutdown() +``` diff --git a/docs_new/docs/basic_usage/ollama_api.mdx b/docs_new/docs/basic_usage/ollama_api.mdx new file mode 100644 index 000000000..c92533c3f --- /dev/null +++ b/docs_new/docs/basic_usage/ollama_api.mdx @@ -0,0 +1,157 @@ +--- +title: "Ollama-Compatible API" +metatags: + description: "SGLang provides Ollama API compatibility, allowing you to use the Ollama CLI and Python library with SGLang as the inference backend." +--- +SGLang provides Ollama API compatibility, allowing you to use the Ollama CLI and Python library with SGLang as the inference backend. + +## Prerequisites + + +```bash Command +# Install the Ollama Python library (for Python client usage) +pip install ollama +``` + + +You don't need the Ollama server installed - SGLang acts as the backend. You only need the `ollama` CLI or Python library as the client. + +## Endpoints + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EndpointMethodDescription
`/`GET, HEADHealth check for Ollama CLI
`/api/tags`GETList available models
`/api/chat`POSTChat completions (streaming & non-streaming)
`/api/generate`POSTText generation (streaming & non-streaming)
`/api/show`POSTModel information
+ +## Quick Start + +### 1. Launch SGLang Server + + +```bash Command +python -m sglang.launch_server \ + --model Qwen/Qwen2.5-1.5B-Instruct \ + --port 30001 \ + --host 0.0.0.0 +``` + + +The model name used with `ollama run` must match exactly what you passed to `--model`. + +### 2. Use Ollama CLI + + +```bash Command +# List available models +OLLAMA_HOST=http://localhost:30001 ollama list + +# Interactive chat +OLLAMA_HOST=http://localhost:30001 ollama run "Qwen/Qwen2.5-1.5B-Instruct" +``` + + +If connecting to a remote server behind a firewall: + + +```bash Command +# SSH tunnel +ssh -L 30001:localhost:30001 user@gpu-server -N & + +# Then use Ollama CLI as above +OLLAMA_HOST=http://localhost:30001 ollama list +``` + + +### 3. Use Ollama Python Library + +```python Example +import ollama + +client = ollama.Client(host='http://localhost:30001') + +# Non-streaming +response = client.chat( + model='Qwen/Qwen2.5-1.5B-Instruct', + messages=[{'role': 'user', 'content': 'Hello!'}] +) +print(response['message']['content']) + +# Streaming +stream = client.chat( + model='Qwen/Qwen2.5-1.5B-Instruct', + messages=[{'role': 'user', 'content': 'Tell me a story'}], + stream=True +) +for chunk in stream: + print(chunk['message']['content'], end='', flush=True) +``` + +## Smart Router + +For intelligent routing between local Ollama (fast) and remote SGLang (powerful) using an LLM judge, see the [Smart Router documentation](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/entrypoints/ollama/README). + +## Summary + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComponentPurpose
**Ollama API**Familiar CLI/API that developers already know
**SGLang Backend**High-performance inference engine
**Smart Router**Intelligent routing - fast local for simple tasks, powerful remote for complex tasks
diff --git a/docs_new/docs/basic_usage/openai_api.mdx b/docs_new/docs/basic_usage/openai_api.mdx new file mode 100644 index 000000000..523fa2db6 --- /dev/null +++ b/docs_new/docs/basic_usage/openai_api.mdx @@ -0,0 +1,7 @@ +--- +title: "OpenAI-Compatible APIs" +description: "Documentation for OpenAI-Compatible APIs" +--- +- [Openai Api Completions](./openai_api_completions) +- [Openai Api Vision](./openai_api_vision) +- [Openai Api Embeddings](./openai_api_embeddings) diff --git a/docs_new/docs/basic_usage/openai_api.rst b/docs_new/docs/basic_usage/openai_api.rst new file mode 100644 index 000000000..370abe99c --- /dev/null +++ b/docs_new/docs/basic_usage/openai_api.rst @@ -0,0 +1,9 @@ +OpenAI-Compatible APIs +====================== + +.. toctree:: + :maxdepth: 1 + + openai_api_completions.ipynb + openai_api_vision.ipynb + openai_api_embeddings.ipynb diff --git a/docs_new/docs/basic_usage/openai_api_completions.ipynb b/docs_new/docs/basic_usage/openai_api_completions.ipynb new file mode 100644 index 000000000..e64b7a13e --- /dev/null +++ b/docs_new/docs/basic_usage/openai_api_completions.ipynb @@ -0,0 +1,552 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# OpenAI APIs - Completions\n", + "\n", + "SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models.\n", + "A complete reference for the API is available in the [OpenAI API Reference](https://platform.openai.com/docs/api-reference).\n", + "\n", + "This tutorial covers the following popular APIs:\n", + "\n", + "- `chat/completions`\n", + "- `completions`\n", + "\n", + "Check out other tutorials to learn about [vision APIs](openai_api_vision) for vision-language models and [embedding APIs](openai_api_embeddings) for embedding models." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Launch A Server\n", + "\n", + "Launch the server in your terminal and wait for it to initialize." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "server_process, port = launch_server_cmd(\n", + " \"python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 --log-level warning\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")\n", + "print(f\"Server started on http://localhost:{port}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Chat Completions\n", + "\n", + "### Usage\n", + "\n", + "The server fully implements the OpenAI API.\n", + "It will automatically apply the chat template specified in the Hugging Face tokenizer, if one is available.\n", + "You can also specify a custom chat template with `--chat-template` when launching the server." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import openai\n", + "\n", + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=64,\n", + ")\n", + "\n", + "print_highlight(f\"Response: {response}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Model Thinking/Reasoning Support\n", + "\n", + "Some models support internal reasoning or thinking processes that can be exposed in the API response. SGLang provides unified support for various reasoning models through the `chat_template_kwargs` parameter and compatible reasoning parsers.\n", + "\n", + "#### Supported Models and Configuration\n", + "\n", + "| Model Family | Chat Template Parameter | Reasoning Parser | Notes |\n", + "|--------------|------------------------|------------------|--------|\n", + "| DeepSeek-R1 (R1, R1-0528, R1-Distill) | `enable_thinking` | `--reasoning-parser deepseek-r1` | Standard reasoning models |\n", + "| DeepSeek-V3.1 | `thinking` | `--reasoning-parser deepseek-v3` | Hybrid model (thinking/non-thinking modes) |\n", + "| Qwen3 (standard) | `enable_thinking` | `--reasoning-parser qwen3` | Hybrid model (thinking/non-thinking modes) |\n", + "| Qwen3-Thinking | N/A (always enabled) | `--reasoning-parser qwen3-thinking` | Always generates reasoning |\n", + "| Kimi | N/A (always enabled) | `--reasoning-parser kimi` | Kimi thinking models |\n", + "| Gpt-Oss | N/A (always enabled) | `--reasoning-parser gpt-oss` | Gpt-Oss thinking models |\n", + "\n", + "#### Basic Usage\n", + "\n", + "To enable reasoning output, you need to:\n", + "1. Launch the server with the appropriate reasoning parser\n", + "2. Set the model-specific parameter in `chat_template_kwargs`\n", + "3. Optionally use `separate_reasoning: False` to not get reasoning content separately (default to `True`)\n", + "\n", + "**Note for Qwen3-Thinking models:** These models always generate thinking content and do not support the `enable_thinking` parameter. Use `--reasoning-parser qwen3-thinking` or `--reasoning-parser qwen3` to parse the thinking content.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Example: Qwen3 Models\n", + "\n", + "```python\n", + "# Launch server:\n", + "# python3 -m sglang.launch_server --model Qwen/Qwen3-4B --reasoning-parser qwen3\n", + "\n", + "from openai import OpenAI\n", + "\n", + "client = OpenAI(\n", + " api_key=\"EMPTY\",\n", + " base_url=f\"http://127.0.0.1:30000/v1\",\n", + ")\n", + "\n", + "model = \"Qwen/Qwen3-4B\"\n", + "messages = [{\"role\": \"user\", \"content\": \"How many r's are in 'strawberry'?\"}]\n", + "\n", + "response = client.chat.completions.create(\n", + " model=model,\n", + " messages=messages,\n", + " extra_body={\n", + " \"chat_template_kwargs\": {\"enable_thinking\": True},\n", + " \"separate_reasoning\": True\n", + " }\n", + ")\n", + "\n", + "print(\"Reasoning:\", response.choices[0].message.reasoning_content)\n", + "print(\"-\"*100)\n", + "print(\"Answer:\", response.choices[0].message.content)\n", + "```\n", + "\n", + "**ExampleOutput:**\n", + "```\n", + "Reasoning: Okay, so the user is asking how many 'r's are in the word 'strawberry'. Let me think. First, I need to make sure I have the word spelled correctly. Strawberry... S-T-R-A-W-B-E-R-R-Y. Wait, is that right? Let me break it down.\n", + "\n", + "Starting with 'strawberry', let's write out the letters one by one. S, T, R, A, W, B, E, R, R, Y. Hmm, wait, that's 10 letters. Let me check again. S (1), T (2), R (3), A (4), W (5), B (6), E (7), R (8), R (9), Y (10). So the letters are S-T-R-A-W-B-E-R-R-Y. \n", + "...\n", + "Therefore, the answer should be three R's in 'strawberry'. But I need to make sure I'm not counting any other letters as R. Let me check again. S, T, R, A, W, B, E, R, R, Y. No other R's. So three in total. Yeah, that seems right.\n", + "\n", + "----------------------------------------------------------------------------------------------------\n", + "Answer: The word \"strawberry\" contains **three** letters 'r'. Here's the breakdown:\n", + "\n", + "1. **S-T-R-A-W-B-E-R-R-Y** \n", + " - The **third letter** is 'R'. \n", + " - The **eighth and ninth letters** are also 'R's. \n", + "\n", + "Thus, the total count is **3**. \n", + "\n", + "**Answer:** 3.\n", + "```\n", + "\n", + "**Note:** Setting `\"enable_thinking\": False` (or omitting it) will result in `reasoning_content` being `None`. Qwen3-Thinking models always generate reasoning content and don't support the `enable_thinking` parameter.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Logit Bias Support\n", + "\n", + "SGLang supports the `logit_bias` parameter for both chat completions and completions APIs. This parameter allows you to modify the likelihood of specific tokens being generated by adding bias values to their logits. The bias values can range from -100 to 100, where:\n", + "\n", + "- **Positive values** (0 to 100) increase the likelihood of the token being selected\n", + "- **Negative values** (-100 to 0) decrease the likelihood of the token being selected\n", + "- **-100** effectively prevents the token from being generated\n", + "\n", + "The `logit_bias` parameter accepts a dictionary where keys are token IDs (as strings) and values are the bias amounts (as floats).\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Getting Token IDs\n", + "\n", + "To use `logit_bias` effectively, you need to know the token IDs for the words you want to bias. Here's how to get token IDs:\n", + "\n", + "```python\n", + "# Get tokenizer to find token IDs\n", + "import tiktoken\n", + "\n", + "# For OpenAI models, use the appropriate encoding\n", + "tokenizer = tiktoken.encoding_for_model(\"gpt-3.5-turbo\") # or your model\n", + "\n", + "# Get token IDs for specific words\n", + "word = \"sunny\"\n", + "token_ids = tokenizer.encode(word)\n", + "print(f\"Token IDs for '{word}': {token_ids}\")\n", + "\n", + "# For SGLang models, you can access the tokenizer through the client\n", + "# and get token IDs for bias\n", + "```\n", + "\n", + "**Important:** The `logit_bias` parameter uses token IDs as string keys, not the actual words.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Example: DeepSeek-V3 Models\n", + "\n", + "DeepSeek-V3 models support thinking mode through the `thinking` parameter:\n", + "\n", + "```python\n", + "# Launch server:\n", + "# python3 -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.1 --tp 8 --reasoning-parser deepseek-v3\n", + "\n", + "from openai import OpenAI\n", + "\n", + "client = OpenAI(\n", + " api_key=\"EMPTY\",\n", + " base_url=f\"http://127.0.0.1:30000/v1\",\n", + ")\n", + "\n", + "model = \"deepseek-ai/DeepSeek-V3.1\"\n", + "messages = [{\"role\": \"user\", \"content\": \"How many r's are in 'strawberry'?\"}]\n", + "\n", + "response = client.chat.completions.create(\n", + " model=model,\n", + " messages=messages,\n", + " extra_body={\n", + " \"chat_template_kwargs\": {\"thinking\": True},\n", + " \"separate_reasoning\": True\n", + " }\n", + ")\n", + "\n", + "print(\"Reasoning:\", response.choices[0].message.reasoning_content)\n", + "print(\"-\"*100)\n", + "print(\"Answer:\", response.choices[0].message.content)\n", + "```\n", + "\n", + "**Example Output:**\n", + "```\n", + "Reasoning: First, the question is: \"How many r's are in 'strawberry'?\"\n", + "\n", + "I need to count the number of times the letter 'r' appears in the word \"strawberry\".\n", + "\n", + "Let me write out the word: S-T-R-A-W-B-E-R-R-Y.\n", + "\n", + "Now, I'll go through each letter and count the 'r's.\n", + "...\n", + "So, I have three 'r's in \"strawberry\".\n", + "\n", + "I should double-check. The word is spelled S-T-R-A-W-B-E-R-R-Y. The letters are at positions: 3, 8, and 9 are 'r's. Yes, that's correct.\n", + "\n", + "Therefore, the answer should be 3.\n", + "----------------------------------------------------------------------------------------------------\n", + "Answer: The word \"strawberry\" contains **3** instances of the letter \"r\". Here's a breakdown for clarity:\n", + "\n", + "- The word is spelled: S-T-R-A-W-B-E-R-R-Y\n", + "- The \"r\" appears at the 3rd, 8th, and 9th positions.\n", + "```\n", + "\n", + "**Note:** DeepSeek-V3 models use the `thinking` parameter (not `enable_thinking`) to control reasoning output.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Example with logit_bias parameter\n", + "# Note: You need to get the actual token IDs from your tokenizer\n", + "# For demonstration, we'll use some example token IDs\n", + "response = client.chat.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"Complete this sentence: The weather today is\"}\n", + " ],\n", + " temperature=0.7,\n", + " max_tokens=20,\n", + " logit_bias={\n", + " \"12345\": 50, # Increase likelihood of token ID 12345\n", + " \"67890\": -50, # Decrease likelihood of token ID 67890\n", + " \"11111\": 25, # Slightly increase likelihood of token ID 11111\n", + " },\n", + ")\n", + "\n", + "print_highlight(f\"Response with logit bias: {response.choices[0].message.content}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Parameters\n", + "\n", + "The chat completions API accepts OpenAI Chat Completions API's parameters. Refer to [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat/create) for more details.\n", + "\n", + "SGLang extends the standard API with the `extra_body` parameter, allowing for additional customization. One key option within `extra_body` is `chat_template_kwargs`, which can be used to pass arguments to the chat template processor." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = client.chat.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " messages=[\n", + " {\n", + " \"role\": \"system\",\n", + " \"content\": \"You are a knowledgeable historian who provides concise responses.\",\n", + " },\n", + " {\"role\": \"user\", \"content\": \"Tell me about ancient Rome\"},\n", + " {\n", + " \"role\": \"assistant\",\n", + " \"content\": \"Ancient Rome was a civilization centered in Italy.\",\n", + " },\n", + " {\"role\": \"user\", \"content\": \"What were their major achievements?\"},\n", + " ],\n", + " temperature=0.3, # Lower temperature for more focused responses\n", + " max_tokens=128, # Reasonable length for a concise response\n", + " top_p=0.95, # Slightly higher for better fluency\n", + " presence_penalty=0.2, # Mild penalty to avoid repetition\n", + " frequency_penalty=0.2, # Mild penalty for more natural language\n", + " n=1, # Single response is usually more stable\n", + " seed=42, # Keep for reproducibility\n", + ")\n", + "\n", + "print_highlight(response.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Streaming mode is also supported." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Logit Bias Support\n", + "\n", + "The completions API also supports the `logit_bias` parameter with the same functionality as described in the chat completions section above.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "stream = client.chat.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " messages=[{\"role\": \"user\", \"content\": \"Say this is a test\"}],\n", + " stream=True,\n", + ")\n", + "for chunk in stream:\n", + " if chunk.choices[0].delta.content is not None:\n", + " print(chunk.choices[0].delta.content, end=\"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Returning Routed Experts (MoE Models)\n", + "\n", + "For MoE models, set `return_routed_experts: true` in `extra_body` to return expert routing data. Requires `--enable-return-routed-experts` server flag. The `routed_experts` field will be returned in the `sgl_ext` object on each choice, containing base64-encoded int32 expert IDs as a flattened array with logical shape `[num_tokens, num_layers, top_k]`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Example with logit_bias parameter for completions API\n", + "# Note: You need to get the actual token IDs from your tokenizer\n", + "# For demonstration, we'll use some example token IDs\n", + "response = client.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " prompt=\"The best programming language for AI is\",\n", + " temperature=0.7,\n", + " max_tokens=20,\n", + " logit_bias={\n", + " \"12345\": 75, # Strongly favor token ID 12345\n", + " \"67890\": -100, # Completely avoid token ID 67890\n", + " \"11111\": -25, # Slightly discourage token ID 11111\n", + " },\n", + ")\n", + "\n", + "print_highlight(f\"Response with logit bias: {response.choices[0].text}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Completions\n", + "\n", + "### Usage\n", + "Completions API is similar to Chat Completions API, but without the `messages` parameter or chat templates." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = client.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " prompt=\"List 3 countries and their capitals.\",\n", + " temperature=0,\n", + " max_tokens=64,\n", + " n=1,\n", + " stop=None,\n", + ")\n", + "\n", + "print_highlight(f\"Response: {response}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Parameters\n", + "\n", + "The completions API accepts OpenAI Completions API's parameters. Refer to [OpenAI Completions API](https://platform.openai.com/docs/api-reference/completions/create) for more details.\n", + "\n", + "Here is an example of a detailed completions request:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "response = client.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " prompt=\"Write a short story about a space explorer.\",\n", + " temperature=0.7, # Moderate temperature for creative writing\n", + " max_tokens=150, # Longer response for a story\n", + " top_p=0.9, # Balanced diversity in word choice\n", + " stop=[\"\\n\\n\", \"THE END\"], # Multiple stop sequences\n", + " presence_penalty=0.3, # Encourage novel elements\n", + " frequency_penalty=0.3, # Reduce repetitive phrases\n", + " n=1, # Generate one completion\n", + " seed=123, # For reproducible results\n", + ")\n", + "\n", + "print_highlight(f\"Response: {response}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Returning Routed Experts (MoE Models)\n", + "\n", + "For MoE models, set `return_routed_experts: true` in `extra_body` to return expert routing data. Requires `--enable-return-routed-experts` server flag. The `routed_experts` field will be returned in the `sgl_ext` object on each choice, containing base64-encoded int32 expert IDs as a flattened array with logical shape `[num_tokens, num_layers, top_k]`." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Structured Outputs (JSON, Regex, EBNF)\n", + "\n", + "For OpenAI compatible structured outputs API, refer to [Structured Outputs](../advanced_features/structured_outputs) for more details.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using LoRA Adapters\n", + "\n", + "SGLang supports LoRA (Low-Rank Adaptation) adapters with OpenAI-compatible APIs. You can specify which adapter to use directly in the `model` parameter using the `base-model:adapter-name` syntax.\n", + "\n", + "**Server Setup:**\n", + "```bash\n", + "python -m sglang.launch_server \\\n", + " --model-path qwen/qwen2.5-0.5b-instruct \\\n", + " --enable-lora \\\n", + " --lora-paths adapter_a=/path/to/adapter_a adapter_b=/path/to/adapter_b\n", + "```\n", + "\n", + "For more details on LoRA serving configuration, see the [LoRA documentation](../advanced_features/lora).\n", + "\n", + "**API Call:**\n", + "\n", + "(Recommended) Use the `model:adapter` syntax to specify which adapter to use:\n", + "```python\n", + "response = client.chat.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct:adapter_a\", # ← base-model:adapter-name\n", + " messages=[{\"role\": \"user\", \"content\": \"Convert to SQL: show all users\"}],\n", + " max_tokens=50,\n", + ")\n", + "```\n", + "\n", + "**Backward Compatible: Using `extra_body`**\n", + "\n", + "The old `extra_body` method is still supported for backward compatibility:\n", + "```python\n", + "# Backward compatible method\n", + "response = client.chat.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " messages=[{\"role\": \"user\", \"content\": \"Convert to SQL: show all users\"}],\n", + " extra_body={\"lora_path\": \"adapter_a\"}, # ← old method\n", + " max_tokens=50,\n", + ")\n", + "```\n", + "**Note:** When both `model:adapter` and `extra_body[\"lora_path\"]` are specified, the `model:adapter` syntax takes precedence." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/basic_usage/openai_api_completions.mdx b/docs_new/docs/basic_usage/openai_api_completions.mdx new file mode 100644 index 000000000..c463fcca5 --- /dev/null +++ b/docs_new/docs/basic_usage/openai_api_completions.mdx @@ -0,0 +1,456 @@ +--- +title: "OpenAI APIs - Completions" +metatags: + description: "This tutorial covers the following popular APIs: 'chat/completions' and 'completions'" +--- +SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models. +A complete reference for the API is available in the [OpenAI API Reference](https://platform.openai.com/docs/api-reference). + +This tutorial covers the following popular APIs: + +- `chat/completions` +- `completions` + +Check out other tutorials to learn about [vision APIs](./openai_api_vision) for vision-language models and [embedding APIs](./openai_api_embeddings) for embedding models. + +## Launch A Server + +Launch the server in your terminal and wait for it to initialize. + +```python Example +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process + +server_process, port = launch_server_cmd( + "python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 --log-level warning" +) + +wait_for_server(f"http://localhost:{port}") +print(f"Server started on http://localhost:{port}") +``` + +## Chat Completions + +### Usage + +The server fully implements the OpenAI API. +It will automatically apply the chat template specified in the Hugging Face tokenizer, if one is available. +You can also specify a custom chat template with `--chat-template` when launching the server. + +```python Example +import openai + +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") + +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, +) + +print_highlight(f"Response: {response}") +``` + +### Model Thinking/Reasoning Support + +Some models support internal reasoning or thinking processes that can be exposed in the API response. SGLang provides unified support for various reasoning models through the `chat_template_kwargs` parameter and compatible reasoning parsers. + +#### Supported Models and Configuration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model FamilyChat Template ParameterReasoning ParserNotes
DeepSeek-R1 (R1, R1-0528, R1-Distill)`enable_thinking``--reasoning-parser deepseek-r1`Standard reasoning models
DeepSeek-V3.1`thinking``--reasoning-parser deepseek-v3`Hybrid model (thinking/non-thinking modes)
Qwen3 (standard)`enable_thinking``--reasoning-parser qwen3`Hybrid model (thinking/non-thinking modes)
Qwen3-ThinkingN/A (always enabled)`--reasoning-parser qwen3-thinking`Always generates reasoning
KimiN/A (always enabled)`--reasoning-parser kimi`Kimi thinking models
Gpt-OssN/A (always enabled)`--reasoning-parser gpt-oss`Gpt-Oss thinking models
+ +#### Basic Usage + +To enable reasoning output, you need to: +1. Launch the server with the appropriate reasoning parser +2. Set the model-specific parameter in `chat_template_kwargs` +3. Optionally use `separate_reasoning: False` to not get reasoning content separately (default to `True`) + + +**Note for Qwen3-Thinking models:** These models always generate thinking content and do not support the `enable_thinking` parameter. Use `--reasoning-parser qwen3-thinking` or `--reasoning-parser qwen3` to parse the thinking content. + + +#### Example: Qwen3 Models + +```python Example +# Launch server: +# python3 -m sglang.launch_server --model Qwen/Qwen3-4B --reasoning-parser qwen3 + +from openai import OpenAI + +client = OpenAI( + api_key="EMPTY", + base_url=f"http://127.0.0.1:30000/v1", +) + +model = "Qwen/Qwen3-4B" +messages = [{"role": "user", "content": "How many r's are in 'strawberry'?"}] + +response = client.chat.completions.create( + model=model, + messages=messages, + extra_body={ + "chat_template_kwargs": {"enable_thinking": True}, + "separate_reasoning": True + } +) + +print("Reasoning:", response.choices[0].message.reasoning_content) +print("-"*100) +print("Answer:", response.choices[0].message.content) +``` + +**ExampleOutput:** +```text Output +Reasoning: Okay, so the user is asking how many 'r's are in the word 'strawberry'. Let me think. First, I need to make sure I have the word spelled correctly. Strawberry... S-T-R-A-W-B-E-R-R-Y. Wait, is that right? Let me break it down. + +Starting with 'strawberry', let's write out the letters one by one. S, T, R, A, W, B, E, R, R, Y. Hmm, wait, that's 10 letters. Let me check again. S (1), T (2), R (3), A (4), W (5), B (6), E (7), R (8), R (9), Y (10). So the letters are S-T-R-A-W-B-E-R-R-Y. +... +Therefore, the answer should be three R's in 'strawberry'. But I need to make sure I'm not counting any other letters as R. Let me check again. S, T, R, A, W, B, E, R, R, Y. No other R's. So three in total. Yeah, that seems right. + +---------------------------------------------------------------------------------------------------- +Answer: The word "strawberry" contains **three** letters 'r'. Here's the breakdown: + +1. **S-T-R-A-W-B-E-R-R-Y** + - The **third letter** is 'R'. + - The **eighth and ninth letters** are also 'R's. + +Thus, the total count is **3**. + +**Answer:** 3. +``` + +Setting `"enable_thinking": False` (or omitting it) will result in `reasoning_content` being `None`. Qwen3-Thinking models always generate reasoning content and don't support the `enable_thinking` parameter. + + +#### Logit Bias Support + +SGLang supports the `logit_bias` parameter for both chat completions and completions APIs. This parameter allows you to modify the likelihood of specific tokens being generated by adding bias values to their logits. The bias values can range from -100 to 100, where: + +- **Positive values** (0 to 100) increase the likelihood of the token being selected +- **Negative values** (-100 to 0) decrease the likelihood of the token being selected +- **-100** effectively prevents the token from being generated + +The `logit_bias` parameter accepts a dictionary where keys are token IDs (as strings) and values are the bias amounts (as floats). + +#### Getting Token IDs + +To use `logit_bias` effectively, you need to know the token IDs for the words you want to bias. Here's how to get token IDs: + +```python Example +# Get tokenizer to find token IDs +import tiktoken + +# For OpenAI models, use the appropriate encoding +tokenizer = tiktoken.encoding_for_model("gpt-3.5-turbo") # or your model + +# Get token IDs for specific words +word = "sunny" +token_ids = tokenizer.encode(word) +print(f"Token IDs for '{word}': {token_ids}") + +# For SGLang models, you can access the tokenizer through the client +# and get token IDs for bias +``` + +**Important:** The `logit_bias` parameter uses token IDs as string keys, not the actual words. + + +#### Example: DeepSeek-V3 Models + +DeepSeek-V3 models support thinking mode through the `thinking` parameter: + +```python Example +# Launch server: +# python3 -m sglang.launch_server --model deepseek-ai/DeepSeek-V3.1 --tp 8 --reasoning-parser deepseek-v3 + +from openai import OpenAI + +client = OpenAI( + api_key="EMPTY", + base_url=f"http://127.0.0.1:30000/v1", +) + +model = "deepseek-ai/DeepSeek-V3.1" +messages = [{"role": "user", "content": "How many r's are in 'strawberry'?"}] + +response = client.chat.completions.create( + model=model, + messages=messages, + extra_body={ + "chat_template_kwargs": {"thinking": True}, + "separate_reasoning": True + } +) + +print("Reasoning:", response.choices[0].message.reasoning_content) +print("-"*100) +print("Answer:", response.choices[0].message.content) +``` + +**Example Output:** +```text Output +Reasoning: First, the question is: "How many r's are in 'strawberry'?" + +I need to count the number of times the letter 'r' appears in the word "strawberry". + +Let me write out the word: S-T-R-A-W-B-E-R-R-Y. + +Now, I'll go through each letter and count the 'r's. +... +So, I have three 'r's in "strawberry". + +I should double-check. The word is spelled S-T-R-A-W-B-E-R-R-Y. The letters are at positions: 3, 8, and 9 are 'r's. Yes, that's correct. + +Therefore, the answer should be 3. +---------------------------------------------------------------------------------------------------- +Answer: The word "strawberry" contains **3** instances of the letter "r". Here's a breakdown for clarity: + +- The word is spelled: S-T-R-A-W-B-E-R-R-Y +- The "r" appears at the 3rd, 8th, and 9th positions. +``` + +DeepSeek-V3 models use the `thinking` parameter (not `enable_thinking`) to control reasoning output. + + +```python Example +# Example with logit_bias parameter +# Note: You need to get the actual token IDs from your tokenizer +# For demonstration, we'll use some example token IDs +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[ + {"role": "user", "content": "Complete this sentence: The weather today is"} + ], + temperature=0.7, + max_tokens=20, + logit_bias={ + "12345": 50, # Increase likelihood of token ID 12345 + "67890": -50, # Decrease likelihood of token ID 67890 + "11111": 25, # Slightly increase likelihood of token ID 11111 + }, +) + +print_highlight(f"Response with logit bias: {response.choices[0].message.content}") +``` + +### Parameters + +The chat completions API accepts OpenAI Chat Completions API's parameters. Refer to [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat/create) for more details. + +SGLang extends the standard API with the `extra_body` parameter, allowing for additional customization. One key option within `extra_body` is `chat_template_kwargs`, which can be used to pass arguments to the chat template processor. + +```python Example +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[ + { + "role": "system", + "content": "You are a knowledgeable historian who provides concise responses.", + }, + {"role": "user", "content": "Tell me about ancient Rome"}, + { + "role": "assistant", + "content": "Ancient Rome was a civilization centered in Italy.", + }, + {"role": "user", "content": "What were their major achievements?"}, + ], + temperature=0.3, # Lower temperature for more focused responses + max_tokens=128, # Reasonable length for a concise response + top_p=0.95, # Slightly higher for better fluency + presence_penalty=0.2, # Mild penalty to avoid repetition + frequency_penalty=0.2, # Mild penalty for more natural language + n=1, # Single response is usually more stable + seed=42, # Keep for reproducibility +) + +print_highlight(response.choices[0].message.content) +``` + +Streaming mode is also supported. + +#### Logit Bias Support + +The completions API also supports the `logit_bias` parameter with the same functionality as described in the chat completions section above. + +```python Example +stream = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[{"role": "user", "content": "Say this is a test"}], + stream=True, +) +for chunk in stream: + if chunk.choices[0].delta.content is not None: + print(chunk.choices[0].delta.content, end="") +``` + +#### Returning Routed Experts (MoE Models) + +For MoE models, set `return_routed_experts: true` in `extra_body` to return expert routing data. Requires `--enable-return-routed-experts` server flag. The `routed_experts` field will be returned in the `sgl_ext` object on each choice, containing base64-encoded int32 expert IDs as a flattened array with logical shape `[num_tokens, num_layers, top_k]`. + +```python Example +# Example with logit_bias parameter for completions API +# Note: You need to get the actual token IDs from your tokenizer +# For demonstration, we'll use some example token IDs +response = client.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + prompt="The best programming language for AI is", + temperature=0.7, + max_tokens=20, + logit_bias={ + "12345": 75, # Strongly favor token ID 12345 + "67890": -100, # Completely avoid token ID 67890 + "11111": -25, # Slightly discourage token ID 11111 + }, +) + +print_highlight(f"Response with logit bias: {response.choices[0].text}") +``` + +## Completions + +### Usage +Completions API is similar to Chat Completions API, but without the `messages` parameter or chat templates. + +```python Example +response = client.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + prompt="List 3 countries and their capitals.", + temperature=0, + max_tokens=64, + n=1, + stop=None, +) + +print_highlight(f"Response: {response}") +``` + +### Parameters + +The completions API accepts OpenAI Completions API's parameters. Refer to [OpenAI Completions API](https://platform.openai.com/docs/api-reference/completions/create) for more details. + +Here is an example of a detailed completions request: + +```python Example +response = client.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + prompt="Write a short story about a space explorer.", + temperature=0.7, # Moderate temperature for creative writing + max_tokens=150, # Longer response for a story + top_p=0.9, # Balanced diversity in word choice + stop=["\n\n", "THE END"], # Multiple stop sequences + presence_penalty=0.3, # Encourage novel elements + frequency_penalty=0.3, # Reduce repetitive phrases + n=1, # Generate one completion + seed=123, # For reproducible results +) + +print_highlight(f"Response: {response}") +``` + +#### Returning Routed Experts (MoE Models) + +For MoE models, set `return_routed_experts: true` in `extra_body` to return expert routing data. Requires `--enable-return-routed-experts` server flag. The `routed_experts` field will be returned in the `sgl_ext` object on each choice, containing base64-encoded int32 expert IDs as a flattened array with logical shape `[num_tokens, num_layers, top_k]`. + +## Structured Outputs (JSON, Regex, EBNF) + +For OpenAI compatible structured outputs API, refer to [Structured Outputs](../advanced_features/structured_outputs) for more details. + +## Using LoRA Adapters + +SGLang supports LoRA (Low-Rank Adaptation) adapters with OpenAI-compatible APIs. You can specify which adapter to use directly in the `model` parameter using the `base-model:adapter-name` syntax. + +**Server Setup:** +```bash Command +python -m sglang.launch_server \ + --model-path qwen/qwen2.5-0.5b-instruct \ + --enable-lora \ + --lora-paths adapter_a=/path/to/adapter_a adapter_b=/path/to/adapter_b +``` + +For more details on LoRA serving configuration, see the [LoRA documentation](../advanced_features/lora). + +**API Call:** + +(Recommended) Use the `model:adapter` syntax to specify which adapter to use: +```python Example +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct:adapter_a", # ← base-model:adapter-name + messages=[{"role": "user", "content": "Convert to SQL: show all users"}], + max_tokens=50, +) +``` + +**Backward Compatible: Using `extra_body`** + +The old `extra_body` method is still supported for backward compatibility: +```python Example +# Backward compatible method +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[{"role": "user", "content": "Convert to SQL: show all users"}], + extra_body={"lora_path": "adapter_a"}, # ← old method + max_tokens=50, +) +``` +**Note:** When both `model:adapter` and `extra_body["lora_path"]` are specified, the `model:adapter` syntax takes precedence. + +```python Example +terminate_process(server_process) +``` diff --git a/docs_new/docs/basic_usage/openai_api_embeddings.ipynb b/docs_new/docs/basic_usage/openai_api_embeddings.ipynb new file mode 100644 index 000000000..07031d32c --- /dev/null +++ b/docs_new/docs/basic_usage/openai_api_embeddings.ipynb @@ -0,0 +1,193 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# OpenAI APIs - Embedding\n", + "\n", + "SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models.\n", + "A complete reference for the API is available in the [OpenAI API Reference](https://platform.openai.com/docs/guides/embeddings).\n", + "\n", + "This tutorial covers the embedding APIs for embedding models. For a list of the supported models see the [corresponding overview page](../supported_models/embedding_models)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Launch A Server\n", + "\n", + "Launch the server in your terminal and wait for it to initialize. Remember to add `--is-embedding` to the command." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "embedding_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-1.5B-instruct \\\n", + " --host 0.0.0.0 --is-embedding --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using cURL" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import subprocess, json\n", + "\n", + "text = \"Once upon a time\"\n", + "\n", + "curl_text = f\"\"\"curl -s http://localhost:{port}/v1/embeddings \\\n", + " -H \"Content-Type: application/json\" \\\n", + " -d '{{\"model\": \"Alibaba-NLP/gte-Qwen2-1.5B-instruct\", \"input\": \"{text}\"}}'\"\"\"\n", + "\n", + "result = subprocess.check_output(curl_text, shell=True)\n", + "\n", + "print(result)\n", + "\n", + "text_embedding = json.loads(result)[\"data\"][0][\"embedding\"]\n", + "\n", + "print_highlight(f\"Text embedding (first 10): {text_embedding[:10]}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Python Requests" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "text = \"Once upon a time\"\n", + "\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/v1/embeddings\",\n", + " json={\"model\": \"Alibaba-NLP/gte-Qwen2-1.5B-instruct\", \"input\": text},\n", + ")\n", + "\n", + "text_embedding = response.json()[\"data\"][0][\"embedding\"]\n", + "\n", + "print_highlight(f\"Text embedding (first 10): {text_embedding[:10]}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using OpenAI Python Client" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import openai\n", + "\n", + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n", + "\n", + "# Text embedding example\n", + "response = client.embeddings.create(\n", + " model=\"Alibaba-NLP/gte-Qwen2-1.5B-instruct\",\n", + " input=text,\n", + ")\n", + "\n", + "embedding = response.data[0].embedding[:10]\n", + "print_highlight(f\"Text embedding (first 10): {embedding}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Input IDs\n", + "\n", + "SGLang also supports `input_ids` as input to get the embedding." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "import os\n", + "from transformers import AutoTokenizer\n", + "\n", + "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n", + "\n", + "tokenizer = AutoTokenizer.from_pretrained(\"Alibaba-NLP/gte-Qwen2-1.5B-instruct\")\n", + "input_ids = tokenizer.encode(text)\n", + "\n", + "curl_ids = f\"\"\"curl -s http://localhost:{port}/v1/embeddings \\\n", + " -H \"Content-Type: application/json\" \\\n", + " -d '{{\"model\": \"Alibaba-NLP/gte-Qwen2-1.5B-instruct\", \"input\": {json.dumps(input_ids)}}}'\"\"\"\n", + "\n", + "input_ids_embedding = json.loads(subprocess.check_output(curl_ids, shell=True))[\"data\"][\n", + " 0\n", + "][\"embedding\"]\n", + "\n", + "print_highlight(f\"Input IDs embedding (first 10): {input_ids_embedding[:10]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(embedding_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Multi-Modal Embedding Model\n", + "Please refer to [Multi-Modal Embedding Model](../supported_models/embedding_models)" + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/basic_usage/openai_api_embeddings.mdx b/docs_new/docs/basic_usage/openai_api_embeddings.mdx new file mode 100644 index 000000000..a0528a0c4 --- /dev/null +++ b/docs_new/docs/basic_usage/openai_api_embeddings.mdx @@ -0,0 +1,126 @@ +--- +title: "OpenAI APIs - Embedding" +metatags: + description: "This tutorial covers the embedding APIs for embedding models." +--- +SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models. +A complete reference for the API is available in the [OpenAI API Reference](https://platform.openai.com/docs/guides/embeddings). + +This tutorial covers the embedding APIs for embedding models. For a list of the supported models see the [corresponding overview page](../supported-models) + + + +## Launch A Server + +Launch the server in your terminal and wait for it to initialize. Remember to add `--is-embedding` to the command. + + + +```python Example +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process + +embedding_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path Alibaba-NLP/gte-Qwen2-1.5B-instruct \ + --host 0.0.0.0 --is-embedding --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + +## Using cURL + + + +```python Example +import subprocess, json + +text = "Once upon a time" + +curl_text = f"""curl -s http://localhost:{port}/v1/embeddings \ + -H "Content-Type: application/json" \ + -d '{{"model": "Alibaba-NLP/gte-Qwen2-1.5B-instruct", "input": "{text}"}}'""" + +result = subprocess.check_output(curl_text, shell=True) + +print(result) + +text_embedding = json.loads(result)["data"][0]["embedding"] + +print_highlight(f"Text embedding (first 10): {text_embedding[:10]}") +``` + +## Using Python Requests + + + +```python Example +import requests + +text = "Once upon a time" + +response = requests.post( + f"http://localhost:{port}/v1/embeddings", + json={"model": "Alibaba-NLP/gte-Qwen2-1.5B-instruct", "input": text}, +) + +text_embedding = response.json()["data"][0]["embedding"] + +print_highlight(f"Text embedding (first 10): {text_embedding[:10]}") +``` + +## Using OpenAI Python Client + + + +```python Example +import openai + +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") + +# Text embedding example +response = client.embeddings.create( + model="Alibaba-NLP/gte-Qwen2-1.5B-instruct", + input=text, +) + +embedding = response.data[0].embedding[:10] +print_highlight(f"Text embedding (first 10): {embedding}") +``` + +## Using Input IDs + +SGLang also supports `input_ids` as input to get the embedding. + + + +```python Example +import json +import os +from transformers import AutoTokenizer + +os.environ["TOKENIZERS_PARALLELISM"] = "false" + +tokenizer = AutoTokenizer.from_pretrained("Alibaba-NLP/gte-Qwen2-1.5B-instruct") +input_ids = tokenizer.encode(text) + +curl_ids = f"""curl -s http://localhost:{port}/v1/embeddings \ + -H "Content-Type: application/json" \ + -d '{{"model": "Alibaba-NLP/gte-Qwen2-1.5B-instruct", "input": {json.dumps(input_ids)}}}'""" + +input_ids_embedding = json.loads(subprocess.check_output(curl_ids, shell=True))["data"][ + 0 +]["embedding"] + +print_highlight(f"Input IDs embedding (first 10): {input_ids_embedding[:10]}") +``` + + +```python Example +terminate_process(embedding_process) +``` + +## Multi-Modal Embedding Model +Please refer to [Multi-Modal Embedding Model](../supported-models) diff --git a/docs_new/docs/basic_usage/openai_api_vision.ipynb b/docs_new/docs/basic_usage/openai_api_vision.ipynb new file mode 100644 index 000000000..aea2c7ef8 --- /dev/null +++ b/docs_new/docs/basic_usage/openai_api_vision.ipynb @@ -0,0 +1,252 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# OpenAI APIs - Vision\n", + "\n", + "SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models.\n", + "A complete reference for the API is available in the [OpenAI API Reference](https://platform.openai.com/docs/guides/vision).\n", + "This tutorial covers the vision APIs for vision language models.\n", + "\n", + "SGLang supports various vision language models such as Llama 3.2, LLaVA-OneVision, Qwen2.5-VL, Gemma3 and [more](../supported_models/multimodal_language_models).\n", + "\n", + "As an alternative to the OpenAI API, you can also use the [SGLang offline engine](https://github.com/sgl-project/sglang/blob/main/examples/runtime/engine/offline_batch_inference_vlm.py)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Launch A Server\n", + "\n", + "Launch the server in your terminal and wait for it to initialize." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "vision_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-VL-7B-Instruct --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using cURL\n", + "\n", + "Once the server is up, you can send test requests using curl or requests." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import subprocess\n", + "\n", + "curl_command = f\"\"\"\n", + "curl -s http://localhost:{port}/v1/chat/completions \\\\\n", + " -H \"Content-Type: application/json\" \\\\\n", + " -d '{{\n", + " \"model\": \"Qwen/Qwen2.5-VL-7B-Instruct\",\n", + " \"messages\": [\n", + " {{\n", + " \"role\": \"user\",\n", + " \"content\": [\n", + " {{\n", + " \"type\": \"text\",\n", + " \"text\": \"What’s in this image?\"\n", + " }},\n", + " {{\n", + " \"type\": \"image_url\",\n", + " \"image_url\": {{\n", + " \"url\": \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\"\n", + " }}\n", + " }}\n", + " ]\n", + " }}\n", + " ],\n", + " \"max_tokens\": 300\n", + " }}'\n", + "\"\"\"\n", + "\n", + "response = subprocess.check_output(curl_command, shell=True).decode()\n", + "print_highlight(response)\n", + "\n", + "\n", + "response = subprocess.check_output(curl_command, shell=True).decode()\n", + "print_highlight(response)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Python Requests" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "url = f\"http://localhost:{port}/v1/chat/completions\"\n", + "\n", + "data = {\n", + " \"model\": \"Qwen/Qwen2.5-VL-7B-Instruct\",\n", + " \"messages\": [\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": [\n", + " {\"type\": \"text\", \"text\": \"What’s in this image?\"},\n", + " {\n", + " \"type\": \"image_url\",\n", + " \"image_url\": {\n", + " \"url\": \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\"\n", + " },\n", + " },\n", + " ],\n", + " }\n", + " ],\n", + " \"max_tokens\": 300,\n", + "}\n", + "\n", + "response = requests.post(url, json=data)\n", + "print_highlight(response.text)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using OpenAI Python Client" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from openai import OpenAI\n", + "\n", + "client = OpenAI(base_url=f\"http://localhost:{port}/v1\", api_key=\"None\")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"Qwen/Qwen2.5-VL-7B-Instruct\",\n", + " messages=[\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": [\n", + " {\n", + " \"type\": \"text\",\n", + " \"text\": \"What is in this image?\",\n", + " },\n", + " {\n", + " \"type\": \"image_url\",\n", + " \"image_url\": {\n", + " \"url\": \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\"\n", + " },\n", + " },\n", + " ],\n", + " }\n", + " ],\n", + " max_tokens=300,\n", + ")\n", + "\n", + "print_highlight(response.choices[0].message.content)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Multiple-Image Inputs\n", + "\n", + "The server also supports multiple images and interleaved text and images if the model supports it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from openai import OpenAI\n", + "\n", + "client = OpenAI(base_url=f\"http://localhost:{port}/v1\", api_key=\"None\")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"Qwen/Qwen2.5-VL-7B-Instruct\",\n", + " messages=[\n", + " {\n", + " \"role\": \"user\",\n", + " \"content\": [\n", + " {\n", + " \"type\": \"image_url\",\n", + " \"image_url\": {\n", + " \"url\": \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\",\n", + " },\n", + " },\n", + " {\n", + " \"type\": \"image_url\",\n", + " \"image_url\": {\n", + " \"url\": \"https://raw.githubusercontent.com/sgl-project/sglang/main/assets/logo.png\",\n", + " },\n", + " },\n", + " {\n", + " \"type\": \"text\",\n", + " \"text\": \"I have two very different images. They are not related at all. \"\n", + " \"Please describe the first image in one sentence, and then describe the second image in another sentence.\",\n", + " },\n", + " ],\n", + " }\n", + " ],\n", + " temperature=0,\n", + ")\n", + "\n", + "print_highlight(response.choices[0].message.content)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(vision_process)" + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/basic_usage/openai_api_vision.mdx b/docs_new/docs/basic_usage/openai_api_vision.mdx new file mode 100644 index 000000000..75e394e7d --- /dev/null +++ b/docs_new/docs/basic_usage/openai_api_vision.mdx @@ -0,0 +1,189 @@ +--- +title: "OpenAI APIs - Vision" +metatags: + description: "This tutorial covers the vision APIs for vision language models." +--- +SGLang provides OpenAI-compatible APIs to enable a smooth transition from OpenAI services to self-hosted local models. +A complete reference for the API is available in the [OpenAI API Reference](https://platform.openai.com/docs/guides/vision). +This tutorial covers the vision APIs for vision language models. + +SGLang supports various vision language models such as Llama 3.2, LLaVA-OneVision, Qwen2.5-VL, Gemma3 and [more](../supported-models). + +As an alternative to the OpenAI API, you can also use the [SGLang offline engine](https://github.com/sgl-project/sglang/blob/main/examples/runtime/engine/offline_batch_inference_vlm.py). + + +## Launch A Server + +Launch the server in your terminal and wait for it to initialize. + + + +```python Example +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process + +vision_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-VL-7B-Instruct --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + +## Using cURL + +Once the server is up, you can send test requests using curl or requests. + + + +```python Example +import subprocess + +curl_command = f""" +curl -s http://localhost:{port}/v1/chat/completions \\ + -H "Content-Type: application/json" \\ + -d '{{ + "model": "Qwen/Qwen2.5-VL-7B-Instruct", + "messages": [ + {{ + "role": "user", + "content": [ + {{ + "type": "text", + "text": "What’s in this image?" + }}, + {{ + "type": "image_url", + "image_url": {{ + "url": "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" + }} + }} + ] + }} + ], + "max_tokens": 300 + }}' +""" + +response = subprocess.check_output(curl_command, shell=True).decode() +print_highlight(response) + + +response = subprocess.check_output(curl_command, shell=True).decode() +print_highlight(response) +``` + +## Using Python Requests + + + +```python Example +import requests + +url = f"http://localhost:{port}/v1/chat/completions" + +data = { + "model": "Qwen/Qwen2.5-VL-7B-Instruct", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What’s in this image?"}, + { + "type": "image_url", + "image_url": { + "url": "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" + }, + }, + ], + } + ], + "max_tokens": 300, +} + +response = requests.post(url, json=data) +print_highlight(response.text) +``` + +## Using OpenAI Python Client + + + +```python Example +from openai import OpenAI + +client = OpenAI(base_url=f"http://localhost:{port}/v1", api_key="None") + +response = client.chat.completions.create( + model="Qwen/Qwen2.5-VL-7B-Instruct", + messages=[ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "What is in this image?", + }, + { + "type": "image_url", + "image_url": { + "url": "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" + }, + }, + ], + } + ], + max_tokens=300, +) + +print_highlight(response.choices[0].message.content) +``` + +## Multiple-Image Inputs + +The server also supports multiple images and interleaved text and images if the model supports it. + + + +```python Example +from openai import OpenAI + +client = OpenAI(base_url=f"http://localhost:{port}/v1", api_key="None") + +response = client.chat.completions.create( + model="Qwen/Qwen2.5-VL-7B-Instruct", + 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": "image_url", + "image_url": { + "url": "https://raw.githubusercontent.com/sgl-project/sglang/main/assets/logo.png", + }, + }, + { + "type": "text", + "text": "I have two very different images. They are not related at all. " + "Please describe the first image in one sentence, and then describe the second image in another sentence.", + }, + ], + } + ], + temperature=0, +) + +print_highlight(response.choices[0].message.content) +``` + + +```python Example +terminate_process(vision_process) +``` diff --git a/docs_new/docs/basic_usage/overview.mdx b/docs_new/docs/basic_usage/overview.mdx new file mode 100644 index 000000000..6f15d1c33 --- /dev/null +++ b/docs_new/docs/basic_usage/overview.mdx @@ -0,0 +1,11 @@ +--- +title: Basic Usage +description: Core APIs and common usage patterns for SGLang. +--- + +- [OpenAI-Compatible APIs](./openai_api_completions) — Chat completions, vision, and embeddings +- [Ollama API](./ollama_api) +- [Offline Engine API](./offline_engine_api) +- [Native API](./native_api) +- [Sampling Parameters](./sampling_params) +- [Popular Model Usage](./popular_model_usage) — DeepSeek, GLM, Qwen, Llama, and more diff --git a/docs_new/docs/basic_usage/popular_model_usage.mdx b/docs_new/docs/basic_usage/popular_model_usage.mdx new file mode 100644 index 000000000..db61169e7 --- /dev/null +++ b/docs_new/docs/basic_usage/popular_model_usage.mdx @@ -0,0 +1,14 @@ +--- +title: "Popular Model Usage (DeepSeek, GPT-OSS, GLM, Llama, MiniMax, Qwen, and more)" +description: "Documentation for Popular Model Usage (DeepSeek, GPT-OSS, GLM, Llama, MiniMax, Qwen, and more)" +--- +- [Deepseek V3](./deepseek_v3) +- [Deepseek V32](./deepseek_v32) +- [Glm45](./glm45) +- [Glmv](./glmv) +- [Gpt Oss](./gpt_oss) +- [Kimi K2 5](./kimi_k2_5) +- [Minimax M2](./minimax_m2) +- [Qwen3](./qwen3) +- [Qwen3 Vl](./qwen3_vl) +- [Llama4](./llama4) diff --git a/docs_new/docs/basic_usage/popular_model_usage.rst b/docs_new/docs/basic_usage/popular_model_usage.rst new file mode 100644 index 000000000..06d426661 --- /dev/null +++ b/docs_new/docs/basic_usage/popular_model_usage.rst @@ -0,0 +1,16 @@ +Popular Model Usage (DeepSeek, GPT-OSS, GLM, Llama, MiniMax, Qwen, and more) +=============================================================== + +.. toctree:: + :maxdepth: 1 + + deepseek_v3.md + deepseek_v32.md + glm45.md + glmv.md + gpt_oss.md + kimi_k2_5.md + minimax_m2.md + qwen3.md + qwen3_vl.md + llama4.md diff --git a/docs_new/docs/basic_usage/qwen3.mdx b/docs_new/docs/basic_usage/qwen3.mdx new file mode 100644 index 000000000..4c316dcf8 --- /dev/null +++ b/docs_new/docs/basic_usage/qwen3.mdx @@ -0,0 +1,42 @@ +--- +title: "Qwen3-Next Usage" +metatags: + description: "Deploy Qwen3-Next with SGLang: 80B hybrid Mamba model, MambaRadixCache prefix caching, EAGLE speculative decoding. Supports H100/H200 GPUs." +--- +SGLang has supported Qwen3-Next-80B-A3B-Instruct and Qwen3-Next-80B-A3B-Thinking since [this PR](https://github.com/sgl-project/sglang/pull/10233). + +## Launch Qwen3-Next with SGLang + +To serve Qwen3-Next models on 4xH100/H200 GPUs: + +```bash Command +python3 -m sglang.launch_server --model Qwen/Qwen3-Next-80B-A3B-Instruct --tp 4 +``` + +### 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`: The ratio of mamba state memory to full kv cache memory. The default is 0.9. + +### Mamba Radix Cache +SGLang supports prefix caching for Qwen3-Next models named `MambaRadixCache`, which improves inference speed by reusing computation results. There are two versions of `MambaRadixCache`: +- `no_buffer`: The default version, which is also other hybrid linear models' choice. When it is enabled, SGLang will automatically close overlap schedule for compatibility reasons. +- `extra_buffer`: An optimized version that is compatible with features like page size > 1, overlap schedule, and speculative decoding. It also supports storing mamba state in branching positions. However, it requires two extra mamba spaces for a ping-pong buffer for each request. To enable it, add the argument `--mamba-scheduler-strategy extra_buffer` when launching the server. + +### EAGLE Speculative Decoding +**Description**: SGLang has supported Qwen3-Next models with [EAGLE speculative decoding](../advanced_features/speculative_decoding#EAGLE-Decoding). + +**Usage**: +Add arguments `--speculative-algorithm`, `--speculative-num-steps`, `--speculative-eagle-topk` and `--speculative-num-draft-tokens` to enable this feature. For example: + +```bash Command +python3 -m sglang.launch_server \ + --model Qwen/Qwen3-Next-80B-A3B-Instruct \ + --tp 4 \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 \ + --speculative-algo NEXTN +``` + +Details can be seen in [this PR](https://github.com/sgl-project/sglang/pull/10233). diff --git a/docs_new/docs/basic_usage/qwen3_vl.mdx b/docs_new/docs/basic_usage/qwen3_vl.mdx new file mode 100644 index 000000000..a98a5b4e8 --- /dev/null +++ b/docs_new/docs/basic_usage/qwen3_vl.mdx @@ -0,0 +1,133 @@ +--- +title: "Qwen3-VL Usage" +metatags: + description: "Deploy Qwen3-VL vision models with SGLang: FP8 and BF16 modes, image and video input, expert parallelism. Supports H100, H200, A100 GPUs." +--- +[Qwen3-VL](https://huggingface.co/collections/Qwen/qwen3-vl) +is Alibaba’s latest multimodal large language model with strong text, vision, and reasoning capabilities. +SGLang supports Qwen3-VL Family of models with Image and Video input support. + +## Launch commands for SGLang + +Below are suggested launch commands tailored for different hardware / precision modes + +### FP8 (quantised) mode +For high memory-efficiency and latency optimized deployments (e.g., on H100, H200) where FP8 checkpoint is supported: +```bash Command +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-235B-A22B-Instruct-FP8 \ + --tp 8 \ + --ep 8 \ + --host 0.0.0.0 \ + --port 30000 \ + --keep-mm-feature-on-device +``` + +### Non-FP8 (BF16 / full precision) mode +For deployments on A100/H100 where BF16 is used (or FP8 snapshot not used): +```bash Command +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-235B-A22B-Instruct \ + --tp 8 \ + --ep 8 \ + --host 0.0.0.0 \ + --port 30000 \ +``` + +## Hardware-specific notes / recommendations + +- On H100 with FP8: Use the FP8 checkpoint for best memory efficiency. +- On A100 / H100 with BF16 (non-FP8): It’s recommended to use `--mm-max-concurrent-calls` to control parallel throughput and GPU memory usage during image/video inference. +- On H200 & B200: The model can be run “out of the box”, supporting full context length plus concurrent image + video processing. + +## Sending Image/Video Requests + +### Image input: + +```python Example +import requests + +url = f"http://localhost:30000/v1/chat/completions" + +data = { + "model": "Qwen/Qwen3-VL-30B-A3B-Instruct", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What’s in this image?"}, + { + "type": "image_url", + "image_url": { + "url": "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" + }, + }, + ], + } + ], + "max_tokens": 300, +} + +response = requests.post(url, json=data) +print(response.text) +``` + +### Video Input: + +```python Example +import requests + +url = f"http://localhost:30000/v1/chat/completions" + +data = { + "model": "Qwen/Qwen3-VL-30B-A3B-Instruct", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What’s happening in this video?"}, + { + "type": "video_url", + "video_url": { + "url": "https://github.com/sgl-project/sgl-test-files/raw/refs/heads/main/videos/jobs_presenting_ipod.mp4" + }, + }, + ], + } + ], + "max_tokens": 300, +} + +response = requests.post(url, json=data) +print(response.text) +``` + +## Important Server Parameters and Flags + +When launching the model server for **multimodal support**, you can use the following command-line arguments to fine-tune performance and behavior: + +- `--mm-attention-backend`: Specify multimodal attention backend. Eg. `fa3`(Flash Attention 3) +- `--mm-max-concurrent-calls `: Specifies the **maximum number of concurrent asynchronous multimodal data processing calls** allowed on the server. Use this to control parallel throughput and GPU memory usage during image/video inference. +- `--mm-per-request-timeout `: Defines the **timeout duration (in seconds)** for each multimodal request. If a request exceeds this time limit (e.g., for very large video inputs), it will be automatically terminated. +- `--keep-mm-feature-on-device`: Instructs the server to **retain multimodal feature tensors on the GPU** after processing. This avoids device-to-host (D2H) memory copies and improves performance for repeated or high-frequency inference workloads. +- `SGLANG_USE_CUDA_IPC_TRANSPORT=1`: Shared memory pool based CUDA IPC for multi-modal data transport. For significantly improving e2e latency. + +### Example usage with the above optimizations: +```bash Command +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 +``` diff --git a/docs_new/docs/basic_usage/sampling_params.mdx b/docs_new/docs/basic_usage/sampling_params.mdx new file mode 100644 index 000000000..4b271a229 --- /dev/null +++ b/docs_new/docs/basic_usage/sampling_params.mdx @@ -0,0 +1,576 @@ +--- +title: "Sampling Parameters" +metatags: + description: "Complete reference for SGLang sampling parameters: temperature, top_p, top_k, frequency penalty, stop tokens, and more." +--- +This doc describes the sampling parameters of the SGLang Runtime. It is the low-level endpoint of the runtime. +If you want a high-level endpoint that can automatically handle chat templates, consider using the [OpenAI Compatible API](./openai_api_completions). + +## `/generate` Endpoint + +The `/generate` endpoint accepts the following parameters in JSON format. For detailed usage, see the [native API doc](./native_api). The object is defined at `io_struct.py::GenerateReqInput`. You can also read the source code to find more arguments and docs. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentType/DefaultDescription
text`Optional[Union[List[str], str]] = None`The input prompt. Can be a single prompt or a batch of prompts.
input_ids`Optional[Union[List[List[int]], List[int]]] = None`The token IDs for text; one can specify either text or input_ids.
input_embeds`Optional[Union[List[List[List[float]]], List[List[float]]]] = None`The embeddings for input_ids; one can specify either text, input_ids, or input_embeds.
image_data`Optional[Union[List[List[ImageDataItem]], List[ImageDataItem], ImageDataItem]] = None`The image input. Supports three formats: (1) **Raw images**: PIL Image, file path, URL, or base64 string; (2) **Processor output**: Dict with `format: "processor_output"` containing HuggingFace processor outputs; (3) **Precomputed embeddings**: Dict with `format: "precomputed_embedding"` and `feature` containing pre-calculated visual embeddings. Can be a single image, list of images, or list of lists of images. See [Multimodal Input Formats](#multimodal-input-formats) for details.
audio_data`Optional[Union[List[AudioDataItem], AudioDataItem]] = None`The audio input. Can be a file name, URL, or base64 encoded string.
sampling_params`Optional[Union[List[Dict], Dict]] = None`The sampling parameters as described in the sections below.
rid`Optional[Union[List[str], str]] = None`The request ID.
return_logprob`Optional[Union[List[bool], bool]] = None`Whether to return log probabilities for tokens.
logprob_start_len`Optional[Union[List[int], int]] = None`If return_logprob, the start location in the prompt for returning logprobs. Default is "-1", which returns logprobs for output tokens only.
top_logprobs_num`Optional[Union[List[int], int]] = None`If return_logprob, the number of top logprobs to return at each position.
token_ids_logprob`Optional[Union[List[List[int]], List[int]]] = None`If return_logprob, the token IDs to return logprob for.
return_text_in_logprobs`bool = False`Whether to detokenize tokens in text in the returned logprobs.
stream`bool = False`Whether to stream output.
lora_path`Optional[Union[List[Optional[str]], Optional[str]]] = None`The path to the LoRA.
custom_logit_processor`Optional[Union[List[Optional[str]], str]] = None`Custom logit processor for advanced sampling control. Must be a serialized instance of `CustomLogitProcessor` using its `to_str()` method. For usage see below.
return_hidden_states`Union[List[bool], bool] = False`Whether to return hidden states.
return_routed_experts`bool = False`Whether to return routed experts for MoE models. Requires `--enable-return-routed-experts` server flag. Returns base64-encoded int32 expert IDs as a flattened array with logical shape `[num_tokens, num_layers, top_k]`.
+ +## Sampling parameters + +The object is defined at `sampling_params.py::SamplingParams`. You can also read the source code to find more arguments and docs. + +### Note on defaults + +By default, SGLang initializes several sampling parameters from the model's `generation_config.json` (when the server is launched with `--sampling-defaults model`, which is the default). To use SGLang/OpenAI constant defaults instead, start the server with `--sampling-defaults openai`. You can always override any parameter per request via `sampling_params`. + +```bash Command +# Use model-provided defaults from generation_config.json (default behavior) +python -m sglang.launch_server --model-path --sampling-defaults model + +# Use SGLang/OpenAI constant defaults instead +python -m sglang.launch_server --model-path --sampling-defaults openai +``` + +### Core parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentType/DefaultDescription
max_new_tokens`int = 128`The maximum output length measured in tokens.
stop`Optional[Union[str, List[str]]] = None`One or multiple [stop words](https://platform.openai.com/docs/api-reference/chat/create#chat-create-stop). Generation will stop if one of these words is sampled.
stop_token_ids`Optional[List[int]] = None`Provide stop words in the form of token IDs. Generation will stop if one of these token IDs is sampled.
stop_regex`Optional[Union[str, List[str]]] = None`Stop when hitting any of the regex patterns in this list
temperature`float (model default; fallback 1.0)`[Temperature](https://platform.openai.com/docs/api-reference/chat/create#chat-create-temperature) when sampling the next token. `temperature = 0` corresponds to greedy sampling, a higher temperature leads to more diversity.
top_p`float (model default; fallback 1.0)`[Top-p](https://platform.openai.com/docs/api-reference/chat/create#chat-create-top_p) selects tokens from the smallest sorted set whose cumulative probability exceeds `top_p`. When `top_p = 1`, this reduces to unrestricted sampling from all tokens.
top_k`int (model default; fallback -1)`[Top-k](https://developer.nvidia.com/blog/how-to-get-better-outputs-from-your-large-language-model/#predictability_vs_creativity) randomly selects from the `k` highest-probability tokens.
min_p`float (model default; fallback 0.0)`[Min-p](https://github.com/huggingface/transformers/issues/27670) samples from tokens with probability larger than `min_p * highest_token_probability`.
+ +### Penalizers + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentType/DefaultDescription
frequency_penalty`float = 0.0`Penalizes tokens based on their frequency in generation so far. Must be between `-2` and `2` where negative numbers encourage repeatment of tokens and positive number encourages sampling of new tokens. The scaling of penalization grows linearly with each appearance of a token.
presence_penalty`float = 0.0`Penalizes tokens if they appeared in the generation so far. Must be between `-2` and `2` where negative numbers encourage repeatment of tokens and positive number encourages sampling of new tokens. The scaling of the penalization is constant if a token occurred.
repetition_penalty`float = 1.0`Scales the logits of previously generated tokens to discourage (values > 1) or encourage (values < 1) repetition. Valid range is `[0, 2]`; `1.0` leaves probabilities unchanged.
min_new_tokens`int = 0`Forces the model to generate at least `min_new_tokens` until a stop word or EOS token is sampled. Note that this might lead to unintended behavior, for example, if the distribution is highly skewed towards these tokens.
+ +### Constrained decoding + +Please refer to our dedicated guide on [constrained decoding](../advanced_features/structured_outputs) for the following parameters. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentType/DefaultDescription
json_schema`Optional[str] = None`JSON schema for structured outputs.
regex`Optional[str] = None`Regex for structured outputs.
ebnf`Optional[str] = None`EBNF for structured outputs.
structural_tag`Optional[str] = None`The structal tag for structured outputs.
+ +### Other options + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentType/DefaultDescription
n`int = 1`Specifies the number of output sequences to generate per request. (Generating multiple outputs in one request (n > 1) is discouraged; repeating the same prompts several times offers better control and efficiency.)
ignore_eos`bool = False`Don't stop generation when EOS token is sampled.
skip_special_tokens`bool = True`Remove special tokens during decoding.
spaces_between_special_tokens`bool = True`Whether or not to add spaces between special tokens during detokenization.
no_stop_trim`bool = False`Don't trim stop words or EOS token from the generated text.
custom_params`Optional[List[Optional[Dict[str, Any]]]] = None`Used when employing `CustomLogitProcessor`. For usage, see below.
+ +## Examples + +### Normal + +Launch a server: + +```bash Command +python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3-8B-Instruct --port 30000 +``` + +Send a request: + +```python Example +import requests + +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + }, + }, +) +print(response.json()) +``` + +Detailed example in [send request](./send_request). + +### Streaming + +Send a request and stream the output: + +```python Example +import requests, json + +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + }, + "stream": True, + }, + stream=True, +) + +prev = 0 +for chunk in response.iter_lines(decode_unicode=False): + chunk = chunk.decode("utf-8") + if chunk and chunk.startswith("data:"): + if chunk == "data: [DONE]": + break + data = json.loads(chunk[5:].strip("\n")) + output = data["text"].strip() + print(output[prev:], end="", flush=True) + prev = len(output) +print("") +``` + +Detailed example in [openai compatible api](./openai_api_completions). + +### Multimodal + +Launch a server: + +```bash Command +python3 -m sglang.launch_server --model-path lmms-lab/llava-onevision-qwen2-7b-ov +``` + +Download an image: + +```bash Command +curl -o example_image.png -L https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true +``` + +Send a request: + +```python Example +import requests + +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n" + "<|im_start|>user\n\nDescribe this image in a very short sentence.<|im_end|>\n" + "<|im_start|>assistant\n", + "image_data": "example_image.png", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + }, + }, +) +print(response.json()) +``` + +The `image_data` can be a file name, a URL, or a base64 encoded string. See also `python/sglang/srt/utils.py:load_image`. + +Streaming is supported in a similar manner as [above](#streaming). + +Detailed example in [OpenAI API Vision](./openai_api_vision). + +### Structured Outputs (JSON, Regex, EBNF) + +You can specify a JSON schema, regular expression or [EBNF](https://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_form) to constrain the model output. The model output will be guaranteed to follow the given constraints. Only one constraint parameter (`json_schema`, `regex`, or `ebnf`) can be specified for a request. + +SGLang supports two grammar backends: + +- [XGrammar](https://github.com/mlc-ai/xgrammar) (default): Supports JSON schema, regular expression, and EBNF constraints. + - XGrammar currently uses the [GGML BNF format](https://github.com/ggerganov/llama.cpp/blob/master/grammars/README). +- [Outlines](https://github.com/dottxt-ai/outlines): Supports JSON schema and regular expression constraints. + +If instead you want to initialize the Outlines backend, you can use `--grammar-backend outlines` flag: + +```bash Command +python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ +--port 30000 --host 0.0.0.0 --grammar-backend [xgrammar|outlines] # xgrammar or outlines (default: xgrammar) +``` + +```python Example +import json +import requests + +json_schema = json.dumps({ + "type": "object", + "properties": { + "name": {"type": "string", "pattern": "^[\\w]+$"}, + "population": {"type": "integer"}, + }, + "required": ["name", "population"], +}) + +# JSON (works with both Outlines and XGrammar) +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "Here is the information of the capital of France in the JSON format.\n", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 64, + "json_schema": json_schema, + }, + }, +) +print(response.json()) + +# Regular expression (Outlines backend only) +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "Paris is the capital of", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 64, + "regex": "(France|England)", + }, + }, +) +print(response.json()) + +# EBNF (XGrammar backend only) +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "Write a greeting.", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 64, + "ebnf": 'root ::= "Hello" | "Hi" | "Hey"', + }, + }, +) +print(response.json()) +``` + +Detailed example in [structured outputs](../advanced_features/structured_outputs). + +### Custom logit processor + +Launch a server with `--enable-custom-logit-processor` flag on. + +```bash Command +python -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3-8B-Instruct \ + --port 30000 \ + --enable-custom-logit-processor +``` + +Define a custom logit processor that will always sample a specific token id. + +```python Example +from sglang.srt.sampling.custom_logit_processor import CustomLogitProcessor + +class DeterministicLogitProcessor(CustomLogitProcessor): + """A dummy logit processor that changes the logits to always + sample the given token id. + """ + + def __call__(self, logits, custom_param_list): + # Check that the number of logits matches the number of custom parameters + assert logits.shape[0] == len(custom_param_list) + key = "token_id" + + for i, param_dict in enumerate(custom_param_list): + # Mask all other tokens + logits[i, :] = -float("inf") + # Assign highest probability to the specified token + logits[i, param_dict[key]] = 0.0 + return logits +``` + +Send a request: + +```python Example +import requests + +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "The capital of France is", + "custom_logit_processor": DeterministicLogitProcessor().to_str(), + "sampling_params": { + "temperature": 0.0, + "max_new_tokens": 32, + "custom_params": {"token_id": 5}, + }, + }, +) +print(response.json()) +``` + +Send an OpenAI chat completion request: + +```python Example +import openai +from sglang.utils import print_highlight + +client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="meta-llama/Meta-Llama-3-8B-Instruct", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0.0, + max_tokens=32, + extra_body={ + "custom_logit_processor": DeterministicLogitProcessor().to_str(), + "custom_params": {"token_id": 5}, + }, +) + +print_highlight(f"Response: {response}") +``` diff --git a/docs_new/docs/basic_usage/send_request.ipynb b/docs_new/docs/basic_usage/send_request.ipynb new file mode 100644 index 000000000..412f1fa60 --- /dev/null +++ b/docs_new/docs/basic_usage/send_request.ipynb @@ -0,0 +1,251 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Sending Requests\n", + "This notebook provides a quick-start guide to use SGLang in chat completions after installation. Once your server is running, API documentation is available at `http://localhost:30000/docs` (Swagger UI), `http://localhost:30000/redoc` (ReDoc), or `http://localhost:30000/openapi.json` (OpenAPI spec, useful for AI agents). Replace `30000` with your port if using a different one.\n", + "\n", + "- For Vision Language Models, see [OpenAI APIs - Vision](openai_api_vision).\n", + "- For Embedding Models, see [OpenAI APIs - Embedding](openai_api_embeddings) and [Encode (embedding model)](native_api#encode-embedding-model).\n", + "- For Reward Models, see [Classify (reward model)](native_api#classify-reward-model)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Launch A Server" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import wait_for_server, print_highlight, terminate_process\n", + "\n", + "# This is equivalent to running the following command in your terminal\n", + "# python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0\n", + "\n", + "server_process, port = launch_server_cmd(\"\"\"\n", + "python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct \\\n", + " --host 0.0.0.0 --log-level warning\n", + "\"\"\")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using cURL\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import subprocess, json\n", + "\n", + "curl_command = f\"\"\"\n", + "curl -s http://localhost:{port}/v1/chat/completions \\\n", + " -H \"Content-Type: application/json\" \\\n", + " -d '{{\"model\": \"qwen/qwen2.5-0.5b-instruct\", \"messages\": [{{\"role\": \"user\", \"content\": \"What is the capital of France?\"}}]}}'\n", + "\"\"\"\n", + "\n", + "response = json.loads(subprocess.check_output(curl_command, shell=True))\n", + "print_highlight(response)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Python Requests" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "url = f\"http://localhost:{port}/v1/chat/completions\"\n", + "\n", + "data = {\n", + " \"model\": \"qwen/qwen2.5-0.5b-instruct\",\n", + " \"messages\": [{\"role\": \"user\", \"content\": \"What is the capital of France?\"}],\n", + "}\n", + "\n", + "response = requests.post(url, json=data)\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using OpenAI Python Client" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import openai\n", + "\n", + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n", + "\n", + "response = client.chat.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=64,\n", + ")\n", + "print_highlight(response)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Streaming" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import openai\n", + "\n", + "client = openai.Client(base_url=f\"http://127.0.0.1:{port}/v1\", api_key=\"None\")\n", + "\n", + "# Use stream=True for streaming responses\n", + "response = client.chat.completions.create(\n", + " model=\"qwen/qwen2.5-0.5b-instruct\",\n", + " messages=[\n", + " {\"role\": \"user\", \"content\": \"List 3 countries and their capitals.\"},\n", + " ],\n", + " temperature=0,\n", + " max_tokens=64,\n", + " stream=True,\n", + ")\n", + "\n", + "# Handle the streaming output\n", + "for chunk in response:\n", + " if chunk.choices[0].delta.content:\n", + " print(chunk.choices[0].delta.content, end=\"\", flush=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using Native Generation APIs\n", + "\n", + "You can also use the native `/generate` endpoint with requests, which provides more flexibility. An API reference is available at [Sampling Parameters](sampling_params)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": \"The capital of France is\",\n", + " \"sampling_params\": {\n", + " \"temperature\": 0,\n", + " \"max_new_tokens\": 32,\n", + " },\n", + " },\n", + ")\n", + "\n", + "print_highlight(response.json())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Streaming" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests, json\n", + "\n", + "response = requests.post(\n", + " f\"http://localhost:{port}/generate\",\n", + " json={\n", + " \"text\": \"The capital of France is\",\n", + " \"sampling_params\": {\n", + " \"temperature\": 0,\n", + " \"max_new_tokens\": 32,\n", + " },\n", + " \"stream\": True,\n", + " },\n", + " stream=True,\n", + ")\n", + "\n", + "prev = 0\n", + "for chunk in response.iter_lines(decode_unicode=False):\n", + " chunk = chunk.decode(\"utf-8\")\n", + " if chunk and chunk.startswith(\"data:\"):\n", + " if chunk == \"data: [DONE]\":\n", + " break\n", + " data = json.loads(chunk[5:].strip(\"\\n\"))\n", + " output = data[\"text\"]\n", + " print(output[prev:], end=\"\", flush=True)\n", + " prev = len(output)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + } + ], + "metadata": { + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/basic_usage/send_request.mdx b/docs_new/docs/basic_usage/send_request.mdx new file mode 100644 index 000000000..15ce9b121 --- /dev/null +++ b/docs_new/docs/basic_usage/send_request.mdx @@ -0,0 +1,172 @@ +--- +title: "Tutorial: Sending a request" +metatags: + description: "This notebook provides a quick-start guide to use SGLang in chat completions after installation. " +--- +This notebook provides a quick-start guide to use SGLang in chat completions after installation. Once your server is running, API documentation is available at `http://localhost:30000/docs` (Swagger UI), `http://localhost:30000/redoc` (ReDoc), or `http://localhost:30000/openapi.json` (OpenAPI spec, useful for AI agents). Replace `30000` with your port if using a different one. + +- For Vision Language Models, see [OpenAI APIs - Vision](./openai_api_vision). +- For Embedding Models, see [OpenAI APIs - Embedding](./openai_api_embeddings) and [Encode (embedding model)](./native_api#encode-embedding-model). +- For Reward Models, see [Classify (reward model)](./native_api#classify-reward-model). + + +## Launch A Server + + + +```python Example +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import wait_for_server, print_highlight, terminate_process + +# This is equivalent to running the following command in your terminal +# python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 + +server_process, port = launch_server_cmd( + """ +python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct \ + --host 0.0.0.0 --log-level warning +""" +) + +wait_for_server(f"http://localhost:{port}") +``` + +## Using cURL + + + + +```python Example +import subprocess, json + +curl_command = f""" +curl -s http://localhost:{port}/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{{"model": "qwen/qwen2.5-0.5b-instruct", "messages": [{{"role": "user", "content": "What is the capital of France?"}}]}}' +""" + +response = json.loads(subprocess.check_output(curl_command, shell=True)) +print_highlight(response) +``` + +## Using Python Requests + + + +```python Example +import requests + +url = f"http://localhost:{port}/v1/chat/completions" + +data = { + "model": "qwen/qwen2.5-0.5b-instruct", + "messages": [{"role": "user", "content": "What is the capital of France?"}], +} + +response = requests.post(url, json=data) +print_highlight(response.json()) +``` + +## Using OpenAI Python Client + + + +```python Example +import openai + +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") + +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, +) +print_highlight(response) +``` + +### Streaming + + + +```python Example +import openai + +client = openai.Client(base_url=f"http://127.0.0.1:{port}/v1", api_key="None") + +# Use stream=True for streaming responses +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, + stream=True, +) + +# Handle the streaming output +for chunk in response: + if chunk.choices[0].delta.content: + print(chunk.choices[0].delta.content, end="", flush=True) +``` + +## Using Native Generation APIs + +You can also use the native `/generate` endpoint with requests, which provides more flexibility. An API reference is available at [Sampling Parameters](./sampling_params). + + + +```python Example +import requests + +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + }, + }, +) + +print_highlight(response.json()) +``` +### Streaming + + + +```python Example +import requests, json + +response = requests.post( + f"http://localhost:{port}/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + }, + "stream": True, + }, + stream=True, +) + +prev = 0 +for chunk in response.iter_lines(decode_unicode=False): + chunk = chunk.decode("utf-8") + if chunk and chunk.startswith("data:"): + if chunk == "data: [DONE]": + break + data = json.loads(chunk[5:].strip("\n")) + output = data["text"] + print(output[prev:], end="", flush=True) + prev = len(output) +``` + +```python Example +terminate_process(server_process) +``` diff --git a/docs_new/docs/developer_guide/JIT_kernels.mdx b/docs_new/docs/developer_guide/JIT_kernels.mdx new file mode 100644 index 000000000..27fe52a45 --- /dev/null +++ b/docs_new/docs/developer_guide/JIT_kernels.mdx @@ -0,0 +1,266 @@ +--- +title: "Development Guide for JIT Kernels" +sidebarTitle: "JIT Kernels" +metatags: + description: "SGLang JIT kernel development: clangd setup, TensorMatcher, LaunchKernel, add_constant example walkthrough." +--- +## Environment Setup + +We strongly recommend using `clangd` as the language server for JIT kernel development. +For Ubuntu/Debian, you can download clangd from [apt.llvm.org](https://apt.llvm.org/). +If you are using VS Code, we recommend installing the `clangd` extension for better IDE integration. + +All JIT-related files are located in `python/sglang/jit_kernel`. +Unlike `sgl-kernel`, which compiles CUDA/C++ binaries ahead of time (AOT), just-in-time (JIT) kernels are compiled at runtime. +Consequently, a static `compile_commands.json` cannot be generated. +To enable code completion with `clangd`, run `python -m sglang.jit_kernel` to generate a `.clangd` configuration file in your current directory. +After generating the file, restart the clangd language server. It should now recognize all JIT kernel files. + +## Code Structure + +### C++ Implementation + +C++ source code is located in `python/sglang/jit_kernel/csrc`. +Reusable functions should be placed in `python/sglang/jit_kernel/include`. + +We use [tvm-ffi](https://github.com/apache/tvm-ffi) for efficient foreign language bindings. +Refer to the [documentation](https://tvm.apache.org/ffi/) for advanced usage, such as exporting C++ objects. +Typically, `tvm::ffi::TensorView` is sufficient for passing PyTorch Tensors from Python. + +### Python Interface + +Python interfaces are defined in `python/sglang/jit_kernel`. +The `load_jit` utility function in `python/sglang/jit_kernel/utils.py` loads and returns the compiled module. +To export a C++ function (e.g., `cpp_func`), pass `cuda_wrappers=[("func", "cpp_func")]` to `load_jit`. +The function can then be called in Python as `module.func`. + +### C++ Utilities + +The following C++ utilities are available: + +#### Integer Range + +Similar to PyTorch, we provide an `irange` function to represent an integer range. + +```C++ Example +#include + +void test() { + for (auto i : host::irange(100)) { // [0, 100) + // do something + } + for (auto i : host::irange(0, 100)) { // [0, 100) + // do something + } +} + +``` + +#### Runtime Checking + +`RuntimeCheck` validates conditions at runtime. It accepts optional arguments for error reporting. +If the check fails, these arguments are output to aid debugging. +`RuntimeDeviceCheck` verifies the status of the last kernel launch. + +```C++ Example +#include +#include + +void test() { + host::RuntimeCheck(1 + 1 == 2, 1 + 1, " != ", 2); + host::RuntimeDeviceCheck(); + // check the provided `cudaError_t` + host::RuntimeDeviceCheck(cudaGetLastError()); +} + +``` + +#### Tensor Checking + +`TensorMatcher` provides a readable way to validate and extract tensor shape information. + +```cpp Example +#include + +void test(const tvm::ffi::TensorView k_cache, const tvm::ffi::TensorView v_cache) { + using namespace host; + + auto D = SymbolicSize{"D"}; // cache dimension + auto N = SymbolicSize{"N"}; // kvcache stride + auto dtype = SymbolicDType{}; + auto device = SymbolicDevice{}; + + TensorMatcher({-1, D}) // + .with_strides({N, 1}) + .with_dtype(dtype) + .with_device(device) + .verify(k_cache) + .verify(v_cache); +} +``` + +Configure the `TensorMatcher` with expected stride, dtype, and device properties before verification. +- If `with_strides` is omitted, the tensor is expected to be contiguous. +- Template arguments in `with_dtype` restrict the allowed data types. +- Template arguments in `with_device` restrict the allowed devices. +- Values passed to `with_xxx` methods enforce equality checks. +- Passing `-1` for size or stride allows matching any value. + +A `Symbolic` variable must resolve to the same value across all verifications. +Use `.unwrap()` to retrieve the matched value after verification. + + +`TensorMatcher` is a temporary expression and should not be stored in a variable. + + + +Add `//` at the end of the `TensorMatcher` chain to enforce proper indentation. + + +#### Kernel Launching + +`LaunchKernel::resolve_device` retrieves the current `cudaStream` from PyTorch. +Kernels can also be launched directly using `LaunchKernel`. + +```cpp Example +#include + +#include + +__global__ void kernel() {} + +void test() { + const auto num_blocks = 1; + const auto num_threads = 32; + const auto dynamic_smem = 0; + + DLDevice dev; // suppose this is initialized properly + host::LaunchKernel(num_blocks, num_threads, dev)(kernel); + + cudaStream_t stream = host::LaunchKernel::resolve_device(dev); + host::LaunchKernel(num_blocks, num_threads, stream, dynamic_smem)(kernel); +} + +``` + +## Add new kernels + +This section walks through a complete, end-to-end example of adding a new JIT kernel to the system. +We use a simple add_constant kernel as a running example, which adds a constant integer value to every element of an input tensor. + +Conceptually, the Python interface looks like this: + +```python Example +def add_constant(src: torch.Tensor, c: int): + return src + c +``` + +### STEP 1: Write the C++ kernel + +Write your CUDA kernel in [jit_kernel/csrc/add_constant.cuh](https://github.com/sgl-project/sglang/blob/main/python/sglang/jit_kernel/csrc/add_constant.cuh). For demonstration purposes, we pass the constant value as a template parameter. + +```cpp Example +#include // For TensorMatcher, SymbolicSize, SymbolicDevice +#include // For LaunchKernel +#include // For div_ceil, RuntimeCheck + +#include +#include + +#include +#include + +namespace { + +template +__global__ void add_constant_kernel(int32_t* dst, const int32_t* src, size_t length) { + size_t idx = blockIdx.x * blockDim.x + threadIdx.x; + if (idx < length) { + dst[idx] = src[idx] + kConstant; + } +} + +constexpr size_t kBlockSize = 256; + +// You can also use struct with static method as an alternative +template +void add_constant(tvm::ffi::TensorView dst, tvm::ffi::TensorView src) { + using namespace host; + + // 1. Validate input tensors + SymbolicSize N = {"num_elements"}; + SymbolicDevice device_; + TensorMatcher({N}) // 1D tensor, must be contiguous + .with_dtype() // must be int32 + .with_device(device_) // must be on CUDA device + .verify(dst) // check tensor dst + .verify(src); // check tensor src + + // 2. Extract required parameters, prepare for kernel launch + const size_t num_elements = N.unwrap(); + const size_t grid_size = div_ceil(num_elements, kBlockSize); + const DLDevice device = device_.unwrap(); + // some extra runtime checks using host::RuntimeCheck + RuntimeCheck(num_elements > 0, "We only support non-empty tensors, got num_elements = ", num_elements); + + // 3. Launch the kernel. Error code will be automatically checked. + LaunchKernel(grid_size, kBlockSize, device /*, dynamic_smem*/)( + // kernel function + add_constant_kernel, + // kernel arguments + static_cast(dst.data_ptr()), + static_cast(src.data_ptr()), + num_elements); +} + +} // namespace + +``` + +### STEP 2: Create Python Interfaces + +Next, expose the kernel through a Python wrapper. +Create a new file at [jit_kernel/add_constant.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/jit_kernel/add_constant.py) and expose the needed interfaces. + +```python Example +from __future__ import annotations + +import functools +from typing import TYPE_CHECKING + +import torch + +from sglang.jit_kernel.utils import load_jit, make_cpp_args + +if TYPE_CHECKING: + from tvm_ffi.module import Module + + +@functools.cache +def _jit_add_constant_module(constant: int) -> Module: + args = make_cpp_args(constant) # pass all the template argument + return load_jit( + "add_constant", + *args, + cuda_files=["add_constant.cuh"], + cuda_wrappers=[("add_constant", f"add_constant<{args}>")], + ) + + +def add_constant(src: torch.Tensor, constant: int) -> torch.Tensor: + dst = torch.empty_like(src) + module = _jit_add_constant_module(constant) + module.add_constant(dst, src) + return dst + +``` + +### STEP 3: Use your kernel + +Finally, import and use the kernel like a regular Python function: + +```python Example +from sglang.jit_kernel.add_constant import add_constant +``` + +For a complete, runnable example, refer to [test_add_constant.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/jit_kernel/test_add_constant.py). diff --git a/docs_new/docs/developer_guide/bench_serving.mdx b/docs_new/docs/developer_guide/bench_serving.mdx new file mode 100644 index 000000000..c00b72da1 --- /dev/null +++ b/docs_new/docs/developer_guide/bench_serving.mdx @@ -0,0 +1,358 @@ +--- +title: "Bench Serving Guide" +metatags: + description: "SGLang bench_serving: benchmark throughput, TTFT, ITL with random/sharegpt/image datasets. Multi-backend support." +--- +This guide explains how to benchmark online serving throughput and latency using `python -m sglang.bench_serving`. It supports multiple inference backends via OpenAI-compatible and native endpoints, and produces both console metrics and optional JSONL outputs. + +### What it does + +- Generates synthetic or dataset-driven prompts and submits them to a target serving endpoint +- Measures throughput, time-to-first-token (TTFT), inter-token latency (ITL), per-request end-to-end latency, and more +- Supports streaming or non-streaming modes, rate control, and concurrency limits + +### Supported backends and endpoints + +- `sglang` / `sglang-native`: `POST /generate` +- `sglang-oai`, `vllm`, `lmdeploy`: `POST /v1/completions` +- `sglang-oai-chat`, `vllm-chat`, `lmdeploy-chat`: `POST /v1/chat/completions` +- `trt` (TensorRT-LLM): `POST /v2/models/ensemble/generate_stream` +- `gserver`: Custom server (Not Implemented yet in this script) +- `truss`: `POST /v1/models/model:predict` + +If `--base-url` is provided, requests are sent to it. Otherwise, `--host` and `--port` are used. When `--model` is not provided, the script will attempt to query `GET /v1/models` for an available model ID (OpenAI-compatible endpoints). + +### Prerequisites + +- Python 3.8+ +- Dependencies typically used by this script: `aiohttp`, `numpy`, `requests`, `tqdm`, `transformers`, and for some datasets `datasets`, `pillow`, `pybase64`. Install as needed. +- An inference server running and reachable via the endpoints above +- If your server requires authentication, set environment variable `OPENAI_API_KEY` (used as `Authorization: Bearer `) + +### Quick start + +Run a basic benchmark against an sglang server exposing `/generate`: + +```bash Command +python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct +``` + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --num-prompts 1000 \ + --model meta-llama/Llama-3.1-8B-Instruct +``` + +Or, using an OpenAI-compatible endpoint (completions): + +```bash Command +python3 -m sglang.bench_serving \ + --backend vllm \ + --base-url http://127.0.0.1:8000 \ + --num-prompts 1000 \ + --model meta-llama/Llama-3.1-8B-Instruct +``` + +### Datasets + +Select with `--dataset-name`: + +- `sharegpt` (default): loads ShareGPT-style pairs; optionally restrict with `--sharegpt-context-len` and override outputs with `--sharegpt-output-len` +- `random`: random text lengths; sampled from ShareGPT token space +- `random-ids`: random token ids (can lead to gibberish) +- `image`: generates images and wraps them in chat messages; supports custom resolutions, multiple formats, and different content types +- `generated-shared-prefix`: synthetic dataset with shared long system prompts and short questions +- `mmmu`: samples from MMMU (Math split) and includes images + +Common dataset flags: + +- `--num-prompts N`: number of requests +- `--random-input-len`, `--random-output-len`, `--random-range-ratio`: for random/random-ids/image +- `--image-count`: Number of images per request (for `image` dataset). + +- `--apply-chat-template`: apply tokenizer chat template when constructing prompts +- `--dataset-path PATH`: file path for ShareGPT json; if blank and missing, it will be downloaded and cached + +Generated Shared Prefix flags (for `generated-shared-prefix`): + +- `--gsp-num-groups` +- `--gsp-prompts-per-group` +- `--gsp-system-prompt-len` +- `--gsp-question-len` +- `--gsp-output-len` + +Image dataset flags (for `image`): + +- `--image-count`: Number of images per request +- `--image-resolution`: Image resolution; supports presets (4k, 1080p, 720p, 360p) or custom 'heightxwidth' format (e.g., 1080x1920, 512x768) +- `--image-format`: Image format (jpeg or png) +- `--image-content`: Image content type (random or blank) + +### Examples + +1. To benchmark image dataset with 3 images per request, 500 prompts, 512 input length, and 512 output length, you can run: + +```bash Command +python -m sglang.launch_server --model-path Qwen/Qwen2.5-VL-3B-Instruct --disable-radix-cache +``` + +```bash Command +python -m sglang.bench_serving \ + --backend sglang-oai-chat \ + --dataset-name image \ + --num-prompts 500 \ + --image-count 3 \ + --image-resolution 720p \ + --random-input-len 512 \ + --random-output-len 512 +``` + +2. To benchmark random dataset with 3000 prompts, 1024 input length, and 1024 output length, you can run: + +```bash Command +python -m sglang.launch_server --model-path Qwen/Qwen2.5-3B-Instruct +``` + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --dataset-name random \ + --num-prompts 3000 \ + --random-input 1024 \ + --random-output 1024 \ + --random-range-ratio 0.5 +``` + +### Choosing model and tokenizer + +- `--model` is required unless the backend exposes `GET /v1/models`, in which case the first model ID is auto-selected. +- `--tokenizer` defaults to `--model`. Both can be HF model IDs or local paths. +- For ModelScope workflows, setting `SGLANG_USE_MODELSCOPE=true` enables fetching via ModelScope (weights are skipped for speed). +- If your tokenizer lacks a chat template, the script warns because token counting can be less robust for gibberish outputs. + +### Rate, concurrency, and streaming + +- `--request-rate`: requests per second. `inf` sends all immediately (burst). Non-infinite rate uses a Poisson process for arrival times. +- `--max-concurrency`: caps concurrent in-flight requests regardless of arrival rate. +- `--disable-stream`: switch to non-streaming mode when supported; TTFT then equals total latency for chat completions. + +### Other key options + +- `--output-file FILE.jsonl`: append JSONL results to file; auto-named if unspecified +- `--output-details`: include per-request arrays (generated texts, errors, ttfts, itls, input/output lens) +- `--extra-request-body '{"top_p":0.9,"temperature":0.6}'`: merged into payload (sampling params, etc.) +- `--disable-ignore-eos`: pass through EOS behavior (varies by backend) +- `--warmup-requests N`: run warmup requests with short output first (default 1) +- `--flush-cache`: call `/flush_cache` (sglang) before main run +- `--profile`: call `/start_profile` and `/stop_profile` (requires server to enable profiling, e.g., `SGLANG_TORCH_PROFILER_DIR`) +- `--lora-name name1 name2 ...`: randomly pick one per request and pass to backend (e.g., `lora_path` for sglang) +- `--tokenize-prompt`: send integer IDs instead of text (currently supports `--backend sglang` only) + +### Authentication + +If your target endpoint requires OpenAI-style auth, set: + +```bash Command +export OPENAI_API_KEY=sk-...yourkey... +``` + +The script will add `Authorization: Bearer $OPENAI_API_KEY` automatically for OpenAI-compatible routes. + +### Metrics explained + +Printed after each run: + +- Request throughput (req/s) +- Input token throughput (tok/s) - includes both text and vision tokens +- Output token throughput (tok/s) +- Total token throughput (tok/s) - includes both text and vision tokens +- Total input text tokens and Total input vision tokens - per-modality breakdown +- Concurrency: aggregate time of all requests divided by wall time +- End-to-End Latency (ms): mean/median/std/p99 per-request total latency +- Time to First Token (TTFT, ms): mean/median/std/p99 for streaming mode +- Inter-Token Latency (ITL, ms): mean/median/std/p95/p99/max between tokens +- TPOT (ms): Token processing time after first token, i.e., `(latency - ttft)/(tokens-1)` +- Accept length (sglang-only, if available): speculative decoding accept length + +The script also retokenizes generated text with the configured tokenizer and reports "retokenized" counts. + +### JSONL output format + +When `--output-file` is set, one JSON object is appended per run. Base fields: + +- Arguments summary: backend, dataset, request_rate, max_concurrency, etc. +- Duration and totals: completed, total_input_tokens, total_output_tokens, retokenized totals +- Throughputs and latency statistics as printed in the console +- `accept_length` when available (sglang) + +With `--output-details`, an extended object also includes arrays: + +- `input_lens`, `output_lens` +- `ttfts`, `itls` (per request: ITL arrays) +- `generated_texts`, `errors` + +### End-to-end examples + +1) sglang native `/generate` (streaming): + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --dataset-name random \ + --random-input-len 1024 --random-output-len 1024 --random-range-ratio 0.5 \ + --num-prompts 2000 \ + --request-rate 100 \ + --max-concurrency 512 \ + --output-file sglang_random.jsonl --output-details +``` + +2) OpenAI-compatible Completions (e.g., vLLM): + +```bash Command +python3 -m sglang.bench_serving \ + --backend vllm \ + --base-url http://127.0.0.1:8000 \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --dataset-name sharegpt \ + --num-prompts 1000 \ + --sharegpt-output-len 256 +``` + +3) OpenAI-compatible Chat Completions (streaming): + +```bash Command +python3 -m sglang.bench_serving \ + --backend vllm-chat \ + --base-url http://127.0.0.1:8000 \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --dataset-name random \ + --num-prompts 500 \ + --apply-chat-template +``` + +4) Images (VLM) with chat template: + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --model your-vlm-model \ + --dataset-name image \ + --image-count 2 \ + --image-resolution 720p \ + --random-input-len 128 --random-output-len 256 \ + --num-prompts 200 \ + --apply-chat-template +``` + +4a) Images with custom resolution: + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --model your-vlm-model \ + --dataset-name image \ + --image-count 1 \ + --image-resolution 512x768 \ + --random-input-len 64 --random-output-len 128 \ + --num-prompts 100 \ + --apply-chat-template +``` + +4b) 1080p images with PNG format and blank content: + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --model your-vlm-model \ + --dataset-name image \ + --image-count 1 \ + --image-resolution 1080p \ + --image-format png \ + --image-content blank \ + --random-input-len 64 --random-output-len 128 \ + --num-prompts 100 \ + --apply-chat-template +``` + +5) Generated shared prefix (long system prompts + short questions): + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --dataset-name generated-shared-prefix \ + --gsp-num-groups 64 --gsp-prompts-per-group 16 \ + --gsp-system-prompt-len 2048 --gsp-question-len 128 --gsp-output-len 256 \ + --num-prompts 1024 +``` + +6) Tokenized prompts (ids) for strict length control (sglang only): + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --dataset-name random \ + --tokenize-prompt \ + --random-input-len 2048 --random-output-len 256 --random-range-ratio 0.2 +``` + +7) Profiling and cache flush (sglang): + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --model meta-llama/Llama-3.1-8B-Instruct \ + --profile \ + --flush-cache +``` + +8) TensorRT-LLM streaming endpoint: + +```bash Command +python3 -m sglang.bench_serving \ + --backend trt \ + --base-url http://127.0.0.1:8000 \ + --model your-trt-llm-model \ + --dataset-name random \ + --num-prompts 100 \ + --disable-ignore-eos +``` + +9) Evaluating large-scale KVCache sharing with mooncake trace (sglang only): + +```bash Command +python3 -m sglang.bench_serving \ + --backend sglang \ + --host 127.0.0.1 --port 30000 \ + --model mode-name \ + --dataset-name mooncake \ + --mooncake-slowdown-factor 1.0 \ + --mooncake-num-rounds 1000 \ + --mooncake-workload conversation|mooncake|agent|synthetic + --use-trace-timestamps true \ + --random-output-len 256 +``` + +### Troubleshooting + +- All requests failed: verify `--backend`, server URL/port, `--model`, and authentication. Check warmup errors printed by the script. +- Throughput seems too low: adjust `--request-rate` and `--max-concurrency`; verify server batch size/scheduling; ensure streaming is enabled if appropriate. +- Token counts look odd: prefer chat/instruct models with proper chat templates; otherwise tokenization of gibberish may be inconsistent. +- Image/MMMU datasets: ensure you installed extra deps (`pillow`, `datasets`, `pybase64`). +- Authentication errors (401/403): set `OPENAI_API_KEY` or disable auth on your server. + +### Notes + +- The script raises the file descriptor soft limit (`RLIMIT_NOFILE`) to help with many concurrent connections. +- For sglang, `/get_server_info` is queried post-run to report speculative decoding accept length when available. diff --git a/docs_new/docs/developer_guide/benchmark_and_profiling.mdx b/docs_new/docs/developer_guide/benchmark_and_profiling.mdx new file mode 100644 index 000000000..7418aaaae --- /dev/null +++ b/docs_new/docs/developer_guide/benchmark_and_profiling.mdx @@ -0,0 +1,459 @@ +--- +title: "Benchmark and Profiling" +metatags: + description: "SGLang benchmarking and profiling: PyTorch Profiler, Nsight Systems, layerwise NVTX, PD disaggregation profiling." +--- +## Benchmark + +- Benchmark the latency of running a single static batch without a server. The arguments are the same as for `launch_server.py`. + Note that this is a simplified test script without a dynamic batching server, so it may run out of memory for a batch size that a real server can handle. A real server truncates the prefill into several batches, while this simplified script does not. + - Without a server (do not need to launch a server) + ```bash Command + python -m sglang.bench_one_batch --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --batch 32 --input-len 256 --output-len 32 + ``` + - With a server (please use `sglang.launch_server` to launch a server first and run the following command.) + ```bash Command + python -m sglang.bench_one_batch_server --base-url http://127.0.0.1:30000 --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --batch-size 32 --input-len 256 --output-len 32 + ``` + + +- Benchmark offline processing. This script will start an offline engine and run the benchmark. + + ```bash Command + python3 -m sglang.bench_offline_throughput --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --num-prompts 10 + ``` + +- Benchmark online serving. Please use `sglang.launch_server` to launch a server first and run the following command. + + ```bash Command + python3 -m sglang.bench_serving --backend sglang --num-prompt 10 + ``` + +## Profile with PyTorch Profiler + +[Pytorch Profiler](https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html) is a convenient basic tool to inspect kernel execution time, call stack, and kernel overlap and occupancy. + +### Profile a server with `sglang.bench_serving` + +```bash Command +# set trace path +export SGLANG_TORCH_PROFILER_DIR=/root/sglang/profile_log + +# start server +python -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct + +# send profiling request from client +python -m sglang.bench_serving --backend sglang --model meta-llama/Llama-3.1-8B-Instruct --num-prompts 10 --sharegpt-output-len 100 --profile +``` + +Please make sure that the `SGLANG_TORCH_PROFILER_DIR` should be set at both server and client side, otherwise the trace file cannot be generated correctly . A secure way will be setting `SGLANG_TORCH_PROFILER_DIR` in the `.*rc` file of shell (e.g. `~/.bashrc` for bash shells). + +For more details, please refer to [Bench Serving Guide](./bench_serving). + +### Profile In PD Disaggregation Mode + +When profiling in PD disaggregation mode, prefill and decode workers **must be profiled separately** due to torch profiler limitations. The `bench_serving` command provides dedicated options for this: + +#### Profile Prefill Workers + +```bash Command +# set trace path +export SGLANG_TORCH_PROFILER_DIR=/root/sglang/profile_log + +# start prefill and decode servers (see PD disaggregation docs for setup) +python -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --disaggregation-mode prefill +python -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --disaggregation-mode decode --port 30001 --base-gpu-id 1 + +# start router +python -m sglang_router.launch_router --pd-disaggregation --prefill http://127.0.0.1:30000 --decode http://127.0.0.1:30001 --host 0.0.0.0 --port 8000 + +# send profiling request targeting prefill workers +python -m sglang.bench_serving --backend sglang --model meta-llama/Llama-3.1-8B-Instruct --num-prompts 10 --sharegpt-output-len 100 --profile --pd-separated --profile-prefill-url http://127.0.0.1:30000 +``` + +#### Profile Decode Workers + +```bash Command +# send profiling request targeting decode workers +python -m sglang.bench_serving --backend sglang --model meta-llama/Llama-3.1-8B-Instruct --num-prompts 10 --sharegpt-output-len 100 --profile --pd-separated --profile-decode-url http://127.0.0.1:30001 +``` + +#### Important Notes + +- `--profile-prefill-url` and `--profile-decode-url` are **mutually exclusive** - you cannot profile both at the same time +- Both options support multiple worker URLs for multi-instance setups: + ```bash Command + # Profile multiple prefill workers + python -m sglang.bench_serving --backend sglang --model meta-llama/Llama-3.1-8B-Instruct --num-prompts 10 --profile --pd-separated --profile-prefill-url http://127.0.0.1:30000 http://127.0.0.1:30002 + + # Profile multiple decode workers + python -m sglang.bench_serving --backend sglang --model meta-llama/Llama-3.1-8B-Instruct --num-prompts 10 --profile --pd-separated --profile-decode-url http://127.0.0.1:30001 http://127.0.0.1:30003 + ``` +- Make sure `SGLANG_TORCH_PROFILER_DIR` is set on all worker nodes before starting the servers +- For more details on setting up PD disaggregation, see [PD Disaggregation Guide](../advanced_features/pd_disaggregation) + +### Profile a server with `sglang.bench_offline_throughput` +```bash Command +export SGLANG_TORCH_PROFILER_DIR=/root/sglang/profile_log + +# profile one batch with bench_one_batch.py +# batch size can be controlled with --batch argument +python3 -m sglang.bench_one_batch --model-path meta-llama/Llama-3.1-8B-Instruct --batch 32 --input-len 1024 --output-len 10 --profile + +# profile multiple batches with bench_offline_throughput.py +python -m sglang.bench_offline_throughput --model-path meta-llama/Llama-3.1-8B-Instruct --dataset-name random --num-prompts 10 --profile --mem-frac=0.8 +``` + +### Profile a server with `sglang.profiler` + +When the server is running (e.g., processing a decoding request), you can start live profiling immediately by sending a profile request to the server. + +You can do this by running `python3 -m sglang.profiler`. For example: + +```text Output +# Terminal 1: Send a generation request +python3 -m sglang.test.send_one + +# Terminal 2: Before the above request finishes, quickly launch the following command in a separate terminal. +# It will generate a profile of the above request for several decoding batches. +python3 -m sglang.profiler +``` + +You can also combine the above operations into a single command + +```text Output +python3 -m sglang.test.send_one --profile +``` + +### Profile a server with HTTP API endpoints + +SGLang provides HTTP API endpoints to control profiling on a running server. This allows you to start and stop profiling programmatically, which is useful for capturing specific workload patterns. + +#### Using `/start_profile` endpoint + +The `/start_profile` endpoint starts profiling on the server. You can control when profiling begins and how long it runs using the following parameters: + +**Basic usage:** + +```bash Command +# Start profiling immediately for 10 steps +curl -X POST http://127.0.0.1:30000/start_profile \ + -H "Content-Type: application/json" \ + -d '{ + "num_steps": 10 + }' +``` + +**Parameters:** + +- `output_dir` (optional): Directory where profile traces will be saved. If not specified, uses `SGLANG_TORCH_PROFILER_DIR` environment variable, or `/tmp` as the default +- `num_steps` (optional): Number of steps to profile. If not specified, profiling continues until manually stopped with `/end_profile` +- `start_step` (optional): Step number at which to start profiling (inclusive). Useful for skipping warmup iterations +- `activities` (optional): List of activities to profile, e.g., `["CPU", "GPU"]`. Default is `["CPU", "GPU"]` +- `merge_profiles` (optional): Whether to merge distributed traces. Default is `false` + +**Note on step ranges:** Profiling starts at `start_step` (inclusive) and continues for `num_steps` iterations. For example, with `start_step=3` and `num_steps=10`, profiling captures steps 3, 4, 5, 6, 7, 8, 9, 10, 11, and 12 (10 steps total, starting from step 3). + +**Advanced usage with `start_step`:** + +```bash Command +# Wait 5 steps (warmup), then profile for 10 steps +curl -X POST http://127.0.0.1:30000/start_profile \ + -H "Content-Type: application/json" \ + -d '{ + "output_dir": "/tmp/profiles", + "start_step": 5, + "num_steps": 10, + "activities": ["CPU", "GPU"] + }' +``` + +**Continuous profiling (manual stop):** + +```bash Command +# Start profiling without num_steps - must manually stop with /end_profile +curl -X POST http://127.0.0.1:30000/start_profile +``` + +#### Using `/end_profile` endpoint + +The `/end_profile` endpoint stops an ongoing profiling session and saves the trace file. + +```bash Command +# Stop profiling and save traces +curl -X POST http://127.0.0.1:30000/end_profile +``` + +This is only needed when you start profiling without specifying `num_steps`. If `num_steps` is specified, profiling will automatically stop after that many steps. + +#### Example workflow + +```bash Command +# Terminal 1: Start the server +export SGLANG_TORCH_PROFILER_DIR=/tmp/profiles +python -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct + +# Terminal 2: Start continuous profiling +curl -X POST http://127.0.0.1:30000/start_profile \ + -H "Content-Type: application/json" \ + -d '{ + "start_step": 3 + }' + +# Terminal 3: Send requests to generate load +python -m sglang.bench_serving --backend sglang --num-prompts 100 + +# Terminal 2: Stop profiling when done +curl -X POST http://127.0.0.1:30000/end_profile +``` + +### Profiler Trace Merger for Distributed Traces + +SGLang now supports automatic merging of profiling traces from distributed setups with multiple parallelism types (TP, DP, PP, EP). This feature is particularly useful for analyzing performance across distributed runs. + +#### Multi-Node Profiling and Shared Storage Considerations + +Single-node profiler output merging is completely supported. When profiling in distributed environments spanning multiple nodes, shared storage (e.g., NFS, Lustre) should be accessible by all nodes for the output directory to enable merging of trace files. + +If there is no shared storage accessible across nodes, automatic merging of trace files during profiling is not supported directly as of now. + +#### HTTP API Usage + +```bash Command +# Start profiling with automatic trace merging enabled +curl -X POST /start_profile \ + -H "Content-Type: application/json" \ + -d '{ + "output_dir": "/tmp/profiles", # where to store profile traces + "num_steps": 10, + "activities": ["CPU", "GPU"], + "merge_profiles": true # optional argument to merge profile traces (default=False) + }' +``` + +#### Command Line Usage + +```bash Command +# Start profiling with merge enabled +python -m sglang.profiler \ + --num-steps 10 \ + --cpu \ + --gpu \ + --output-dir /tmp/profiles \ + --merge-profiles # optional argument to merge profile traces (default=False) +``` + +#### Output Files + +The profile merger generates: +- Individual rank trace files: `{profile_id}-TP-{tp}-DP-{dp}-PP-{pp}-EP-{ep}.trace.json.gz` +- Merged trace file: `merged-{profile_id}.trace.json.gz` + +### Possible PyTorch bugs +If in any cases you encounter the following error (for example, using qwen 2.5 VL): +```bash Command +RuntimeError: !stack.empty() INTERNAL ASSERT FAILED at "/pytorch/torch/csrc/autograd/profiler_python.cpp":983, please report a bug to PyTorch. Python replay stack is empty. +``` +This is likely a PyTorch Bug reported in [Bug: vLLM Profiler](https://github.com/vllm-project/vllm/issues/18240) and [Bug: torch.profiler.profile](https://github.com/pytorch/pytorch/issues/101632). As a workaround, you may disable `with_stack` with an environment variable such as follows: +```bash Command +export SGLANG_PROFILE_WITH_STACK=False +python -m sglang.bench_offline_throughput --model-path meta-llama/Llama-3.1-8B-Instruct --dataset-name random --num-prompts 10 --profile --mem-frac=0.8 +``` + +### View traces + +Trace files can be loaded and visualized from: + +1. https://ui.perfetto.dev/ (any browser) +2. chrome://tracing (Chrome browser only) + +If browser cannot open trace file due to its large size, +client can generate a small trace file (<100MB) by controlling number of prompts and lengths of prompt outputs. +For example, when profiling a server, + +```bash Command +python -m sglang.bench_serving --backend sglang --model meta-llama/Llama-3.1-8B-Instruct --num-prompts 2 --sharegpt-output-len 100 --profile +``` + +This command sets the number of prompts to 2 with `--num-prompts` argument and limits the length of output sequences to 100 with `--sharegpt-output-len` argument, which can generate a small trace file for browser to open smoothly. + +Additionally, if you want to locate the SGLang Python source code through the cuda kernel in Trace, you need to disable CUDA Graph when starting the service. This can be done by using the `--disable-cuda-graph` parameter in the command to start the service. + +## Profile with Nsight + +[Nsight systems](https://docs.nvidia.com/nsight-systems/) is an advanced tool that exposes more profiling details, such as register and shared memory usage, annotated code regions and low-level CUDA APIs and events. + +1. Prerequisite: + + Install using apt, or run inside a [NVIDIA Docker container](https://catalog.ngc.nvidia.com/orgs/nvidia/containers/pytorch/tags) or [SGLang Docker container](https://github.com/sgl-project/sglang/tree/main/docker). + + ```bash Command + # install nsys + # https://docs.nvidia.com/nsight-systems/InstallationGuide/index.html + apt update + apt install -y --no-install-recommends gnupg + echo "deb http://developer.download.nvidia.com/devtools/repos/ubuntu$(source /etc/lsb-release; echo "$DISTRIB_RELEASE" | tr -d .)/$(dpkg --print-architecture) /" | tee /etc/apt/sources.list.d/nvidia-devtools.list + apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub + apt update + apt install nsight-systems-cli + ``` + +2. To profile a single batch, use + + ```bash Command + nsys profile --trace-fork-before-exec=true --cuda-graph-trace=node python3 -m sglang.bench_one_batch --model meta-llama/Meta-Llama-3-8B --batch-size 64 --input-len 512 + ``` + +3. To profile a server, e.g. + + ```bash Command + # launch the server, set the delay and duration times according to needs + # after the duration time has been used up, server will be killed by nsys + + nsys profile --trace-fork-before-exec=true --cuda-graph-trace=node -o sglang.out --delay 60 --duration 70 python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --disable-radix-cache + + # client + python3 -m sglang.bench_serving --backend sglang --num-prompts 1000 --dataset-name random --random-input 1024 --random-output 512 + ``` + + In practice, we recommend users to set `--duration` argument to a large value. Whenever user wants the server to stop profiling. Firstly run: + + ```bash Command + nsys sessions list + ``` + + to get the session id in the form of `profile-XXXXX`, then run: + + ```bash Command + nsys stop --session=profile-XXXXX + ``` + + to manually kill the profiler and generate `nsys-rep` files instantly. + +4. Use NVTX to annotate code regions, e.g. to see their execution time. + + ```bash Command + # install nvtx + pip install nvtx + ``` + + ```python Example + # code snippets + import nvtx + with nvtx.annotate("description", color="color"): + # some critical code + ``` + +### Layer-wise NVTX Profiling with Nsight Systems + +SGLang provides built-in layerwise NVTX annotations that can be combined with the CUDA Profiler for detailed per-layer profiling in Nsight Systems. This is particularly useful for identifying performance bottlenecks at the layer level. + +#### Using `--enable-layerwise-nvtx-marker` with Nsight Systems and `/start_profile` + +The `--enable-layerwise-nvtx-marker` flag automatically adds NVTX markers to every layer in your model. This is particularly powerful when combined with Nsight Systems profiling to see detailed per-layer performance. + +**Method 1: Using `/start_profile` with CUDA_PROFILER (for programmatic control)** + +This method allows you to control exactly when profiling starts/stops via HTTP API while Nsight Systems is running. + +1. Launch the server with layerwise NVTX enabled under Nsight Systems: + + ```bash Command + # Terminal 1: Start server with nsys and capture-range option + nsys profile --trace-fork-before-exec=true \ + --cuda-graph-trace=node \ + --capture-range=cudaProfilerApi \ + --capture-range-end=stop \ + -o layerwise_profile \ + python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --enable-layerwise-nvtx-marker \ + --disable-cuda-graph + ``` + + Note: NVTX markers are not emitted for kernel launches captured by CUDA graphs. Use `--disable-cuda-graph` to ensure all layerwise NVTX markers are emitted in the trace. + +2. In another terminal, control profiling via `/start_profile` with `CUDA_PROFILER` activity: + + ```bash Command + # Terminal 2: Wait for server to be ready, then start CUDA profiling + # Wait 3 steps for warmup, then profile for 10 steps + curl -X POST http://127.0.0.1:30000/start_profile \ + -H "Content-Type: application/json" \ + -d '{ + "start_step": 3, + "num_steps": 10, + "activities": ["CUDA_PROFILER"] + }' + ``` + +3. Send requests to generate load: + + ```bash Command + # Terminal 3: Generate workload + python -m sglang.bench_serving --backend sglang --num-prompts 100 + ``` + +4. Profiling will automatically stop after 10 steps (due to `num_steps: 10`). If you hadn't specified `num_steps`, you would need to manually stop it: + + ```bash Command + # Terminal 2: Only needed if num_steps was not specified + curl -X POST http://127.0.0.1:30000/end_profile + ``` + +The `--capture-range=cudaProfilerApi` option tells Nsight Systems to only capture data between `cudaProfilerStart()` and `cudaProfilerStop()` calls (triggered by `/start_profile` and `/end_profile`), reducing overhead and file size. The `start_step` parameter skips the first 3 steps to avoid capturing warmup overhead. + +**Method 2: Simpler approach without `/start_profile` API** + +For simpler use cases where you don't need fine-grained control over profiling start/stop, you can profile with Nsight Systems capturing the entire workload: + +```bash Command +# Terminal 1: Start server with layerwise NVTX +# Note: --disable-cuda-graph ensures all NVTX markers are emitted +python -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --enable-layerwise-nvtx-marker \ + --disable-cuda-graph + +# Terminal 2: Profile the benchmarking client +nsys profile --trace-fork-before-exec=true \ + --cuda-graph-trace=node \ + -o layerwise_profile \ + python -m sglang.bench_serving --backend sglang --num-prompts 10 +``` + +This approach profiles the entire client execution, including all server interactions. The layerwise NVTX markers will be visible in the Nsight Systems timeline. + +**Viewing the profiling results:** + +Open the generated `.qdrep` file with Nsight Systems: + +```bash Command +nsys-ui layerwise_profile.qdrep +``` + +In the Nsight Systems GUI, you'll see: +- **NVTX ranges**: Each layer appears as a labeled range in the timeline with detailed information in the marker metadata +- **CUDA kernels**: All GPU kernels are shown alongside the layer annotations +- **Layer hierarchy**: The full module path (e.g., `meta-llama/Meta-Llama-3.1-8B-Instruct.model.layers.0.self_attn.qkv_proj`) helps identify specific layers. The prefix uses the full model path from `--model-path`. +- **Tensor shapes**: Input/output dimensions and parameter shapes are included in the NVTX marker data + +**Benefits of layerwise NVTX profiling:** + +- **Granular visibility**: See exactly which layers are taking the most time +- **Memory tracking**: Identify layers with large memory allocations +- **Bottleneck identification**: Quickly locate inefficient operations +- **Communication overhead**: In multi-GPU setups, see per-layer communication costs +- **Development debugging**: Validate that model architecture changes have the expected performance impact + +## Other tips + +1. You can benchmark a model using dummy weights by only providing the config.json file. This allows for quick testing of model variants without training. To do so, add `--load-format dummy` to the above commands and then you only need a correct `config.json` under the checkpoint folder. +2. You can benchmark a model with modified configs (e.g., less layers) by using `--json-model-override-args`. For example, you can benchmark a model with only 2 layers and 2 kv heads using: + + ```bash Command + python -m sglang.bench_one_batch --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --batch 32 --input-len 256 --output-len 32 --load-format dummy --json-model-override-args '{"num_hidden_layers": 1, "num_key_value_heads": 1}' + ``` + +3. You can use `--python-backtrace=cuda` to see python call stack for all CUDA kernels, as in PyTorch Profiler. (Caveat: this can cause inaccurately long kernel runtimes for CUDA event based timing) +4. For more arguments see [Nsight Systems User Guide](https://docs.nvidia.com/nsight-systems/UserGuide/index.html). diff --git a/docs_new/docs/developer_guide/contribution_guide.mdx b/docs_new/docs/developer_guide/contribution_guide.mdx new file mode 100644 index 000000000..a1de8d6c8 --- /dev/null +++ b/docs_new/docs/developer_guide/contribution_guide.mdx @@ -0,0 +1,149 @@ +--- +title: "Contribution Guide" +mode: wide +metatags: + description: "SGLang contribution guide: source install, pre-commit, unit tests, CI triggers, code style, sgl-kernel updates." +--- +Welcome to **SGLang**! We appreciate your interest in contributing. This guide provides a concise overview of how to set up your environment, run tests, build documentation, and open a Pull Request (PR). Whether you're fixing a small bug or developing a major feature, we encourage following these steps for a smooth contribution process. + +## Install SGLang from Source + +### Fork and clone the repository + +**Note**: New contributors do **not** have the write permission to push to the official SGLang repo. Please fork the repository under your GitHub account, then clone your fork locally. + +```bash +git clone https://github.com//sglang.git +``` + +### Build from source + +Refer to [Install SGLang from Source](../get-started/installation). + +## Format code with pre-commit + +We use [pre-commit](https://pre-commit.com/) to maintain consistent code style checks. Before pushing your changes, please run: + +```bash +pip3 install pre-commit +pre-commit install +pre-commit run --all-files +``` + +- **`pre-commit run --all-files`** manually runs all configured checks, applying fixes if possible. If it fails the first time, re-run it to ensure lint errors are fully resolved. Make sure your code passes all checks **before** creating a Pull Request. +- **Do not commit** directly to the `main` branch. Always create a new branch (e.g., `feature/my-new-feature`), push your changes, and open a PR from that branch. + +## Run and add unit tests + +If you add a new feature or fix a bug, please add corresponding unit tests to ensure coverage and prevent regression. +SGLang uses Python's built-in [unittest](https://docs.python.org/3/library/unittest.html) framework. +For detailed instructions on running tests and integrating them into CI, refer to [test/README](https://github.com/sgl-project/sglang/tree/main/test/README). + +## Write documentations + +We recommend new contributors start from writing documentation, which helps you quickly understand SGLang codebase. +For more details, please refer to [docs/README](https://github.com/sgl-project/sglang/blob/main/docs/README.md). + +## Test the accuracy +If your code changes the model output, please run the accuracy tests. A quick sanity check is the few-shot GSM8K. + +```text Output +# Launch a server +python3 -m sglang.launch_server --model Qwen/Qwen2-7B-Instruct + +# Evaluate +python3 -m sglang.test.few_shot_gsm8k --num-questions 200 +``` + +Please note that the above script is primarily a sanity check, not a rigorous accuracy or speed test. +This test can have significant variance (1%-5%) in accuracy due to batching and the non-deterministic nature of the inference engine. +Also, do not rely on the "Latency/Output throughput" from this script, as it is not a proper speed test. + +GSM8K is too easy for state-of-the-art models nowadays. Please try your own more challenging accuracy tests. +You can find additional accuracy eval examples in: +- [test_eval_accuracy_large.py](https://github.com/sgl-project/sglang/blob/main/test/srt/test_eval_accuracy_large.py) +- [test_gpt_oss_1gpu.py](https://github.com/sgl-project/sglang/blob/main/test/srt/test_gpt_oss_1gpu.py) + +## Benchmark the speed +Refer to [Benchmark and Profiling](../developer_guide/benchmark_and_profiling). + +## Requesting a review for merge +You can follow the pull request merge process described in [MAINTAINER](https://github.com/sgl-project/sglang/blob/main/.github/MAINTAINER). +You will need to work with the Merge Oncall, Codeowner, and other reviewers to get their approvals. +Then your PR can be merged. + +## How to Trigger CI Tests + +We have a lot of open PRs but limited CI machines, so only top and trusted contributors have permission to trigger CI tests. +Users with permission are listed in the [CI_PERMISSIONS.json](https://github.com/sgl-project/sglang/blob/main/.github/CI_PERMISSIONS.json) + +For CI to run on a pull request, it must have the "run-ci" label. Authorized users can add the label or rerun failed tests by commenting on the PR with one of these commands: + +- `/tag-run-ci-label`: Adds the "run-ci" label. Every future commit will trigger CI. +- `/rerun-failed-ci`: Reruns the failed or flaky tests from the most recent commit. +- `/tag-and-rerun-ci`: A single command that performs both `/tag-run-ci-label` and `/rerun-failed-ci`. +- `/rerun-stage `: Reruns a specific test stage without waiting for its dependencies. This is useful when you want to quickly validate a fix for a specific test failure instead of waiting ~30 minutes for preceding stages to complete. + +If you have permission, the [Slash Command Handler](https://github.com/sgl-project/sglang/actions/workflows/slash-command-handler.yml) will run your command and react with a +1 to your comment. It may take up to a few minutes for the reaction to appear. Here's a usage [example](https://github.com/sgl-project/sglang/pull/14253#issuecomment-3599509302). + +To avoid spamming a PR with too many `/rerun-failed-ci` comments, you can also trigger the command by editing an existing comment and adding any suffix (e.g., `/rerun-failed-ci try again`). + +Example of rerunning a single test stage: `/rerun-stage unit-test-backend-4-gpu`. + +If you don't have permission, please ask maintainers to trigger CI for you. + +### CI rate limits + +Due to CI scheduling and limited resources, higher-priority PRs may preempt running jobs. In such cases, you may need to rerun the tests. + +We apply CI rate limits to prevent abuse and ensure fair usage of our CI resources. + +Each CI workflow has a default limit defined in its workflow configuration file. For example, in [pr-gate.yml](https://github.com/sgl-project/sglang/blob/main/.github/workflows/pr-gate.yml), the default cooldown period is 120 minutes, and each workflow can override it via the `cool-down-minutes` input parameter: + +```yaml Config +cool-down-minutes: + description: "Default cooldown period in minutes; 0 disables rate limiting" + type: number + default: 120 +``` + +Users listed in [CI_PERMISSIONS.json](https://github.com/sgl-project/sglang/blob/main/.github/CI_PERMISSIONS.json) may have a per-user cooldown interval. In practice, we use the minimum of the workflow's default window and the user-specific interval. + + +## Code style guidance +- Avoid code duplication. If the same code snippet (more than five lines) appears multiple times, extract it into a shared function. +- Minimize device synchronization. Reduce expensive CPU-GPU synchronization operations, such as `tensor.item()` or `tensor.cpu()`, whenever possible. Use vectorized code. +- Prioritize extreme efficiency. SGLang is a runtime, and most of your code runs on the critical path for every request. Optimize all minor overheads as much as possible, especially in the model forward code. + - A common pattern is some runtime checks in the model forward pass (e.g., [this](https://github.com/sgl-project/sglang/blob/f1b0eda55c2c4838e8ab90a0fac7fb1e3d7064ab/python/sglang/srt/models/deepseek_v2.py#L486-L491)). These are very likely the same for every layer. Please cache the result as a single boolean value whenever possible. +- Make functions as pure as possible. Avoid in-place modification of arguments. +- Keep files concise. If a file exceeds 2,000 lines of code, split it into multiple smaller files. (e.g., `scheduler.py`, `scheduler_output_processor_mixin.py`) +- Keep tests run fast. + - If a single test file run longer than 500 seconds, split it into multiple smaller files (e.g., `test_eagle_infer_a.py`, `test_eagle_infer_b.py`). + - If a single job in a github workflow runs longer than 30 mins, split it into smaller jobs/steps. + - Reuse server launches in your unit tests to make tests run faster. +- When supporting new hardware or features, follow these guidelines: + - Do not drastically change existing code. + - Always prefer new files to introduce specific components for your new hardware (e.g., `allocator_ascend.py`). + - If you write multiple if/else blocks for new features, ensure the common path (e.g., NVIDIA hardware or the existing code path) is the first branch. + +## How to update sgl-kernel +Since sglang and sgl-kernel are separate Python packages, our current GitHub CI infrastructure does not support updating a kernel and using it immediately within the same pull request (PR). +To add a new kernel or modify an existing one in the sgl-kernel package, you must use multiple PRs. + +Follow these steps: + +1. Submit a PR to update the sgl-kernel source code without using it in sglang python package (e.g., [#8884](https://github.com/sgl-project/sglang/pull/8884/files)). +2. Bump the version of sgl-kernel (e.g., [#9220](https://github.com/sgl-project/sglang/pull/9220/files)). + - Once merged, this will trigger an automatic release of the sgl-kernel wheel to PyPI. + - If not urgent, you can wait for other people to release the wheel. A new version will typically be released within one week. +3. Apply the changes: + - Update the sgl-kernel version in `sglang/python/pyproject.toml` to use the modified kernels. + - Update the related caller code in the sglang to use the new kernel. + +## Tips for newcomers + +If you want to contribute but don't have a specific idea in mind, pick issues labeled ["good first issue" or "help wanted"](https://github.com/sgl-project/sglang/issues?q=is%3Aissue+label%3A%22good+first+issue%22%2C%22help+wanted%22). These tasks typically have lower complexity and provide an excellent introduction to the codebase. Also check out this [code walk-through](https://github.com/zhaochenyang20/Awesome-ML-SYS-Tutorial/tree/main/sglang/code-walk-through) for a deeper look into SGLang's workflow. + +If you have any questions or want to start a discussion, please feel free to ask in our [Slack channel](https://slack.sglang.io). + +Thank you for your interest in SGLang. Happy coding! diff --git a/docs_new/docs/developer_guide/development_guide_using_docker.mdx b/docs_new/docs/developer_guide/development_guide_using_docker.mdx new file mode 100644 index 000000000..d7e167f9b --- /dev/null +++ b/docs_new/docs/developer_guide/development_guide_using_docker.mdx @@ -0,0 +1,119 @@ +--- +title: "Development Guide Using Docker" +sidebarTitle: "Using Docker" +metatags: + description: "SGLang Docker development: VSCode dev container, remote tunnels, debugger setup, nsys profiling." +--- +## Setup VSCode on a Remote Host +(Optional - you can skip this step if you plan to run sglang dev container locally) + +1. In the remote host, download `code` from [Https://code.visualstudio.com/docs/?dv=linux64cli](https://code.visualstudio.com/download) and run `code tunnel` in a shell. + +Example +```bash Command +wget https://vscode.download.prss.microsoft.com/dbazure/download/stable/fabdb6a30b49f79a7aba0f2ad9df9b399473380f/vscode_cli_alpine_x64_cli.tar.gz +tar xf vscode_cli_alpine_x64_cli.tar.gz + +# https://code.visualstudio.com/docs/remote/tunnels +./code tunnel +``` + +2. In your local machine, press F1 in VSCode and choose "Remote Tunnels: Connect to Tunnel". + +## Setup Docker Container + +### Option 1. Use the default dev container automatically from VSCode +There is a `.devcontainer` folder in the sglang repository root folder to allow VSCode to automatically start up within dev container. You can read more about this VSCode extension in VSCode official document [Developing inside a Container](https://code.visualstudio.com/docs/devcontainers/containers). + + VSCode Dev Container Architecture + + +*Figure 1: Diagram from VSCode official documentation [Developing inside a Container](https://code.visualstudio.com/docs/devcontainers/containers).* + +To enable this, you only need to: +1. Start Visual Studio Code and install [VSCode dev container extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers). +2. Press F1, type and choose "Dev Container: Open Folder in Container. +3. Input the `sglang` local repo path in your machine and press enter. + +The first time you open it in dev container might take longer due to docker pull and build. Once it's successful, you should set on your status bar at the bottom left displaying that you are in a dev container: + + + VSCode Dev Container Status Bar + + +Now when you run `sglang.launch_server` in the VSCode terminal or start debugging using F5, sglang server will be started in the dev container with all your local changes applied automatically: + + + SGLang Server Running in Dev Container + + + +### Option 2. Start up containers manually (advanced) + +The following startup command is an example for internal development by the SGLang team. You can **modify or add directory mappings as needed**, especially for model weight downloads, to prevent repeated downloads by different Docker containers. + +❗️ **Note on RDMA** + + 1. `--network host` and `--privileged` are required by RDMA. If you don't need RDMA, you can remove them but keeping them there does not harm. Thus, we enable these two flags by default in the commands below. + 2. You may need to set `NCCL_IB_GID_INDEX` if you are using RoCE, for example: `export NCCL_IB_GID_INDEX=3`. + +```bash Command +# Change the name to yours +docker run -itd --shm-size 32g --gpus all -v --ipc=host --network=host --privileged --name sglang_dev lmsysorg/sglang:dev /bin/zsh +docker exec -it sglang_dev /bin/zsh +``` +Some useful volumes to mount are: +1. **Huggingface model cache**: mounting model cache can avoid re-download every time docker restarts. Default location on Linux is `~/.cache/huggingface/`. +2. **SGLang repository**: code changes in the SGLang local repository will be automatically synced to the .devcontainer. + +Example 1: Monting local cache folder `/opt/dlami/nvme/.cache` but not the SGLang repo. Use this when you prefer to manually transfer local code changes to the devcontainer. +```bash Command +docker run -itd --shm-size 32g --gpus all -v /opt/dlami/nvme/.cache:/root/.cache --ipc=host --network=host --privileged --name sglang_zhyncs lmsysorg/sglang:dev /bin/zsh +docker exec -it sglang_zhyncs /bin/zsh +``` +Example 2: Mounting both HuggingFace cache and local SGLang repo. Local code changes are automatically synced to the devcontainer as the SGLang is installed in editable mode in the dev image. +```bash Command +docker run -itd --shm-size 32g --gpus all -v $HOME/.cache/huggingface/:/root/.cache/huggingface -v $HOME/src/sglang:/sgl-workspace/sglang --ipc=host --network=host --privileged --name sglang_zhyncs lmsysorg/sglang:dev /bin/zsh +docker exec -it sglang_zhyncs /bin/zsh +``` +## Debug SGLang with VSCode Debugger +1. (Create if not exist) open `launch.json` in VSCode. +2. Add the following config and save. Please note that you can edit the script as needed to apply different parameters or debug a different program (e.g. benchmark script). + ```JSON Config + { + "version": "0.2.0", + "configurations": [ + { + "name": "Python Debugger: launch_server", + "type": "debugpy", + "request": "launch", + "module": "sglang.launch_server", + "console": "integratedTerminal", + "args": [ + "--model-path", "meta-llama/Llama-3.2-1B", + "--host", "0.0.0.0", + "--port", "30000", + "--trust-remote-code", + ], + "justMyCode": false + } + ] + } + ``` + +3. Press "F5" to start. VSCode debugger will ensure that the program will pause at the breakpoints even if the program is running at remote SSH/Tunnel host + dev container. + +## Profile + +```bash Command +# Change batch size, input, output and add `disable-cuda-graph` (for easier analysis) +# e.g. DeepSeek V3 +nsys profile -o deepseek_v3 python3 -m sglang.bench_one_batch --batch-size 1 --input 128 --output 256 --model deepseek-ai/DeepSeek-V3 --trust-remote-code --tp 8 --disable-cuda-graph +``` + +## Evaluation + +```bash Command +# e.g. gsm8k 8 shot +python3 benchmark/gsm8k/bench_sglang.py --num-questions 2000 --parallel 2000 --num-shots 8 +``` diff --git a/docs_new/docs/developer_guide/evaluating_new_models.mdx b/docs_new/docs/developer_guide/evaluating_new_models.mdx new file mode 100644 index 000000000..9f5aade7a --- /dev/null +++ b/docs_new/docs/developer_guide/evaluating_new_models.mdx @@ -0,0 +1,149 @@ +--- +title: "Evaluating New Models with SGLang" +metatags: + description: "SGLang model evaluation: MMLU, GSM8K, GPQA, HumanEval, MMMU benchmarks. Latency and throughput testing commands." +--- +This document provides commands for evaluating models' accuracy and performance. Before open-sourcing new models, we strongly suggest running these commands to verify whether the score matches your internal benchmark results. + +**For cross verification, please submit commands for installation, server launching, and benchmark running with all the scores and hardware requirements when open-sourcing your models.** + +[Reference: MiniMax M2](https://github.com/sgl-project/sglang/pull/12129) + +## Accuracy + +### LLMs + +SGLang provides built-in scripts to evaluate common benchmarks. + +**MMLU** + +```bash Command +python -m sglang.test.run_eval \ + --eval-name mmlu \ + --port 30000 \ + --num-examples 1000 \ + --max-tokens 8192 +``` + +**GSM8K** + +```bash Command +python -m sglang.test.few_shot_gsm8k \ + --host http://127.0.0.1 \ + --port 30000 \ + --num-questions 200 \ + --num-shots 5 +``` + +**HellaSwag** + +```bash Command +python benchmark/hellaswag/bench_sglang.py \ + --host http://127.0.0.1 \ + --port 30000 \ + --num-questions 200 \ + --num-shots 20 +``` + +**GPQA** + +```bash Command +python -m sglang.test.run_eval \ + --eval-name gpqa \ + --port 30000 \ + --num-examples 198 \ + --max-tokens 120000 \ + --repeat 8 +``` + + +For reasoning models, add `--thinking-mode ` (e.g., `qwen3`, `deepseek-r1`, `deepseek-v3`). You may skip it if the model has forced thinking enabled. + + +**HumanEval** + +```bash Command +pip install human_eval + +python -m sglang.test.run_eval \ + --eval-name humaneval \ + --num-examples 10 \ + --port 30000 +``` + +### VLMs + +**MMMU** + +```bash Command +python benchmark/mmmu/bench_sglang.py \ + --port 30000 \ + --concurrency 64 +``` + + +You can set max tokens by passing `--extra-request-body '{"max_tokens": 4096}'`. + + +For models capable of processing video, we recommend extending the evaluation to include `VideoMME`, `MVBench`, and other relevant benchmarks. + +## Performance + +Performance benchmarks measure **Latency** (Time To First Token - TTFT) and **Throughput** (tokens/second). + +### LLMs + +**Latency-Sensitive Benchmark** + +This simulates a scenario with low concurrency (e.g., single user) to measure latency. + +```bash Command +python -m sglang.bench_serving \ + --backend sglang \ + --host 0.0.0.0 \ + --port 30000 \ + --dataset-name random \ + --num-prompts 10 \ + --max-concurrency 1 +``` + +**Throughput-Sensitive Benchmark** + +This simulates a high-traffic scenario to measure maximum system throughput. + +```bash Command +python -m sglang.bench_serving \ + --backend sglang \ + --host 0.0.0.0 \ + --port 30000 \ + --dataset-name random \ + --num-prompts 1000 \ + --max-concurrency 100 +``` + +**Single Batch Performance** + +You can also benchmark the performance of processing a single batch offline. + +```bash Command +python -m sglang.bench_one_batch_server \ + --model \ + --batch-size 8 \ + --input-len 1024 \ + --output-len 1024 +``` + +You can run more granular benchmarks: + +- **Low Concurrency**: `--num-prompts 10 --max-concurrency 1` +- **Medium Concurrency**: `--num-prompts 80 --max-concurrency 16` +- **High Concurrency**: `--num-prompts 500 --max-concurrency 100` + +## Reporting Results + +For each evaluation, please report: + +1. **Metric Score**: Accuracy % (LLMs and VLMs); Latency (ms) and Throughput (tok/s) (LLMs only). +2. **Environment settings**: GPU type/count, SGLang commit hash. +3. **Launch configuration**: Model path, TP size, and any special flags. +4. **Evaluation parameters**: Number of shots, examples, max tokens. diff --git a/docs_new/docs/developer_guide/overview.mdx b/docs_new/docs/developer_guide/overview.mdx new file mode 100644 index 000000000..3c952d724 --- /dev/null +++ b/docs_new/docs/developer_guide/overview.mdx @@ -0,0 +1,11 @@ +--- +title: Developer Guide +description: Contributing to SGLang — development setup, benchmarking, and evaluation. +--- + +- [Contribution Guide](./contribution_guide) +- [Development Guide (Docker)](./development_guide_using_docker) +- [JIT Kernels](./JIT_kernels) +- [Benchmark and Profiling](./benchmark_and_profiling) +- [Bench Serving](./bench_serving) +- [Evaluating New Models](./evaluating_new_models) diff --git a/docs_new/docs/developer_guide/release_process.mdx b/docs_new/docs/developer_guide/release_process.mdx new file mode 100644 index 000000000..cac283675 --- /dev/null +++ b/docs_new/docs/developer_guide/release_process.mdx @@ -0,0 +1,21 @@ +--- +title: "PyPI Package Release Process" +metatags: + description: "SGLang PyPI release: version update, upload_pypi.sh script, GitHub release creation." +--- +## Update the version in code +Update the package version in `python/pyproject.toml` and `python/sglang/__init__.py`. + +## Upload the PyPI package + +```text Output +pip install build twine +``` + +```text Output +cd python +bash upload_pypi.sh +``` + +## Make a release in GitHub +Make a new release https://github.com/sgl-project/sglang/releases/new. diff --git a/docs_new/docs/developer_guide/setup_github_runner.mdx b/docs_new/docs/developer_guide/setup_github_runner.mdx new file mode 100644 index 000000000..4c4243623 --- /dev/null +++ b/docs_new/docs/developer_guide/setup_github_runner.mdx @@ -0,0 +1,54 @@ +--- +title: "Set Up Self-Hosted Runners for GitHub Action" +metatags: + description: "SGLang GitHub Actions self-hosted runner: Docker setup for NVIDIA/AMD GPUs, config.sh and run.sh." +--- +## Add a Runner + +### Step 1: Start a docker container. + +**You can mount a folder for the shared huggingface model weights cache. ** +The command below uses `/tmp/huggingface` as an example. + +```text Output +docker pull nvidia/cuda:12.9.1-devel-ubuntu22.04 +# Nvidia +docker run --shm-size 128g -it -v /tmp/huggingface:/hf_home --gpus all nvidia/cuda:12.9.1-devel-ubuntu22.04 /bin/bash +# AMD +docker run --rm --device=/dev/kfd --device=/dev/dri --group-add video --shm-size 128g -it -v /tmp/huggingface:/hf_home lmsysorg/sglang:v0.5.0rc1-rocm630 /bin/bash +# AMD just the last 2 GPUs +docker run --rm --device=/dev/kfd --device=/dev/dri/renderD176 --device=/dev/dri/renderD184 --group-add video --shm-size 128g -it -v /tmp/huggingface:/hf_home lmsysorg/sglang:v0.5.0rc1-rocm630 /bin/bash +``` + +### Step 2: Configure the runner by `config.sh` + +Run these commands inside the container. + +```text Output +apt update && apt install -y curl python3-pip git +pip install --upgrade pip +export RUNNER_ALLOW_RUNASROOT=1 +``` + +Then follow https://github.com/sgl-project/sglang/settings/actions/runners/new?arch=x64&os=linux to run `config.sh` + +**Notes** +- Do not need to specify the runner group +- Give it a name (e.g., `test-sgl-gpu-0`) and some labels (e.g., `1-gpu-runner`). The labels can be edited later in Github Settings. +- Do not need to change the work folder. + +### Step 3: Run the runner by `run.sh` + +- Set up environment variables +```text Output +export HF_HOME=/hf_home +export SGLANG_IS_IN_CI=true +export HF_TOKEN=hf_xxx +export OPENAI_API_KEY=sk-xxx +export CUDA_VISIBLE_DEVICES=0 +``` + +- Run it forever +```text Output +while true; do ./run.sh; echo "Restarting..."; sleep 2; done +``` diff --git a/docs_new/docs/get-started/installation.mdx b/docs_new/docs/get-started/installation.mdx new file mode 100644 index 000000000..0402af64a --- /dev/null +++ b/docs_new/docs/get-started/installation.mdx @@ -0,0 +1,256 @@ +--- +title: Installation +description: Install SGLang with pip/uv, source, Docker, Kubernetes, and cloud deployment options. +keywords: + - installation + - sglang + - pip + - docker +--- + +You can install SGLang using one of the methods below. +This page primarily applies to common NVIDIA GPU platforms. +For other or newer platforms, please refer to the dedicated pages for [AMD GPUs](../hardware-platforms/amd-gpus), [Intel Xeon CPUs](../hardware-platforms/cpu-server), [Google TPU](../hardware-platforms/tpu), [NVIDIA DGX Spark](https://lmsys.org/blog/2025-11-03-gpt-oss-on-nvidia-dgx-spark/), [NVIDIA Jetson](../hardware-platforms/nvidia), [Ascend NPUs](../hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support), and [Intel XPU](../hardware-platforms/xpu). + + +## Install methods + + + + It is recommended to use uv for faster installation: + + ```bash + pip install --upgrade pip + pip install uv + uv pip install "sglang" + ``` + + ### Quick fixes to common problems + + + + In some cases (for example, GB200), the command above might install a wrong torch version (for example, the CPU version) due to dependency resolution. Reinstall the correct [PyTorch](https://pytorch.org/get-started/locally/) with the following: + + ```bash + uv pip install "torch" "torchvision" --extra-index-url https://download.pytorch.org/whl/cu129 --force-reinstall + ``` + + + + If you do not have Docker access, install the matching `sgl_kernel` wheel from [the sgl-project whl releases](https://github.com/sgl-project/whl/releases) after installing SGLang. Replace `X.Y.Z` with the `sgl_kernel` version required by your SGLang (you can find this by running `uv pip show sgl_kernel`). + + **x86_64** + + ```bash + uv pip install "https://github.com/sgl-project/whl/releases/download/vX.Y.Z/sgl_kernel-X.Y.Z+cu130-cp310-abi3-manylinux2014_x86_64.whl" + ``` + + **aarch64** + + ```bash + uv pip install "https://github.com/sgl-project/whl/releases/download/vX.Y.Z/sgl_kernel-X.Y.Z+cu130-cp310-abi3-manylinux2014_aarch64.whl" + ``` + + + + Choose one of the following solutions: + + 1. Set `CUDA_HOME` to your CUDA install root: + + ```bash + export CUDA_HOME=/usr/local/cuda- + ``` + + 2. Install FlashInfer first following the [FlashInfer installation doc](https://docs.flashinfer.ai/installation.html), then install SGLang as described above. + + + + + +```bash +git clone https://github.com/sgl-project/sglang.git +cd sglang +pip install --upgrade pip +pip install -e "python" +``` + + ### Quick fixes to common problems + + + + If you want to develop SGLang, try the dev docker image. Refer to [setup docker container](../developer_guide/development_guide_using_docker#setup-docker-container). The docker image is `lmsysorg/sglang:dev`. + + + + + + The docker images are available on Docker Hub at [lmsysorg/sglang](https://hub.docker.com/r/lmsysorg/sglang/tags), built from [Dockerfile](https://github.com/sgl-project/sglang/tree/main/docker). + Replace `` below with your huggingface hub [token](https://huggingface.co/docs/hub/en/security-tokens). + + **Standard image** + + ```bash + docker run --gpus all \ + --shm-size 32g \ + -p 30000:30000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --env "HF_TOKEN=" \ + --ipc=host \ + lmsysorg/sglang:latest \ + python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --host 0.0.0.0 --port 30000 + ``` + + **Runtime image for production** + + ```bash + docker run --gpus all \ + --shm-size 32g \ + -p 30000:30000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --env "HF_TOKEN=" \ + --ipc=host \ + lmsysorg/sglang:latest-runtime \ + python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --host 0.0.0.0 --port 30000 + ``` + + You can also find the nightly docker images [here](https://hub.docker.com/r/lmsysorg/sglang/tags?name=nightly). + + + On B300/GB300 (SM103) or CUDA 13 environment, use the nightly image at `lmsysorg/sglang:dev-cu13` or stable image at `lmsysorg/sglang:latest-cu130-runtime`. Do not re-install the project as editable inside the docker image, since it will override the version of libraries specified by the cu13 docker image. + + + + + Please check out [OME](https://github.com/sgl-project/ome), a Kubernetes operator for enterprise-grade management and serving of large language models (LLMs). + + + + For models that fit into GPUs on one node, create the deployment and service with llama-31-8b as example. + + ```bash + kubectl apply -f docker/k8s-sglang-service.yaml + ``` + + + + For larger models (for example, `DeepSeek-R1`), modify the model path and arguments, then create the statefulset and service. + + ```bash + kubectl apply -f docker/k8s-sglang-distributed-sts.yaml + ``` + + + + + + + This method is recommended if you plan to serve it as a service. A better approach is to use the [k8s-sglang-service.yaml](https://github.com/sgl-project/sglang/blob/main/docker/k8s-sglang-service.yaml). + + + 1. Copy the [compose.yml](https://github.com/sgl-project/sglang/blob/main/docker/compose.yaml) to your local machine. + 2. Start the service: + + ```bash + docker compose up -d + ``` + + + + To deploy on Kubernetes or 12+ clouds, you can use [SkyPilot](https://github.com/skypilot-org/skypilot). + + 1. Install SkyPilot and set up Kubernetes cluster or cloud access. See [SkyPilot's documentation](https://skypilot.readthedocs.io/en/latest/getting-started/installation.html). + 2. Deploy on your own infra with a single command and get the HTTP API endpoint: + + **SkyPilot YAML: `sglang.yaml`** + + ```yaml Config + # sglang.yaml + envs: + HF_TOKEN: null + + resources: + image_id: docker:lmsysorg/sglang:latest + accelerators: A100 + ports: 30000 + + run: | + conda deactivate + python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --host 0.0.0.0 \ + --port 30000 + ``` + + ```bash + # Deploy on any cloud or Kubernetes cluster. Use --cloud to select a specific cloud provider. + HF_TOKEN= sky launch -c sglang --env HF_TOKEN sglang.yaml + + # Get the HTTP API endpoint + sky status --endpoint 30000 sglang + ``` + + 3. To scale with autoscaling and failure recovery, check out the [SkyServe + SGLang guide](https://github.com/skypilot-org/skypilot/tree/master/llm/sglang#serving-llama-2-with-sglang-for-more-traffic-using-skyserve). + + + + To deploy on SGLang on AWS SageMaker, check out [AWS SageMaker Inference](https://aws.amazon.com/sagemaker/ai/deploy). + + Amazon Web Services provide supports for SGLang containers along with routine security patching. For available SGLang containers, check out [AWS SGLang DLCs](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#sglang-containers). + + To host a model with your own container, follow the following steps: + + 1. Build a docker container with [sagemaker.Dockerfile](https://github.com/sgl-project/sglang/blob/main/docker/sagemaker.Dockerfile) alongside the [serve](https://github.com/sgl-project/sglang/blob/main/docker/serve) script, then push it to AWS ECR. + + **Dockerfile build script: `build-and-push.sh`** + + ```bash + #!/bin/bash + AWS_ACCOUNT="" + AWS_REGION="" + REPOSITORY_NAME="" + IMAGE_TAG="" + + ECR_REGISTRY="${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com" + IMAGE_URI="${ECR_REGISTRY}/${REPOSITORY_NAME}:${IMAGE_TAG}" + + echo "Starting build and push process..." + + # Login to ECR + echo "Logging into ECR..." + aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${ECR_REGISTRY} + + # Build the image + echo "Building Docker image..." + docker build -t ${IMAGE_URI} -f sagemaker.Dockerfile . + + echo "Pushing ${IMAGE_URI}" + docker push ${IMAGE_URI} + + echo "Build and push completed successfully!" + ``` + + 2. Deploy a model for serving on AWS Sagemaker. Refer to [deploy_and_serve_endpoint.py](https://github.com/sgl-project/sglang/blob/main/examples/sagemaker/deploy_and_serve_endpoint.py). For more information, check out [sagemaker-python-sdk](https://github.com/aws/sagemaker-python-sdk). + + **Default command** + + The model server on SageMaker runs: `python3 -m sglang.launch_server --model-path opt/ml/model --host 0.0.0.0 --port 8080`. + + **Custom arguments** + + The [serve](https://github.com/sgl-project/sglang/blob/main/docker/serve) script exposes all options in `python3 -m sglang.launch_server --help` through environment variables prefixed with `SM_SGLANG_`. + + **Environment variable mapping** + + The serve script converts variables with prefix `SM_SGLANG_` from `SM_SGLANG_INPUT_ARGUMENT` into `--input-argument` for the `python3 -m sglang.launch_server` CLI. + + **Example** + + To run [Qwen/Qwen3-0.6B](https://huggingface.co/Qwen/Qwen3-0.6B) with reasoning parser, add `SM_SGLANG_MODEL_PATH=Qwen/Qwen3-0.6B` and `SM_SGLANG_REASONING_PARSER=qwen3`. + + + +## Common notes + +- [FlashInfer](https://github.com/flashinfer-ai/flashinfer) is the default attention kernel backend. It only supports sm75 and above. If you encounter any FlashInfer-related issues on sm75+ devices (for example, T4, A10, A100, L4, L40S, H100), switch to other kernels by adding `--attention-backend triton --sampling-backend pytorch` and open an issue on GitHub. +- To reinstall flashinfer locally, use the following command: `pip3 install --upgrade flashinfer-python --force-reinstall --no-deps` and then delete the cache with `rm -rf ~/.cache/flashinfer`. +- When encountering `ptxas fatal : Value 'sm_103a' is not defined for option 'gpu-name'` on B300/GB300, fix it with `export TRITON_PTXAS_PATH=/usr/local/cuda/bin/ptxas`. diff --git a/docs_new/docs/get-started/quickstart.mdx b/docs_new/docs/get-started/quickstart.mdx new file mode 100644 index 000000000..d33a1fb12 --- /dev/null +++ b/docs_new/docs/get-started/quickstart.mdx @@ -0,0 +1,332 @@ +--- +title: "Quickstart" +description: "Get up and running with SGLang in minutes: install, launch a server, and send your first request." +--- + +## Overview + +This guide walks you through the entire flow of getting started with SGLang: + +1. **Install** SGLang +2. **Launch** an inference server +3. **Send requests** using cURL, OpenAI Python client, Python `requests`, or the native SGLang API + +By the end, you'll have a working SGLang server responding to your prompts. + +--- + +## Prerequisites + +- **Python**: 3.9 or higher +- **GPU**: NVIDIA GPU with CUDA support (sm75 and above, e.g., T4, A10, A100, L4, L40S, H100) +- **OS**: Linux (recommended) + + +For other platforms, see the dedicated guides for [AMD GPUs](../hardware-platforms/amd-gpus), [Intel Xeon CPUs](../hardware-platforms/cpu-server), [Google TPUs](../hardware-platforms/tpu), [NVIDIA Jetson](../hardware-platforms/nvidia), [Ascend NPUs](../hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support), and [Intel XPU](../hardware-platforms/xpu). + + +--- + +## Installation + + + + We recommend using **uv** for faster installation: + +```bash +pip install --upgrade pip +pip install uv +uv pip install sglang +``` + + +```bash +# Clone and install from source +git clone https://github.com/sgl-project/sglang.git +cd sglang +pip install --upgrade pip +pip install -e "python" +``` + + + The Docker images are available on Docker Hub at [lmsysorg/sglang](https://hub.docker.com/r/lmsysorg/sglang/tags). + + Replace `` with your [Hugging Face token](https://huggingface.co/docs/hub/en/security-tokens): + + ```bash + docker run --gpus all \ + --shm-size 32g \ + -p 30000:30000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --env "HF_TOKEN=" \ + --ipc=host \ + lmsysorg/sglang:latest \ + python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --host 0.0.0.0 --port 30000 + ``` + + For production deployments, use the smaller **runtime** variant (~40% size reduction): + + ```bash + docker run --gpus all \ + --shm-size 32g \ + -p 30000:30000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --env "HF_TOKEN=" \ + --ipc=host \ + lmsysorg/sglang:latest-runtime \ + python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --host 0.0.0.0 --port 30000 + ``` + + + + +If you encounter `OSError: CUDA_HOME environment variable is not set`, set it with: +```bash +export CUDA_HOME=/usr/local/cuda- +``` + + +--- + +## Launch a Server + +Start the SGLang server with a model. Here we use `qwen/qwen2.5-0.5b-instruct` as a lightweight example: + +```bash +python3 -m sglang.launch_server --model-path qwen/qwen2.5-0.5b-instruct --host 0.0.0.0 --port 30000 +``` + +Wait until you see `The server is fired up and ready to roll!` in the terminal output. + + +Once the server is running, API documentation is available at: +- **Swagger UI**: `http://localhost:30000/docs` +- **ReDoc**: `http://localhost:30000/redoc` +- **OpenAPI Spec**: `http://localhost:30000/openapi.json` + + + +The server automatically applies the chat template from the Hugging Face tokenizer. You can override it with `--chat-template` when launching. + + +--- + +## Send Requests + +SGLang is fully **OpenAI API-compatible**, so you can use the same tools and libraries you already know. + +### Using cURL + +```bash +curl http://localhost:30000/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{ + "model": "qwen/qwen2.5-0.5b-instruct", + "messages": [ + {"role": "user", "content": "What is the capital of France?"} + ] + }' +``` + +### Using OpenAI Python Client + +Install the OpenAI Python library if you haven't: + +```bash +pip install openai +``` + +Then send a request: + +```python Example +import openai + +client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, +) + +print(response.choices[0].message.content) +``` + +#### Streaming + +```python Example +import openai + +client = openai.Client(base_url="http://127.0.0.1:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="qwen/qwen2.5-0.5b-instruct", + messages=[ + {"role": "user", "content": "List 3 countries and their capitals."}, + ], + temperature=0, + max_tokens=64, + stream=True, +) + +for chunk in response: + if chunk.choices[0].delta.content: + print(chunk.choices[0].delta.content, end="", flush=True) +``` + +### Using Python Requests + +```python Example +import requests + +url = "http://localhost:30000/v1/chat/completions" + +data = { + "model": "qwen/qwen2.5-0.5b-instruct", + "messages": [{"role": "user", "content": "What is the capital of France?"}], +} + +response = requests.post(url, json=data) +print(response.json()) +``` + +### Using the Native `/generate` API + +SGLang also provides a native `/generate` endpoint for more flexibility. + +```python Example +import requests + +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + }, + }, +) + +print(response.json()) +``` + +#### Streaming with `/generate` + +```python Example +import requests +import json + +response = requests.post( + "http://localhost:30000/generate", + json={ + "text": "The capital of France is", + "sampling_params": { + "temperature": 0, + "max_new_tokens": 32, + }, + "stream": True, + }, + stream=True, +) + +prev = 0 +for chunk in response.iter_lines(decode_unicode=False): + chunk = chunk.decode("utf-8") + if chunk and chunk.startswith("data:"): + if chunk == "data: [DONE]": + break + data = json.loads(chunk[5:].strip("\n")) + output = data["text"] + print(output[prev:], end="", flush=True) + prev = len(output) +``` + +--- + +## Offline Batch Inference (No Server) + +SGLang also supports offline batch inference using the `Engine` class directly -- no HTTP server required. + +```python Example +import sglang as sgl + +llm = sgl.Engine(model_path="qwen/qwen2.5-0.5b-instruct") + +prompts = [ + "Hello, my name is", + "The president of the United States is", + "The capital of France is", + "The future of AI is", +] + +sampling_params = {"temperature": 0.8, "top_p": 0.95} + +outputs = llm.generate(prompts, sampling_params) + +for prompt, output in zip(prompts, outputs): + print(f"Prompt: {prompt}\nGenerated text: {output['text']}\n") + +llm.shutdown() +``` + +--- + +## Common Troubleshooting + + + + Set the `CUDA_HOME` environment variable to your CUDA install root: + ```bash + export CUDA_HOME=/usr/local/cuda- + ``` + + + Switch to alternative backends by adding these flags when launching the server: + ```bash + --attention-backend triton --sampling-backend pytorch + ``` + + + ```bash + pip3 install --upgrade flashinfer-python --force-reinstall --no-deps + rm -rf ~/.cache/flashinfer + ``` + + + ```bash + export TRITON_PTXAS_PATH=/usr/local/cuda/bin/ptxas + ``` + + + +--- + +{/* +WIP, TBD linked later +## What's Next? + + + + Explore the full Chat Completions and Completions APIs, including multi-turn conversations. + + + Send image inputs alongside text using OpenAI-compatible vision APIs. + + + Fine-tune generation with temperature, top-p, frequency penalty, and more. + + + Customize server behavior with advanced launch arguments like tensor parallelism. + + + Constrain model output to JSON, regex, or EBNF grammars. + + + Use the familiar Ollama CLI and Python library with SGLang as the backend. + + +*/} diff --git a/docs_new/docs/hardware-platforms/amd-gpus.mdx b/docs_new/docs/hardware-platforms/amd-gpus.mdx new file mode 100644 index 000000000..823f783dd --- /dev/null +++ b/docs_new/docs/hardware-platforms/amd-gpus.mdx @@ -0,0 +1,194 @@ +--- +title: "AMD GPUs" +--- +This document describes how run SGLang on AMD GPUs. If you encounter issues or have questions, please [open an issue](https://github.com/sgl-project/sglang/issues). + +## System Configuration + +When using AMD GPUs (such as MI300X), certain system-level optimizations help ensure stable performance. Here we take MI300X as an example. AMD provides official documentation for MI300X optimization and system tuning: + +* [AMD MI300X Tuning Guides](https://rocm.docs.amd.com/en/latest/how-to/tuning-guides/mi300x/index.html) +* [LLM inference performance validation on AMD Instinct MI300X](https://rocm.docs.amd.com/en/latest/how-to/rocm-for-ai/inference/vllm-benchmark.html) +* [AMD Instinct MI300X System Optimization](https://rocm.docs.amd.com/en/latest/how-to/system-optimization/mi300x.html) +* [AMD Instinct MI300X Workload Optimization](https://rocm.docs.amd.com/en/latest/how-to/rocm-for-ai/inference-optimization/workload.html) +* [Supercharge DeepSeek-R1 Inference on AMD Instinct MI300X](https://rocm.blogs.amd.com/artificial-intelligence/DeepSeekR1-Part2/README.html) + + +We strongly recommend reading these docs and guides entirely to fully utilize your system. + + +Below are a few key settings to confirm or enable for SGLang: + +### Update GRUB Settings + +In `/etc/default/grub`, append the following to `GRUB_CMDLINE_LINUX`: + + +```text GRUB Configuration +pci=realloc=off iommu=pt +``` + + +Afterward, run `sudo update-grub` (or your distro's equivalent) and reboot. + +### Disable NUMA Auto-Balancing + + +```bash Disable NUMA +sudo sh -c 'echo 0 > /proc/sys/kernel/numa_balancing' +``` + + +You can automate or verify this change using [this helpful script](https://github.com/ROCm/triton/blob/rocm_env/scripts/amd/env_check.sh). + +Again, please go through the entire documentation to confirm your system is using the recommended configuration. + +## Install SGLang + + + + The docker images are available on Docker Hub at [lmsysorg/sglang](https://hub.docker.com/r/lmsysorg/sglang/tags), built from [rocm.Dockerfile](https://github.com/sgl-project/sglang/tree/main/docker). + + 1. **Build the docker image** + If you use pre-built images, you can skip this step and replace `sglang_image` with the pre-built image names in the steps below. + + + ```bash Build Image + docker build -t sglang_image -f rocm.Dockerfile . + ``` + + + 2. **Create a convenient alias** + + ```bash Create Alias + alias drun='docker run -it --rm --network=host --privileged --device=/dev/kfd --device=/dev/dri \ + --ipc=host --shm-size 16G --group-add video --cap-add=SYS_PTRACE \ + --security-opt seccomp=unconfined \ + -v $HOME/dockerx:/dockerx \ + -v /data:/data' + ``` + + + If you are using RDMA, please note that: + + * `--network host` and `--privileged` are required by RDMA. If you don't need RDMA, you can remove them. + * You may need to set `NCCL_IB_GID_INDEX` if you are using RoCE, for example: `export NCCL_IB_GID_INDEX=3`. + + 3. **Launch the server** + + Replace `` below with your [huggingface hub token](https://huggingface.co/docs/hub/en/security-tokens). + + + + ```bash Launch Server + drun -p 30000:30000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --env "HF_TOKEN=" \ + sglang_image \ + python3 -m sglang.launch_server \ + --model-path NousResearch/Meta-Llama-3.1-8B \ + --host 0.0.0.0 \ + --port 30000 + ``` + + + 4. **Verify the installation** + You can run a benchmark in another terminal or refer to [other docs](../basic_usage/openai_api_completions) to send requests to the engine. + + + ```bash Run Benchmark + drun sglang_image \ + python3 -m sglang.bench_serving \ + --backend sglang \ + --dataset-name random \ + --num-prompts 4000 \ + --random-input 128 \ + --random-output 128 + ``` + + + With your AMD system properly configured and SGLang installed, you can now fully leverage AMD hardware to power SGLang's machine learning capabilities. + + + + 1. **Clone the repository** + Clone the SGLang repository. + + + ```bash + git clone https://github.com/sgl-project/sglang.git + cd sglang + ``` + + + 2. **Compile sgl-kernel** + Upgrade pip and compile the sgl-kernel for ROCm support. + + + ```bash + pip install --upgrade pip + cd sgl-kernel + python setup_rocm.py install + ``` + + + 3. **Install sglang package** + Install the SGLang Python package with HIP and diffusion support. + + + ```bash + cd .. + rm -rf python/pyproject.toml && mv python/pyproject_other.toml python/pyproject.toml + pip install -e "python[all_hip]" + ``` + + + + +## Examples + +### Running DeepSeek-V3 + +The only difference when running DeepSeek-V3 is in how you start the server. + + +```bash DeepSeek-V3 +drun -p 30000:30000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --ipc=host \ + --env "HF_TOKEN=" \ + sglang_image \ + python3 -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-V3 \ + --tp 8 \ + --trust-remote-code \ + --host 0.0.0.0 \ + --port 30000 +``` + + +[Running DeepSeek-R1 on a single NDv5 MI300X VM](https://techcommunity.microsoft.com/blog/azurehighperformancecomputingblog/running-deepseek-r1-on-a-single-ndv5-mi300x-vm/4372726) could also be a good reference. + +### Running Llama3.1 + +Running Llama3.1 is nearly identical to running DeepSeek-V3. The only difference is in the model specified when starting the server. + + +```bash Llama3.1 +drun -p 30000:30000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --ipc=host \ + --env "HF_TOKEN=" \ + sglang_image \ + python3 -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --tp 8 \ + --trust-remote-code \ + --host 0.0.0.0 \ + --port 30000 +``` + + +### Warmup Step + +When the server displays `The server is fired up and ready to roll!`, it means the startup is successful. diff --git a/docs_new/docs/hardware-platforms/ascend-npus/Best-Practice-on-Ascend-NPU.mdx b/docs_new/docs/hardware-platforms/ascend-npus/Best-Practice-on-Ascend-NPU.mdx new file mode 100644 index 000000000..0b4b3e917 --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/Best-Practice-on-Ascend-NPU.mdx @@ -0,0 +1,2911 @@ +This section describes the best practice data of mainstream LLM models such as DeepSeek and Qwen on the Ascend NPU. If +you encounter issues or have any questions, please [open an issue](https://github.com/sgl-project/sglang/issues). + +## DeepSeek Series Models + +### Low Latency + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelHardwareCardsDeploy ModeDatasetTPOTQuantizationConfiguration
Deepseek-R1Atlas 800I A332PD Separation6K+1.6K20msW8A8 INT8[Optimal Configuration](#deepseek-r1-6k-1_6k-20ms-on-a3-32-cards-separation-mode)
Deepseek-R1Atlas 800I A332PD Separation3.9K+1K20msW8A8 INT8[Optimal Configuration](#deepseek-r1-3_9k-1k-20ms-on-a3-32-cards-separation-mode)
Deepseek-R1Atlas 800I A332PD Separation3.5K+1.5K20msW8A8 INT8[Optimal Configuration](#deepseek-r1-3_5k-1_5k-20ms-on-a3-32-cards-separation-mode)
Deepseek-R1Atlas 800I A332PD Separation3.5K+1K20msW8A8 INT8[Optimal Configuration](#deepseek-r1-3_5k-1k-20ms-on-a3-32-cards-separation-mode)
DeepSeek-V3.2-ExpAtlas 800I A332PD Separation64K+3K30msW8A8 INT8[Optimal Configuration](#deepseek-v32-exp-64k-3k-30ms-on-a3-32-cards-separation-mode)
+ +### High Throughput + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelHardwareCardsDeploy ModeDatasetTPOTQuantizationConfiguration
Deepseek-R1Atlas 800I A332PD Separation3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#deepseek-r1-3_5k-1_5k-50ms-on-a3-32-cards-separation-mode)
Deepseek-R1Atlas 800I A38PD Mixed2K+2K50msW4A8 INT8[Optimal Configuration](#deepseek-r1-2k-2k-50ms-on-a3-8-cards-mixed-mode)
Deepseek-R1Atlas 800I A316PD Separation2K+2K50msW4A8 INT8[Optimal Configuration](#deepseek-r1-2k-2k-50ms-on-a3-16-cards-separation-mode)
Deepseek-R1Atlas 800I A38PD Mixed3.5K+1.5K50msW4A8 INT8[Optimal Configuration](#deepseek-r1-3_5k-1_5k-50ms-on-a3-8-cards-mixed-mode)
Deepseek-R1Atlas 800I A316PD Separation3.5K+1.5K50msW4A8 INT8[Optimal Configuration](#deepseek-r1-3_5k-1_5k-50ms-on-a3-16-cards-separation-mode)
+ +## Qwen Series Models + +### Low Latency + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelHardwareCardsDeploy ModeDatasetTPOTQuantizationConfiguration
Qwen3-235B-A22BAtlas 800I A38PD Mixed11K+1K10msBF16[Optimal Configuration](#qwen3-235b-a22b-11k-1k-10ms-on-a3-8-cards-mixed-mode)
Qwen3-32BAtlas 800I A34PD Mixed6K+1.5K18msBF16[Optimal Configuration](#qwen3-32b-6k-1_5k-18ms-on-a3-4-cards-mixed-mode)
Qwen3-32BAtlas 800I A34PD Mixed4K+1.5K11msBF16[Optimal Configuration](#qwen3-32b-4k-1_5k-11ms-on-a3-4-cards-mixed-mode)
Qwen3-32BAtlas 800I A38PD Mixed18K+4K12msBF16[Optimal Configuration](#qwen3-32b-18k-4k-12ms-on-a3-8-cards-mixed-mode)
Qwen3-32BAtlas 800I A28PD Mixed6K+1.5K18msW8A8 INT8[Optimal Configuration](#qwen3-32b-6k-1_5k-18ms-on-a2-8-cards-mixed-mode)
Qwen3-32BAtlas 800I A28PD Mixed4K+1.5K11msBF16[Optimal Configuration](#qwen3-32b-4k-1_5k-11ms-on-a2-8-cards-mixed-mode)
+ +### High Throughput + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelHardwareCardsDeploy ModeDatasetTPOTQuantizationConfiguration
Qwen3-235B-A22BAtlas 800I A324PD Separation3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-235b-a22b-3_5k-1_5k-50ms-on-a3-24-cards-separation-mode)
Qwen3-235B-A22BAtlas 800I A38PD Mixed3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-235b-a22b-3_5k-1_5k-50ms-on-a3-8-cards-mixed-mode)
Qwen3-235B-A22BAtlas 800I A38PD Mixed2K+2K100msW8A8 INT8[Optimal Configuration](#qwen3-235b-a22b-2k-2k-100ms-on-a3-8-cards-mixed-mode)
Qwen3-235B-A22BAtlas 800I A38PD Mixed2K+2K50msW8A8 INT8[Optimal Configuration](#qwen3-235b-a22b-2k-2k-50ms-on-a3-8-cards-mixed-mode)
Qwen3-235B-A22BAtlas 800I A316PD Mixed2K+2K50msW8A8 INT8[Optimal Configuration](#qwen3-235b-a22b-2k-2k-50ms-on-a3-16-cards-mixed-mode)
Qwen3-32BAtlas 800I A32PD Mixed3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-32b-3_5k-1_5k-50ms-on-a3-2-cards-mixed-mode)
Qwen3-32BAtlas 800I A32PD Mixed2K+2K50msW8A8 INT8[Optimal Configuration](#qwen3-32b-2k-2k-50ms-on-a3-2-cards-mixed-mode)
Qwen3-30B-A3BAtlas 800I A31PD Mixed3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-30b-a3b-3_5k-1_5k-50ms-on-a3-1-card-mixed-mode)
Qwen3-Coder-480B-A35B-InstructAtlas 800I A324PD Separation3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-coder-480b-a35b-instruct-3_5k-1_5k-50ms-on-a3-24-cards-separation-mode)
Qwen3-Coder-480B-A35B-InstructAtlas 800I A316PD Mixed3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-coder-480b-a35b-instruct-3_5k-1_5k-50ms-on-a3-16-cards-mixed-mode)
Qwen3-Coder-480B-A35B-InstructAtlas 800I A38PD Mixed3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-coder-480b-a35b-instruct-3_5k-1_5k-50ms-on-a3-8-cards-mixed-mode)
Qwen3-Next-80B-A3B-InstructAtlas 800I A32PD Mixed3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-next-80B-a3b-instruct-3_5k-1_5k-50ms-on-a3-2-cards-mixed-mode)
Qwen3-32BAtlas 800I A28PD Mixed3.5K+1.5K50msW8A8 INT8[Optimal Configuration](#qwen3-32b-3_5k-1_5k-50ms-on-a2-8-cards-mixed-mode)
Qwen3-32BAtlas 800I A28PD Mixed2K+2K50msW8A8 INT8[Optimal Configuration](#qwen3-32b-2k-2k-50ms-on-a2-8-cards-mixed-mode)
+ +## Optimal Configuration + +### DeepSeek-R1 3_5K-1_5K 50ms on A3 32 Cards Separation Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 32Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 +export SGLANG_SET_CPU_AFFINITY=1 +unset ASCEND_LAUNCH_BLOCKING +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 + +export ASCEND_MF_STORE_URL="tcp://your prefill ip1:24669" + +P_IP=('your prefill ip1' 'your prefill ip2') + +D_IP=('your decode ip1' 'your decode ip2') + +MODEL_PATH=xxx + +export SGLANG_NPU_USE_MLAPO=1 +export SGLANG_USE_FIA_NZ=1 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" +# prefill +for i in "${!P_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${P_IP[$i]}" || "$LOCAL_HOST2" == "${P_IP[$i]}" ]]; + then + echo "${P_IP[$i]}" + export HCCL_BUFFSIZE=1536 + export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + export TASK_QUEUE_ENABLE=2 + + export HCCL_SOCKET_IFNAME=lo + export GLOO_SOCKET_IFNAME=lo + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode prefill --host ${P_IP[$i]} \ + --port 8000 --disaggregation-bootstrap-port $((8998+$i)) --trust-remote-code --nnodes 1 --node-rank 0 \ + --tp-size 16 --mem-fraction-static 0.81 --attention-backend ascend --device npu --quantization modelslim \ + --disaggregation-transfer-backend ascend --max-running-requests 8 --context-length 8192 --disable-radix-cache \ + --chunked-prefill-size -1 --max-prefill-tokens 28680 --moe-a2a-backend deepep --deepep-mode normal \ + --speculative-algorithm NEXTN --speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2 \ + --dp-size 2 --enable-dp-attention --disable-shared-experts-fusion --dtype bfloat16 --enable-attn-tp-input-scattered + NODE_RANK=$i + break + fi +done + +# decode +for i in "${!D_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${D_IP[$i]}" || "$LOCAL_HOST2" == "${D_IP[$i]}" ]]; + then + echo "${D_IP[$i]}" + export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + export SGLANG_ENABLE_SPEC_V2=1 + export HCCL_BUFFSIZE=650 + export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=78 + export TASK_QUEUE_ENABLE=1 + export SGLANG_SCHEDULER_SKIP_ALL_GATHER=1 + export HCCL_SOCKET_IFNAME=xxx + export GLOO_SOCKET_IFNAME=xxx + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode decode --host ${D_IP[$i]} \ + --port 8001 --trust-remote-code --dist-init-addr ${D_IP[0]}:5000 --nnodes 2 --node-rank $i --tp-size 32 --dp-size 32 \ + --mem-fraction-static 0.815 --max-running-requests 832 --attention-backend ascend --device npu --quantization modelslim \ + --moe-a2a-backend deepep --enable-dp-attention --deepep-mode low_latency --enable-dp-lm-head --moe-dense-tp 1 \ + --cuda-graph-bs 12 14 16 18 20 22 24 26 --disaggregation-transfer-backend ascend --watchdog-timeout 9000 --context-length 8192 \ + --speculative-algorithm NEXTN --speculative-num-steps 2 --speculative-eagle-topk 1 --speculative-num-draft-tokens 3 \ + --tokenizer-worker-num 4 --prefill-round-robin-balance --disable-shared-experts-fusion --dtype bfloat16 \ + --load-balance-method decode_round_robin + NODE_RANK=$i + break + fi +done + +``` + +```shell Command +export SGLANG_DP_ROUND_ROBIN=1 +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://P_IP:8000 8998 \ + --prefill http://P_IP:8000 8999 \ + --decode http://D_IP:8001 \ + --host 127.0.0.1 \ + --port 6688 \ + --mini-lb +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6688 --max-concurrency 768 --random-input-len 3500 --random-output-len 1500 --num-prompts 3072 --random-range-ratio 1 --request-rate 16 +``` + +### DeepSeek-R1 6K-1_6K 20ms on A3 32 Cards Separation Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 32Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 6K+1.6K + +TPOT: 20ms + +#### Model Deployment + +```shell Command +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 +export SGLANG_SET_CPU_AFFINITY=1 +unset ASCEND_LAUNCH_BLOCKING +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 +export ASCEND_MF_STORE_URL="tcp://your prefill ip1:24669" + +P_IP=('your prefill ip1' 'your prefill ip2') + +D_IP=('your decode ip1' 'your decode ip2') + +MODEL_PATH=xxx + +export SGLANG_NPU_USE_MLAPO=1 +export SGLANG_USE_FIA_NZ=1 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" +# prefill +for i in "${!P_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${P_IP[$i]}" || "$LOCAL_HOST2" == "${P_IP[$i]}" ]]; + then + echo "${P_IP[$i]}" + export HCCL_BUFFSIZE=1536 + export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + export TASK_QUEUE_ENABLE=2 + + export HCCL_SOCKET_IFNAME=lo + export GLOO_SOCKET_IFNAME=lo + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode prefill --host ${P_IP[$i]} \ + --port 8000 --disaggregation-bootstrap-port $((8998+$i)) --trust-remote-code --nnodes 1 --node-rank 0 \ + --tp-size 16 --mem-fraction-static 0.81 --attention-backend ascend --device npu --quantization modelslim \ + --disaggregation-transfer-backend ascend --max-running-requests 4 --context-length 8192 --disable-radix-cache \ + --chunked-prefill-size -1 --max-prefill-tokens 28680 --moe-a2a-backend deepep --deepep-mode normal \ + --speculative-algorithm NEXTN --speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2 \ + --dp-size 2 --enable-dp-attention --disable-shared-experts-fusion --dtype bfloat16 --enable-attn-tp-input-scattered + NODE_RANK=$i + break + fi +done + +# decode +for i in "${!D_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${D_IP[$i]}" || "$LOCAL_HOST2" == "${D_IP[$i]}" ]]; + then + echo "${D_IP[$i]}" + export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + export SGLANG_ENABLE_SPEC_V2=1 + export HCCL_BUFFSIZE=650 + export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=12 + export TASK_QUEUE_ENABLE=1 + export SGLANG_SCHEDULER_SKIP_ALL_GATHER=1 + export HCCL_SOCKET_IFNAME=xxx + export GLOO_SOCKET_IFNAME=xxx + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode decode --host ${D_IP[$i]} \ + --port 8001 --trust-remote-code --dist-init-addr DIP1:5000 --nnodes 2 --node-rank $i --tp-size 32 --dp-size 16 \ + --mem-fraction-static 0.75 --max-running-requests 32 --attention-backend ascend --device npu --quantization modelslim \ + --moe-a2a-backend deepep --enable-dp-attention --deepep-mode low_latency --enable-dp-lm-head --moe-dense-tp 1 \ + --cuda-graph-bs 2 4 6 --disaggregation-transfer-backend ascend --watchdog-timeout 9000 --context-length 8192 \ + --speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --tokenizer-worker-num 4 --prefill-round-robin-balance --disable-shared-experts-fusion --dtype bfloat16 \ + --load-balance-method decode_round_robin + NODE_RANK=$i + break + fi +done + +``` + +```shell Command +export SGLANG_DP_ROUND_ROBIN=1 +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://P_IP:8000 8998 \ + --prefill http://P_IP:8000 8999 \ + --decode http://D_IP:8001 \ + --host 127.0.0.1 \ + --port 6688 \ + --mini-lb +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6688 --max-concurrency 32 --random-input-len 6000 --random-output-len 1600 --num-prompts 32 --random-range-ratio 1 +``` + +### DeepSeek-R1 3_9K-1K 20ms on A3 32 Cards Separation Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 32Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 3.9K+1K + +TPOT: 20ms + +#### Model Deployment + +Please Turn to [DeepSeek-R1 6K-1_6K 20ms on A3 32 Cards Separation Mode](#deepseek-r1-6k-1_6k-20ms-on-a3-32-cards-separation-mode) + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6688 --max-concurrency 768 --random-input-len 3900 --random-output-len 1000 --num-prompts 768 --random-range-ratio 1 --request-rate 16 +``` + +### DeepSeek-R1 3_5K-1_5K 20ms on A3 32 Cards Separation Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 32Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 20ms + +#### Model Deployment + +Please Turn to [DeepSeek-R1 6K-1_6K 20ms on A3 32 Cards Separation Mode](#deepseek-r1-6k-1_6k-20ms-on-a3-32-cards-separation-mode) + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```bash Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6688 --max-concurrency 768 --random-input-len 3500 --random-output-len 1500 --num-prompts 768 --random-range-ratio 1 --request-rate 16 +``` + +### DeepSeek-R1 3_5K-1K 20ms on A3 32 Cards Separation Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 32Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 3.5K+1K + +TPOT: 20ms + +#### Model Deployment + +Please Turn to [DeepSeek-R1 6K-1_6K 20ms on A3 32 Cards Separation Mode](#deepseek-r1-6k-1_6k-20ms-on-a3-32-cards-separation-mode) + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6688 --max-concurrency 768 --random-input-len 3500 --random-output-len 1000 --num-prompts 768 --random-range-ratio 1 --request-rate 16 +``` + +### DeepSeek-R1 2K-2K 50ms on A3 8 Cards Mixed Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 2K+2K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 +export SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE=1 + +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo + +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=64 +export HCCL_BUFFSIZE=1600 +export DEEPEP_NORMAL_LONG_SEQ_ROUND=10 +export DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS=512 + +MODEL_PATH=xxx + +export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 +export SGLANG_NPU_USE_MLAPO=1 +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_USE_FIA_NZ=1 +export ENABLE_MOE_NZ=1 + +python3 -m sglang.launch_server --model-path ${MODEL_PATH} \ +--tp 16 \ +--trust-remote-code \ +--attention-backend ascend \ +--device npu \ +--quantization modelslim \ +--watchdog-timeout 9000 \ +--host 127.0.0.1 --port 6699 \ +--cuda-graph-bs 4 8 16 \ +--mem-fraction-static 0.74 \ +--max-running-requests 256 \ +--disable-radix-cache --chunked-prefill-size -1 --max-prefill-tokens 1500 \ +--moe-a2a-backend deepep --deepep-mode auto \ +--enable-dp-attention --dp-size 16 --enable-dp-lm-head \ +--speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ +--dtype bfloat16 + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6699 --max-concurrency 256 --random-input-len 2048 --random-output-len 2048 --num-prompts 1024 --random-range-ratio 1 +``` + +### DeepSeek-R1 2K-2K 50ms on A3 16 Cards Separation Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 16Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 2K+2K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 + +export ASCEND_MF_STORE_URL="tcp://your prefill ip1:24667" + +P_IP=('your prefill ip1') + +D_IP=('your decode ip1') + +MODEL_PATH=xxx + +export SGLANG_NPU_USE_MLAPO=1 +export SGLANG_USE_FIA_NZ=1 +export ENABLE_MOE_NZ=1 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +# prefill +for i in "${!P_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${P_IP[$i]}" || "$LOCAL_HOST2" == "${P_IP[$i]}" ]]; + then + echo "${P_IP[$i]}" + export HCCL_BUFFSIZE=1536 + export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + export TASK_QUEUE_ENABLE=2 + + export HCCL_SOCKET_IFNAME=lo + export GLOO_SOCKET_IFNAME=lo + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode prefill --host ${P_IP[$i]} \ + --port 8000 --disaggregation-bootstrap-port $((8998+$i)) --trust-remote-code --nnodes 1 --node-rank 0 \ + --tp-size 16 --mem-fraction-static 0.6 --attention-backend ascend --device npu --quantization modelslim \ + --disaggregation-transfer-backend ascend --max-running-requests 8 --context-length 8192 --disable-radix-cache \ + --chunked-prefill-size 32768 --max-prefill-tokens 28680 --moe-a2a-backend deepep --deepep-mode normal \ + --speculative-algorithm NEXTN --speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2 \ + --dp-size 2 --enable-dp-attention --disable-shared-experts-fusion --dtype bfloat16 + NODE_RANK=$i + break + fi +done + +# decode +for i in "${!D_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${D_IP[$i]}" || "$LOCAL_HOST2" == "${D_IP[$i]}" ]]; + then + echo "${D_IP[$i]}" + export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + export SGLANG_ENABLE_SPEC_V2=1 + export HCCL_BUFFSIZE=720 + export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=96 + export TASK_QUEUE_ENABLE=1 + export HCCL_SOCKET_IFNAME=xxx + export GLOO_SOCKET_IFNAME=xxx + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode decode --host ${D_IP[$i]} \ + --port 8001 --trust-remote-code --nnodes 1 --node-rank 0 --tp-size 16 --dp-size 16 \ + --mem-fraction-static 0.8 --max-running-requests 384 --attention-backend ascend --device npu --quantization modelslim \ + --moe-a2a-backend deepep --enable-dp-attention --deepep-mode low_latency --enable-dp-lm-head \ + --cuda-graph-bs 8 10 12 14 16 18 20 22 24 --disaggregation-transfer-backend ascend --watchdog-timeout 9000 --context-length 8192 \ + --speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --prefill-round-robin-balance --disable-shared-experts-fusion --dtype bfloat16 --tokenizer-worker-num 4 \ + --load-balance-method decode_round_robin + NODE_RANK=$i + break + fi +done + +``` + +```shell Command +export SGLANG_DP_ROUND_ROBIN=1 +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://P_IP:8000 8998 \ + --decode http://D_IP:8001 \ + --host 127.0.0.1 \ + --port 6688 \ + --mini-lb +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6688 --max-concurrency 400 --random-input-len 2048 --random-output-len 2048 --num-prompts 3200 --random-range-ratio 1 --request-rate 8 +``` + +### DeepSeek-R1 3_5K-1_5K 50ms on A3 8 Cards Mixed Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +export STREAMS_PER_DEVICE=32 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE=1 +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=36 +export HCCL_BUFFSIZE=1600 +export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 +export SGLANG_NPU_USE_MLAPO=1 +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_USE_FIA_NZ=1 +export ENABLE_MOE_NZ=1 + +MODEL_PATH=xxx + +python3 -m sglang.launch_server --model-path ${MODEL_PATH} \ +--tp 16 \ +--trust-remote-code \ +--attention-backend ascend \ +--device npu \ +--quantization modelslim \ +--watchdog-timeout 9000 \ +--host 127.0.0.1 --port 6699 \ +--cuda-graph-bs 8 16 24 28 32 36 \ +--mem-fraction-static 0.71 \ +--max-running-requests 144 \ +--context-length 8188 --disable-radix-cache --chunked-prefill-size -1 --max-prefill-tokens 9000 \ +--moe-a2a-backend deepep --deepep-mode auto \ +--enable-dp-attention --dp-size 4 --enable-dp-lm-head \ +--speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ +--dtype bfloat16 + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6699 --max-concurrency 144 --random-input-len 3500 --random-output-len 1500 --num-prompts 576 --random-range-ratio 1 +``` + +### DeepSeek-R1 3_5K-1_5K 50ms on A3 16 Cards Separation Mode + +Model: Deepseek R1 + +Hardware: Atlas 800I A3 16Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 + +export ASCEND_MF_STORE_URL="tcp://your prefill ip1:24667" + +P_IP=('your prefill ip1') + +D_IP=('your decode ip1') + +MODEL_PATH=xxx + +export SGLANG_NPU_USE_MLAPO=1 +export SGLANG_USE_FIA_NZ=1 +export ENABLE_MOE_NZ=1 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +# prefill +for i in "${!P_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${P_IP[$i]}" || "$LOCAL_HOST2" == "${P_IP[$i]}" ]]; + then + echo "${P_IP[$i]}" + export HCCL_BUFFSIZE=1536 + export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + export TASK_QUEUE_ENABLE=2 + + export HCCL_SOCKET_IFNAME=lo + export GLOO_SOCKET_IFNAME=lo + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode prefill --host ${P_IP[$i]} \ + --port 8000 --disaggregation-bootstrap-port $((8998+$i)) --trust-remote-code --nnodes 1 --node-rank 0 \ + --tp-size 16 --mem-fraction-static 0.6 --attention-backend ascend --device npu --quantization modelslim \ + --disaggregation-transfer-backend ascend --max-running-requests 8 --context-length 8192 --disable-radix-cache \ + --chunked-prefill-size -1 --max-prefill-tokens 28680 --moe-a2a-backend deepep --deepep-mode normal \ + --speculative-algorithm NEXTN --speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2 \ + --dp-size 2 --enable-dp-attention --disable-shared-experts-fusion --dtype bfloat16 + NODE_RANK=$i + break + fi +done + +# decode +for i in "${!D_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${D_IP[$i]}" || "$LOCAL_HOST2" == "${D_IP[$i]}" ]]; + then + echo "${D_IP[$i]}" + export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + export SGLANG_ENABLE_SPEC_V2=1 + export HCCL_BUFFSIZE=720 + export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=96 + export TASK_QUEUE_ENABLE=1 + export HCCL_SOCKET_IFNAME=xxx + export GLOO_SOCKET_IFNAME=xxx + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode decode --host ${D_IP[$i]} \ + --port 8001 --trust-remote-code --nnodes 1 --node-rank 0 --tp-size 16 --dp-size 16 \ + --mem-fraction-static 0.8 --max-running-requests 384 --attention-backend ascend --device npu --quantization modelslim \ + --moe-a2a-backend deepep --enable-dp-attention --deepep-mode low_latency --enable-dp-lm-head \ + --cuda-graph-bs 8 10 12 14 16 18 20 22 24 --disaggregation-transfer-backend ascend --watchdog-timeout 9000 --context-length 8192 \ + --speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --prefill-round-robin-balance --disable-shared-experts-fusion --dtype bfloat16 --tokenizer-worker-num 4 \ + --load-balance-method decode_round_robin + NODE_RANK=$i + break + fi +done + +``` + +```shell Command +export SGLANG_DP_ROUND_ROBIN=1 +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://P_IP:8000 8998 \ + --decode http://D_IP:8001 \ + --host 127.0.0.1 \ + --port 6688 \ + --mini-lb +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6688 --max-concurrency 384 --random-input-len 3500 --random-output-len 1500 --num-prompts 1536 --random-range-ratio 1 +``` + +### DeepSeek-V3.2-Exp 64K-3K 30ms on A3 32 Cards Separation Mode + +Model: DeepSeek-V3.2-Exp-W8A8 + +Hardware: Atlas 800I A3 32Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 64K+3K + +TPOT: 30ms + +#### Model Deployment + +Deploy Prefill Instance + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING + +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh +export LD_LIBRARY_PATH=/usr/local/Ascend/ascend-toolkit/latest/opp/vendors/customize/op_api/lib/:${LD_LIBRARY_PATH} +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export ASCEND_HOME_PATH=/usr/local/Ascend/ascend-toolkit/latest + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 + +export HCCL_BUFFSIZE=1024 +export DEEPEP_NORMAL_LONG_SEQ_ROUND=5 +export DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS=512 + +MODEL_PATH=xxx + +export SGLANG_NPU_USE_MLAPO=1 +export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 +export SGLANG_NPU_USE_MULTI_STREAM=1 +export HCCL_OP_EXPANSION_MODE=AIV + +IPs=('your prefill ip1' 'your prefill ip2') + +# get IP in current node +LOCAL_HOST=`hostname -I|awk -F " " '{print$1}'` +echo "LOCAL_HOST = " ${LOCAL_HOST} +# get node index +for i in "${!IPs[@]}"; +do + echo "LOCAL_HOST=${LOCAL_HOST}, IPs[${i}]=${IPs[$i]}" + if [ "$LOCAL_HOST" == "${IPs[$i]}" ]; then + echo "Node Rank : ${i}" + VC_TASK_INDEX=$i + break + fi +done + +IFNAMES=('xxx' 'xxx') + +export HCCL_SOCKET_IFNAME=${IFNAMES[$VC_TASK_INDEX]} +export GLOO_SOCKET_IFNAME=${HCCL_SOCKET_IFNAME} +echo "HCCL_SOCKET_IFNAME : ${HCCL_SOCKET_IFNAME}" +nnodes=${#IPs[@]} +tp_size=`expr 16 \* ${nnodes}` +export ASCEND_MF_STORE_URL=tcp://${IPs[0]}:24667 + +python3 -m sglang.launch_server --model-path ${MODEL_PATH} \ +--tp $tp_size \ +--trust-remote-code \ +--attention-backend ascend \ +--device npu \ +--watchdog-timeout 9000 \ +--host ${IPs[$VC_TASK_INDEX]} --port 8000 \ +--mem-fraction-static 0.73 \ +--disable-radix-cache --chunked-prefill-size -1 --max-prefill-tokens 68000 \ +--max-running-requests 1 \ +--moe-a2a-backend deepep --deepep-mode normal \ +--quantization modelslim \ +--disaggregation-transfer-backend ascend \ +--disaggregation-mode prefill \ +--disable-cuda-graph \ +--nnodes $nnodes --node-rank $VC_TASK_INDEX \ +--disaggregation-bootstrap-port 8995 \ +--enable-nsa-prefill-context-parallel --moe-dense-tp-size 1 \ +--speculative-algorithm NEXTN --speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2 \ +--dist-init-addr ${IPs[0]}:10000 +``` + +Deploy Decode Instance + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh +export LD_LIBRARY_PATH=/usr/local/Ascend/ascend-toolkit/latest/opp/vendors/customize/op_api/lib/:${LD_LIBRARY_PATH} +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH +export ASCEND_HOME_PATH=/usr/local/Ascend/ascend-toolkit/latest + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 + +MODEL_PATH=xxx + +export SGLANG_NPU_USE_MULTI_STREAM=1 +export SGLANG_NPU_USE_MLAPO=1 +export HCCL_OP_EXPANSION_MODE=AIV +export SGLANG_SCHEDULER_SKIP_ALL_GATHER=1 +export TASK_QUEUE_ENABLE=0 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +IPs=('your decode ip1' 'your decode ip2') + +export prefill_ip=your prefill ip1 +# get IP in current node +LOCAL_HOST=`hostname -I|awk -F " " '{print$1}'` +echo "LOCAL_HOST = " ${LOCAL_HOST} +# get node index +for i in "${!IPs[@]}"; +do + echo "LOCAL_HOST=${LOCAL_HOST}, IPs[${i}]=${IPs[$i]}" + if [ "$LOCAL_HOST" == "${IPs[$i]}" ]; then + echo "Node Rank : ${i}" + VC_TASK_INDEX=$i + break + fi +done + +IFNAMES=('xxx' 'xxx') + +export HCCL_SOCKET_IFNAME=${IFNAMES[$VC_TASK_INDEX]} +export GLOO_SOCKET_IFNAME=${HCCL_SOCKET_IFNAME} +nnodes=${#IPs[@]} +tp_size=`expr 16 \* ${nnodes}` +export ASCEND_MF_STORE_URL=tcp://${prefill_ip}:24667 + +CHUNKED_SIZE=65536 +DP=8 +export HCCL_BUFFSIZE=400 +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=8 + +python3 -m sglang.launch_server --model-path ${MODEL_PATH} \ +--tp $tp_size \ +--dp ${DP} \ +--ep $tp_size \ +--moe-dense-tp-size 1 \ +--enable-dp-attention \ +--enable-dp-lm-head \ +--trust-remote-code \ +--attention-backend ascend \ +--device npu \ +--watchdog-timeout 9000 \ +--host ${IPs[$VC_TASK_INDEX]} --port 8001 \ +--mem-fraction-static 0.79 \ +--disable-radix-cache \ +--chunked-prefill-size -1 --max-prefill-tokens 68000 \ +--max-running-requests 32 \ +--cuda-graph-max-bs 4 \ +--moe-a2a-backend deepep \ +--deepep-mode low_latency \ +--quantization modelslim \ +--speculative-algorithm NEXTN --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ +--disaggregation-transfer-backend ascend \ +--disaggregation-mode decode \ +--prefill-round-robin-balance \ +--load-balance-method round_robin \ +--nnodes $nnodes --node-rank $VC_TASK_INDEX \ +--dist-init-addr ${IPs[0]}:10000 --load-balance-method decode_round_robin +``` + +```shell Command +export SGLANG_DP_ROUND_ROBIN=1 +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://PIP1:8000 8995 \ + --decode http://DIP1:8001 \ + --host 127.0.0.1 \ + --port 6688 \ + --mini-lb +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6688 --max-concurrency 32 --random-input-len 64000 --random-output-len 3000 --num-prompts 64 --random-range-ratio 1 +``` + +### Qwen3-235B-A22B 3_5K-1_5K 50ms on A3 24 Cards Separation Mode + +Model: Qwen3-235B-A22B-W8A8 + +Hardware: Atlas 800I A3 24Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING + +source /usr/local/Ascend/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=16 + +MODEL_PATH=xxx +export ASCEND_MF_STORE_URL="tcp://your prefill ip1:24667" +P_IP=('your prefill ip1') +D_IP=('your decode ip1' 'your decode ip2') +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_DP_ROUND_ROBIN=1 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + + +for i in "${!P_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${P_IP[$i]}" || "$LOCAL_HOST2" == "${P_IP[$i]}" ]]; + then + echo "${P_IP[$i]}" + source /usr/local/Ascend/ascend-toolkit/set_env.sh + source /usr/local/Ascend/nnal/atb/set_env.sh + export DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS=1024 + export DEEPEP_NORMAL_LONG_SEQ_ROUND=16 + export HCCL_BUFFSIZE=4300 + export TASK_QUEUE_ENABLE=2 + export HCCL_SOCKET_IFNAME=lo + export GLOO_SOCKET_IFNAME=lo + export STREAMS_PER_DEVICE=32 + export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + + # P节点 + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode prefill \ + --host ${P_IP[$i]} --port 8000 --disaggregation-bootstrap-port 8995 --trust-remote-code \ + --nnodes 1 --node-rank $i --tp-size 16 --dp-size 16 --mem-fraction-static 0.6 \ + --disable-radix-cache \ + --attention-backend ascend --device npu --quantization modelslim --disaggregation-transfer-backend ascend \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --speculative-draft-model-quantization unquant \ + --max-running-requests 128 --chunked-prefill-size 262144 --max-prefill-tokens 262144 \ + --enable-dp-attention \ + --moe-a2a-backend deepep --deepep-mode normal --dtype bfloat16 + NODE_RANK=$i + break + fi +done + + +for i in "${!D_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${D_IP[$i]}" || "$LOCAL_HOST2" == "${D_IP[$i]}" ]]; + then + echo "${D_IP[$i]}" + source /usr/local/Ascend/ascend-toolkit/set_env.sh + source /usr/local/Ascend/nnal/atb/set_env.sh + export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=24 + export HCCL_BUFFSIZE=512 + export HCCL_SOCKET_IFNAME=data0.3001 + export GLOO_SOCKET_IFNAME=data0.3001 + export STREAMS_PER_DEVICE=32 + + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode decode \ + --host ${D_IP[$i]} --port 8001 --trust-remote-code \ + --nnodes 2 --node-rank $i --tp-size 32 --dp-size 32 --mem-fraction-static 0.83 --max-running-requests 768 \ + --attention-backend ascend --device npu --quantization modelslim --enable-dp-attention \ + --moe-a2a-backend ascend_fuseep --cuda-graph-bs 6 8 12 15 18 20 22 24 \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-draft-model-quantization unquant \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --dist-init-addr xxx:5000 \ + --disaggregation-transfer-backend ascend --watchdog-timeout 9000 --context-length 8192 \ + --prefill-round-robin-balance --enable-dp-lm-head --dtype bfloat16 --tokenizer-worker-num 4 \ + --load-balance-method decode_round_robin + NODE_RANK=$i + break + fi +done + +``` + +```shell Command +export SGLANG_DP_ROUND_ROBIN=1 +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://PIP:8000 8995 \ + --decode http://DIP:8001 \ + --host 127.0.0.1 \ + --port 6688 \ + --mini-lb +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang-oai --host 127.0.0.1 --port 7239 --max-concurrency 860 --random-input-len 3500 --random-output-len 1500 --num-prompts 3440 --random-range-ratio 1 +``` + +### Qwen3-235B-A22B 3_5K-1_5K 50ms on A3 8 Cards Mixed Mode + +Model: Qwen3-235B-A22B-W8A8 + +Hardware: Atlas 800I A3 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=1600 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_SCHEDULER_DECREASE_PREFILL_IDLE=2 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7439 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 272 --context-length 8192 --dtype bfloat16 \ + --chunked-prefill-size 32768 --max-prefill-tokens 32768 \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --disable-radix-cache --moe-a2a-backend deepep --deepep-mode auto --speculative-draft-model-quantization unquant \ + --tp 16 --dp-size 16 --enable-dp-attention --enable-dp-lm-head --mem-fraction-static 0.8 --cuda-graph-bs 3 4 6 8 10 12 13 14 15 16 17 + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 272 --random-input-len 3500 --random-output-len 1500 --num-prompts 1088 --random-range-ratio 1 +``` + +### Qwen3-235B-A22B 2K-2K 100ms on A3 8 Cards Mixed Mode + +Model: Qwen3-235B-A22B-W8A8 + +Hardware: Atlas 800I A3 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 2K+2K + +TPOT: 100ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=1200 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7439 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 576 --context-length 8192 --dtype bfloat16 \ + --chunked-prefill-size 32768 --max-prefill-tokens 458880 \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --disable-radix-cache --moe-a2a-backend deepep --deepep-mode auto --speculative-draft-model-quantization unquant \ + --tp 16 --dp-size 16 --enable-dp-attention --enable-dp-lm-head --mem-fraction-static 0.81 --cuda-graph-bs 8 16 20 24 32 36 + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 576 --random-input-len 2000 --random-output-len 2000 --num-prompts 576 --random-range-ratio 1 +``` + +### Qwen3-235B-A22B 2K-2K 50ms on A3 8 Cards Mixed Mode + +Model: Qwen3-235B-A22B-W8A8 + +Hardware: Atlas 800I A3 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 2K+2K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=2100 +export HCCL_SOCKET_IFNAME=xxx +export GLOO_SOCKET_IFNAME=xxx +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7439 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 480 --context-length 8192 --dtype bfloat16 \ + --chunked-prefill-size -1 --max-prefill-tokens 4096 --speculative-draft-model-quantization unquant \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --disable-radix-cache --moe-a2a-backend deepep --deepep-mode auto \ + --tp 16 --dp-size 16 --enable-dp-attention --enable-dp-lm-head --mem-fraction-static 0.75 --cuda-graph-bs 6 8 10 12 15 18 28 30 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 480 --random-input-len 2048 --random-output-len 2048 --num-prompts 480 --random-range-ratio 1 +``` + +### Qwen3-235B-A22B 2K-2K 50ms on A3 16 Cards Mixed Mode + +Model: Qwen3-235B-A22B-W8A8 + +Hardware: Atlas 800I A3 16Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 2K+2K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=1600 +export HCCL_SOCKET_IFNAME=xxx +export GLOO_SOCKET_IFNAME=xxx +export HCCL_OP_EXPANSION_MODE="AIV" + +MIX_IP=('IP1' 'IP2') + +for i in "${!MIX_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${MIX_IP[$i]}" || "$LOCAL_HOST2" == "${MIX_IP[$i]}" ]]; + then + echo "${MIX_IP[$i]}" + export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + export SGLANG_ENABLE_SPEC_V2=1 + + python -m sglang.launch_server --model-path ${MODEL_PATH} \ + --host 127.0.0.1 --port 7439 --trust-remote-code \ + --nnodes 2 --node-rank $i --tp-size 32 --dp-size 32 --mem-fraction-static 0.8 --max-running-requests 768 \ + --attention-backend ascend --device npu --quantization modelslim --enable-dp-attention \ + --moe-a2a-backend deepep --deepep-mode auto --cuda-graph-bs 6 8 10 12 18 24 \ + --dist-init-addr ${MIX_IP[0]}:5000 --chunked-prefill-size 131072 --max-prefill-tokens 458880 \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx --speculative-draft-model-quantization= unquant \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --context-length 8192 --disable-radix-cache \ + --enable-dp-lm-head --dtype bfloat16 + NODE_RANK=$i + break + fi +done + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 768 --random-input-len 2000 --random-output-len 2000 --num-prompts 768 --random-range-ratio 1 +``` + +### Qwen3-235B-A22B 11K-1K 10ms on A3 8 Cards Mixed Mode + +Model: Qwen3-235B-A22B-W8A8 + +Hardware: Atlas 800I A3 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 11K+1K + +TPOT: 10ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=1600 +export HCCL_SOCKET_IFNAME=xxx +export GLOO_SOCKET_IFNAME=xxx +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7439 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 1 --dtype bfloat16 \ + --chunked-prefill-size -1 --max-prefill-tokens 16384 --speculative-draft-model-quantization unquant \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 4 --speculative-eagle-topk 1 --speculative-num-draft-tokens 5 \ + --disable-radix-cache --enable-dp-lm-head \ + --tp 16 --mem-fraction-static 0.78 --cuda-graph-bs 1 + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 1 --random-input-len 11000 --random-output-len 1000 --num-prompts 1 --random-range-ratio 1 +``` + +### Qwen3-32B 6K-1_5K 18ms on A3 4 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A3 4Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 6K+1.5K + +TPOT: 18ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=xxx +export GLOO_SOCKET_IFNAME=xxx +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7439 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu \ + --max-running-requests 32 \ + --disable-radix-cache \ + --chunked-prefill-size 24576 --max-prefill-tokens 65536 \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 4 --speculative-eagle-topk 1 --speculative-num-draft-tokens 5 \ + --tp-size 8 --mem-fraction-static 0.72 --cuda-graph-bs 8 16 24 32 --dtype bfloat16 + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 32 --random-output-len 1500 --random-input-len 6000 --num-prompts 32 --random-range-ratio 1 +``` + +### Qwen3-32B 4K-1_5K 11ms on A3 4 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A3 4Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 4K+1.5K + +TPOT: 11ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7339 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu \ + --max-running-requests 1 \ + --disable-radix-cache \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 4 --speculative-eagle-topk 1 --speculative-num-draft-tokens 5 \ + --chunked-prefill-size 24576 --max-prefill-tokens 65536 \ + --tp-size 8 --mem-fraction-static 0.72 --cuda-graph-bs 1 --dtype bfloat16 + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7239 --random-range-ratio 1 --max-concurrency 1 --random-output-len 1500 --random-input-len 4096 --num-prompts 4 +``` + +### Qwen3-32B 18K-4K 12ms on A3 8 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A3 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 18K+4K + +TPOT: 12ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7339 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu \ + --max-running-requests 1 \ + --disable-radix-cache --speculative-draft-model-quantization unquant \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 4 --speculative-eagle-topk 1 --speculative-num-draft-tokens 5 \ + --chunked-prefill-size -1 --max-prefill-tokens 65536 \ + --tp-size 16 --mem-fraction-static 0.72 --cuda-graph-bs 1 --dtype bfloat16 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7339 --random-range-ratio 1 --max-concurrency 1 --random-output-len 18000 --random-input-len 4000 --num-prompts 1 +``` + +### Qwen3-32B 3_5K-1_5K 50ms on A3 2 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A3 2Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7239 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 78 \ + --disable-radix-cache --speculative-draft-model-quantization unquant \ + --chunked-prefill-size -1 --max-prefill-tokens 49152 \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --tp-size 4 --mem-fraction-static 0.72 --cuda-graph-bs 16 32 64 68 72 78 --dtype bfloat16 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7239 --max-concurrency 78 --random-output-len 1500 --random-input-len 3500 --num-prompts 312 --random-range-ratio 1 +``` + +### Qwen3-32B 2K-2K 50ms on A3 2 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A3 2Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 2K+2K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7239 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 120 \ + --disable-radix-cache --speculative-draft-model-quantization unquant \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --chunked-prefill-size -1 --max-prefill-tokens 49152 \ + --tp-size 4 --mem-fraction-static 0.7 --cuda-graph-bs 54 60 66 72 78 84 90 108 114 120 --dtype bfloat16 + +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7239 --max-concurrency 120 --random-output-len 2000 --random-input-len 2000 --num-prompts 480 --random-range-ratio 1 +``` + +### Qwen3-30B-A3B 3_5K-1_5K 50ms on A3 1 Card Mixed Mode + +Model: Qwen3-30B-A3B-Instruct-2507 + +Hardware: Atlas 800I A3 1Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7239 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 192 \ + --disable-radix-cache \ + --speculative-draft-model-quantization unquant \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --chunked-prefill-size -1 --max-prefill-tokens 32768 \ + --tp-size 2 --mem-fraction-static 0.86 --cuda-graph-bs 42 88 96 132 144 156 172 178 192 --dtype bfloat16 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7239 --max-concurrency 156 --random-input-len 3500 --random-output-len 1500 --num-prompts 624 --random-range-ratio 1 +``` + +### Qwen3-Coder-480B-A35B-Instruct 3_5K-1_5K 50ms on A3 24 Cards Separation Mode + +Model: Qwen3-Coder-480B-A35B-Instruct + +Hardware: Atlas 800I A3 24Card + +DeployMode: PD Separation + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING + +source /usr/local/Ascend/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=16 + +MODEL_PATH=xxx +export ASCEND_MF_STORE_URL="tcp://PIP:24667" +P_IP=('PIP') +D_IP=('DIP1' 'DIP2') +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + + +for i in "${!P_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${P_IP[$i]}" || "$LOCAL_HOST2" == "${P_IP[$i]}" ]]; + then + echo "${P_IP[$i]}" + source /usr/local/Ascend/ascend-toolkit/set_env.sh + source /usr/local/Ascend/nnal/atb/set_env.sh + export DEEPEP_NORMAL_LONG_SEQ_PER_ROUND_TOKENS=1024 + export DEEPEP_NORMAL_LONG_SEQ_ROUND=16 + export HCCL_BUFFSIZE=4300 + export TASK_QUEUE_ENABLE=2 + export HCCL_SOCKET_IFNAME=lo + export GLOO_SOCKET_IFNAME=lo + export STREAMS_PER_DEVICE=32 + export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode prefill \ + --host ${P_IP[$i]} --port 8000 --disaggregation-bootstrap-port 8995 --trust-remote-code \ + --nnodes 1 --node-rank $i --tp-size 16 --dp-size 2 --mem-fraction-static 0.6 \ + --disable-radix-cache \ + --attention-backend ascend --device npu --quantization modelslim --disaggregation-transfer-backend ascend \ + --max-running-requests 128 --chunked-prefill-size 65536 --max-prefill-tokens 262144 \ + --enable-dp-attention \ + --moe-a2a-backend deepep --deepep-mode normal --dtype bfloat16 + NODE_RANK=$i + break + fi +done + +for i in "${!D_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${D_IP[$i]}" || "$LOCAL_HOST2" == "${D_IP[$i]}" ]]; + then + echo "${D_IP[$i]}" + source /usr/local/Ascend/ascend-toolkit/set_env.sh + source /usr/local/Ascend/nnal/atb/set_env.sh + export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=72 + export HCCL_BUFFSIZE=512 + export HCCL_SOCKET_IFNAME=xxx + export GLOO_SOCKET_IFNAME=xxx + export STREAMS_PER_DEVICE=32 + + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode decode \ + --host ${D_IP[$i]} --port 8001 --trust-remote-code \ + --nnodes 2 --node-rank $i --tp-size 32 --dp-size 4 --mem-fraction-static 0.73 --max-running-requests 384 \ + --attention-backend ascend --device npu --quantization modelslim --enable-dp-attention \ + --moe-a2a-backend ascend_fuseep --cuda-graph-bs 16 32 48 56 64 72 80 88 96 \ + --dist-init-addr DIP1:5000 \ + --disaggregation-transfer-backend ascend --watchdog-timeout 9000 --context-length 8192 \ + --prefill-round-robin-balance --enable-dp-lm-head --dtype bfloat16 --tokenizer-worker-num 4 --load-balance-method decode_round_robin + NODE_RANK=$i + break + fi +done + +``` + +```shell Command +export SGLANG_DP_ROUND_ROBIN=1 +python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://PIP:8000 8995 \ + --decode http://DIP:8001 \ + --host 127.0.0.1 \ + --port 6688 \ + --mini-lb +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7239 --max-concurrency 410 --random-input-len 3500 --random-output-len 1500 --num-prompts 1640 --random-range-ratio 1 --request-rate 8 +``` + +### Qwen3-Coder-480B-A35B-Instruct 3_5K-1_5K 50ms on A3 16 Cards Mixed Mode + +Model: Qwen3-Coder-480B-A35B-Instruct + +Hardware: Atlas 800I A3 16Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=16 + +export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=1800 +export HCCL_SOCKET_IFNAME=xxx +export GLOO_SOCKET_IFNAME=xxx +export HCCL_OP_EXPANSION_MODE="AIV" + +MIX_IP=('IP1' 'IP2') + +for i in "${!MIX_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${MIX_IP[$i]}" || "$LOCAL_HOST2" == "${MIX_IP[$i]}" ]]; + then + echo "${MIX_IP[$i]}" + + python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7439 --trust-remote-code --nnodes 2 --node-rank $i \ + --dist-init-addr 141.61.133.128:5000 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 288 --context-length 8192 --dtype bfloat16 \ + --chunked-prefill-size 114688 --max-prefill-tokens 458880 \ + --disable-radix-cache --moe-a2a-backend deepep --deepep-mode auto \ + --tp 32 --dp-size 4 --enable-dp-attention --enable-dp-lm-head --mem-fraction-static 0.7 --cuda-graph-bs 56 64 72 + NODE_RANK=$i + break + fi +done +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 288 --random-input-len 3500 --random-output-len 1500 --num-prompts 1152 --random-range-ratio 1 --request-rate 20 +``` + +### Qwen3-Coder-480B-A35B-Instruct 3_5K-1_5K 50ms on A3 8 Cards Mixed Mode + +Model: Qwen3-Coder-480B-A35B-Instruct + +Hardware: Atlas 800I A3 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=2100 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" + +python -m sglang.launch_server --model-path $MODEL_PATH \ +--host 127.0.0.1 --port 7439 --trust-remote-code --nnodes 1 --node-rank 0 \ +--attention-backend ascend --device npu --quantization modelslim \ +--max-running-requests 80 --context-length 8192 --dtype bfloat16 \ +--chunked-prefill-size 28672 --max-prefill-tokens 458880 \ +--disable-radix-cache --moe-a2a-backend deepep --deepep-mode auto --enable-dp-attention --enable-dp-lm-head \ +--tp 16 --dp-size 4 --mem-fraction-static 0.7 --cuda-graph-bs 16 20 24 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 80 --random-input-len 3500 --random-output-len 1500 --num-prompts 320 --random-range-ratio 1 +``` + +### Qwen3-Next-80B-A3B-Instruct 3_5K-1_5K 50ms on A3 2 Cards Mixed Mode + +Model: Qwen3-Next-80B-A3B-Instruct + +Hardware: Atlas 800I A3 2Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +export cann_path=/usr/local/Ascend/ascend-toolkit/latest +source /usr/local/Ascend/driver/bin/setenv.bash +source ${cann_path}/../set_env.sh +source ${cann_path}/../../nnal/atb/set_env.sh +source ${cann_path}/opp/vendors/customize/bin/set_env.bash +export ASCEND_HOME_PATH=${cann_path} +source /usr/local/Ascend/8.5.0/bisheng_toolkit/set_env.sh + +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo + +export HCCL_OP_EXPANSION_MODE=AIV +export HCCL_ALGO="level0:NA;level1:ring" + +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=20 +export HCCL_BUFFSIZE=2000 + +python -m sglang.launch_server \ + --model-path /path/to/Qwen3-Next-80B-A3B-Instruct-W8A8-3 \ + --host 127.0.0.1 \ + --port 6699 \ + --tp-size 4 \ + --device npu \ + --attention-backend ascend \ + --mem-fraction-static 0.685 \ + --max-running-requests 80 \ + --watchdog-timeout 3600 \ + --disable-radix-cache \ + --cuda-graph-bs 80 \ + --max-prefill-tokens 28672 --max-total-tokens 450560 \ + --moe-a2a-backend deepep --deepep-mode auto \ + --quantization modelslim \ + --chunked-prefill-size -1 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 6699 --max-concurrency 80 --random-output-len 1536 --random-input-len 3584 --num-prompts 160 --random-range-ratio 1 +``` + +### Qwen3-32B 6K-1_5K 18ms on A2 8 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A2 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 6K+1.5K + +TPOT: 18ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7439 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 32 \ + --disable-radix-cache \ + --chunked-prefill-size 24576 --max-prefill-tokens 65536 \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 4 --speculative-eagle-topk 1 --speculative-num-draft-tokens 5 \ + --tp-size 8 --mem-fraction-static 0.72 --cuda-graph-bs 8 16 24 32 --dtype bfloat16 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7439 --max-concurrency 32 --random-output-len 1500 --random-input-len 6000 --num-prompts 32 --random-range-ratio 1 +``` + +### Qwen3-32B 4K-1_5K 11ms on A2 8 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A2 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 4K+1.5K + +TPOT: 11ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7339 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu \ + --max-running-requests 32 \ + --disable-radix-cache \ + --speculative-draft-model-quantization unquant \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 4 --speculative-eagle-topk 1 --speculative-num-draft-tokens 5 \ + --chunked-prefill-size -1 --max-prefill-tokens 65536 \ + --tp-size 8 --mem-fraction-static 0.72 --cuda-graph-bs 1 4 6 12 18 24 30 32 --dtype bfloat16 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7339 --random-range-ratio 1 --max-concurrency 1 --random-output-len 1500 --random-input-len 4096 --num-prompts 4 +``` + +### Qwen3-32B 3_5K-1_5K 50ms on A2 8 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A2 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 3.5K+1.5K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7239 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 78 \ + --disable-radix-cache --speculative-draft-model-quantization unquant \ + --chunked-prefill-size -1 --max-prefill-tokens 65536 \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 \ + --tp-size 4 --mem-fraction-static 0.72 --cuda-graph-bs 1 4 8 16 32 64 68 72 78 --dtype bfloat16 --base-gpu-id 4 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7239 --max-concurrency 78 --random-output-len 1500 --random-input-len 3500 --num-prompts 312 --random-range-ratio 1 +``` + +### Qwen3-32B 2K-2K 50ms on A2 8 Cards Mixed Mode + +Model: Qwen3-32B + +Hardware: Atlas 800I A2 8Card + +DeployMode: PD Mixed + +Dataset: random + +Input Output Length: 2K+2K + +TPOT: 50ms + +#### Model Deployment + +```shell Command +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 + +export SGLANG_SET_CPU_AFFINITY=1 +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset 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/ascend-toolkit/latest/opp/vendors/customize/bin/set_env.bash +export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + +MODEL_PATH=xxx + +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + +echo "${LOCAL_HOST1}" +echo "${LOCAL_HOST2}" + +export HCCL_BUFFSIZE=400 +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo +export HCCL_OP_EXPANSION_MODE="AIV" +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server --model-path $MODEL_PATH \ + --host 127.0.0.1 --port 7239 --trust-remote-code --nnodes 1 --node-rank 0 \ + --attention-backend ascend --device npu --quantization modelslim \ + --max-running-requests 120 \ + --disable-radix-cache \ + --speculative-algorithm EAGLE3 --speculative-draft-model-path xxx \ + --speculative-num-steps 3 --speculative-eagle-topk 1 --speculative-num-draft-tokens 4 --speculative-draft-model-quantization unquant \ + --chunked-prefill-size -1 --max-prefill-tokens 49152 --base-gpu-id 4 \ + --tp-size 4 --mem-fraction-static 0.7 --cuda-graph-bs 54 60 66 72 78 84 90 108 114 120 --dtype bfloat16 +``` + +#### Benchmark + +We tested it based on the `RANDOM` dataset. + +```shell Command +python3 -m sglang.bench_serving --dataset-name random --backend sglang --host 127.0.0.1 --port 7239 --max-concurrency 120 --random-output-len 2000 --random-input-len 2000 --num-prompts 120 --random-range-ratio 1 +``` diff --git a/docs_new/docs/hardware-platforms/ascend-npus/DeepSeek-Examples.mdx b/docs_new/docs/hardware-platforms/ascend-npus/DeepSeek-Examples.mdx new file mode 100644 index 000000000..243a3897b --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/DeepSeek-Examples.mdx @@ -0,0 +1,309 @@ +## Running DeepSeek-V3 + +### Running DeepSeek in PD mixed mode on 1 x Atlas 800I A3 + +W4A8 Model weights could be found [here](https://modelers.cn/models/Modelers_Park/DeepSeek-R1-0528-w4a8). + + +```shell Launch Server +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 + +#Deepep communication settings +export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=32 +export HCCL_BUFFSIZE=1600 + +#spec overlap +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + +#npu acceleration operator +export SGLANG_NPU_USE_MLAPO=1 +export SGLANG_USE_FIA_NZ=1 + +python3 -m sglang.launch_server \ + --model-path ${MODEL_PATH} \ + --tp 16 \ + --trust-remote-code \ + --attention-backend ascend \ + --device npu \ + --quantization modelslim \ + --watchdog-timeout 9000 \ + --cuda-graph-bs 8 16 24 28 32 \ + --mem-fraction-static 0.68 \ + --max-running-requests 128 \ + --context-length 8188 \ + --disable-radix-cache \ + --chunked-prefill-size -1 \ + --max-prefill-tokens 16384 \ + --moe-a2a-backend deepep \ + --deepep-mode auto \ + --enable-dp-attention \ + --dp-size 4 \ + --enable-dp-lm-head \ + --speculative-algorithm NEXTN \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 \ + --dtype bfloat16 +``` + + +### Running DeepSeek with PD disaggregation mode on 2 x Atlas 800I A3 + +W4A8 Model weights could be found [here](https://modelers.cn/models/Modelers_Park/DeepSeek-R1-0528-w4a8). + + + + ```shell Command + export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + export STREAMS_PER_DEVICE=32 + + #memfabric config store + export ASCEND_MF_STORE_URL="tcp://:" + + #Deepep communication settings + export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + export HCCL_BUFFSIZE=1536 + + #npu acceleration operator + export SGLANG_NPU_USE_MLAPO=1 + export SGLANG_USE_FIA_NZ=1 + export TASK_QUEUE_ENABLE=2 + + python -m sglang.launch_server \ + --model-path ${MODEL_PATH} \ + --host $PREFILL_HOST_IP \ + --port 8000 \ + --disaggregation-mode prefill \ + --disaggregation-bootstrap-port 8996 \ + --disaggregation-transfer-backend ascend \ + --trust-remote-code \ + --nnodes 1 \ + --node-rank 0 \ + --tp-size 16 \ + --mem-fraction-static 0.6 \ + --attention-backend ascend \ + --device npu \ + --quantization modelslim \ + --load-balance-method round_robin \ + --max-running-requests 8 \ + --context-length 8192 \ + --disable-radix-cache \ + --chunked-prefill-size -1 \ + --max-prefill-tokens 28680 \ + --moe-a2a-backend deepep \ + --deepep-mode normal \ + --speculative-algorithm NEXTN \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 \ + --dp-size 2 \ + --enable-dp-attention \ + --disable-shared-experts-fusion \ + --dtype bfloat16 + ``` + + + + + ```shell Command + export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + export STREAMS_PER_DEVICE=32 + + #memfabric config store + export ASCEND_MF_STORE_URL="tcp://:" + + #Deepep communication settings + export HCCL_BUFFSIZE=720 + export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=88 + + #spec overlap + export SGLANG_ENABLE_SPEC_V2=1 + export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + + #npu acceleration operator + unset TASK_QUEUE_ENABLE + export SGLANG_NPU_USE_MLAPO=1 + export SGLANG_USE_FIA_NZ=1 + export ENABLE_MOE_NZ=1 + + # suggest max-running-requests <= max-cuda-graph-bs * dp_size, Because when this value is exceeded, performance will significantly degrade. + python -m sglang.launch_server \ + --model-path ${MODEL_PATH} \ + --disaggregation-mode decode \ + --host $DECODE_HOST_IP \ + --port 8001 \ + --trust-remote-code \ + --nnodes 1 \ + --node-rank 0 \ + --tp-size 16 \ + --dp-size 16 \ + --mem-fraction-static 0.8 \ + --max-running-requests 352 \ + --attention-backend ascend \ + --device npu \ + --quantization modelslim \ + --prefill-round-robin-balance \ + --moe-a2a-backend deepep \ + --enable-dp-attention \ + --deepep-mode low_latency \ + --enable-dp-lm-head \ + --cuda-graph-bs 8 10 12 14 16 18 20 22 \ + --disaggregation-transfer-backend ascend \ + --watchdog-timeout 9000 \ + --context-length 8192 \ + --speculative-algorithm NEXTN \ + --speculative-num-steps 3 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 4 \ + --disable-shared-experts-fusion \ + --dtype bfloat16 \ + --tokenizer-worker-num 4 + ``` + + + + + ```shell Command + python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://:8000 8996 \ + --decode http://:8001 \ + --host 127.0.0.1 \ + --port 6688 + ``` + + + +### Running DeepSeek with PD disaggregation on 4 x Atlas 800I A3 + +W8A8 Model weights could be found [here](https://modelers.cn/models/State_Cloud/Deepseek-R1-bf16-hfd-w8a8). + + + + ```shell Command + 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 + export SGLANG_SET_CPU_AFFINITY=1 + unset ASCEND_LAUNCH_BLOCKING + source /usr/local/Ascend/ascend-toolkit/set_env.sh + source /usr/local/Ascend/nnal/atb/set_env.sh + export PATH=/usr/local/Ascend/8.5.0/compiler/bishengir/bin:$PATH + + export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True + export STREAMS_PER_DEVICE=32 + + export ASCEND_MF_STORE_URL="tcp://your prefill ip1:24669" + + P_IP=('your prefill ip1' 'your prefill ip2') + + D_IP=('your decode ip1' 'your decode ip2') + + MODEL_PATH=xxx + + export SGLANG_NPU_USE_MLAPO=1 + export SGLANG_USE_FIA_NZ=1 + + LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` + LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` + echo "${LOCAL_HOST1}" + echo "${LOCAL_HOST2}" + # prefill + for i in "${!P_IP[@]}"; + do + if [[ "$LOCAL_HOST1" == "${P_IP[$i]}" || "$LOCAL_HOST2" == "${P_IP[$i]}" ]]; + then + echo "${P_IP[$i]}" + export HCCL_BUFFSIZE=1536 + export DEEP_NORMAL_MODE_USE_INT8_QUANT=1 + export TASK_QUEUE_ENABLE=2 + + export HCCL_SOCKET_IFNAME=lo + export GLOO_SOCKET_IFNAME=lo + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode prefill --host ${P_IP[$i]} \ + --port 8000 --disaggregation-bootstrap-port $((8998+$i)) --trust-remote-code --nnodes 1 --node-rank 0 \ + --tp-size 16 --mem-fraction-static 0.81 --attention-backend ascend --device npu --quantization modelslim \ + --disaggregation-transfer-backend ascend --max-running-requests 8 --context-length 8192 --disable-radix-cache \ + --chunked-prefill-size -1 --max-prefill-tokens 28680 --moe-a2a-backend deepep --deepep-mode normal \ + --speculative-algorithm NEXTN --speculative-num-steps 1 --speculative-eagle-topk 1 --speculative-num-draft-tokens 2 \ + --dp-size 2 --enable-dp-attention --disable-shared-experts-fusion --dtype bfloat16 --enable-attn-tp-input-scattered + NODE_RANK=$i + break + fi + done + + # decode + for i in "${!D_IP[@]}"; + do + if [[ "$LOCAL_HOST1" == "${D_IP[$i]}" || "$LOCAL_HOST2" == "${D_IP[$i]}" ]]; + then + echo "${D_IP[$i]}" + export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + export SGLANG_ENABLE_SPEC_V2=1 + export HCCL_BUFFSIZE=650 + export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=78 + export TASK_QUEUE_ENABLE=1 + export SGLANG_SCHEDULER_SKIP_ALL_GATHER=1 + export HCCL_SOCKET_IFNAME=xxx + export GLOO_SOCKET_IFNAME=xxx + python -m sglang.launch_server --model-path ${MODEL_PATH} --disaggregation-mode decode --host ${D_IP[$i]} \ + --port 8001 --trust-remote-code --dist-init-addr ${D_IP[0]}:5000 --nnodes 2 --node-rank $i --tp-size 32 --dp-size 32 \ + --mem-fraction-static 0.815 --max-running-requests 832 --attention-backend ascend --device npu --quantization modelslim \ + --moe-a2a-backend deepep --enable-dp-attention --deepep-mode low_latency --enable-dp-lm-head --moe-dense-tp 1 \ + --cuda-graph-bs 12 14 16 18 20 22 24 26 --disaggregation-transfer-backend ascend --watchdog-timeout 9000 --context-length 8192 \ + --speculative-algorithm NEXTN --speculative-num-steps 2 --speculative-eagle-topk 1 --speculative-num-draft-tokens 3 \ + --tokenizer-worker-num 4 --prefill-round-robin-balance --disable-shared-experts-fusion --dtype bfloat16 \ + --load-balance-method decode_round_robin + NODE_RANK=$i + break + fi + done + ``` + + + + + ```shell Command + export SGLANG_DP_ROUND_ROBIN=1 + python -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://P_IP:8000 8998 \ + --prefill http://P_IP:8000 8999 \ + --decode http://D_IP:8001 \ + --host 127.0.0.1 \ + --port 6688 \ + --mini-lb + ``` + + + +### Test GSM8K + + +```python Test GSM8K +from types import SimpleNamespace +from sglang.test.few_shot_gsm8k import run_eval + +def gsm8k(): + args = SimpleNamespace( + num_shots=5, + data_path=None, + num_questions=200, + max_new_tokens=512, + parallel=32, + host=f"http://127.0.0.1", + port=6688, + ) + metrics = run_eval(args) + print(f"{metrics=}") + print(f"{metrics['accuracy']=}") +if __name__ == "__main__": + gsm8k() +``` + diff --git a/docs_new/docs/hardware-platforms/ascend-npus/GLM-5.mdx b/docs_new/docs/hardware-platforms/ascend-npus/GLM-5.mdx new file mode 100644 index 000000000..783cbf122 --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/GLM-5.mdx @@ -0,0 +1,200 @@ +## Introduction + +The GLM (General Language Model) series is an open-source bilingual large language model family jointly developed by the KEG Laboratory of Tsinghua University and Zhipu AI. This series of models has performed outstandingly in the field of Chinese NLP with its unique unified pre-training framework and bilingual capabilities. [GLM-5](https://huggingface.co/zai-org/GLM-5) adopts the DeepSeek-V3/V3.2 architecture, including the sparse attention (DSA) and multi-token prediction (MTP). Ascend supports GLM-5 with 0Day based on the SGLang inference framework, achieving low-code seamless enablement and compatibility with the mainstream distributed parallel capabilities within the current SGLang framework. We welcome developers to download and experience it. + +## Environment Preparation + +### Model Weight + +- `GLM-5.0`(BF16 version): [Download model weight](https://www.modelscope.cn/models/ZhipuAI/GLM-5). +- `GLM-5.0-w4a8`(Quantized version without mtp): [Download model weight](https://modelers.cn/models/Eco-Tech/GLM-5-w4a8). +- You can use [msmodelslim](https://gitcode.com/Ascend/msmodelslim) to quantify the model naively. + + +### Installation + +The dependencies required for the NPU runtime environment have been integrated into a Docker image and uploaded to the quay.io platform. You can directly pull it. + + +```bash Pull and Start Container +#Atlas 800 A3 +docker pull swr.cn-southwest-2.myhuaweicloud.com/base_image/dockerhub/lmsysorg/sglang:cann8.5.0-a3-glm5 +#Atlas 800 A2 +docker pull swr.cn-southwest-2.myhuaweicloud.com/base_image/dockerhub/lmsysorg/sglang:cann8.5.0-910b-glm5 + +#start container +docker run -itd --shm-size=16g --privileged=true --name ${NAME} \ +--privileged=true --net=host \ +-v /var/queue_schedule:/var/queue_schedule \ +-v /etc/ascend_install.info:/etc/ascend_install.info \ +-v /usr/local/sbin:/usr/local/sbin \ +-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \ +-v /usr/local/Ascend/firmware:/usr/local/Ascend/firmware \ +--device=/dev/davinci0:/dev/davinci0 \ +--device=/dev/davinci1:/dev/avinci1 \ +--device=/dev/davinci2:/dev/davinci2 \ +--device=/dev/davinci3:/dev/davinci3 \ +--device=/dev/davinci4:/dev/davinci4 \ +--device=/dev/davinci5:/dev/davinci5 \ +--device=/dev/davinci6:/dev/davinci6 \ +--device=/dev/davinci7:/dev/davinci7 \ +--device=/dev/davinci8:/dev/davinci8 \ +--device=/dev/davinci9:/dev/davinci9 \ +--device=/dev/davinci10:/dev/davinci10 \ +--device=/dev/davinci11:/dev/davinci11 \ +--device=/dev/davinci12:/dev/davinci12 \ +--device=/dev/davinci13:/dev/davinci13 \ +--device=/dev/davinci14:/dev/davinci14 \ +--device=/dev/davinci15:/dev/davinci15 \ +--device=/dev/davinci_manager:/dev/davinci_manager \ +--device=/dev/hisi_hdc:/dev/hisi_hdc \ +--entrypoint=bash \ +swr.cn-southwest-2.myhuaweicloud.com/base_image/dockerhub/lmsysorg/sglang:${TAG} +``` + + +Note: Using this image, you need to update transformers to main branch + +```shell Update Transformers +# reinstall transformers +pip install git+https://github.com/huggingface/transformers.git +``` + + +## Deployment + +### Single-node Deployment + +- Quantized model `glm5_w4a8` can be deployed on 1 Atlas 800 A3 (64G × 16) . + +Run the following script to execute online inference. + + +```shell Launch Server +# high performance cpu +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 +# bind cpu +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING +# cann +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh + +export STREAMS_PER_DEVICE=32 +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_NPU_USE_MULTI_STREAM=1 +export HCCL_BUFFSIZE=1000 +export HCCL_OP_EXPANSION_MODE=AIV +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo + +python3 -m sglang.launch_server \ + --model-path $MODEL_PATH \ + --attention-backend ascend \ + --device npu \ + --tp-size 16 --nnodes 1 --node-rank 0 \ + --chunked-prefill-size 16384 --max-prefill-tokens 280000 \ + --trust-remote-code \ + --host 127.0.0.1 \ + --mem-fraction-static 0.7 \ + --port 8000 \ + --served-model-name glm-5 \ + --cuda-graph-bs 16 \ + --quantization modelslim \ + --moe-a2a-backend deepep --deepep-mode auto +``` + + +### Multi-node Deployment + +- `GLM-5-bf16`: require at least 2 Atlas 800 A3 (64G × 16). + +**A3 series** + +Modify the IP of 2 nodes, then run the same scripts on two nodes. + +**node 0/1** + + +```shell Launch Multi-node Server +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 +# bind cpu +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING +# cann +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh + +export STREAMS_PER_DEVICE=32 +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_NPU_USE_MULTI_STREAM=1 +export HCCL_BUFFSIZE=1000 +export HCCL_OP_EXPANSION_MODE=AIV + +# Run command ifconfig on two nodes, find out which inet addr has same IP with your node IP. That is your public interface, which should be added here +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo + + +P_IP=('your ip1' 'your ip2') +P_MASTER="${P_IP[0]}:your port" +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 + +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 + +LOCAL_HOST1=`hostname -I|awk -F " " '{print$1}'` +LOCAL_HOST2=`hostname -I|awk -F " " '{print$2}'` +for i in "${!P_IP[@]}"; +do + if [[ "$LOCAL_HOST1" == "${P_IP[$i]}" || "$LOCAL_HOST2" == "${P_IP[$i]}" ]]; + then + echo "${P_IP[$i]}" + python3 -m sglang.launch_server \ + --model-path $MODEL_PATH \ + --attention-backend ascend \ + --device npu \ + --tp-size 32 --nnodes 2 --node-rank $i --dist-init-addr $P_MASTER \ + --chunked-prefill-size 16384 --max-prefill-tokens 131072 \ + --trust-remote-code \ + --host 127.0.0.1 \ + --mem-fraction-static 0.8\ + --port 8000 \ + --served-model-name glm-5 \ + --cuda-graph-max-bs 16 \ + --disable-radix-cache + NODE_RANK=$i + break + fi +done + +``` + + +### Prefill-Decode Disaggregation + +Not test yet. + +### Using Benchmark + +Refer to [Benchmark and Profiling](../../developer_guide/benchmark_and_profiling) for details. diff --git a/docs_new/docs/hardware-platforms/ascend-npus/MindSpore-Models.mdx b/docs_new/docs/hardware-platforms/ascend-npus/MindSpore-Models.mdx new file mode 100644 index 000000000..63ccfcf86 --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/MindSpore-Models.mdx @@ -0,0 +1,169 @@ +## Introduction + +MindSpore is a high-performance AI framework optimized for Ascend NPUs. This doc guides users to run MindSpore models in SGLang. + +## Requirements + +MindSpore currently only supports Ascend NPU devices. Users need to first install Ascend CANN software packages. +The CANN software packages can be downloaded from the [Ascend Official Website](https://www.hiascend.com). The recommended version is 8.3.RC2. + +## Supported Models + +Currently, the following models are supported: + +- **Qwen3**: Dense and MoE models +- **DeepSeek V3/R1** +- *More models coming soon...* + +## Installation + + +Currently, MindSpore models are provided by an independent package `sgl-mindspore`. Support for MindSpore is built upon current SGLang support for Ascend NPU platform. Please first [install SGLang for Ascend NPU](./SGLang-installation-with-NPUs-support) and then install `sgl-mindspore`: + + + +```shell Install +git clone https://github.com/mindspore-lab/sgl-mindspore.git +cd sgl-mindspore +pip install -e . +``` + + + +## Run Model + +Current SGLang-MindSpore supports Qwen3 and DeepSeek V3/R1 models. This doc uses Qwen3-8B as an example. + +### Offline infer + +Use the following script for offline infer: + + +```python Offline Inference +import sglang as sgl + +# Initialize the engine with MindSpore backend +llm = sgl.Engine( + model_path="/path/to/your/model", # Local model path + device="npu", # Use NPU device + model_impl="mindspore", # MindSpore implementation + attention_backend="ascend", # Attention backend + tp_size=1, # Tensor parallelism size + dp_size=1 # Data parallelism size +) + +# Generate text +prompts = [ + "Hello, my name is", + "The capital of France is", + "The future of AI is" +] + +sampling_params = {"temperature": 0, "top_p": 0.9} +outputs = llm.generate(prompts, sampling_params) + +for prompt, output in zip(prompts, outputs): + print(f"Prompt: {prompt}") + print(f"Generated: {output['text']}") + print("---") +``` + + +### Start server + +Launch a server with MindSpore backend: + + +```bash Launch Server +# Basic server startup +python3 -m sglang.launch_server \ + --model-path /path/to/your/model \ + --host 0.0.0.0 \ + --device npu \ + --model-impl mindspore \ + --attention-backend ascend \ + --tp-size 1 \ + --dp-size 1 +``` + + +For distributed server with multiple nodes: + + +```bash Multi-node Distributed +# Multi-node distributed server +python3 -m sglang.launch_server \ + --model-path /path/to/your/model \ + --host 0.0.0.0 \ + --device npu \ + --model-impl mindspore \ + --attention-backend ascend \ + --dist-init-addr 127.0.0.1:29500 \ + --nnodes 2 \ + --node-rank 0 \ + --tp-size 4 \ + --dp-size 2 +``` + + +## Troubleshooting + +#### Debug Mode + +Enable sglang debug logging by log-level argument. + + +```bash Debug Mode +python3 -m sglang.launch_server \ + --model-path /path/to/your/model \ + --host 0.0.0.0 \ + --device npu \ + --model-impl mindspore \ + --attention-backend ascend \ + --log-level DEBUG +``` + + +Enable mindspore info and debug logging by setting environments. + + +```bash Set Log Level +export GLOG_v=1 # INFO +export GLOG_v=0 # DEBUG +``` + + +#### Explicitly select devices + +Use the following environment variable to explicitly select the devices to use. + + +```shell Select Devices +export ASCEND_RT_VISIBLE_DEVICES=4,5,6,7 # to set device +``` + + +#### Some communication environment issues + +In case of some environment with special communication environment, users need set some environment variables. + + +```shell Disable LCCL +export MS_ENABLE_LCCL=off # current not support LCCL communication mode in SGLang-MindSpore +``` + + +#### Some dependencies of protobuf + +In case of some environment with special protobuf version, users need set some environment variables to avoid binary version mismatch. + + +```shell Fix Protobuf +export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python # to avoid protobuf binary version mismatch +``` + + +## Support +For MindSpore-specific issues: + +- Refer to the [MindSpore documentation](https://www.mindspore.cn/) diff --git a/docs_new/docs/hardware-platforms/ascend-npus/Qwen3-Examples.mdx b/docs_new/docs/hardware-platforms/ascend-npus/Qwen3-Examples.mdx new file mode 100644 index 000000000..469ea172f --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/Qwen3-Examples.mdx @@ -0,0 +1,124 @@ +## Running Qwen3 + +### Running Qwen3-32B on 1 x Atlas 800I A3 + +Model weights could be found [here](https://huggingface.co/Qwen/Qwen3-32B) + + +```shell Launch Server +export SGLANG_SET_CPU_AFFINITY=1 +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 +export HCCL_BUFFSIZE=1536 +export HCCL_OP_EXPANSION_MODE=AIV + +python -m sglang.launch_server \ + --device npu \ + --attention-backend ascend \ + --trust-remote-code \ + --tp-size 4 \ + --model-path Qwen/Qwen3-32B \ + --mem-fraction-static 0.8 +``` + + +### Running Qwen3-32B on 1 x Atlas 800I A3 with Qwen3-32B-Eagle3 + +Model weights could be found [here](https://huggingface.co/Qwen/Qwen3-32B) + +Speculative model weights could be found [here](https://huggingface.co/Zhihu-ai/Zhi-Create-Qwen3-32B-Eagle3) + + +```shell Launch Server with Eagle3 +export SGLANG_SET_CPU_AFFINITY=1 +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 +export HCCL_OP_EXPANSION_MODE=AIV +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_ENABLE_SPEC_V2=1 + +python -m sglang.launch_server \ + --device npu \ + --attention-backend ascend \ + --trust-remote-code \ + --tp-size 4 \ + --model-path Qwen/Qwen3-32B \ + --mem-fraction-static 0.8 \ + --speculative-algorithm EAGLE3 \ + --speculative-draft-model-path Qwen/Qwen3-32B-Eagle3 \ + --speculative-num-steps 1 \ + --speculative-eagle-topk 1 \ + --speculative-num-draft-tokens 2 +``` + + +### Running Qwen3-30B-A3B MOE on 1 x Atlas 800I A3 + +Model weights could be found [here](https://huggingface.co/Qwen/Qwen3-30B-A3B) + + +```shell Launch Server +export SGLANG_SET_CPU_AFFINITY=1 +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 +export HCCL_BUFFSIZE=1536 +export HCCL_OP_EXPANSION_MODE=AIV +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=32 +export SGLANG_DEEPEP_BF16_DISPATCH=1 + +python -m sglang.launch_server \ + --device npu \ + --attention-backend ascend \ + --trust-remote-code \ + --tp-size 4 \ + --model-path Qwen/Qwen3-30B-A3B \ + --mem-fraction-static 0.8 +``` + + +### Running Qwen3-235B-A22B-Instruct-2507 MOE on 1 x Atlas 800I A3 + +Model weights could be found [here](https://huggingface.co/Qwen/Qwen3-235B-A22B-Instruct-2507) + + +```shell Launch Server +export SGLANG_SET_CPU_AFFINITY=1 +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 +export HCCL_BUFFSIZE=1536 +export SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK=32 +export SGLANG_DEEPEP_BF16_DISPATCH=1 + +python -m sglang.launch_server \ + --model-path Qwen/Qwen3-235B-A22B-Instruct-2507 \ + --tp-size 16 \ + --trust-remote-code \ + --attention-backend ascend \ + --device npu \ + --watchdog-timeout 9000 \ + --mem-fraction-static 0.8 +``` + + +### Running Qwen3-VL-8B-Instruct on 1 x Atlas 800I A3 + +Model weights could be found [here](https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct) + + +```shell Launch Server +export SGLANG_SET_CPU_AFFINITY=1 +export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True +export STREAMS_PER_DEVICE=32 +export HCCL_BUFFSIZE=1536 +export HCCL_OP_EXPANSION_MODE=AIV + +python -m sglang.launch_server \ + --enable-multimodal \ + --attention-backend ascend \ + --mm-attention-backend ascend_attn \ + --trust-remote-code \ + --tp-size 4 \ + --model-path Qwen/Qwen3-VL-8B-Instruct \ + --mem-fraction-static 0.8 +``` + diff --git a/docs_new/docs/hardware-platforms/ascend-npus/Qwen3.5.mdx b/docs_new/docs/hardware-platforms/ascend-npus/Qwen3.5.mdx new file mode 100644 index 000000000..baca8dd9f --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/Qwen3.5.mdx @@ -0,0 +1,106 @@ +## Environment Preparation + +### Installation + +The dependencies required for the NPU runtime environment have been integrated into a Docker image and uploaded to the quay.io platform. You can directly pull it. + + +```bash Pull and Start Container +#Atlas 800 A3 +docker pull swr.cn-southwest-2.myhuaweicloud.com/base_image/dockerhub/lmsysorg/sglang:cann8.5.0-a3-qwen3.5 +#Atlas 800 A2 +docker pull swr.cn-southwest-2.myhuaweicloud.com/base_image/dockerhub/lmsysorg/sglang:cann8.5.0-910b-qwen3.5 + +#start container +docker run -itd --shm-size=16g --privileged=true --name ${NAME} \ +--privileged=true --net=host \ +-v /var/queue_schedule:/var/queue_schedule \ +-v /etc/ascend_install.info:/etc/ascend_install.info \ +-v /usr/local/sbin:/usr/local/sbin \ +-v /usr/local/Ascend/driver:/usr/local/Ascend/driver \ +-v /usr/local/Ascend/firmware:/usr/local/Ascend/firmware \ +--device=/dev/davinci0:/dev/davinci0 \ +--device=/dev/davinci1:/dev/davinci1 \ +--device=/dev/davinci2:/dev/davinci2 \ +--device=/dev/davinci3:/dev/davinci3 \ +--device=/dev/davinci4:/dev/davinci4 \ +--device=/dev/davinci5:/dev/davinci5 \ +--device=/dev/davinci6:/dev/davinci6 \ +--device=/dev/davinci7:/dev/davinci7 \ +--device=/dev/davinci8:/dev/davinci8 \ +--device=/dev/davinci9:/dev/davinci9 \ +--device=/dev/davinci10:/dev/davinci10 \ +--device=/dev/davinci11:/dev/davinci11 \ +--device=/dev/davinci12:/dev/davinci12 \ +--device=/dev/davinci13:/dev/davinci13 \ +--device=/dev/davinci14:/dev/davinci14 \ +--device=/dev/davinci15:/dev/davinci15 \ +--device=/dev/davinci_manager:/dev/davinci_manager \ +--device=/dev/hisi_hdc:/dev/hisi_hdc \ +--entrypoint=bash \ +swr.cn-southwest-2.myhuaweicloud.com/base_image/dockerhub/lmsysorg/sglang:${TAG} +``` + + +## Deployment + +### Single-node Deployment + +- Quantized model `qwen35_w8a8` can be deployed on 1 Atlas 800 A3 (64G × 16) . + +Run the following script to execute online inference. + + +```shell Launch Server +# high performance cpu +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 +# bind cpu +export SGLANG_SET_CPU_AFFINITY=1 + +unset https_proxy +unset http_proxy +unset HTTPS_PROXY +unset HTTP_PROXY +unset ASCEND_LAUNCH_BLOCKING +# cann +source /usr/local/Ascend/ascend-toolkit/set_env.sh +source /usr/local/Ascend/nnal/atb/set_env.sh + +export STREAMS_PER_DEVICE=32 +export SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT=600 +export SGLANG_ENABLE_SPEC_V2=1 +export SGLANG_ENABLE_OVERLAP_PLAN_STREAM=1 +export SGLANG_NPU_USE_MULTI_STREAM=1 +export HCCL_BUFFSIZE=1000 +export HCCL_OP_EXPANSION_MODE=AIV +export HCCL_SOCKET_IFNAME=lo +export GLOO_SOCKET_IFNAME=lo + +python3 -m sglang.launch_server \ + --model-path $MODEL_PATH \ + --attention-backend ascend \ + --device npu \ + --tp-size 16 --nnodes 1 --node-rank 0 \ + --chunked-prefill-size 16384 --max-prefill-tokens 280000 \ + --trust-remote-code \ + --host 127.0.0.1 \ + --mem-fraction-static 0.7 \ + --port 8000 \ + --cuda-graph-bs 16 \ + --quantization modelslim \ + --enable-multimodal \ + --mm-attention-backend ascend_attn \ + --dtype bfloat16 +``` + + +### Prefill-Decode Disaggregation + +Not test yet. + +### Using Benchmark + +Refer to [Benchmark and Profiling](../../developer_guide/benchmark_and_profiling) for details. diff --git a/docs_new/docs/hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support.mdx b/docs_new/docs/hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support.mdx new file mode 100644 index 000000000..23323cbbf --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support.mdx @@ -0,0 +1,318 @@ +--- +title: SGLang installation with NPUs support +--- + +You can install SGLang using any of the methods below. Please go through `System Settings` section to ensure the clusters are roaring at max performance. Feel free to leave an issue [here at sglang](https://github.com/sgl-project/sglang/issues) if you encounter any issues or have any problems. + +## Component Version Mapping For SGLang + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ComponentVersionObtain Way
HDK25.3.RC1[](https://hiascend.com/hardware/firmware-drivers/commercial?product=7\&model=33)
CANN8.5.0[Obtain Images](#obtain-cann-image)
Pytorch Adapter7.3.0[](https://gitcode.com/Ascend/pytorch/releases)
MemFabric1.0.5`pip install memfabric-hybrid==1.0.5`
Triton3.2.0`pip install triton-ascend`
Bisheng20251121[](https://sglang-ascend.obs.cn-east-3.myhuaweicloud.com/sglang/triton_ascend/Ascend-BiSheng-toolkit_aarch64_20251121.run)
SGLang NPU KernelNA[](https://github.com/sgl-project/sgl-kernel-npu/releases)
+ + + + You can obtain the dependency of a specified version of CANN through an image. + + ```bash + # for Atlas 800I A3 and Ubuntu OS + docker pull quay.io/ascend/cann:8.5.0-a3-ubuntu22.04-py3.11 + # for Atlas 800I A2 and Ubuntu OS + docker pull quay.io/ascend/cann:8.5.0-910b-ubuntu22.04-py3.11 + ``` + + +## Preparing the Running Environment + + + + + + Only `python==3.11` is supported currently. If you don't want to break system pre-installed python, try installing with [conda](https://github.com/conda/conda). + + ```bash + conda create --name sglang_npu python=3.11 + conda activate sglang_npu + ``` + + + Prior to start work with SGLang on Ascend you need to install CANN Toolkit, Kernels operator package and NNAL version 8.3.RC2 or higher, check the [installation guide](https://www.hiascend.com/document/detail/zh/CANNCommunityEdition/83RC1/softwareinst/instg/instg_0008.html?Mode=PmIns\&InstallType=local\&OS=openEuler\&Software=cannToolKit) + + + If you want to use PD disaggregation mode, you need to install MemFabric-Hybrid. MemFabric-Hybrid is a drop-in replacement of Mooncake Transfer Engine that enables KV cache transfer on Ascend NPU clusters. + + ```bash + pip install memfabric-hybrid==1.0.5 + ``` + + + ```bash + PYTORCH_VERSION=2.8.0 + TORCHVISION_VERSION=0.23.0 + TORCH_NPU_VERSION=2.8.0 + pip install torch==$PYTORCH_VERSION torchvision==$TORCHVISION_VERSION --index-url https://download.pytorch.org/whl/cpu + pip install torch_npu==$TORCH_NPU_VERSION + ``` + + If you are using other versions of `torch` and install `torch_npu`, check [installation guide](https://github.com/Ascend/pytorch/blob/master/README) + + + We provide our own implementation of Triton for Ascend. + + ```bash + BISHENG_NAME="Ascend-BiSheng-toolkit_aarch64_20251121.run" + BISHENG_URL="https://sglang-ascend.obs.cn-east-3.myhuaweicloud.com/sglang/triton_ascend/${BISHENG_NAME}" + wget -O "${BISHENG_NAME}" "${BISHENG_URL}" && chmod a+x "${BISHENG_NAME}" && "./${BISHENG_NAME}" --install && rm "${BISHENG_NAME}" + ``` + + ```bash + pip install triton-ascend + ``` + + For installation of Triton on Ascend nightly builds or from sources, follow [installation guide](https://gitcode.com/Ascend/triton-ascend/blob/master/docs/sources/getting-started/installation) + + + + We provide SGL kernels for Ascend NPU, check [installation guide](https://github.com/sgl-project/sgl-kernel-npu/blob/main/python/sgl_kernel_npu/README). + + + We provide a DeepEP-compatible Library as a drop-in replacement of deepseek-ai's DeepEP library, check the [installation guide](https://github.com/sgl-project/sgl-kernel-npu/blob/main/python/deep_ep/README). + + + ```bash + # Use the last release branch + git clone https://github.com/sgl-project/sglang.git + cd sglang + mv python/pyproject_npu.toml python/pyproject.toml + pip install -e python[all_npu] + ``` + + + + + + + ### Obtain Image + + You can download the SGLang image or build an image based on Dockerfile to obtain the Ascend NPU image. + + 1. **Download SGLang image** + + ```bash + dockerhub: docker.io/lmsysorg/sglang:$tag + # Main-based tag, change main to specific version like v0.5.6, + # you can get image for specific version + Atlas 800I A3 : {main}-cann8.5.0-a3 + Atlas 800I A2: {main}-cann8.5.0-910b + ``` + + 2. **Build an image based on Dockerfile** + + ```bash + # Clone the SGLang repository + git clone https://github.com/sgl-project/sglang.git + cd sglang/docker + + # Build the docker image + # If there are network errors, please modify the Dockerfile to use offline dependencies or use a proxy + docker build -t -f npu.Dockerfile . + ``` + + ### Create Docker + + `--privileged` and `--network=host` are required by RDMA, which is typically needed by Ascend NPU clusters. + The following docker command is based on Atlas 800I A3 machines. If you are using Atlas 800I A2, make sure only `davinci[0-7]` are mapped into container. + + ```bash + alias drun='docker run -it --rm --privileged --network=host --ipc=host --shm-size=16g \ + --device=/dev/davinci0 --device=/dev/davinci1 --device=/dev/davinci2 --device=/dev/davinci3 \ + --device=/dev/davinci4 --device=/dev/davinci5 --device=/dev/davinci6 --device=/dev/davinci7 \ + --device=/dev/davinci8 --device=/dev/davinci9 --device=/dev/davinci10 --device=/dev/davinci11 \ + --device=/dev/davinci12 --device=/dev/davinci13 --device=/dev/davinci14 --device=/dev/davinci15 \ + --device=/dev/davinci_manager --device=/dev/hisi_hdc \ + --volume /usr/local/sbin:/usr/local/sbin --volume /usr/local/Ascend/driver:/usr/local/Ascend/driver \ + --volume /usr/local/Ascend/firmware:/usr/local/Ascend/firmware \ + --volume /etc/ascend_install.info:/etc/ascend_install.info \ + --volume /var/queue_schedule:/var/queue_schedule --volume ~/.cache/:/root/.cache/' + + # Add HF_TOKEN env for download model by SGLang. + drun --env "HF_TOKEN=" \ + \ + python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --attention-backend ascend + ``` + + + + +## System Settings + + + + The default power scheme on Ascend hardware is `ondemand` which could affect performance, changing it to `performance` is recommended. + + ```bash + echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor + + # Make sure changes are applied successfully + cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor # shows performance + ``` + + + ```bash + sudo sysctl -w kernel.numa_balancing=0 + # Check + cat /proc/sys/kernel/numa_balancing # shows 0 + ``` + + + ```bash + sudo sysctl -w vm.swappiness=10 + + # Check + cat /proc/sys/vm/swappiness # shows 10 + ``` + + + +## Running SGLang Service + + + + + ### PD Mixed Scene + + ```bash + # Enabling CPU Affinity + export SGLANG_SET_CPU_AFFINITY=1 + python3 -m sglang.launch_server --model-path meta-llama/Llama-3.1-8B-Instruct --attention-backend ascend + ``` + + ### PD Separation Scene + + 1. **Launch Prefill Server** + + ```bash + # Enabling CPU Affinity + export SGLANG_SET_CPU_AFFINITY=1 + + # PIP: recommended to config first Prefill Server IP + # PORT: one free port + # all sglang servers need to be config the same PIP and PORT, + export ASCEND_MF_STORE_URL="tcp://PIP:PORT" + # if you are Atlas 800I A2 hardware and use rdma for kv cache transfer, add this parameter + export ASCEND_MF_TRANSFER_PROTOCOL="device_rdma" + python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode prefill \ + --disaggregation-transfer-backend ascend \ + --disaggregation-bootstrap-port 8995 \ + --attention-backend ascend \ + --device npu \ + --base-gpu-id 0 \ + --tp-size 1 \ + --host 127.0.0.1 \ + --port 8000 + ``` + + 2. **Launch Decode Server** + + ```bash + # PIP: recommended to config first Prefill Server IP + # PORT: one free port + # all sglang servers need to be config the same PIP and PORT, + export ASCEND_MF_STORE_URL="tcp://PIP:PORT" + # if you are Atlas 800I A2 hardware and use rdma for kv cache transfer, add this parameter + export ASCEND_MF_TRANSFER_PROTOCOL="device_rdma" + python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.1-8B-Instruct \ + --disaggregation-mode decode \ + --disaggregation-transfer-backend ascend \ + --attention-backend ascend \ + --device npu \ + --base-gpu-id 1 \ + --tp-size 1 \ + --host 127.0.0.1 \ + --port 8001 + ``` + + 3. **Launch Router** + + ```bash + python3 -m sglang_router.launch_router \ + --pd-disaggregation \ + --policy cache_aware \ + --prefill http://127.0.0.1:8000 8995 \ + --decode http://127.0.0.1:8001 \ + --host 127.0.0.1 \ + --port 6688 + ``` + + + + ### PD Mixed Scene + + ```bash + python3 -m sglang.launch_server \ + --model-path Qwen3-VL-30B-A3B-Instruct \ + --host 127.0.0.1 \ + --port 8000 \ + --tp 4 \ + --device npu \ + --attention-backend ascend \ + --mm-attention-backend ascend_attn \ + --disable-radix-cache \ + --trust-remote-code \ + --enable-multimodal \ + --sampling-backend ascend + ``` + + + diff --git a/docs_new/docs/hardware-platforms/ascend-npus/Support-Features-on-Ascend-NPU.mdx b/docs_new/docs/hardware-platforms/ascend-npus/Support-Features-on-Ascend-NPU.mdx new file mode 100644 index 000000000..7f91e4e68 --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/Support-Features-on-Ascend-NPU.mdx @@ -0,0 +1,3327 @@ +This section describes the basic functions and features supported by the Ascend NPU.If you encounter issues or have any +questions, please [open an issue](https://github.com/sgl-project/sglang/issues). + +If you want to know the meaning and usage of each parameter, +click [Server Arguments](../../advanced_features/server_arguments). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--model-path`
`--model`
`None`Type: str
`--tokenizer-path``None`Type: str
`--tokenizer-mode``auto``auto`, `slow`
`--tokenizer-worker-num``1`Type: int
`--skip-tokenizer-init``False`bool flag (set to enable)
`--load-format``auto``auto`, `safetensors`
`--model-loader-`
`extra-config`
{}Type: str
`--trust-remote-code``False`bool flag (set to enable)
`--context-length``None`Type: int
`--is-embedding``False`bool flag (set to enable)
`--enable-multimodal``None`bool flag (set to enable)
`--revision``None`Type: str
`--model-impl``auto``auto`, `sglang`,
`transformers`
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--host``127.0.0.1`Type: str
`--port``30000`Type: int
`--skip-server-warmup``False`bool flag (set to enable)
`--warmups``None`Type: str
`--nccl-port``None`Type: int
`--fastapi-root-path``None`Type: str
`--grpc-mode``False`bool flag (set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--dtype``auto``auto`,
`float16`,
`bfloat16`
`--quantization``None``modelslim`
`--quantization-param-path``None`Type: str
`--kv-cache-dtype``auto``auto`
`--enable-fp32-lm-head``False`bool flag
(set to enable)
`--modelopt-quant``None`Type: str
`--modelopt-checkpoint-`
`restore-path`
`None`Type: str
`--modelopt-checkpoint-`
`save-path`
`None`Type: str
`--modelopt-export-path``None`Type: str
`--quantize-and-serve``False`bool flag
(set to enable)
`--rl-quant-profile``None`Type: str
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--mem-fraction-static``None`Type: float
`--max-running-requests``None`Type: int
`--prefill-max-requests``None`Type: int
`--max-queued-requests``None`Type: int
`--max-total-tokens``None`Type: int
`--chunked-prefill-size``None`Type: int
`--max-prefill-tokens``16384`Type: int
`--schedule-policy``fcfs``lpm`, `fcfs`
`--enable-priority-`
`scheduling`
`False`bool flag
(set to enable)
`--schedule-low-priority-`
`values-first`
`False`bool flag
(set to enable)
`--priority-scheduling-`
`preemption-threshold`
`10`Type: int
`--schedule-conservativeness``1.0`Type: float
`--page-size``128`Type: int
`--swa-full-tokens-ratio``0.8`Type: float
`--disable-hybrid-swa-memory``False`bool flag
(set to enable)
`--abort-on-priority-`
`when-disabled`
`False`bool flag
(set to enable)
`--enable-dynamic-chunking``False`bool flag
(set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--device``None`Type: str
`--tensor-parallel-size`
`--tp-size`
`1`Type: int
`--pipeline-parallel-size`
`--pp-size`
`1`Type: int
`--pp-max-micro-batch-size``None`Type: int
`--pp-async-batch-depth``None`Type: int
`--stream-interval``1`Type: int
`--stream-output``False`bool flag (set to enable)
`--random-seed``None`Type: int
`--constrained-json-`
`whitespace-pattern`
`None`Type: str
`--constrained-json-`
`disable-any-whitespace`
`False`bool flag (set to enable)
`--watchdog-timeout``300`Type: float
`--soft-watchdog-timeout``300`Type: float
`--dist-timeout``None`Type: int
`--base-gpu-id``0`Type: int
`--gpu-id-step``1`Type: int
`--sleep-on-idle``False`bool flag (set to enable)
`--custom-sigquit-handler``None`Optional[Callable]
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--log-level``info`Type: str
`--log-level-http``None`Type: str
`--log-requests``False`bool flag
(set to enable)
`--log-requests-level``2``0`, `1`, `2`, `3`
`--log-requests-format`texttext, json
`--crash-dump-folder``None`Type: str
`--enable-metrics``False`bool flag
(set to enable)
`--enable-metrics-for-`
`all-schedulers`
`False`bool flag
(set to enable)
`--tokenizer-metrics-`
`custom-labels-header`
`x-custom-labels`Type: str
`--tokenizer-metrics-`
`allowed-custom-labels`
`None`List[str]
`--bucket-time-to-`
`first-token`
`None`List[float]
`--bucket-inter-token-`
`latency`
`None`List[float]
`--bucket-e2e-request-`
`latency`
`None`List[float]
`--collect-tokens-`
`histogram`
`False`bool flag
(set to enable)
`--prompt-tokens-buckets``None`List[str]
`--generation-tokens-buckets``None`List[str]
`--gc-warning-threshold-secs``0.0`Type: float
`--decode-log-interval``40`Type: int
`--enable-request-time-`
`stats-logging`
`False`bool flag
(set to enable)
`--kv-events-config``None`Type: str
`--enable-trace``False`bool flag
(set to enable)
`--oltp-traces-endpoint``localhost:4317`Type: str
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--export-metrics-to-`
`file`
`False`bool flag
(set to enable)
`--export-metrics-to-`
`file-dir`
`None`Type: str
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--api-key``None`Type: str
`--admin-api-key``None`Type: str
`--served-model-name``None`Type: str
`--weight-version``default`Type: str
`--chat-template``None`Type: str
`--completion-template``None`Type: str
`--enable-cache-report``False`bool flag
(set to enable)
`--reasoning-parser``None``deepseek-r1`
`--tool-call-parser``None``llama`,`pythonic`
`--sampling-defaults``model``openai`, `model`
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--data-parallel-size`
`--dp-size`
`1`Type: int
`--load-balance-method``round_robin``round_robin`,
`total_requests`,
`total_tokens`
`--prefill-round-robin-balance``False`bool flag
(set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--dist-init-addr`
`--nccl-init-addr`
`None`Type: str
`--nnodes``1`Type: int
`--node-rank``0`Type: int
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--json-model-override-`
`args`
`{}`Type: str
`--preferred-sampling-`
`params`
`None`Type: str
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--enable-lora``False`Bool flag
(set to enable)
`--max-lora-rank``None`Type: int
`--lora-target-modules``None``all`
`--lora-paths``None`Type: List[str] /
JSON objects
`--max-loras-per-batch``8`Type: int
`--max-loaded-loras``None`Type: int
`--lora-eviction-policy``lru``lru`,
`fifo`
`--lora-backend``triton``triton`
`--max-lora-chunk-size``16``16`, `32`,
`64`, `128`
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--attention-backend``None``ascend`
`--prefill-attention-backend``None``ascend`
`--decode-attention-backend``None``ascend`
`--sampling-backend``None``pytorch`,
`ascend`
`--grammar-backend``None``xgrammar`
`--mm-attention-backend``None``ascend_attn`
`--nsa-prefill-backend``flashmla_sparse``flashmla_sparse`,
`flashmla_decode`,
`fa3`,
`tilelang`,
`aiter`
`--nsa-decode-backend``fa3``flashmla_prefill`,
`flashmla_kv`,
`fa3`,
`tilelang`,
`aiter`
`--fp8-gemm-backend``auto``auto`,
`deep_gemm`,
`flashinfer_trtllm`,
`cutlass`,
`triton`,
`aiter`
`--disable-flashinfer-`
`autotune`
`False`bool flag
(set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--speculative-algorithm``None``EAGLE3`,
`NEXTN`
`--speculative-draft-model-path`
`--speculative-draft-model`
`None`Type: str
`--speculative-draft-model-`
`revision`
`None`Type: str
`--speculative-draft-load-format``None``auto`
`--speculative-num-steps``None`Type: int
`--speculative-eagle-topk``None`Type: int
`--speculative-num-draft-tokens``None`Type: int
`--speculative-accept-`
`threshold-single`
`1.0`Type: float
`--speculative-accept-`
`threshold-acc`
`1.0`Type: float
`--speculative-token-map``None`Type: str
`--speculative-attention-`
`mode`
`prefill``prefill`,
`decode`
`--speculative-moe-runner-`
`backend`
`None``auto`
`--speculative-moe-a2a-`
`backend`
`None``ascend_fuseep`
`--speculative-draft-attention-backend``None``ascend`
`--speculative-draft-model-quantization``None``unquant`
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Experimental
`--speculative-ngram-`
`min-match-window-size`
`1`Type: int
`--speculative-ngram-`
`max-match-window-size`
`12`Type: int
`--speculative-ngram-`
`min-bfs-breadth`
`1`Type: int
`--speculative-ngram-`
`max-bfs-breadth`
`10`Type: int
`--speculative-ngram-`
`match-type`
`BFS``BFS`,
`PROB`
`--speculative-ngram-`
`branch-length`
`18`Type: int
`--speculative-ngram-`
`capacity`
`10000000`Type: int
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--expert-parallel-size`
`--ep-size`
`--ep`
`1`Type: int
`--moe-a2a-backend``none``none`,
`deepep`,
`ascend_fuseep`
`--moe-runner-backend``auto``auto`, `triton`
`--flashinfer-mxfp4-`
`moe-precision`
`default``default`,
`bf16`
`--enable-flashinfer-`
`allreduce-fusion`
`False`bool flag
(set to enable)
`--deepep-mode``auto``normal`,
`low_latency`,
`auto`
`--deepep-config``None`Type: str
`--ep-num-redundant-experts``0`Type: int
`--ep-dispatch-algorithm``None`Type: str
`--init-expert-location``trivial`Type: str
`--enable-eplb``False`bool flag
(set to enable)
`--eplb-algorithm``auto`Type: str
`--eplb-rebalance-layers-`
`per-chunk`
`None`Type: int
`--eplb-min-rebalancing-`
`utilization-threshold`
`1.0`Type: float
`--expert-distribution-`
`recorder-mode`
`None`Type: str
`--expert-distribution-`
`recorder-buffer-size`
`None`Type: int
`--enable-expert-distribution-`
`metrics`
`False`bool flag (set to enable)
`--moe-dense-tp-size``None`Type: int
`--elastic-ep-backend``None``none`, `mooncake`
`--mooncake-ib-device``None`Type: str
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--max-mamba-cache-size``None`Type: int
`--mamba-ssm-dtype``float32``float32`,
`bfloat16`
`--mamba-full-memory-ratio``0.2`Type: float
`--mamba-scheduler-strategy``auto``auto`,
`no_buffer`,
`extra_buffer`
`--mamba-track-interval``256`Type: int
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--enable-hierarchical-`
`cache`
`False`bool flag
(set to enable)
`--hicache-ratio``2.0`Type: float
`--hicache-size``0`Type: int
`--hicache-write-policy``write_through``write_back`,
`write_through`,
`write_through_selective`
`--radix-eviction-policy``lru``lru`, `lfu`
`--hicache-io-backend``kernel``kernel_ascend`,
`direct`
`--hicache-mem-layout``layer_first``page_first_direct`,
`page_first_kv_split`
`--hicache-storage-`
`backend`
`None``file`
`--hicache-storage-`
`prefetch-policy`
`best_effort``best_effort`,
`wait_complete`,
`timeout`
`--hicache-storage-`
`backend-extra-config`
`None`Type: str
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--enable-lmcache``False`bool flag
(set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--cpu-offload-gb``0`Type: int
`--offload-group-size``-1`Type: int
`--offload-num-in-group``1`Type: int
`--offload-prefetch-step``1`Type: int
`--offload-mode``cpu`Type: str
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--multi-item-scoring-delimiter``None`Type: int
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3SpecialPlanned
`--disable-radix-cache``False`bool flag
(set to enable)
`--cuda-graph-max-bs``None`Type: int
`--cuda-graph-bs``None`List[int]
`--disable-cuda-graph``False`bool flag
(set to enable)
`--disable-cuda-graph-`
`padding`
`False`bool flag
(set to enable)
`--enable-profile-`
`cuda-graph`
`False`bool flag
(set to enable)
`--enable-cudagraph-gc``False`bool flag
(set to enable)
`--enable-nccl-nvls``False`bool flag
(set to enable)
`--enable-symm-mem``False`bool flag
(set to enable)
`--disable-flashinfer-`
`cutlass-moe-fp4-allgather`
`False`bool flag
(set to enable)
`--enable-tokenizer-`
`batch-encode`
`False`bool flag
(set to enable)
`--disable-tokenizer-`
`batch-encode`
`False`bool flag
(set to enable)
`--disable-outlines-`
`disk-cache`
`False`bool flag
(set to enable)
`--disable-custom-`
`all-reduce`
`False`bool flag
(set to enable)
`--enable-mscclpp``False`bool flag
(set to enable)
`--enable-torch-`
`symm-mem`
`False`bool flag
(set to enable)
`--disable-overlap`
`-schedule`
`False`bool flag
(set to enable)
`--enable-mixed-`
`chunk`
`False`bool flag
(set to enable)
`--enable-dp-attention``False`bool flag
(set to enable)
`--enable-dp-lm-head``False`bool flag
(set to enable)
`--enable-two-`
`batch-overlap`
`False`bool flag
(set to enable)
`--enable-single-`
`batch-overlap`
`False`bool flag
(set to enable)
`--tbo-token-`
`distribution-threshold`
`0.48`Type: float
`--enable-torch-`
`compile`
`False`bool flag
(set to enable)
`--enable-torch-`
`compile-debug-mode`
`False`bool flag
(set to enable)
`--enable-piecewise-`
`cuda-graph`
`False`bool flag
(set to enable)
`--piecewise-cuda-`
`graph-tokens`
`None`Type: JSON
list
`--piecewise-cuda-`
`graph-compiler`
`eager`["eager", "inductor"]
`--torch-compile-max-bs``32`Type: int
`--piecewise-cuda-`
`graph-max-tokens`
`4096`Type: int
`--torchao-config```Type: str
`--enable-nan-detection``False`bool flag
(set to enable)
`--enable-p2p-check``False`bool flag
(set to enable)
`--triton-attention-`
`reduce-in-fp32`
`False`bool flag
(set to enable)
`--triton-attention-`
`num-kv-splits`
`8`Type: int
`--triton-attention-`
`split-tile-size`
`None`Type: int
`--delete-ckpt-`
`after-loading`
`False`bool flag
(set to enable)
`--enable-memory-saver``False`bool flag
(set to enable)
`--enable-weights-`
`cpu-backup`
`False`bool flag
(set to enable)
`--enable-draft-weights-`
`cpu-backup`
`False`bool flag
(set to enable)
`--allow-auto-truncate``False`bool flag
(set to enable)
`--enable-custom-`
`logit-processor`
`False`bool flag
(set to enable)
`--flashinfer-mla-`
`disable-ragged`
`False`bool flag
(set to enable)
`--disable-shared-`
`experts-fusion`
`False`bool flag
(set to enable)
`--disable-chunked-`
`prefix-cache`
`False`bool flag
(set to enable)
`--disable-fast-`
`image-processor`
`False`bool flag
(set to enable)
`--keep-mm-feature-`
`on-device`
`False`bool flag
(set to enable)
`--enable-return-`
`hidden-states`
`False`bool flag
(set to enable)
`--enable-return-`
`routed-experts`
`False`bool flag
(set to enable)
`--scheduler-recv-`
`interval`
`1`Type: int
`--numa-node``None`List[int]
`--rl-on-policy-target``None``fsdp`
`--enable-layerwise-`
`nvtx-marker`
`False`bool flag
(set to enable)
`--enable-attn-tp-`
`input-scattered`
`False`bool flag
(set to enable)
`--enable-nsa-prefill-`
`context-parallel`
`False`bool flag
(set to enable)
`--enable-fused-qk-`
`norm-rope`
`False`bool flag
(set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--enable-dynamic-`
`batch-tokenizer`
`False`bool flag
(set to enable)
`--dynamic-batch-`
`tokenizer-batch-size`
`32`Type: int
`--dynamic-batch-`
`tokenizer-batch-timeout`
`0.002`Type: float
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--debug-tensor-dump-`
`output-folder`
`None`Type: str
`--debug-tensor-dump-`
`layers`
`None`List[int]
`--debug-tensor-dump-`
`input-file`
`None`Type: str
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--disaggregation-mode``null``null`,
`prefill`,
`decode`
`--disaggregation-transfer-backend``mooncake``ascend`
`--disaggregation-bootstrap-port``8998`Type: int
`--disaggregation-decode-tp``None`Type: int
`--disaggregation-decode-dp``None`Type: int
`--disaggregation-ib-device``None`Type: str
`--disaggregation-decode-`
`enable-offload-kvcache`
`False`bool flag
(set to enable)
`--disaggregation-decode-`
`enable-fake-auto`
`False`bool flag
(set to enable)
`--num-reserved-decode-tokens``512`Type: int
`--disaggregation-decode-`
`polling-interval`
`1`Type: int
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--encoder-only``False`bool flag
(set to enable)
`--language-only``False`bool flag
(set to enable)
`--encoder-transfer-backend``zmq_to_scheduler``zmq_to_scheduler`,
`zmq_to_tokenizer`,
`mooncake`
`--encoder-urls``[]`List[str]
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--custom-weight-loader``None`List[str]
`--weight-loader-disable-`
`mmap`
`False`bool flag
(set to enable)
`--remote-instance-weight-`
`loader-seed-instance-ip`
`None`Type: str
`--remote-instance-weight-`
`loader-seed-instance-service-port`
`None`Type: int
`--remote-instance-weight-`
`loader-send-weights-group-ports`
`None`Type: JSON
list
`--remote-instance-weight-`
`loader-backend`
`nccl``transfer_engine`,
`nccl`
`--remote-instance-weight-`
`loader-start-seed-via-transfer-engine`
`False`bool flag
(set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Special
`--enable-pdmux``False`bool flag
(set to enable)
`--pdmux-config-path``None`Type: str
`--sm-group-num``8`Type: int
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--mm-max-concurrent-calls`32Type: int
`--mm-per-request-timeout`10.0Type: float
`--enable-broadcast-mm-`
`inputs-process`
`False`bool flag
(set to enable)
`--mm-process-config``None`Type: JSON / Dict
`--mm-enable-dp-encoder``False`bool flag
(set to enable)
`--limit-mm-data-per-request``None`Type: JSON / Dict
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--decrypted-config-file``None`Type: str
`--decrypted-draft-config-file``None`Type: str
`--enable-prefix-mm-cache``False`bool flag
(set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3Planned
`--enable-deterministic-`
`inference`
`False`bool flag
(set to enable)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--forward-hooks``None`Type: JSON list
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptionsA2A3
`--config``None`Type: str
+ + +
+ + + + + +The following parameters are not supported because the third-party components that depend on are not compatible with the +NPU, like Ktransformer, checkpoint-engine etc. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptions
`--checkpoint-engine-`
`wait-weights-`
`before-ready`
`False`bool flag (set to enable)
`--kt-weight-path``None`Type: str
`--kt-method``AMXINT4`Type: str
`--kt-cpuinfer``None`Type: int
`--kt-threadpool-count`2Type: int
`--kt-num-gpu-experts``None`Type: int
`--kt-max-deferred-`
`experts-per-token`
`None`Type: int
+ +The following parameters have some functional deficiencies on community + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArgumentDefaultsOptions
`--enable-double-sparsity``False`bool flag
(set to enable)
`--ds-channel-config-path``None`Type: str
`--ds-heavy-channel-num``32`Type: int
`--ds-heavy-token-num``256`Type: int
`--ds-heavy-channel-type``qk`Type: str
`--ds-sparse-decode-`
`threshold`
`4096`Type: int
`--tool-server``None`Type: str
+ +
diff --git a/docs_new/docs/hardware-platforms/ascend-npus/Support-Models-on-Ascend-NPU.mdx b/docs_new/docs/hardware-platforms/ascend-npus/Support-Models-on-Ascend-NPU.mdx new file mode 100644 index 000000000..6e07d021c --- /dev/null +++ b/docs_new/docs/hardware-platforms/ascend-npus/Support-Models-on-Ascend-NPU.mdx @@ -0,0 +1,610 @@ +This section describes the models supported on the Ascend NPU, including Large Language Models, Multimodal Language +Models, Embedding Models, Reward Models and Rerank Models. Mainstream DeepSeek/Qwen/GLM series are included. +You are welcome to enable various models based on your business requirements. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelsModel FamilyA2A3
DeepSeek V3/V3.1DeepSeek
vllm-ascend/DeepSeek-V3.2-Exp-W8A8DeepSeek
vllm-ascend/DeepSeek-R1-0528-W8A8DeepSeek
vllm-ascend/DeepSeek-V2-Lite-W8A8DeepSeek
Qwen/Qwen3-30B-A3B-Instruct-2507Qwen
Qwen/Qwen3-32BQwen
Qwen/Qwen3-0.6BQwen
vllm-ascend/Qwen3-235B-A22B-W8A8Qwen
Qwen/Qwen3-Next-80B-A3B-InstructQwen
Qwen3-Coder-480B-A35B-Instruct-w8a8-QuaRotQwen
Qwen/Qwen2.5-7B-InstructQwen
vllm-ascend/QWQ-32B-W8A8Qwen
meta-llama/Llama-4-Scout-17B-16E-InstructLlama
AI-ModelScope/Llama-3.1-8B-InstructLlama
LLM-Research/llama-2-7bLlama
LLM-Research/Llama-3.2-1B-InstructLlama
mistralai/Mistral-7B-Instruct-v0.2Mistral
google/gemma-3-4b-itGemma
microsoft/Phi-4-multimodal-instructPhi
allenai/OLMoE-1B-7B-0924OLMoE
stabilityai/stablelm-2-1_6bStableLM
CohereForAI/c4ai-command-r-v01Command-R
huihui-ai/grok-2Grok
ZhipuAI/chatglm2-6bChatGLM
Shanghai_AI_Laboratory/internlm2-7bInternLM 2
LGAI-EXAONE/EXAONE-3.5-7.8B-InstructExaONE 3
xverse/XVERSE-MoE-A36BXVERSE
HuggingFaceTB/SmolLM-1.7BSmolLM
ZhipuAI/glm-4-9b-chatGLM-4
XiaomiMiMo/MiMo-7B-RLMiMo
arcee-ai/AFM-4.5B-BaseArcee AFM-4.5B
Howeee/persimmon-8b-chatPersimmon
inclusionAI/Ling-liteLing
ibm-granite/granite-3.1-8b-instructGranite
ibm-granite/granite-3.0-3b-a800m-instructGranite MoE
AI-ModelScope/dbrx-instructDBRX (Databricks)
baichuan-inc/Baichuan2-13B-ChatBaichuan 2 (7B, 13B)
baidu/ERNIE-4.5-21B-A3B-PTERNIE-4.5 (4.5, 4.5MoE series)
OpenBMB/MiniCPM3-4BMiniCPM (v3, 4B)
Kimi/Kimi-K2-ThinkingKimi
openai/gpt-oss-120bGPTOSS
allenai/OLMo-2-1124-7B-InstructOLMo
minimax/MiniMax-M2MiniMax-M2
upstage/SOLAR-10.7B-Instruct-v1.0Solar
bigcode/starcoder2-7bStarCoder2
arcee-ai/Trinity-MiniTrinity (Nano, Mini)
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelsModel Family (Variants)A2A3
Qwen/Qwen2.5-VL-3B-InstructQwen-VL
Qwen/Qwen2.5-VL-72B-InstructQwen-VL
Qwen/Qwen3-VL-30B-A3B-InstructQwen-VL
Qwen/Qwen3-VL-8B-InstructQwen-VL
Qwen/Qwen3-VL-4B-InstructQwen-VL
Qwen/Qwen3-VL-235B-A22B-InstructQwen-VL
deepseek-ai/deepseek-vl2DeepSeek-VL2
deepseek-ai/Janus-Pro-1BJanus-Pro (1B, 7B)
deepseek-ai/Janus-Pro-7BJanus-Pro (1B, 7B)
openbmb/MiniCPM-V-2_6MiniCPM-V / MiniCPM-o
openbmb/MiniCPM-o-2_6MiniCPM-V / MiniCPM-o
google/gemma-3-4b-itGemma 3 (Multimodal)
mistralai/Mistral-Small-3.1-24B-Instruct-2503Mistral-Small-3.1-24B
microsoft/Phi-4-multimodal-instructPhi-4-multimodal-instruct
XiaomiMiMo/MiMo-VL-7B-RLMiMo-VL (7B)
AI-ModelScope/llava-v1.6-34bLLaVA (v1.5 & v1.6)
lmms-lab/llava-next-72bLLaVA-NeXT (8B, 72B)
lmms-lab/llava-onevision-qwen2-7b-ovLLaVA-OneVision
Kimi/Kimi-VL-A3B-InstructKimi-VL (A3B)
ZhipuAI/GLM-4.5VGLM-4.5V (106B)
LLM-Research/Llama-3.2-11B-Vision-InstructLlama 3.2 Vision (11B)
rednote-hilab/dots.ocrDotsVLM-OCR
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelsModel FamilyA2A3
intfloat/e5-mistral-7b-instructE5 (Llama/Mistral based)
iic/gte_Qwen2-1.5B-instructGTE-Qwen2
Qwen/Qwen3-Embedding-8BQwen3-Embedding
Alibaba-NLP/gme-Qwen2-VL-2B-InstructGME (Multimodal)
AI-ModelScope/clip-vit-large-patch14-336CLIP
BAAI/bge-large-en-v1.5BGE
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelsModel FamilyA2A3
Skywork/Skywork-Reward-Llama-3.1-8B-v0.2Llama3.1 Reward
Shanghai_AI_Laboratory/internlm2-7b-rewardInternLM 2 Reward
Qwen/Qwen2.5-Math-RM-72BQwen2.5 Reward - Math
Howeee/Qwen2.5-1.5B-apeachQwen2.5 Reward - Sequence
AI-ModelScope/Skywork-Reward-Gemma-2-27B-v0.2Gemma 2-27B Reward
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelsModel FamilyA2A3
BAAI/bge-reranker-v2-m3BGE-Reranker
+
diff --git a/docs_new/docs/hardware-platforms/cpu-server.mdx b/docs_new/docs/hardware-platforms/cpu-server.mdx new file mode 100644 index 000000000..b3fa72e36 --- /dev/null +++ b/docs_new/docs/hardware-platforms/cpu-server.mdx @@ -0,0 +1,355 @@ +--- +title: "CPU Servers" +--- + +The document addresses how to set up the [SGLang](https://github.com/sgl-project/sglang) environment and run LLM inference on CPU servers. +SGLang is enabled and optimized on the CPUs equipped with Intel® AMX® Instructions, +which are 4th generation or newer Intel® Xeon® Scalable Processors. + +## Optimized Model List + +A list of popular LLMs are optimized and run efficiently on CPU, +including the most notable open-source models like Llama series, Qwen series, +and DeepSeek series like DeepSeek-R1 and DeepSeek-V3.1-Terminus. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model NameBF16W8A8_INT8FP8
DeepSeek-R1DeepSeek-R1-Channel-INT8DeepSeek-R1
DeepSeek-V3.1-TerminusDeepSeek-V3.1-Terminus-Channel-int8DeepSeek-V3.1-Terminus
Llama-3.2-3BLlama-3.2-3B-InstructLlama-3.2-3B-quantized.w8a8
Llama-3.1-8BLlama-3.1-8B-InstructLlama-3.1-8B-quantized.w8a8
QwQ-32BQwQ-32B-quantized.w8a8
DeepSeek-Distilled-LlamaDeepSeek-R1-Distill-Llama-70B-quantized.w8a8
Qwen3-235BQwen3-235B-A22B-FP8
+ +> **Note:** The model identifiers listed in the table above have been verified on 6th Gen Intel® Xeon® P-core platforms. + +## Installation + + + + It is recommended to use Docker for setting up the SGLang environment. + A [Dockerfile](https://github.com/sgl-project/sglang/blob/main/docker/xeon.Dockerfile) is provided to facilitate the installation. + + > **Note:** Replace `` below with your [HuggingFace access token](https://huggingface.co/docs/hub/en/security-tokens). + + + ```bash Clone, Build and Run + # Clone the SGLang repository + git clone https://github.com/sgl-project/sglang.git + cd sglang/docker + + # Build the docker image + docker build -t sglang-cpu:latest -f xeon.Dockerfile . + + # Initiate a docker container + docker run \ + -it \ + --privileged \ + --ipc=host \ + --network=host \ + -v /dev/shm:/dev/shm \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + -p 30000:30000 \ + -e "HF_TOKEN=" \ + sglang-cpu:latest /bin/bash + ``` + + + + + If you prefer to install SGLang in a bare metal environment, the setup process is as follows. + + Please install the required packages and libraries beforehand if they are not already present on your system. + You can refer to the Ubuntu-based installation commands in + [the Dockerfile](https://github.com/sgl-project/sglang/blob/main/docker/xeon.Dockerfile#L11) for guidance. + + 1. **Install uv and create a virtual environment** + + ```bash Create Virtual Environment + # Taking '/opt' as the example uv env folder, feel free to change it as needed + cd /opt + curl -LsSf https://astral.sh/uv/install.sh | sh + source $HOME/.local/bin/env + uv venv --python 3.12 + source .venv/bin/activate + ``` + + + 2. **Create a config file for torch package indexes** + Create the `uv.toml` config file: + + + ```bash Open Config File + vim .venv/uv.toml + ``` + + + Press `a` to enter insert mode in `vim`, then paste the following content: + + + ```toml + [[index]] + name = "torch" + url = "https://download.pytorch.org/whl/cpu" + + [[index]] + name = "torchvision" + url = "https://download.pytorch.org/whl/cpu" + + [[index]] + name = "torchaudio" + url = "https://download.pytorch.org/whl/cpu" + + [[index]] + name = "triton" + url = "https://download.pytorch.org/whl/cpu" + ``` + + + Save the file (press `Esc`, then type `:x` and hit `Enter`), then set it as the default `uv` config: + + + ```bash Set Config Path + export UV_CONFIG_FILE=/opt/.venv/uv.toml + ``` + + + 3. **Clone SGLang and build packages** + + ```bash Build SGLang + # Clone the SGLang code + git clone https://github.com/sgl-project/sglang.git + cd sglang + git checkout + + # Use dedicated toml file + cd python + cp pyproject_cpu.toml pyproject.toml + # Install SGLang dependent libs, and build SGLang main package + uv pip install --upgrade pip setuptools + uv pip install . + + # Build the CPU backend kernels + cd ../sgl-kernel + cp pyproject_cpu.toml pyproject.toml + uv pip install . + ``` + + + 4. **Set required environment variables** + + ```bash Set Environment Variables + export SGLANG_USE_CPU_ENGINE=1 + + # Set 'LD_LIBRARY_PATH' and 'LD_PRELOAD' to ensure the libs can be loaded by sglang processes + export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu + export LD_PRELOAD=${LD_PRELOAD}:/opt/.venv/lib/libiomp5.so:${LD_LIBRARY_PATH}/libtcmalloc.so.4:${LD_LIBRARY_PATH}/libtbbmalloc.so.2 + ``` + + + > **Note:** The environment variable `SGLANG_USE_CPU_ENGINE=1` is required to enable the SGLang service with the CPU engine. + + > **Note:** If you encounter code compilation issues during the `sgl-kernel` building process, please check your `gcc` and `g++` versions and upgrade them if they are outdated. It is recommended to use `gcc-13` and `g++-13` as they have been verified in the official Docker container. + + > **Note:** The system library path is typically located in one of the following directories: `~/.local/lib/`, `/usr/local/lib/`, `/usr/local/lib64/`, `/usr/lib/`, `/usr/lib64/`, and `/usr/lib/x86_64-linux-gnu/`. In the above example commands, `/usr/lib/x86_64-linux-gnu` is used. Please adjust the path according to your server configuration. + + It is recommended to add the following to your `~/.bashrc` file to avoid setting these variables every time you open a new terminal: + + + ```bash Persist in ~/.bashrc + source .venv/bin/activate + export SGLANG_USE_CPU_ENGINE=1 + export LD_LIBRARY_PATH= + export LD_PRELOAD= + ``` + + + + +## Launch of the Serving Engine + +Example command to launch SGLang serving: + + +```bash Launch Server +python -m sglang.launch_server \ + --model \ + --trust-remote-code \ + --disable-overlap-schedule \ + --device cpu \ + --host 0.0.0.0 \ + --tp 6 +``` + + +> **Note:** For running W8A8 quantized models, please add the flag `--quantization w8a8_int8`. + +> **Note:** The flag `--tp 6` specifies that tensor parallelism will be applied using 6 ranks (TP6). On a CPU platform, a TP rank means a sub-NUMA cluster (SNC). You can get the SNC count using `lscpu`. If the specified TP rank number differs from the total SNC count, the system will automatically utilize the first `n` SNCs — but `n` cannot exceed the total SNC number. +> +> To specify the cores to be used, set the environment variable `SGLANG_CPU_OMP_THREADS_BIND`. For example, to use the first 40 cores of each SNC on a Xeon® 6980P server (which has 43-43-42 cores on the 3 SNCs of a socket): + + +```bash Set Thread Binding +export SGLANG_CPU_OMP_THREADS_BIND="0-39|43-82|86-125|128-167|171-210|214-253" +``` + + +> Please beware that with `SGLANG_CPU_OMP_THREADS_BIND` set, the available memory amounts of the ranks may not be determined in advance. You may need to set `--max-total-tokens` to avoid out-of-memory errors. + +> **Note:** For optimizing decoding with `torch.compile`, add the flag `--enable-torch-compile`. To specify the maximum batch size, set `--torch-compile-max-bs`. For example, `--enable-torch-compile --torch-compile-max-bs 4` uses `torch.compile` with a maximum batch size of 4. The maximum applicable batch size is 16. + +> **Note:** A warmup step is automatically triggered when the service is started. The server is ready when you see the log `The server is fired up and ready to roll!`. + +## Benchmarking with Requests + +You can benchmark the performance via the `bench_serving` script. +Run the command in another terminal. An example command would be: + + +```bash Run Benchmark +python -m sglang.bench_serving \ + --dataset-name random \ + --random-input-len 1024 \ + --random-output-len 1024 \ + --num-prompts 1 \ + --request-rate inf \ + --random-range-ratio 1.0 +``` + + +Detailed parameter descriptions are available via the command: + + +```bash Benchmark Help +python -m sglang.bench_serving -h +``` + + +Additionally, requests can be formatted using +[the OpenAI Completions API](../basic_usage/openai_api_completions) +and sent via the command line (e.g., using `curl`) or through your own scripts. + +## Example Usage Commands + +Large Language Models can range from fewer than 1 billion to several hundred billion parameters. +Dense models larger than 20B are expected to run on flagship 6th Gen Intel® Xeon® processors +with dual sockets and a total of 6 sub-NUMA clusters. Dense models of approximately 10B parameters or fewer, +or MoE (Mixture of Experts) models with fewer than 10B activated parameters, can run on more common +4th generation or newer Intel® Xeon® processors, or utilize a single socket of the flagship 6th Gen Intel® Xeon® processors. + +### Example: Running DeepSeek-V3.1-Terminus + + +```bash W8A8_INT8 +python -m sglang.launch_server \ + --model IntervitensInc/DeepSeek-V3.1-Terminus-Channel-int8 \ + --trust-remote-code \ + --disable-overlap-schedule \ + --device cpu \ + --quantization w8a8_int8 \ + --host 0.0.0.0 \ + --enable-torch-compile \ + --torch-compile-max-bs 4 \ + --tp 6 +``` + +```bash FP8 +python -m sglang.launch_server \ + --model deepseek-ai/DeepSeek-V3.1-Terminus \ + --trust-remote-code \ + --disable-overlap-schedule \ + --device cpu \ + --host 0.0.0.0 \ + --enable-torch-compile \ + --torch-compile-max-bs 4 \ + --tp 6 +``` + + +> **Note:** Please set `--torch-compile-max-bs` to the maximum desired batch size for your deployment, which can be up to 16. The value `4` in the examples is illustrative. + +### Example: Running Llama-3.2-3B + + +```bash BF16 +python -m sglang.launch_server \ + --model meta-llama/Llama-3.2-3B-Instruct \ + --trust-remote-code \ + --disable-overlap-schedule \ + --device cpu \ + --host 0.0.0.0 \ + --enable-torch-compile \ + --torch-compile-max-bs 16 \ + --tp 2 +``` + +```bash W8A8_INT8 +python -m sglang.launch_server \ + --model RedHatAI/Llama-3.2-3B-quantized.w8a8 \ + --trust-remote-code \ + --disable-overlap-schedule \ + --device cpu \ + --quantization w8a8_int8 \ + --host 0.0.0.0 \ + --enable-torch-compile \ + --torch-compile-max-bs 16 \ + --tp 2 +``` + + +> **Note:** The `--torch-compile-max-bs` and `--tp` settings are examples that should be adjusted for your setup. For instance, use `--tp 3` to utilize 1 socket with 3 sub-NUMA clusters on an Intel® Xeon® 6980P server. + +Once the server has been launched, you can test it using the `bench_serving` command or create +your own commands or scripts following [the benchmarking example](#benchmarking-with-requests). diff --git a/docs_new/docs/hardware-platforms/nvidia-gpus.mdx b/docs_new/docs/hardware-platforms/nvidia-gpus.mdx new file mode 100644 index 000000000..6d85d1d07 --- /dev/null +++ b/docs_new/docs/hardware-platforms/nvidia-gpus.mdx @@ -0,0 +1,5 @@ +--- +title: NVIDIA GPUs +--- + +Please refer to the [Installation Guide](/docs/get-started/installation) to get started with SGLang on NVIDIA GPUs. diff --git a/docs_new/docs/hardware-platforms/nvidia.mdx b/docs_new/docs/hardware-platforms/nvidia.mdx new file mode 100644 index 000000000..b4703e81b --- /dev/null +++ b/docs_new/docs/hardware-platforms/nvidia.mdx @@ -0,0 +1,102 @@ +--- +title: NVIDIA Jetson Orin +description: Guide for installing and running SGLang on NVIDIA Jetson Orin devices. +--- + +## Prerequisites + +Before starting, ensure the following: + +- [NVIDIA Jetson AGX Orin Devkit](https://www.nvidia.com/en-us/autonomous-machines/embedded-systems/jetson-orin/) is set up with JetPack 6.1 or later. +- CUDA Toolkit and cuDNN are installed. +- Verify that the Jetson AGX Orin is in high-performance mode: + + +```bash +sudo nvpmodel -m 0 +``` + + +## Installing and Running SGLang with Jetson Containers + +1. **Clone the jetson-containers repository** + +```bash +git clone https://github.com/dusty-nv/jetson-containers.git +``` + +2. **Run the installation script** + +```bash +bash jetson-containers/install.sh +``` + +3. **Build the container image** + +```bash +jetson-containers build sglang +``` + +4. **Run the container** + + + + ```bash + jetson-containers run $(autotag sglang) + ``` + + + ```bash + docker run --runtime nvidia -it --rm --network=host IMAGE_NAME + ``` + + + +## Running Inference + +Launch the server: + + +```bash +python -m sglang.launch_server \ + --model-path deepseek-ai/DeepSeek-R1-Distill-Llama-8B \ + --device cuda \ + --dtype half \ + --attention-backend flashinfer \ + --mem-fraction-static 0.8 \ + --context-length 8192 +``` + + +The quantization and limited context length (`--dtype half` `--context-length 8192`) are due to the limited computational resources in [Nvidia jetson kit](https://www.nvidia.com/en-us/autonomous-machines/embedded-systems/jetson-orin/). A detailed explanation can be found in [Server Arguments](../advanced_features/server_arguments). + +After launching the engine, refer to [Chat completions](../basic_usage/openai_api_completions#Usage) to test the usability. + +## Running Quantization with TorchAO + +TorchAO is suggested to NVIDIA Jetson Orin. + + +```bash +python -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-8B-Instruct \ + --device cuda \ + --dtype bfloat16 \ + --attention-backend flashinfer \ + --mem-fraction-static 0.8 \ + --context-length 8192 \ + --torchao-config int4wo-128 +``` + + +This enables TorchAO's int4 weight-only quantization with a 128-group size. The usage of `--torchao-config int4wo-128` is also for memory efficiency. + +## Structured Output with XGrammar + +Please refer to [SGLang doc structured output](../advanced_features/structured_outputs). + +Thanks to the support from [Nurgaliyev Shakhizat](https://github.com/shahizat), [Dustin Franklin](https://github.com/dusty-nv) and [Johnny Núñez Cano](https://github.com/johnnynunez). + +## References + +- [NVIDIA Jetson AGX Orin Documentation](https://developer.nvidia.com/embedded/jetson-agx-orin) diff --git a/docs_new/docs/hardware-platforms/overview.mdx b/docs_new/docs/hardware-platforms/overview.mdx new file mode 100644 index 000000000..b53e06fa0 --- /dev/null +++ b/docs_new/docs/hardware-platforms/overview.mdx @@ -0,0 +1,12 @@ +--- +title: Hardware Platforms +description: Platform-specific guides for running SGLang on GPUs, TPUs, NPUs, CPUs, and more. +--- + +- [NVIDIA GPUs](./nvidia-gpus) +- [AMD GPUs](./amd-gpus) +- [Ascend NPUs](./ascend-npus/SGLang-installation-with-NPUs-support) +- [CPU Server](./cpu-server) +- [NVIDIA (Edge & Embedded)](./nvidia) +- [TPU](./tpu) +- [XPU](./xpu) diff --git a/docs_new/docs/hardware-platforms/tpu.mdx b/docs_new/docs/hardware-platforms/tpu.mdx new file mode 100644 index 000000000..12e89b2ea --- /dev/null +++ b/docs_new/docs/hardware-platforms/tpu.mdx @@ -0,0 +1,673 @@ +--- +title: "TPU" +description: "SGLang supports high-performance TPU inference through the SGLang-JAX backend, which is specifically optimized for Google Cloud TPUs. The JAX-based implementation delivers exceptional throughput and low latency for Large Language Model (LLM) serving workloads on TPU hardware." +--- + + + SGLang TPU support is implemented via the SGLang-JAX backend, a dedicated JAX-based inference engine maintained as a separate repository at [sgl-project/sglang-jax](https://github.com/sgl-project/sglang-jax). + + +For TPU-specific issues or feature requests, please visit the [sglang-jax GitHub issues page](https://github.com/sgl-project/sglang-jax/issues). + +--- + +# System Requirements + +--- + +## Supported TPU Hardware + + + + **32 GB** HBM Memory — Available on Google Cloud + + + **96 GB per core** HBM Memory — Available on Google Cloud + + + +--- + +## Software Requirements + + + + Version **3.12 or higher** + + + **Latest version** with TPU support + + + Google Cloud TPU VM or compatible TPU runtime. **Optional:** SkyPilot for simplified cloud deployment. + + + +--- + +# Feature Support Matrix + +SGLang-JAX provides comprehensive TPU-optimized features for production LLM serving: + +### Supported Features + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Feature****Support Status****Description**
High-Throughput Continuous BatchingDynamic request batching for maximum TPU utilization
Radix Tree KV CacheMemory-efficient prefix sharing between requests
FlashAttention BackendTPU-optimized attention kernel for long sequences
Tensor ParallelismDistribute models across multiple TPU cores
Paged AttentionFlexible KV cache management with paging
Speculative Decoding (EAGLE/EAGLE3)20-40% throughput improvement for compatible models
Chunked PrefillMixed prefill-decode batching
OpenAI-Compatible APIDrop-in replacement for OpenAI API
Data Parallel Attention🚧In development — Attention computation with data parallelism
Quantization🚧In development — Model quantization for reduced memory usage
Multi-LoRA🚧In development — Serve multiple LoRA adapters simultaneously
+ +--- + +### Attention Backend Comparison + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Backend****Paged Attention****Spec Decoding****MLA****Sliding Window**
FlashAttention (fa)
Native
+ + + FlashAttention backend is recommended for production workloads due to superior memory efficiency and performance. + + +--- + +# Optimized Model List + +The following models have been tested and optimized for TPU deployment: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Model Family****Performance Status**
Qwen 3⭐ Recommended for production
Qwen 3 MoE⭐ Best performance
Qwen 2Needs improvement
Qwen 2 MoENeeds improvement
Qwen 1.5Needs improvement
Llama/LLaMANeeds improvement
Grok-2Needs improvement
Gemma 2Verified on TPU
Bailing MoENeeds improvement
+ +--- + +# Installation + + + + ```bash + pip install sglang-jax + ``` + + + ```bash + git clone https://github.com/sgl-project/sglang-jax + cd sglang-jax + uv venv --python 3.12 && source .venv/bin/activate + uv pip install -e "python[all]" + ``` + + + + Docker support for TPU is currently under development. Please use PyPI or source installation methods. + + + + SkyPilot provides simplified deployment on Google Cloud TPU: + + 1. **Install SkyPilot and configure GCP access** + + See the [SkyPilot documentation](https://docs.skypilot.co/en/latest/) for setup instructions. + + 2. **Create a SkyPilot configuration file** + + Create a SkyPilot YAML file: `sglang-jax.sky.yaml` + + 3. **Launch your TPU cluster** + + ```bash + # Standard deployment + sky launch -c sglang-jax sglang-jax.sky.yaml --infra=gcp + + # With spot instances for cost savings + sky launch -c sglang-jax sglang-jax.sky.yaml --infra=gcp --use-spot + ``` + + + +--- + +# Launch the Serving Engine + + + + ```bash + JAX_COMPILATION_CACHE_DIR=/tmp/jit_cache python3 -u -m sgl_jax.launch_server \ + --model-path Qwen/Qwen-7B-Chat \ + --trust-remote-code \ + --dist-init-addr=0.0.0.0:10011 \ + --nnodes=1 \ + --tp-size=4 \ + --device=tpu \ + --random-seed=3 \ + --node-rank=0 \ + --mem-fraction-static=0.8 \ + --max-prefill-tokens=8192 \ + --download-dir=/tmp \ + --dtype=bfloat16 \ + --skip-server-warmup \ + --host 0.0.0.0 \ + --port 30000 + ``` + + + + + Enables JIT compilation caching to accelerate server startup on subsequent runs. Recommended: `/tmp/jit_cache` + + + Tensor parallelism size; match this to your TPU core count (typically `1`, `4`, or `8`). + + + Specifies TPU device. This is the default for `sglang-jax`. + + + Uses bfloat16 precision, which TPUs are optimized for. + + + Allocates this fraction of TPU HBM for static memory. Adjustable from `0.2` to `0.9`. + + + Maximum number of tokens processed in the prefill phase. + + + + + + For production workloads with optimal throughput: + + ```bash + python3 -u -m sgl_jax.launch_server \ + --model-path Qwen/Qwen3-8B \ + --trust-remote-code \ + --tp-size=4 \ + --device=tpu \ + --mem-fraction-static=0.8 \ + --chunked-prefill-size=2048 \ + --dtype=bfloat16 \ + --max-running-requests=256 \ + --page-size=128 \ + --attention-backend=fa + ``` + + + Speculative decoding can improve throughput by 20-40% for compatible models: + + ```bash + python3 -u -m sgl_jax.launch_server \ + --model-path Qwen/Qwen3-32B \ + --trust-remote-code \ + --device=tpu \ + --tp-size=4 \ + --mem-fraction-static=0.8 \ + --max-prefill-tokens=4096 \ + --attention-backend=fa \ + --dtype=bfloat16 \ + --port=30000 \ + --host=0.0.0.0 \ + --disable-overlap-schedule \ + --speculative-algorithm=EAGLE3 \ + --speculative-draft-model-path=AngelSlim/Qwen3-32B_eagle3 \ + --page-size=64 \ + --speculative-eagle-topk=1 \ + --speculative-num-steps=3 \ + --speculative-num-draft-tokens=4 + ``` + + + Speculative decoding is currently supported for Qwen3 and LLaMA model families. See the [Speculative Decoding documentation](../advanced_features/speculative_decoding) for detailed configuration guidance. + + + + For large models requiring multiple TPU VMs: + + ```bash + # Node 0 (coordinator) + python3 -m sgl_jax.launch_server \ + --model-path MODEL_PATH \ + --dist-init-addr=NODE0_IP:10011 \ + --nnodes=2 \ + --node-rank=0 \ + --tp-size=8 \ + [other parameters...] + + # Node 1 (worker) + python3 -m sgl_jax.launch_server \ + --model-path MODEL_PATH \ + --dist-init-addr=NODE0_IP:10011 \ + --nnodes=2 \ + --node-rank=1 \ + --tp-size=8 \ + [other parameters...] + ``` + + + +--- + +# Benchmarking with Requests + + + + Basic throughput benchmark: + + ```bash + python3 -m sgl_jax.bench_serving \ + --backend sgl-jax \ + --dataset-name random \ + --num-prompts=100 \ + --random-input=512 \ + --random-output=128 \ + --max-concurrency=8 \ + --random-range-ratio=1 \ + --warmup-requests=0 + ``` + + + Measure single-batch latency: + + ```bash + python3 -m sgl_jax.bench_one_batch_server \ + --base-url http://127.0.0.1:30000 \ + --model-path Qwen/Qwen-7B-Chat \ + --batch-size=32 \ + --input-len=256 \ + --output-len=32 + ``` + + + For systematic performance evaluation across different configurations: + + ```bash + #!/bin/bash + set -e + + backend=${1:-sgl-jax} + num_prompts_per_concurrency=3 + input_seq_lens=(1024 4096 8192) + output_seq_lens=(1 1024) + max_concurrencies=(8 16 32 64 128 256) + + for input_seq_len in "${input_seq_lens[@]}"; do + for output_seq_len in "${output_seq_lens[@]}"; do + echo "=======================================" + echo "Testing ISL/OSL: $input_seq_len/$output_seq_len" + echo "=======================================" + for max_concurrency in "${max_concurrencies[@]}"; do + num_prompts=$((num_prompts_per_concurrency * max_concurrency)) + python3 -m sgl_jax.bench_serving \ + --backend ${backend} \ + --dataset-name random \ + --num-prompts ${num_prompts} \ + --random-input ${input_seq_len} \ + --random-output ${output_seq_len} \ + --max-concurrency ${max_concurrency} \ + --random-range-ratio 1 \ + --disable-ignore-eos \ + --warmup-requests 0 + done + done + done + ``` + + For detailed help on all benchmark parameters: + + ```bash + python3 -m sgl_jax.bench_serving --help + ``` + + See the [Benchmark and Profiling Guide](../developer_guide/benchmark_and_profiling) for advanced benchmarking techniques and profiling with JAX Profiler. + + + +--- + +# Performance Optimization + + + + **Reduce memory usage:** + - Lower `--mem-fraction-static` (from `0.8` → `0.5` → `0.3`) + - Decrease `--max-prefill-tokens` (from `16384` → `8192` → `4096`) + - Reduce `--max-running-requests` + + **Handle OOM errors:** + - Start with conservative memory settings (`--mem-fraction-static=0.5`) + - Gradually increase until you find the optimal balance + - Increase `--page-size` for better memory locality (`1` → `16` → `64` → `128`) + + + To maximize tokens per second: + - Use FlashAttention backend: `--attention-backend=fa` + - Enable speculative decoding (EAGLE3) for Qwen3 models (20-40% improvement) + - Increase `--max-running-requests` to `256+` + - Set `--mem-fraction-static` to `0.8+` (if memory allows) + - Use larger page sizes (`64-128`) + - Enable chunked prefill: `--chunked-prefill-size=2048` + + + To minimize time-to-first-token (TTFT) and inter-token latency: + - Reduce `--page-size` to `1-4` + - Lower `--max-running-requests` (`16-32`) for smaller batches + - Reduce `--chunked-prefill-size` + - Use conservative memory settings to avoid GC pauses + + + **JIT Compilation Cache:** + + ```bash + export JAX_COMPILATION_CACHE_DIR=/tmp/jit_cache + ``` + + Always set this environment variable to cache compiled kernels and accelerate server startup. + + **Data Type Optimization:** Use `--dtype=bfloat16` for TPU native optimization. TPUs are specifically designed for bfloat16 computations. + + **Tensor Parallelism:** Match `--tp-size` to your TPU core configuration (`1`, `4`, or `8`) for optimal model distribution. + + **Attention Backend:** Always use `--attention-backend=fa` (FlashAttention) for production workloads. + + + +--- + +# Troubleshooting + + + + If you encounter out-of-memory errors: + + 1. **Reduce mem-fraction-static** + + Lower `--mem-fraction-static` from `0.8` to `0.5` or lower. + + 2. **Decrease max-prefill-tokens** + + Decrease `--max-prefill-tokens` from `8192` to `4096` or `2048`. + + 3. **Lower max-running-requests** + + Lower `--max-running-requests` to reduce concurrent batch size. + + 4. **Increase page-size** + + Increase `--page-size` for better memory layout efficiency. + + + If the server takes too long to start: + + Ensure `JAX_COMPILATION_CACHE_DIR` is properly set + Understand that the first run requires JIT compilation — this is normal + Subsequent runs will be significantly faster with cached compilations + Consider using `--skip-server-warmup` to defer compilation until first request + + + If you're not achieving expected throughput: + + Verify `--tp-size` matches your TPU core configuration + Check that `--attention-backend=fa` is enabled + Increase `--max-running-requests` to enable larger batch formation + Consider enabling speculative decoding for compatible models + Ensure memory settings allow for sufficient batch sizes + + + If clients cannot connect to the server: + + Ensure `--host=0.0.0.0` for external access (not just `127.0.0.1`) + Verify firewall rules allow traffic on the specified port (default: `30000`) + Check that the server process is running: `curl http://localhost:30000/health` + + + +--- + +# Advanced Features + + + + SGLang-JAX supports EAGLE and EAGLE3 speculative decoding algorithms for Qwen3 and LLaMA model families. Speculative decoding can improve throughput by 20-40% without affecting output quality. + + See the [Speculative Decoding documentation](../advanced_features/speculative_decoding) for detailed configuration and supported model combinations. + + + Enable mixed prefill-decode batching for better TPU utilization: + + ```bash + --chunked-prefill-size=2048 --enable-mixed-chunk + ``` + + This allows the scheduler to mix prefill operations with decode operations in the same batch, improving overall throughput. + + + SGLang-JAX supports a plugin-based attention backend system. You can implement custom attention kernels optimized for specific use cases. + + See the [Attention Backend documentation](https://github.com/sgl-project/sglang-jax/tree/main/docs) for implementation details. + + + Verify your TPU setup before deploying: + + ```bash + python -c "from sgl_jax import check_env; check_env.check_env()" + ``` + + This command checks: + - Installed package versions + - TPU device availability and specifications + - System resources and configuration + - Compatibility of settings + + + +--- + +# Contributing + +We welcome contributions to improve TPU support in SGLang-JAX! + + + Check the [Development Roadmap](https://github.com/sgl-project/sglang-jax) to see planned features and find opportunities to contribute new functionality. + + +Current contribution areas include: + +- Performance optimizations for specific TPU generations +- Support for additional model architectures +- Documentation improvements and examples +- Bug reports and fixes +- Benchmark results and performance analysis + + + + Visit the sglang-jax repository + + + Read the Contribution Guide + + + Join the SGL-JAX Slack community for discussions + + + +--- + +## Testing on TPU + +For contributors who need TPU access for testing: + +- Refer to the [TPU Resources Guide](https://cloud.google.com/tpu/docs/managing-tpus-tpu-vm) for information on accessing TPU hardware +- Use SkyPilot with spot instances for cost-effective testing +- Follow the [Benchmark and Profiling Guide](../developer_guide/benchmark_and_profiling) for performance validation + +--- + +# References + + + + Source code and issue tracker for the JAX TPU backend. + + + Step-by-step installation instructions. + + + Get up and running quickly with the Qwen model family. + + + Advanced benchmarking techniques and JAX Profiler usage. + + + EAGLE and EAGLE3 speculative decoding configuration. + + + Official JAX documentation and API reference. + + + Google Cloud TPU product documentation. + + + Simplified cloud deployment with SkyPilot. + + diff --git a/docs_new/docs/hardware-platforms/xpu.mdx b/docs_new/docs/hardware-platforms/xpu.mdx new file mode 100644 index 000000000..97bd3946d --- /dev/null +++ b/docs_new/docs/hardware-platforms/xpu.mdx @@ -0,0 +1,146 @@ +--- +title: XPU +sidebarTitle: Intel GPUs (XPU) +--- + +The document addresses how to set up the [SGLang](https://github.com/sgl-project/sglang) environment and run LLM inference on Intel GPU, [see more context about Intel GPU support within PyTorch ecosystem](https://docs.pytorch.org/docs/stable/notes/get_start_xpu.html). + +Specifically, SGLang is optimized for: +- [Intel® Arc™ Pro B-Series Graphics](https://www.intel.com/content/www/us/en/ark/products/series/242616/intel-arc-pro-b-series-graphics.html) +- [Intel® Arc™ B-Series Graphics](https://www.intel.com/content/www/us/en/ark/products/series/240391/intel-arc-b-series-graphics.html). + +## Optimized Model List + +A list of LLMs have been optimized on Intel GPU, and more are on the way: + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model NameBF16
Llama-3.2-3B[meta-llama/Llama-3.2-3B-Instruct](https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct)
Llama-3.1-8B[meta-llama/Llama-3.1-8B-Instruct](https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct)
Qwen2.5-1.5B[Qwen/Qwen2.5-1.5B](https://huggingface.co/Qwen/Qwen2.5-1.5B)
+ +The model identifiers listed in the table above have been verified on [Intel® Arc™ B580 Graphics](https://www.intel.com/content/www/us/en/products/sku/241598/intel-arc-b580-graphics/specifications.html). + +## Installation + + + + + + Currently SGLang XPU only supports installation from source. Please refer to [“Getting Started on Intel GPU”](https://docs.pytorch.org/docs/stable/notes/get_start_xpu.html) to install XPU dependency. + + 1. **Creation & Activation** + + Create and activate a conda environment. + + ```bash + conda create -n sgl-xpu python=3.12 -y + conda activate sgl-xpu + ``` + + 2. **Install PyTorch and Dependencies** + + Set PyTorch XPU as primary pip install channel to avoid installing the larger CUDA-enabled version and prevent potential runtime issues. + + ```bash + pip3 install torch==2.9.0+xpu torchao torchvision torchaudio pytorch-triton-xpu==3.5.0 --index-url https://download.pytorch.org/whl/xpu + pip3 install xgrammar --no-deps # xgrammar will introduce CUDA-enabled triton which might conflict with XPU + ``` + + 3. **Cloning** + + Clone the SGLang code + + ```bash + git clone https://github.com/sgl-project/sglang.git + cd sglang + git checkout + ``` + + 4. **Configure Build File** + + Use dedicated toml file + + ```bash + cd python + cp pyproject_xpu.toml pyproject.toml + ``` + + 5. **Build and Install** + + Install SGLang dependent libs, and build SGLang main package + + ```bash + pip install --upgrade pip setuptools + pip install -v . + ``` + + + + The docker for XPU is under active development. Please stay tuned. + + +## Launch of the Serving Engine + +Example command to launch SGLang serving: + + +```bash +python -m sglang.launch_server \ + --model \ + --trust-remote-code \ + --disable-overlap-schedule \ + --device xpu \ + --host 0.0.0.0 \ + --tp 2 \ # using multi GPUs + --attention-backend intel_xpu \ # using intel optimized XPU attention backend + --page-size \ # intel_xpu attention backend supports [32, 64, 128] +``` + + +## Benchmarking with Requests + +You can benchmark the performance via the `bench_serving` script. Run the command in another terminal. + + +```bash +python -m sglang.bench_serving \ + --dataset-name random \ + --random-input-len 1024 \ + --random-output-len 1024 \ + --num-prompts 1 \ + --request-rate inf \ + --random-range-ratio 1.0 +``` + + +The detail explanations of the parameters can be looked up by the command: + + +```bash +python -m sglang.bench_serving -h +``` + + +Additionally, the requests can be formed with [OpenAI Completions API](../basic_usage/openai_api_completions) and sent via the command line (e.g. using `curl`) or via your own script. diff --git a/docs_new/docs/references/custom_chat_template.mdx b/docs_new/docs/references/custom_chat_template.mdx new file mode 100644 index 000000000..19cae6004 --- /dev/null +++ b/docs_new/docs/references/custom_chat_template.mdx @@ -0,0 +1,54 @@ +--- +title: "Custom Chat Template" +metatags: + description: "SGLang custom chat templates: JSON and Jinja formats for OpenAI-compatible API server. Override tokenizer defaults." +--- +**NOTE**: There are two chat template systems in SGLang project. This document is about setting a custom chat template for the OpenAI-compatible API server (defined at [conversation.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/conversation.py)). It is NOT related to the chat template used in the SGLang language frontend (defined at [chat_template.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/lang/chat_template.py)). + +By default, the server uses the chat template specified in the model tokenizer from Hugging Face. +It should just work for most official models such as Llama-2/Llama-3. + +If needed, you can also override the chat template when launching the server: + +```bash Command +python -m sglang.launch_server \ + --model-path meta-llama/Llama-2-7b-chat-hf \ + --port 30000 \ + --chat-template llama-2 +``` + +If the chat template you are looking for is missing, you are welcome to contribute it or load it from a file. + +## JSON Format + +You can load the JSON format, which is defined by `conversation.py`. + +```json Config +{ + "name": "my_model", + "system": "<|im_start|>system", + "user": "<|im_start|>user", + "assistant": "<|im_start|>assistant", + "sep_style": "CHATML", + "sep": "<|im_end|>", + "stop_str": ["<|im_end|>", "<|im_start|>"] +} +``` + +```bash Command +python -m sglang.launch_server \ + --model-path meta-llama/Llama-2-7b-chat-hf \ + --port 30000 \ + --chat-template ./my_model_template.json +``` + +## Jinja Format + +You can also use the [Jinja template format](https://huggingface.co/docs/transformers/main/en/chat_templating) as defined by Hugging Face Transformers. + +```bash Command +python -m sglang.launch_server \ + --model-path meta-llama/Llama-2-7b-chat-hf \ + --port 30000 \ + --chat-template ./my_model_template.jinja +``` diff --git a/docs_new/docs/references/environment_variables.mdx b/docs_new/docs/references/environment_variables.mdx new file mode 100644 index 000000000..d9693284a --- /dev/null +++ b/docs_new/docs/references/environment_variables.mdx @@ -0,0 +1,652 @@ +--- +title: "Environment Variables" +metatags: + description: "SGLang environment variables: SGLANG_* and SGL_* configs for performance, memory, DeepGEMM, DeepEP, profiling." +--- +SGLang supports various environment variables that can be used to configure its runtime behavior. This document provides a comprehensive list and aims to stay updated over time. + +*Note: SGLang uses two prefixes for environment variables: `SGL_` and `SGLANG_`. This is likely due to historical reasons. While both are currently supported for different settings, future versions might consolidate them.* + +## General Configuration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_USE_MODELSCOPE`Enable using models from ModelScope`false`
`SGLANG_HOST_IP`Host IP address for the server`0.0.0.0`
`SGLANG_PORT`Port for the serverauto-detected
`SGLANG_LOGGING_CONFIG_PATH`Custom logging configuration pathNot set
`SGLANG_DISABLE_REQUEST_LOGGING`Disable request logging`false`
`SGLANG_HEALTH_CHECK_TIMEOUT`Timeout for health check in seconds`20`
`SGLANG_EPLB_HEATMAP_COLLECTION_INTERVAL`The interval of passes to collect the metric of selected count of physical experts on each layer and GPU rank. 0 means disabled.`0`
`SGLANG_FORWARD_UNKNOWN_TOOLS`Forward unknown tool calls to clients instead of dropping them`false` (drop unknown tools)
`SGLANG_QUEUED_TIMEOUT_MS`Timeout (in ms) for requests in the waiting queue`-1`
+ +## Performance Tuning + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_ENABLE_TORCH_INFERENCE_MODE`Control whether to use torch.inference_mode`false`
`SGLANG_ENABLE_TORCH_COMPILE`Enable torch.compile`true`
`SGLANG_SET_CPU_AFFINITY`Enable CPU affinity setting (often set to `1` in Docker builds)`0`
`SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN`Allows the scheduler to overwrite longer context length requests (often set to `1` in Docker builds)`0`
`SGLANG_IS_FLASHINFER_AVAILABLE`Control FlashInfer availability check`true`
`SGLANG_SKIP_P2P_CHECK`Skip P2P (peer-to-peer) access check`false`
`SGLANG_CHUNKED_PREFIX_CACHE_THRESHOLD`Sets the threshold for enabling chunked prefix caching`8192`
`SGLANG_FUSED_MLA_ENABLE_ROPE_FUSION`Enable RoPE fusion in Fused Multi-Layer Attention`1`
`SGLANG_DISABLE_CONSECUTIVE_PREFILL_OVERLAP`Disable overlap schedule for consecutive prefill batches`false`
`SGLANG_SCHEDULER_MAX_RECV_PER_POLL`Set the maximum number of requests per poll, with a negative value indicating no limit`-1`
`SGLANG_DISABLE_FA4_WARMUP`Disable Flash Attention 4 warmup passes (set to `1`, `true`, `yes`, or `on` to disable)`false`
`SGLANG_DATA_PARALLEL_BUDGET_INTERVAL`Interval for DPBudget updates`1`
`SGLANG_SCHEDULER_RECV_SKIPPER_WEIGHT_DEFAULT`Default weight value for scheduler recv skipper counter (used when forward mode doesn't match specific modes). Only active when `--scheduler-recv-interval > 1`. The counter accumulates weights and triggers request polling when reaching the interval threshold.`1000`
`SGLANG_SCHEDULER_RECV_SKIPPER_WEIGHT_DECODE`Weight increment for decode forward mode in scheduler recv skipper. Works with `--scheduler-recv-interval` to control polling frequency during decode phase.`1`
`SGLANG_SCHEDULER_RECV_SKIPPER_WEIGHT_VERIFY`Weight increment for target verify forward mode in scheduler recv skipper. Works with `--scheduler-recv-interval` to control polling frequency during verification phase.`1`
`SGLANG_SCHEDULER_RECV_SKIPPER_WEIGHT_NONE`Weight increment when forward mode is None in scheduler recv skipper. Works with `--scheduler-recv-interval` to control polling frequency when no specific forward mode is active.`1`
`SGLANG_MM_BUFFER_SIZE_MB`Size of preallocated GPU buffer (in MB) for multi-modal feature hashing optimization. When set to a positive value, temporarily moves features to GPU for faster hash computation, then moves them back to CPU to save GPU memory. Larger features benefit more from GPU hashing. Set to `0` to disable.`0`
`SGLANG_MM_PRECOMPUTE_HASH`Enable precomputing of hash values for MultimodalDataItem`false`
`SGLANG_NCCL_ALL_GATHER_IN_OVERLAP_SCHEDULER_SYNC_BATCH`Enable NCCL for gathering when preparing mlp sync batch under overlap scheduler (without this flag gloo is used for gathering)`false`
`SGLANG_SYMM_MEM_PREALLOC_GB_SIZE`Size of preallocated GPU buffer (in GB) for NCCL symmetric memory pool to limit memory fragmentation. Only have an effect when server arg `--enable-symm-mem` is set.`4`
+ + +## DeepGEMM Configuration (Advanced Optimization) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_ENABLE_JIT_DEEPGEMM`Enable Just-In-Time compilation of DeepGEMM kernels (enabled by default on NVIDIA Hopper (SM90) and Blackwell (SM100) GPUs when the DeepGEMM package is installed; set to `"0"` to disable)`"true"`
`SGLANG_JIT_DEEPGEMM_PRECOMPILE`Enable precompilation of DeepGEMM kernels`"true"`
`SGLANG_JIT_DEEPGEMM_COMPILE_WORKERS`Number of workers for parallel DeepGEMM kernel compilation`4`
`SGLANG_IN_DEEPGEMM_PRECOMPILE_STAGE`Indicator flag used during the DeepGEMM precompile script`"false"`
`SGLANG_DG_CACHE_DIR`Directory for caching compiled DeepGEMM kernels`~/.cache/deep_gemm`
`SGL_DG_USE_NVRTC`Use NVRTC (instead of Triton) for JIT compilation (Experimental)`"0"`
`SGL_USE_DEEPGEMM_BMM`Use DeepGEMM for Batched Matrix Multiplication (BMM) operations`"false"`
+ +## DeepEP Configuration + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_DEEPEP_BF16_DISPATCH`Use Bfloat16 for dispatch`"false"`
`SGLANG_DEEPEP_NUM_MAX_DISPATCH_TOKENS_PER_RANK`The maximum number of dispatched tokens on each GPU`"128"`
`SGLANG_FLASHINFER_NUM_MAX_DISPATCH_TOKENS_PER_RANK`The maximum number of dispatched tokens on each GPU for --moe-a2a-backend=flashinfer`"1024"`
`SGLANG_DEEPEP_LL_COMBINE_SEND_NUM_SMS`Number of SMs used for DeepEP combine when single batch overlap is enabled`"32"`
`SGLANG_BLACKWELL_OVERLAP_SHARED_EXPERTS_OUTSIDE_SBO`Run shared experts on an alternate stream when single batch overlap is enabled on GB200. When not setting this flag, shared experts and down gemm will be overlapped with DeepEP combine together.`"false"`
+ +## NSA Backend Configuration (For DeepSeek V3.2) + +{/* # Environment variable to control mtp precomputing of metadata for multi-step speculative decoding */} + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_NSA_FUSE_TOPK`Fuse the operation of picking topk logits and picking topk indices from page table`true`
`SGLANG_NSA_ENABLE_MTP_PRECOMPUTE_METADATA`Precompute metadata that can be shared among different draft steps when MTP is enabled`true`
+ + +## Memory Management + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_DEBUG_MEMORY_POOL`Enable memory pool debugging`false`
`SGLANG_CLIP_MAX_NEW_TOKENS_ESTIMATION`Clip max new tokens estimation for memory planning`4096`
`SGLANG_DETOKENIZER_MAX_STATES`Maximum states for detokenizerDefault value based on system
`SGLANG_ENABLE_TP_MEMORY_INBALANCE_CHECK`Enable checks for memory imbalance across Tensor Parallel ranks`true`
+ +## Model-Specific Options + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_USE_AITER`Use AITER optimize implementation`false`
`SGLANG_MOE_PADDING`Enable MoE padding (sets padding size to 128 if value is `1`, often set to `1` in Docker builds)`0`
`SGLANG_CUTLASS_MOE` (deprecated)Use Cutlass FP8 MoE kernel on Blackwell GPUs (deprecated, use --moe-runner-backend=cutlass)`false`
+ +## Quantization + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_INT4_WEIGHT`Enable INT4 weight quantization`false`
`SGLANG_PER_TOKEN_GROUP_QUANT_8BIT_V2`Apply per token group quantization kernel with fused silu and mul and masked m`false`
`SGLANG_FORCE_FP8_MARLIN`Force using FP8 MARLIN kernels even if other FP8 kernels are available`false`
`SGLANG_FLASHINFER_FP4_GEMM_BACKEND` (deprecated)Select backend for `mm_fp4` on Blackwell GPUs. **DEPRECATED**: Please use `--fp4-gemm-backend` instead.``
`SGLANG_NVFP4_CKPT_FP8_GEMM_IN_ATTN`Quantize q_b_proj from BF16 to FP8 when launching DeepSeek NVFP4 checkpoint`false`
`SGLANG_MOE_NVFP4_DISPATCH`Use nvfp4 for moe dispatch (on flashinfer_cutlass or flashinfer_cutedsl moe runner backend)`"false"`
`SGLANG_NVFP4_CKPT_FP8_NEXTN_MOE`Quantize moe of nextn layer from BF16 to FP8 when launching DeepSeek NVFP4 checkpoint`false`
`SGLANG_ENABLE_FLASHINFER_FP8_GEMM` (deprecated)Use flashinfer kernels when running blockwise fp8 GEMM on Blackwell GPUs. **DEPRECATED**: Please use `--fp8-gemm-backend=flashinfer_trtllm` instead.`false`
`SGLANG_SUPPORT_CUTLASS_BLOCK_FP8` (deprecated)Use Cutlass kernels when running blockwise fp8 GEMM on Hopper or Blackwell GPUs. **DEPRECATED**: Please use `--fp8-gemm-backend=cutlass` instead.`false`
+ + +## Distributed Computing + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_BLOCK_NONZERO_RANK_CHILDREN`Control blocking of non-zero rank children processes`1`
`SGLANG_IS_FIRST_RANK_ON_NODE`Indicates if the current process is the first rank on its node`"true"`
`SGLANG_PP_LAYER_PARTITION`Pipeline parallel layer partition specificationNot set
`SGLANG_ONE_VISIBLE_DEVICE_PER_PROCESS`Set one visible device per process for distributed computing`false`
+ +## Testing & Debugging (Internal/CI) + +*These variables are primarily used for internal testing, continuous integration, or debugging.* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_IS_IN_CI`Indicates if running in CI environment`false`
`SGLANG_IS_IN_CI_AMD`Indicates running in AMD CI environment`0`
`SGLANG_TEST_RETRACT`Enable retract decode testing`false`
`SGLANG_TEST_RETRACT_NO_PREFILL_BS`When SGLANG_TEST_RETRACT is enabled, no prefill is performed if the batch size exceeds SGLANG_TEST_RETRACT_NO_PREFILL_BS.`2 ** 31`
`SGLANG_RECORD_STEP_TIME`Record step time for profiling`false`
`SGLANG_TEST_REQUEST_TIME_STATS`Test request time statistics`false`
+ +## Profiling & Benchmarking + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_TORCH_PROFILER_DIR`Directory for PyTorch profiler output`/tmp`
`SGLANG_PROFILE_WITH_STACK`Set `with_stack` option (bool) for PyTorch profiler (capture stack trace)`true`
`SGLANG_PROFILE_RECORD_SHAPES`Set `record_shapes` option (bool) for PyTorch profiler (record shapes)`true`
`SGLANG_OTLP_EXPORTER_SCHEDULE_DELAY_MILLIS`Config BatchSpanProcessor.schedule_delay_millis if tracing is enabled`500`
`SGLANG_OTLP_EXPORTER_MAX_EXPORT_BATCH_SIZE`Config BatchSpanProcessor.max_export_batch_size if tracing is enabled`64`
+ +## Storage & Caching + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
`SGLANG_WAIT_WEIGHTS_READY_TIMEOUT`Timeout period for waiting on weights`120`
`SGLANG_DISABLE_OUTLINES_DISK_CACHE`Disable Outlines disk cache`true`
`SGLANG_USE_CUSTOM_TRITON_KERNEL_CACHE`Use SGLang's custom Triton kernel cache implementation for lower overheads (automatically enabled on CUDA)`false`
+ +## Function Calling / Tool Use + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDescriptionDefault Value
` SGLANG_TOOL_STRICT_LEVEL`Controls strictness for tool-call parsing and validation: **Level 0** off (no strict validation); **Level 1** function strict (enables structural tag constraints for all tools, even if none have `strict=True`); **Level 2** parameter strict (enforces strict parameter validation for all tools as if all had `strict=True`).` 0`
diff --git a/docs_new/docs/references/faq.mdx b/docs_new/docs/references/faq.mdx new file mode 100644 index 000000000..a2cb48695 --- /dev/null +++ b/docs_new/docs/references/faq.mdx @@ -0,0 +1,42 @@ +--- +title: "Troubleshooting and Frequently Asked Questions" +metatags: + description: "SGLang troubleshooting: CUDA OOM, illegal memory access, server hangs, non-deterministic outputs." +--- +## Troubleshooting + +This page lists common errors and tips for resolving them. + +### CUDA Out of Memory +If you encounter out-of-memory (OOM) errors, you can adjust the following parameters: + +- If OOM occurs during prefill, try reducing `--chunked-prefill-size` to `4096` or `2048`. This saves memory but slows down the prefill speed for long prompts. +- If OOM occurs during decoding, try lowering `--max-running-requests`. +- You can also decrease `--mem-fraction-static` to a smaller value, such as 0.8 or 0.7. This decreases the memory usage of the KV cache memory pool and helps prevent OOM errors during both prefill and decoding. However, it limits maximum concurrency and reduces peak throughput. +- Another common case for OOM is requesting input logprobs for a long prompt as it requires significant memory. To address this, set `logprob_start_len` in your sampling parameters to include only the necessary parts. If you do need input logprobs for a long prompt, try reducing `--mem-fraction-static`. + +### CUDA Error: Illegal Memory Access Encountered +This error may result from kernel errors or out-of-memory issues: +- If it is a kernel error, resolving it may be challenging. Please file an issue on GitHub. +- If it is an out-of-memory issue, it may sometimes be reported as this error instead of "Out of Memory." Refer to the section above for guidance on avoiding OOM issues. + +### The server hangs +- If the server hangs during initialization or running, it can be memory issues (out of memory), network issues (nccl errors), or other bugs in sglang. + - If it is out of memory, you might see that `avail mem` is very low during the initialization or right after initialization. In this case, + you can try to decrease `--mem-fraction-static`, decrease `--cuda-graph-max-bs`, or decrease `--chunked-prefill-size`. +- Other bugs, please file an issue on GitHub. + + +## Frequently Asked Questions + +### The results are not deterministic, even with a temperature of 0 + +You may notice that when you send the same request twice, the results from the engine will be slightly different, even when the temperature is set to 0. + +From our initial investigation, this indeterminism arises from two factors: dynamic batching and prefix caching. Roughly speaking, dynamic batching accounts for about 95% of the indeterminism, while prefix caching accounts for the remaining portion. The server runs dynamic batching under the hood. Different batch sizes can cause PyTorch/CuBLAS to dispatch to different CUDA kernels, which can lead to slight numerical differences. This difference accumulates across many layers, resulting in nondeterministic output when the batch size changes. Similarly, when prefix caching is enabled, it can also dispatch to different kernels. Even when the computations are mathematically equivalent, small numerical differences from different kernel implementations lead to the final nondeterministic outputs. + +To achieve more deterministic outputs in the current code, you can add `--disable-radix-cache` and send only one request at a time. The results will be mostly deterministic under this setting. + +**Update**: +Recently, we also introduced a deterministic mode, you can enable it with `--enable-deterministic-inference`. +Please find more details in this blog post: https://lmsys.org/blog/2025-09-22-sglang-deterministic/ diff --git a/docs_new/docs/references/frontend/choices_methods.mdx b/docs_new/docs/references/frontend/choices_methods.mdx new file mode 100644 index 000000000..6bfa8747c --- /dev/null +++ b/docs_new/docs/references/frontend/choices_methods.mdx @@ -0,0 +1,81 @@ +--- +title: "Choices Methods in SGLang" +metatags: + description: "SGLang choices methods: token_length_normalized, greedy_token_selection, unconditional_likelihood_normalized." +--- +This doc describes the choices methods supported by SGLang. + +The optional `choices_method` arg determines how options supplied to SGLang's `choices` primitive are selected. Only the `RuntimeEndpoint` backend supports the `choices_method` arg. Other backends, such as `OpenAI`, have bespoke selection implementations due to API limitations. + +## Methods + +### Token Length Normalized + +Token length normalized is the default SGLang choices method. It selects the option with the highest average logprob across all of its tokens. + +Usage example (alternatively, simply omit the `choices_method` arg): +```python Example +@sgl.function +def example(s): + s += sgl.user("What is the capital of France?") + s += sgl.assistant( + sgl.gen( + "answer", + choices=["London", "Paris", "Berlin"], + choices_method=sgl.token_length_normalized, + ) + ) +``` + + +This can perform poorly if an option contains many tokens, where its later tokens are predicted with high confidence based on its earlier tokens. For instance, even strong models will fail the above example if the specified options are `["Paris", "Antidisestablishmentarianism"]`. + +### Greedy Token Selection + +Greedy token selection simply selects the option with the highest logprob for its initial token. For overlapping options where one option is a subset of a longer option, the logprobs of the shorter option are extended using its average logprob for comparison against the longer option. + +Usage example: +```python Example +@sgl.function +def example(s): + s += sgl.user("What is the capital of France?") + s += sgl.assistant( + sgl.gen( + "answer", + choices=["London", "Paris", "Berlin"], + choices_method=sgl.greedy_token_selection, + ) + ) +``` + +This can perform poorly if an option misleads the model down a bad path based on an attractive initial token. For instance, greedy selection will result in an incorrect response for this example: +```python Example +@sgl.function +def us_president_example(s): + s += sgl.user("Name a US president.") + s += sgl.assistant( + sgl.gen( + "answer", + choices=["Donald Duck", "Millard Fillmore"], + choices_method=sgl.greedy_token_selection, + ) + ) +``` + +### Unconditional Likelihood Normalized + +Unconditional likelihood normalized selects the option with the highest average token logprob once normalized by the unconditional token logprobs, as described in [this EleutherAI blogpost](https://blog.eleuther.ai/multiple-choice-normalization/). This method incurs an additional LLM call to obtain the unconditional likelihoods. + +Usage example: +```python Example +@sgl.function +def example(s): + s += sgl.user("What is the capital of France?") + s += sgl.assistant( + sgl.gen( + "answer", + choices=["London", "Paris", "Berlin"], + choices_method=sgl.unconditional_likelihood_normalized, + ) + ) +``` diff --git a/docs_new/docs/references/frontend/frontend_index.mdx b/docs_new/docs/references/frontend/frontend_index.mdx new file mode 100644 index 000000000..0e5daf0c9 --- /dev/null +++ b/docs_new/docs/references/frontend/frontend_index.mdx @@ -0,0 +1,7 @@ +--- +title: "Frontend Language" +metatags: + description: "SGLang frontend language documentation: tutorials and choices methods reference." +--- +- [Frontend Tutorial](./frontend_tutorial) +- [Choices Methods](./choices_methods) diff --git a/docs_new/docs/references/frontend/frontend_index.rst b/docs_new/docs/references/frontend/frontend_index.rst new file mode 100644 index 000000000..62544cba5 --- /dev/null +++ b/docs_new/docs/references/frontend/frontend_index.rst @@ -0,0 +1,9 @@ +Frontend Language +================= + +.. toctree:: + :maxdepth: 1 + :caption: Frontend Language + + frontend_tutorial.ipynb + choices_methods.md diff --git a/docs_new/docs/references/frontend/frontend_tutorial.ipynb b/docs_new/docs/references/frontend/frontend_tutorial.ipynb new file mode 100644 index 000000000..166f8cacc --- /dev/null +++ b/docs_new/docs/references/frontend/frontend_tutorial.ipynb @@ -0,0 +1,456 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# SGLang Frontend Language" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "SGLang frontend language can be used to define simple and easy prompts in a convenient, structured way." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Launch A Server\n", + "\n", + "Launch the server in your terminal and wait for it to initialize." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from sglang import assistant_begin, assistant_end\n", + "from sglang import assistant, function, gen, system, user\n", + "from sglang import image\n", + "from sglang import RuntimeEndpoint\n", + "from sglang.lang.api import set_default_backend\n", + "from sglang.srt.utils import load_image\n", + "from sglang.test.doc_patch import launch_server_cmd\n", + "from sglang.utils import print_highlight, terminate_process, wait_for_server\n", + "\n", + "server_process, port = launch_server_cmd(\n", + " \"python -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --host 0.0.0.0 --log-level warning\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")\n", + "print(f\"Server started on http://localhost:{port}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Set the default backend. Note: Besides the local server, you may use also `OpenAI` or other API endpoints." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "set_default_backend(RuntimeEndpoint(f\"http://localhost:{port}\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Basic Usage\n", + "\n", + "The most simple way of using SGLang frontend language is a simple question answer dialog between a user and an assistant." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def basic_qa(s, question):\n", + " s += system(f\"You are a helpful assistant than can answer questions.\")\n", + " s += user(question)\n", + " s += assistant(gen(\"answer\", max_tokens=512))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "state = basic_qa(\"List 3 countries and their capitals.\")\n", + "print_highlight(state[\"answer\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Multi-turn Dialog\n", + "\n", + "SGLang frontend language can also be used to define multi-turn dialogs." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def multi_turn_qa(s):\n", + " s += system(f\"You are a helpful assistant than can answer questions.\")\n", + " s += user(\"Please give me a list of 3 countries and their capitals.\")\n", + " s += assistant(gen(\"first_answer\", max_tokens=512))\n", + " s += user(\"Please give me another list of 3 countries and their capitals.\")\n", + " s += assistant(gen(\"second_answer\", max_tokens=512))\n", + " return s\n", + "\n", + "\n", + "state = multi_turn_qa()\n", + "print_highlight(state[\"first_answer\"])\n", + "print_highlight(state[\"second_answer\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Control flow\n", + "\n", + "You may use any Python code within the function to define more complex control flows." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def tool_use(s, question):\n", + " s += assistant(\n", + " \"To answer this question: \"\n", + " + question\n", + " + \". I need to use a \"\n", + " + gen(\"tool\", choices=[\"calculator\", \"search engine\"])\n", + " + \". \"\n", + " )\n", + "\n", + " if s[\"tool\"] == \"calculator\":\n", + " s += assistant(\"The math expression is: \" + gen(\"expression\"))\n", + " elif s[\"tool\"] == \"search engine\":\n", + " s += assistant(\"The key word to search is: \" + gen(\"word\"))\n", + "\n", + "\n", + "state = tool_use(\"What is 2 * 2?\")\n", + "print_highlight(state[\"tool\"])\n", + "print_highlight(state[\"expression\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Parallelism\n", + "\n", + "Use `fork` to launch parallel prompts. Because `sgl.gen` is non-blocking, the for loop below issues two generation calls in parallel." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def tip_suggestion(s):\n", + " s += assistant(\n", + " \"Here are two tips for staying healthy: \"\n", + " \"1. Balanced Diet. 2. Regular Exercise.\\n\\n\"\n", + " )\n", + "\n", + " forks = s.fork(2)\n", + " for i, f in enumerate(forks):\n", + " f += assistant(\n", + " f\"Now, expand tip {i+1} into a paragraph:\\n\"\n", + " + gen(\"detailed_tip\", max_tokens=256, stop=\"\\n\\n\")\n", + " )\n", + "\n", + " s += assistant(\"Tip 1:\" + forks[0][\"detailed_tip\"] + \"\\n\")\n", + " s += assistant(\"Tip 2:\" + forks[1][\"detailed_tip\"] + \"\\n\")\n", + " s += assistant(\n", + " \"To summarize the above two tips, I can say:\\n\" + gen(\"summary\", max_tokens=512)\n", + " )\n", + "\n", + "\n", + "state = tip_suggestion()\n", + "print_highlight(state[\"summary\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Constrained Decoding\n", + "\n", + "Use `regex` to specify a regular expression as a decoding constraint. This is only supported for local models." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def regular_expression_gen(s):\n", + " s += user(\"What is the IP address of the Google DNS servers?\")\n", + " s += assistant(\n", + " gen(\n", + " \"answer\",\n", + " temperature=0,\n", + " regex=r\"((25[0-5]|2[0-4]\\d|[01]?\\d\\d?).){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\",\n", + " )\n", + " )\n", + "\n", + "\n", + "state = regular_expression_gen()\n", + "print_highlight(state[\"answer\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use `regex` to define a `JSON` decoding schema." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "character_regex = (\n", + " r\"\"\"\\{\\n\"\"\"\n", + " + r\"\"\" \"name\": \"[\\w\\d\\s]{1,16}\",\\n\"\"\"\n", + " + r\"\"\" \"house\": \"(Gryffindor|Slytherin|Ravenclaw|Hufflepuff)\",\\n\"\"\"\n", + " + r\"\"\" \"blood status\": \"(Pure-blood|Half-blood|Muggle-born)\",\\n\"\"\"\n", + " + r\"\"\" \"occupation\": \"(student|teacher|auror|ministry of magic|death eater|order of the phoenix)\",\\n\"\"\"\n", + " + r\"\"\" \"wand\": \\{\\n\"\"\"\n", + " + r\"\"\" \"wood\": \"[\\w\\d\\s]{1,16}\",\\n\"\"\"\n", + " + r\"\"\" \"core\": \"[\\w\\d\\s]{1,16}\",\\n\"\"\"\n", + " + r\"\"\" \"length\": [0-9]{1,2}\\.[0-9]{0,2}\\n\"\"\"\n", + " + r\"\"\" \\},\\n\"\"\"\n", + " + r\"\"\" \"alive\": \"(Alive|Deceased)\",\\n\"\"\"\n", + " + r\"\"\" \"patronus\": \"[\\w\\d\\s]{1,16}\",\\n\"\"\"\n", + " + r\"\"\" \"bogart\": \"[\\w\\d\\s]{1,16}\"\\n\"\"\"\n", + " + r\"\"\"\\}\"\"\"\n", + ")\n", + "\n", + "\n", + "@function\n", + "def character_gen(s, name):\n", + " s += user(\n", + " f\"{name} is a character in Harry Potter. Please fill in the following information about this character.\"\n", + " )\n", + " s += assistant(gen(\"json_output\", max_tokens=256, regex=character_regex))\n", + "\n", + "\n", + "state = character_gen(\"Harry Potter\")\n", + "print_highlight(state[\"json_output\"])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Batching \n", + "\n", + "Use `run_batch` to run a batch of prompts." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def text_qa(s, question):\n", + " s += user(question)\n", + " s += assistant(gen(\"answer\", stop=\"\\n\"))\n", + "\n", + "\n", + "states = text_qa.run_batch(\n", + " [\n", + " {\"question\": \"What is the capital of the United Kingdom?\"},\n", + " {\"question\": \"What is the capital of France?\"},\n", + " {\"question\": \"What is the capital of Japan?\"},\n", + " ],\n", + " progress_bar=True,\n", + ")\n", + "\n", + "for i, state in enumerate(states):\n", + " print_highlight(f\"Answer {i+1}: {states[i]['answer']}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Streaming \n", + "\n", + "Use `stream` to stream the output to the user." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def text_qa(s, question):\n", + " s += user(question)\n", + " s += assistant(gen(\"answer\", stop=\"\\n\"))\n", + "\n", + "\n", + "state = text_qa.run(\n", + " question=\"What is the capital of France?\", temperature=0.1, stream=True\n", + ")\n", + "\n", + "for out in state.text_iter():\n", + " print(out, end=\"\", flush=True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Complex Prompts\n", + "\n", + "You may use `{system|user|assistant}_{begin|end}` to define complex prompts." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def chat_example(s):\n", + " s += system(\"You are a helpful assistant.\")\n", + " # Same as: s += s.system(\"You are a helpful assistant.\")\n", + "\n", + " with s.user():\n", + " s += \"Question: What is the capital of France?\"\n", + "\n", + " s += assistant_begin()\n", + " s += \"Answer: \" + gen(\"answer\", max_tokens=100, stop=\"\\n\")\n", + " s += assistant_end()\n", + "\n", + "\n", + "state = chat_example()\n", + "print_highlight(state[\"answer\"])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Multi-modal Generation\n", + "\n", + "You may use SGLang frontend language to define multi-modal prompts.\n", + "See [here](https://docs.sglang.io/supported_models/generative_models.html) for supported models." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "server_process, port = launch_server_cmd(\n", + " \"python -m sglang.launch_server --model-path Qwen/Qwen2.5-VL-7B-Instruct --host 0.0.0.0 --log-level warning\"\n", + ")\n", + "\n", + "wait_for_server(f\"http://localhost:{port}\")\n", + "print(f\"Server started on http://localhost:{port}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "set_default_backend(RuntimeEndpoint(f\"http://localhost:{port}\"))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Ask a question about an image." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "@function\n", + "def image_qa(s, image_file, question):\n", + " s += user(image(image_file) + question)\n", + " s += assistant(gen(\"answer\", max_tokens=256))\n", + "\n", + "\n", + "image_url = \"https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true\"\n", + "image_bytes, _ = load_image(image_url)\n", + "state = image_qa(image_bytes, \"What is in the image?\")\n", + "print_highlight(state[\"answer\"])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "terminate_process(server_process)" + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/docs_new/docs/references/frontend/frontend_tutorial.mdx b/docs_new/docs/references/frontend/frontend_tutorial.mdx new file mode 100644 index 000000000..6814095ac --- /dev/null +++ b/docs_new/docs/references/frontend/frontend_tutorial.mdx @@ -0,0 +1,318 @@ +--- +title: "SGLang Frontend Language" +metatags: + description: "SGLang frontend tutorial: multi-turn dialog, fork parallelism, regex constraints, batching, streaming." +--- +SGLang frontend language can be used to define simple and easy prompts in a convenient, structured way. + + +## Launch A Server + +Launch the server in your terminal and wait for it to initialize. + + + +```python Example +from sglang import assistant_begin, assistant_end +from sglang import assistant, function, gen, system, user +from sglang import image +from sglang import RuntimeEndpoint +from sglang.lang.api import set_default_backend +from sglang.srt.utils import load_image +from sglang.test.doc_patch import launch_server_cmd +from sglang.utils import print_highlight, terminate_process, wait_for_server + +server_process, port = launch_server_cmd( + "python -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --host 0.0.0.0 --log-level warning" +) + +wait_for_server(f"http://localhost:{port}") +print(f"Server started on http://localhost:{port}") +``` + +Set the default backend. Note: Besides the local server, you may use also `OpenAI` or other API endpoints. + + + +```python Example +set_default_backend(RuntimeEndpoint(f"http://localhost:{port}")) +``` + +## Basic Usage + +The most simple way of using SGLang frontend language is a simple question answer dialog between a user and an assistant. + + + +```python Example +@function +def basic_qa(s, question): + s += system(f"You are a helpful assistant than can answer questions.") + s += user(question) + s += assistant(gen("answer", max_tokens=512)) +``` + + +```python Example +state = basic_qa("List 3 countries and their capitals.") +print_highlight(state["answer"]) +``` + +## Multi-turn Dialog + +SGLang frontend language can also be used to define multi-turn dialogs. + + + +```python Example +@function +def multi_turn_qa(s): + s += system(f"You are a helpful assistant than can answer questions.") + s += user("Please give me a list of 3 countries and their capitals.") + s += assistant(gen("first_answer", max_tokens=512)) + s += user("Please give me another list of 3 countries and their capitals.") + s += assistant(gen("second_answer", max_tokens=512)) + return s + + +state = multi_turn_qa() +print_highlight(state["first_answer"]) +print_highlight(state["second_answer"]) +``` + +## Control flow + +You may use any Python code within the function to define more complex control flows. + + + +```python Example +@function +def tool_use(s, question): + s += assistant( + "To answer this question: " + + question + + ". I need to use a " + + gen("tool", choices=["calculator", "search engine"]) + + ". " + ) + + if s["tool"] == "calculator": + s += assistant("The math expression is: " + gen("expression")) + elif s["tool"] == "search engine": + s += assistant("The key word to search is: " + gen("word")) + + +state = tool_use("What is 2 * 2?") +print_highlight(state["tool"]) +print_highlight(state["expression"]) +``` + +## Parallelism + +Use `fork` to launch parallel prompts. Because `sgl.gen` is non-blocking, the for loop below issues two generation calls in parallel. + + + +```python Example +@function +def tip_suggestion(s): + s += assistant( + "Here are two tips for staying healthy: " + "1. Balanced Diet. 2. Regular Exercise.\n\n" + ) + + forks = s.fork(2) + for i, f in enumerate(forks): + f += assistant( + f"Now, expand tip {i+1} into a paragraph:\n" + + gen("detailed_tip", max_tokens=256, stop="\n\n") + ) + + s += assistant("Tip 1:" + forks[0]["detailed_tip"] + "\n") + s += assistant("Tip 2:" + forks[1]["detailed_tip"] + "\n") + s += assistant( + "To summarize the above two tips, I can say:\n" + gen("summary", max_tokens=512) + ) + + +state = tip_suggestion() +print_highlight(state["summary"]) +``` + +## Constrained Decoding + +Use `regex` to specify a regular expression as a decoding constraint. This is only supported for local models. + + + +```python Example +@function +def regular_expression_gen(s): + s += user("What is the IP address of the Google DNS servers?") + s += assistant( + gen( + "answer", + temperature=0, + regex=r"((25[0-5]|2[0-4]\d|[01]?\d\d?).){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)", + ) + ) + + +state = regular_expression_gen() +print_highlight(state["answer"]) +``` + +Use `regex` to define a `JSON` decoding schema. + + + +```python Example +character_regex = ( + r"""\{\n""" + + r""" "name": "[\w\d\s]{1,16}",\n""" + + r""" "house": "(Gryffindor|Slytherin|Ravenclaw|Hufflepuff)",\n""" + + r""" "blood status": "(Pure-blood|Half-blood|Muggle-born)",\n""" + + r""" "occupation": "(student|teacher|auror|ministry of magic|death eater|order of the phoenix)",\n""" + + r""" "wand": \{\n""" + + r""" "wood": "[\w\d\s]{1,16}",\n""" + + r""" "core": "[\w\d\s]{1,16}",\n""" + + r""" "length": [0-9]{1,2}\.[0-9]{0,2}\n""" + + r""" \},\n""" + + r""" "alive": "(Alive|Deceased)",\n""" + + r""" "patronus": "[\w\d\s]{1,16}",\n""" + + r""" "bogart": "[\w\d\s]{1,16}"\n""" + + r"""\}""" +) + + +@function +def character_gen(s, name): + s += user( + f"{name} is a character in Harry Potter. Please fill in the following information about this character." + ) + s += assistant(gen("json_output", max_tokens=256, regex=character_regex)) + + +state = character_gen("Harry Potter") +print_highlight(state["json_output"]) +``` + +## Batching + +Use `run_batch` to run a batch of prompts. + + + +```python Example +@function +def text_qa(s, question): + s += user(question) + s += assistant(gen("answer", stop="\n")) + + +states = text_qa.run_batch( + [ + {"question": "What is the capital of the United Kingdom?"}, + {"question": "What is the capital of France?"}, + {"question": "What is the capital of Japan?"}, + ], + progress_bar=True, +) + +for i, state in enumerate(states): + print_highlight(f"Answer {i+1}: {states[i]['answer']}") +``` + +## Streaming + +Use `stream` to stream the output to the user. + + + +```python Example +@function +def text_qa(s, question): + s += user(question) + s += assistant(gen("answer", stop="\n")) + + +state = text_qa.run( + question="What is the capital of France?", temperature=0.1, stream=True +) + +for out in state.text_iter(): + print(out, end="", flush=True) +``` + +## Complex Prompts + +You may use `{system|user|assistant}_{begin|end}` to define complex prompts. + + + +```python Example +@function +def chat_example(s): + s += system("You are a helpful assistant.") + # Same as: s += s.system("You are a helpful assistant.") + + with s.user(): + s += "Question: What is the capital of France?" + + s += assistant_begin() + s += "Answer: " + gen("answer", max_tokens=100, stop="\n") + s += assistant_end() + + +state = chat_example() +print_highlight(state["answer"]) +``` + + +```python Example +terminate_process(server_process) +``` + +## Multi-modal Generation + +You may use SGLang frontend language to define multi-modal prompts. +See [here](../../supported-models/large-language-models) for supported models. + + + +```python Example +server_process, port = launch_server_cmd( + "python -m sglang.launch_server --model-path Qwen/Qwen2.5-VL-7B-Instruct --host 0.0.0.0 --log-level warning" +) + +wait_for_server(f"http://localhost:{port}") +print(f"Server started on http://localhost:{port}") +``` + + +```python Example +set_default_backend(RuntimeEndpoint(f"http://localhost:{port}")) +``` + +Ask a question about an image. + + + +```python Example +@function +def image_qa(s, image_file, question): + s += user(image(image_file) + question) + s += assistant(gen("answer", max_tokens=256)) + + +image_url = "https://github.com/sgl-project/sglang/blob/main/examples/assets/example_image.png?raw=true" +image_bytes, _ = load_image(image_url) +state = image_qa(image_bytes, "What is in the image?") +print_highlight(state["answer"]) +``` + + +```python Example +terminate_process(server_process) +``` diff --git a/docs_new/docs/references/multi_node_deployment/deploy_on_k8s.mdx b/docs_new/docs/references/multi_node_deployment/deploy_on_k8s.mdx new file mode 100644 index 000000000..e2070fd1c --- /dev/null +++ b/docs_new/docs/references/multi_node_deployment/deploy_on_k8s.mdx @@ -0,0 +1,340 @@ +--- +title: "Deploy On Kubernetes" +metatags: + description: "SGLang on Kubernetes with LWS: DeepSeek-R1 multi-node deployment, RoCE RDMA setup, NCCL debugging." +--- +This document is for deploying a RoCE network-based SGLang two-node inference service on a Kubernetes (K8S) cluster. + +[LeaderWorkerSet (LWS)](https://github.com/kubernetes-sigs/lws) is a Kubernetes API that aims to address common deployment patterns of AI/ML inference workloads. A major use case is for multi-host/multi-node distributed inference. + +SGLang can also be deployed with LWS on Kubernetes for distributed model serving. + +Please see this guide for more details on deploying SGLang on Kubernetes using LWS. + +Here we take the deployment of DeepSeek-R1 as an example. + +## Prerequisites + +1. At least two Kubernetes nodes, each with two H20 systems and eight GPUs, are required. + +2. Make sure your K8S cluster has LWS correctly installed. If it hasn't been set up yet, please follow the [installation instructions](https://github.com/kubernetes-sigs/lws/blob/main/site/content/en/docs/installation/_index). **Note:** For LWS versions ≤0.5.x, you must use the Downward API to obtain `LWS_WORKER_INDEX`, as native support for this feature was introduced in v0.6.0. + +## Basic example + +For the basic example documentation, refer to [Deploy Distributed Inference Service with SGLang and LWS on GPUs](https://github.com/kubernetes-sigs/lws/tree/main/docs/examples/sglang). + +However, that document only covers the basic NCCL socket mode. + +In this section, we’ll make some simple modifications to adapt the setup to the RDMA scenario. + +## RDMA RoCE case + +* Check your env: + +```bash Command +[root@node1 ~]# ibstatus +Infiniband device 'mlx5_bond_0' port 1 status: + default gid: fe80:0000:0000:0000:0225:9dff:fe64:c79a + base lid: 0x0 + sm lid: 0x0 + state: 4: ACTIVE + phys state: 5: LinkUp + rate: 200 Gb/sec (2X NDR) + link_layer: Ethernet + +Infiniband device 'mlx5_bond_1' port 1 status: + default gid: fe80:0000:0000:0000:0225:9dff:fe6e:c3ec + base lid: 0x0 + sm lid: 0x0 + state: 4: ACTIVE + phys state: 5: LinkUp + rate: 200 Gb/sec (2X NDR) + link_layer: Ethernet + +Infiniband device 'mlx5_bond_2' port 1 status: + default gid: fe80:0000:0000:0000:0225:9dff:fe73:0dd7 + base lid: 0x0 + sm lid: 0x0 + state: 4: ACTIVE + phys state: 5: LinkUp + rate: 200 Gb/sec (2X NDR) + link_layer: Ethernet + +Infiniband device 'mlx5_bond_3' port 1 status: + default gid: fe80:0000:0000:0000:0225:9dff:fe36:f7ff + base lid: 0x0 + sm lid: 0x0 + state: 4: ACTIVE + phys state: 5: LinkUp + rate: 200 Gb/sec (2X NDR) + link_layer: Ethernet +``` + +* Prepare the `lws.yaml` file for deploying on k8s. + +```yaml Config +apiVersion: leaderworkerset.x-k8s.io/v1 +kind: LeaderWorkerSet +metadata: + name: sglang +spec: + replicas: 1 + leaderWorkerTemplate: + size: 2 + restartPolicy: RecreateGroupOnPodRestart + leaderTemplate: + metadata: + labels: + role: leader + spec: + dnsPolicy: ClusterFirstWithHostNet + hostNetwork: true + hostIPC: true + containers: + - name: sglang-leader + image: sglang:latest + securityContext: + privileged: true + env: + - name: NCCL_IB_GID_INDEX + value: "3" + command: + - python3 + - -m + - sglang.launch_server + - --model-path + - /work/models + - --mem-fraction-static + - "0.93" + - --torch-compile-max-bs + - "8" + - --max-running-requests + - "20" + - --tp + - "16" # Size of Tensor Parallelism + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20000 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + - --host + - "0.0.0.0" + - --port + - "40000" + resources: + limits: + nvidia.com/gpu: "8" + ports: + - containerPort: 40000 + readinessProbe: + tcpSocket: + port: 40000 + initialDelaySeconds: 15 + periodSeconds: 10 + volumeMounts: + - mountPath: /dev/shm + name: dshm + - name: model + mountPath: /work/models + - name: ib + mountPath: /dev/infiniband + volumes: + - name: dshm + emptyDir: + medium: Memory + - name: model + hostPath: + path: '< your models dir >' # modify it according your models dir + - name: ib + hostPath: + path: /dev/infiniband + workerTemplate: + spec: + dnsPolicy: ClusterFirstWithHostNet + hostNetwork: true + hostIPC: true + containers: + - name: sglang-worker + image: sglang:latest + securityContext: + privileged: true + env: + - name: NCCL_IB_GID_INDEX + value: "3" + command: + - python3 + - -m + - sglang.launch_server + - --model-path + - /work/models + - --mem-fraction-static + - "0.93" + - --torch-compile-max-bs + - "8" + - --max-running-requests + - "20" + - --tp + - "16" # Size of Tensor Parallelism + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20000 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + resources: + limits: + nvidia.com/gpu: "8" + volumeMounts: + - mountPath: /dev/shm + name: dshm + - name: model + mountPath: /work/models + - name: ib + mountPath: /dev/infiniband + volumes: + - name: dshm + emptyDir: + medium: Memory + - name: ib + hostPath: + path: /dev/infiniband + - name: model + hostPath: + path: /data1/models/deepseek_v3_moe +*** +apiVersion: v1 +kind: Service +metadata: + name: sglang-leader +spec: + selector: + leaderworkerset.sigs.k8s.io/name: sglang + role: leader + ports: + - protocol: TCP + port: 40000 + targetPort: 40000 + +``` + +* Then use `kubectl apply -f lws.yaml` you will get this output. + +```text Output +NAME READY STATUS RESTARTS AGE +sglang-0 0/1 Running 0 9s +sglang-0-1 1/1 Running 0 9s +``` + +Wait for the sglang leader (`sglang-0`) status to change to 1/1, which indicates it is `Ready`. + +You can use the command `kubectl logs -f sglang-0` to view the logs of the leader node. + +Once successful, you should see output like this: + +```text Output +[2025-02-17 05:27:24 TP1] Capture cuda graph end. Time elapsed: 84.89 s +[2025-02-17 05:27:24 TP6] max_total_num_tokens=712400, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=50, context_len=163840 +[2025-02-17 05:27:24 TP0] max_total_num_tokens=712400, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=50, context_len=163840 +[2025-02-17 05:27:24 TP7] max_total_num_tokens=712400, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=50, context_len=163840 +[2025-02-17 05:27:24 TP3] max_total_num_tokens=712400, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=50, context_len=163840 +[2025-02-17 05:27:24 TP2] max_total_num_tokens=712400, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=50, context_len=163840 +[2025-02-17 05:27:24 TP4] max_total_num_tokens=712400, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=50, context_len=163840 +[2025-02-17 05:27:24 TP1] max_total_num_tokens=712400, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=50, context_len=163840 +[2025-02-17 05:27:24 TP5] max_total_num_tokens=712400, chunked_prefill_size=8192, max_prefill_tokens=16384, max_running_requests=50, context_len=163840 +[2025-02-17 05:27:24] INFO: Started server process [1] +[2025-02-17 05:27:24] INFO: Waiting for application startup. +[2025-02-17 05:27:24] INFO: Application startup complete. +[2025-02-17 05:27:24] INFO: Uvicorn running on http://0.0.0.0:40000 (Press CTRL+C to quit) +[2025-02-17 05:27:25] INFO: 127.0.0.1:48908 - "GET /get_model_info HTTP/1.1" 200 OK +[2025-02-17 05:27:25 TP0] Prefill batch. #new-seq: 1, #new-token: 7, #cached-token: 0, cache hit rate: 0.00%, token usage: 0.00, #running-req: 0, #queue-req: 0 +[2025-02-17 05:27:32] INFO: 127.0.0.1:48924 - "POST /generate HTTP/1.1" 200 OK +[2025-02-17 05:27:32] The server is fired up and ready to roll! +``` + +If it doesn’t start up successfully, please follow these steps to check for any remaining issues. Thanks! + +### Debug + +* Set `NCCL_DEBUG=TRACE` to check if it is a NCCL communication problem. + +This should resolve most NCCL-related issues. + +***Notice: If you find that NCCL_DEBUG=TRACE is not effective in the container environment, but the process is stuck or you encounter hard-to-diagnose issues, try switching to a different container image. Some images may not handle standard error output properly.*** + +#### RoCE scenario + +* Please make sure that RDMA devices are available in the cluster environment. +* Please make sure that the nodes in the cluster have Mellanox NICs with RoCE. In this example, we use Mellanox ConnectX 5 model NICs, and the proper OFED driver has been installed. If not, please refer to the document [Install OFED Driver](https://docs.nvidia.com/networking/display/mlnxofedv461000/installing+mellanox+ofed) to install the driver. +* Check your env: + + ```shell Command + $ lspci -nn | grep Eth | grep Mellanox + 0000:7f:00.0 Ethernet controller [0200]: Mellanox Technologies MT43244 BlueField-3 integrated ConnectX-7 network controller [15b3:a2dc] (rev 01) + 0000:7f:00.1 Ethernet controller [0200]: Mellanox Technologies MT43244 BlueField-3 integrated ConnectX-7 network controller [15b3:a2dc] (rev 01) + 0000:c7:00.0 Ethernet controller [0200]: Mellanox Technologies MT43244 BlueField-3 integrated ConnectX-7 network controller [15b3:a2dc] (rev 01) + 0000:c7:00.1 Ethernet controller [0200]: Mellanox Technologies MT43244 BlueField-3 integrated ConnectX-7 network controller [15b3:a2dc] (rev 01) + 0001:08:00.0 Ethernet controller [0200]: Mellanox Technologies MT43244 BlueField-3 integrated ConnectX-7 network controller [15b3:a2dc] (rev 01) + 0001:08:00.1 Ethernet controller [0200]: Mellanox Technologies MT43244 BlueField-3 integrated ConnectX-7 network controller [15b3:a2dc] (rev 01) + 0001:a2:00.0 Ethernet controller [0200]: Mellanox Technologies MT43244 BlueField-3 integrated ConnectX-7 network controller [15b3:a2dc] (rev 01) + 0001:a2:00.1 Ethernet controller [0200]: Mellanox Technologies MT43244 BlueField-3 integrated ConnectX-7 network controller [15b3:a2dc] (rev 01) + ``` + +* Check the OFED driver: + + ```shell Command + ofed_info -s + OFED-internal-23.07-0.5.0: + ``` + +* Show RDMA link status and check IB devices: + + ```shell Command + $ rdma link show + 8/1: mlx5_bond_0/1: state ACTIVE physical_state LINK_UP netdev reth0 + 9/1: mlx5_bond_1/1: state ACTIVE physical_state LINK_UP netdev reth2 + 10/1: mlx5_bond_2/1: state ACTIVE physical_state LINK_UP netdev reth4 + 11/1: mlx5_bond_3/1: state ACTIVE physical_state LINK_UP netdev reth6 + + $ ibdev2netdev + 8/1: mlx5_bond_0/1: state ACTIVE physical_state LINK_UP netdev reth0 + 9/1: mlx5_bond_1/1: state ACTIVE physical_state LINK_UP netdev reth2 + 10/1: mlx5_bond_2/1: state ACTIVE physical_state LINK_UP netdev reth4 + 11/1: mlx5_bond_3/1: state ACTIVE physical_state LINK_UP netdev reth6 + ``` + +* Test RoCE network speed on the host: + + ```shell Command + yum install qperf + # for server: + execute qperf + # for client + qperf -t 60 -cm1 rc_rdma_write_bw + ``` + +* Check RDMA accessible in your container: + + ```shell Command + # ibv_devices + # ibv_devinfo + ``` + +## Keys to success + +* In the YAML configuration above, pay attention to the NCCL environment variable. For older versions of NCCL, you should check the NCCL_IB_GID_INDEX environment setting. +* NCCL_SOCKET_IFNAME is also crucial, but in a containerized environment, this typically isn’t an issue. +* In some cases, it’s necessary to configure GLOO_SOCKET_IFNAME correctly. +* NCCL_DEBUG is essential for troubleshooting, but I've found that sometimes it doesn't show error logs within containers. This could be related to the Docker image you're using. You may want to try switching images if needed. +* Avoid using Docker images based on Ubuntu 18.04, as they tend to have compatibility issues. + +## Remaining issues + +* In Kubernetes, Docker, or Containerd environments, we use hostNetwork to prevent performance degradation. +* We utilize privileged mode, which isn’t secure. Additionally, in containerized environments, full GPU isolation cannot be achieved. + +## TODO + +* Integrated with [k8s-rdma-shared-dev-plugin](https://github.com/Mellanox/k8s-rdma-shared-dev-plugin). diff --git a/docs_new/docs/references/multi_node_deployment/lws_pd/lws_pd_deploy.mdx b/docs_new/docs/references/multi_node_deployment/lws_pd/lws_pd_deploy.mdx new file mode 100644 index 000000000..53778af8d --- /dev/null +++ b/docs_new/docs/references/multi_node_deployment/lws_pd/lws_pd_deploy.mdx @@ -0,0 +1,786 @@ +--- +title: "LWS Based PD Deploy" +metatags: + description: "SGLang LWS PD deployment: DeepSeek R1 prefill/decode disaggregation on Kubernetes with RDMA." +--- +## 0. Prerequisites + +1. k8s >=1.26 +2. lws installed on k8s. + +## 1. Image Preparation + +`lmsysorg/sglang:deepep` + +## 2. Deployment Manifest Files + +***Notice: We will package all deployment files into Helm Chart format in the near future. Interested community members can contact us to contribute*** + +### Prefill + +Prefill manifest file [prefill.yaml](https://github.com/sgl-project/sglang/blob/main/docs/references/multi_node_deployment/lws_pd/lws-examples/p.yaml) + +*Note: The NodeSelector section, model location section, and taint toleration section can be adjusted according to your actual deployment environment* + +```yaml Config +apiVersion: leaderworkerset.x-k8s.io/v1 +kind: LeaderWorkerSet +metadata: + name: deepseekr10528-prefill-main +spec: + leaderWorkerTemplate: + leaderTemplate: + metadata: + labels: + role: leader + spec: + containers: + - command: + - python3 + - -m + - sglang.launch_server + - --port + - "30000" + - --host + - "0.0.0.0" + - --model-path + - /work/models + - --disaggregation-ib-device + # should modify according your rdma env + - mlx5_bond_0,mlx5_bond_1,mlx5_bond_2,mlx5_bond_3 + - --chunked-prefill-size + - "524288" + - --max-prefill-tokens + - "32768" + - --page-size + - "64" + # - --init-expert-location + # - /home/aiges/tuned/attachment_ep_statistics/prefill_in1024.json + - --ep-dispatch-algorithm + - dynamic + - --eplb-algorithm + - deepseek + # - --deepep-config + # - /home/aiges/tuned/tuned_8sms.json + - --enable-dp-lm-head + - --enable-dp-attention + - --dp-size + - "16" + - --disable-radix-cache + - --moe-a2a-backend + - deepep + - --disaggregation-mode + - prefill + - --mem-fraction-static + - "0.7" + - --context-length + - "32768" + - --tp + - "16" + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20102 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + - --ep-num-redundant-experts + - "32" + - --moe-dense-tp-size + - "1" + - --max-running-requests + - "1024" + env: +# - name: NVSHMEM_HCA_PE_MAPPING +# value: "mlx5_bond_0:1:2,mlx5_bond_1:1:2,mlx5_bond_2:1:2,mlx5_bond_3:1:2" +# - name: NVSHMEM_HCA_LIST +# value: "mlx5_bond_0:1,mlx5_bond_1:1,mlx5_bond_2:1,mlx5_bond_3:1" + - name: NVSHMEM_IB_GID_INDEX + value: "3" + - name: NVSHMEM_ENABLE_NIC_PE_MAPPING + value: "1" + - name: SGLANG_SET_CPU_AFFINITY + value: "true" + - name: SGLANG_ENABLE_JIT_DEEPGEMM + value: "1" + - name: NCCL_IB_QPS_PER_CONNECTION + value: "8" + - name: NCCL_IB_SPLIT_DATA_ON_QPS + value: "1" + - name: NCCL_NET_PLUGIN + value: none + - name: NCCL_IB_TC + value: "136" + - name: NCCL_MIN_NCHANNELS + value: "4" + - name: MC_TE_METRIC + value: "false" + - name: NCCL_IB_SL + value: "5" + - name: NCCL_IB_HCA + value: ^=mlx5_0,mlx5_5,mlx5_6 + - name: LWS_WORKER_INDEX + valueFrom: + fieldRef: + fieldPath: metadata.labels['leaderworkerset.sigs.k8s.io/worker-index'] + image: lmsysorg/sglang:deepep + name: sglang-leader + ports: + - containerPort: 30000 + protocol: TCP + readinessProbe: + periodSeconds: 30 + tcpSocket: + port: 30000 + resources: + limits: + nvidia.com/gpu: "8" + securityContext: + capabilities: + add: + - IPC_LOCK + privileged: true + volumeMounts: + - mountPath: /dev/shm + name: dshm + - mountPath: /work/models + name: model + - mountPath: /dev/infiniband + name: ib + - mountPath: /sgl-workspace/sglang/python/sglang/srt/layers/moe/fused_moe_triton/configs + name: cf + - mountPath: /root/.cache + name: sgl-cache + dnsPolicy: ClusterFirstWithHostNet + hostIPC: true + hostNetwork: true + nodeSelector: + pd: "yes" + tolerations: + - key: pd + operator: Exists + - key: node-role + operator: Exists + volumes: + - emptyDir: + medium: Memory + name: dshm + - hostPath: + # modify according to you deployment env + path: /data1/maas_hosted_models/models/DeepSeek-R1-0528/deepseek_r1_0528 + name: model + - hostPath: + path: /dev/infiniband + name: ib + - hostPath: + # modify according to you deployment env + path: /data1/maas_hosted_models/models/fused_moe_triton/configs + name: cf + - hostPath: + # modify according to you deployment env + path: /data1/sgl_cache + type: DirectoryOrCreate + name: sgl-cache + restartPolicy: RecreateGroupOnPodRestart + size: 2 + workerTemplate: + metadata: {} + spec: + containers: + - command: + - python3 + - -m + - sglang.launch_server + - --model-path + - /work/models + - --disaggregation-ib-device + - mlx5_bond_0,mlx5_bond_1,mlx5_bond_2,mlx5_bond_3 + - --chunked-prefill-size + - "524288" + - --max-prefill-tokens + - "32768" + - --page-size + - "64" + #- --init-expert-location + #- /home/aiges/tuned/attachment_ep_statistics/prefill_in1024.json + - --ep-dispatch-algorithm + - dynamic + - --eplb-algorithm + - deepseek +# - --deepep-config +# - /home/aiges/tuned/tuned_8sms.json + - --enable-dp-lm-head + - --enable-dp-attention + - --dp-size + - "16" + - --disable-radix-cache + - --moe-a2a-backend + - deepep + - --disaggregation-mode + - prefill + - --mem-fraction-static + - "0.7" + - --context-length + - "32768" + - --tp + - "16" + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20102 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + - --ep-num-redundant-experts + - "32" + - --moe-dense-tp-size + - "1" + - --max-running-requests + - "1024" + env: + - name: SGLANG_SET_CPU_AFFINITY + value: "true" + - name: SGLANG_HACK_DEEPEP_NUM_SMS + value: "8" + - name: SGLANG_HACK_DEEPEP_NEW_MODE + value: "0" +# - name: NVSHMEM_HCA_PE_MAPPING +# value: "mlx5_bond_0:1:2,mlx5_bond_1:1:2,mlx5_bond_2:1:2,mlx5_bond_3:1:2" +# - name: NVSHMEM_HCA_LIST +# value: "mlx5_bond_0:1,mlx5_bond_1:1,mlx5_bond_2:1,mlx5_bond_3:1" + - name: NCCL_IB_HCA + value: ^=mlx5_0,mlx5_5,mlx5_6 + - name: NVSHMEM_IB_TRAFFIC_CLASS + value: "16" + - name: NVSHMEM_IB_GID_INDEX + value: "3" + - name: NVSHMEM_ENABLE_NIC_PE_MAPPING + value: "1" + - name: CUDA_LAUNCH_BLOCKING + value: "0" + - name: SGLANG_MOONCAKE_TRANS_THREAD + value: "8" + - name: SGLANG_ENABLE_JIT_DEEPGEMM + value: "1" + - name: SGLANG_CHUNKED_PREFIX_CACHE_THRESHOLD + value: "0" + - name: NCCL_IB_QPS_PER_CONNECTION + value: "8" + - name: NCCL_IB_SPLIT_DATA_ON_QPS + value: "1" + - name: NCCL_NET_PLUGIN + value: none + - name: NCCL_IB_TC + value: "136" + - name: NCCL_MIN_NCHANNELS + value: "4" + - name: MC_TE_METRIC + value: "true" + - name: NCCL_IB_SL + value: "5" + - name: LWS_WORKER_INDEX + valueFrom: + fieldRef: + fieldPath: metadata.labels['leaderworkerset.sigs.k8s.io/worker-index'] + image: lmsysorg/sglang:deepep + name: sglang-worker + ports: + - containerPort: 30001 + protocol: TCP + resources: + limits: + nvidia.com/gpu: "8" + securityContext: + capabilities: + add: + - IPC_LOCK + privileged: true + volumeMounts: + + - mountPath: /root/.cache + name: sgl-cache + - mountPath: /dev/shm + name: dshm + - mountPath: /work/models + name: model + - mountPath: /dev/infiniband + name: ib + - mountPath: /sgl-workspace/sglang/python/sglang/srt/layers/moe/fused_moe_triton/configs + name: cf + dnsPolicy: ClusterFirstWithHostNet + hostIPC: true + hostNetwork: true + nodeSelector: + pd: "yes" + tolerations: + - key: pd + operator: Exists + - key: node-role + operator: Exists + volumes: + - emptyDir: + medium: Memory + name: dshm + - hostPath: + path: /dev/infiniband + name: ib + - hostPath: + path: /data1/maas_hosted_models/models/DeepSeek-R1-0528/deepseek_r1_0528 + name: model + - hostPath: + path: /data1/maas_hosted_models/models/fused_moe_triton/configs + name: cf + - hostPath: + path: /data1/sgl_cache + type: DirectoryOrCreate + name: sgl-cache + +``` + +### Decode + +Decode node deployment manifest file [decode.yaml](https://github.com/sgl-project/sglang/blob/main/docs/references/multi_node_deployment/lws_pd/lws-examples/d.yaml) + +*Note: The NodeSelector section, model location section, and taint toleration section can be adjusted according to your actual deployment environment* + +```yaml Config +apiVersion: leaderworkerset.x-k8s.io/v1 +kind: LeaderWorkerSet +metadata: + name: deepseekr10528-decode-main +spec: + leaderWorkerTemplate: + leaderTemplate: + metadata: + labels: + role: leader + spec: + containers: + - command: + - python3 + - -m + - sglang.launch_server + - --port + - "30000" + - --host + - "0.0.0.0" + - --model-path + - /work/models + - --chunked-prefill-size + - "262144" + - --page-size + - "64" + - --enable-dp-attention + - --enable-dp-lm-head + - --dp-size + - "16" + - --moe-a2a-backend + - deepep + - --disaggregation-mode + - decode + - --mem-fraction-static + - "0.849" + - --context-length + - "32768" + - --disaggregation-ib-device + - "mlx5_bond_0,mlx5_bond_1,mlx5_bond_2,mlx5_bond_3" + - --cuda-graph-max-bs + - "64" + - --max-running-requests + - "2048" + - --tp-size + - "16" # Size of Tensor Parallelism + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20102 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + - --ep-num-redundant-experts + - "32" + - --moe-dense-tp-size + - "1" + env: + - name: CUDA_LAUNCH_BLOCKING + value: "0" + - name: NVSHMEM_IB_GID_INDEX + value: "3" + - name: NVSHMEM_ENABLE_NIC_PE_MAPPING + value: "1" + - name: NCCL_IB_QPS_PER_CONNECTION + value: "8" + - name: NCCL_IB_SPLIT_DATA_ON_QPS + value: "1" + - name: NCCL_NET_PLUGIN + value: "none" + - name: NCCL_IB_TC + value: "136" + - name: NCCL_MIN_NCHANNELS + value: "4" + - name: NCCL_IB_SL + value: "5" + - name: MC_TE_METRIC + value: "true" + - name: SGLANG_MOONCAKE_TRANS_THREAD + value: "16" + - name: SGLANG_ENABLE_JIT_DEEPGEMM + value: "1" + - name: NCCL_IB_HCA + value: ^=mlx5_0,mlx5_5,mlx5_6 + - name: LWS_WORKER_INDEX + valueFrom: + fieldRef: + fieldPath: metadata.labels['leaderworkerset.sigs.k8s.io/worker-index'] + image: lmsysorg/sglang:deepep + name: sglang-leader + ports: + - containerPort: 30000 + protocol: TCP + readinessProbe: + periodSeconds: 30 + tcpSocket: + port: 30000 + resources: + limits: + nvidia.com/gpu: "8" + securityContext: + capabilities: + add: + - IPC_LOCK + privileged: true + volumeMounts: + - mountPath: /root/.cache + name: sgl-cache + - mountPath: /dev/shm + name: dshm + - mountPath: /work/models + name: model + - mountPath: /dev/infiniband + name: ib + - mountPath: /sgl-workspace/sglang/python/sglang/srt/layers/moe/fused_moe_triton/configs + name: cf + dnsPolicy: ClusterFirstWithHostNet + hostIPC: true + hostNetwork: true + nodeSelector: + pd: "yes" + tolerations: + - key: pd + operator: Exists + - key: node-role + operator: Exists + volumes: + - hostPath: + path: /data1/sgl_cache1 + type: DirectoryOrCreate + name: sgl-cache + - emptyDir: + medium: Memory + name: dshm + - hostPath: + path: /data1/maas_hosted_models/models/DeepSeek-R1-0528/deepseek_r1_0528 + name: model + - hostPath: + path: /dev/infiniband + name: ib + - hostPath: + path: /data1/maas_hosted_models/models/fused_moe_triton/configs + name: cf + restartPolicy: RecreateGroupOnPodRestart + size: 2 + workerTemplate: + metadata: {} + spec: + containers: + - command: + - python3 + - -m + - sglang.launch_server + - --model-path + - /work/models + - --chunked-prefill-size + - "262144" + - --page-size + - "64" + - --enable-dp-attention + - --enable-dp-lm-head + #- --enable-two-batch-overlap + - --dp-size + - "16" + - --moe-a2a-backend + - deepep + - --disaggregation-mode + - decode + - --mem-fraction-static + - "0.849" + - --context-length + - "32768" + - --disaggregation-ib-device + # should modify according your rdma env + - "mlx5_bond_0,mlx5_bond_1,mlx5_bond_2,mlx5_bond_3" + - --cuda-graph-max-bs + - "64" + - --max-running-requests + - "2048" + - --tp-size + - "16" # Size of Tensor Parallelism + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20102 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + - --ep-num-redundant-experts + - "32" + - --moe-dense-tp-size + - "1" + env: + - name: SGLANG_HACK_DEEPEP_NUM_SMS + value: "24" + - name: SGLANG_HACK_DEEPEP_NEW_MODE + value: "0" + - name: NVSHMEM_IB_TRAFFIC_CLASS + value: "16" + - name: NVSHMEM_IB_GID_INDEX + value: "3" + - name: NVSHMEM_ENABLE_NIC_PE_MAPPING + value: "1" + - name: NCCL_IB_QPS_PER_CONNECTION + value: "8" + - name: NCCL_IB_SPLIT_DATA_ON_QPS + value: "1" + - name: NCCL_NET_PLUGIN + value: "none" + - name: NCCL_IB_TC + value: "136" + - name: NCCL_MIN_NCHANNELS + value: "4" + - name: MC_TE_METRIC + value: "true" + - name: NCCL_IB_SL + value: "5" + - name: SGLANG_MOONCAKE_TRANS_THREAD + value: "16" + - name: SGLANG_ENABLE_JIT_DEEPGEMM + value: "1" + - name: NCCL_IB_HCA + value: ^=mlx5_0,mlx5_5,mlx5_6 + - name: LWS_WORKER_INDEX + valueFrom: + fieldRef: + fieldPath: metadata.labels['leaderworkerset.sigs.k8s.io/worker-index'] + image: lmsysorg/sglang:deepep + name: sglang-worker + ports: + - containerPort: 30001 + resources: + limits: + nvidia.com/gpu: "8" + securityContext: + capabilities: + add: + - IPC_LOCK + privileged: true + volumeMounts: + - mountPath: /root/.cache + name: sgl-cache + - mountPath: /dev/shm + name: dshm + - mountPath: /work/models + name: model + - mountPath: /dev/infiniband + name: ib + - mountPath: /sgl-workspace/sglang/python/sglang/srt/layers/moe/fused_moe_triton/configs + name: cf + dnsPolicy: ClusterFirstWithHostNet + hostIPC: true + hostNetwork: true + nodeSelector: + pd: "yes" + tolerations: + - key: pd + operator: Exists + - key: node-role + operator: Exists + volumes: + - hostPath: + path: /data1/sgl_cache1 + type: DirectoryOrCreate + name: sgl-cache + - emptyDir: + medium: Memory + name: dshm + - hostPath: + path: /dev/infiniband + name: ib + - hostPath: + # modify according to you deployment env + path: /data1/maas_hosted_models/models/DeepSeek-R1-0528/deepseek_r1_0528 + name: model + - hostPath: + # modify according to you deployment env + path: /data1/maas_hosted_models/models/fused_moe_triton/configs + name: cf + networkConfig: + subdomainPolicy: Shared + replicas: 1 + rolloutStrategy: + rollingUpdateConfiguration: + maxSurge: 0 + maxUnavailable: 1 + type: RollingUpdate + startupPolicy: LeaderCreated +``` + +Execute separately: + +```bash Command +kubectl apply -f p.yaml +kubectl apply -f d.yaml +``` + +At this point, we have completed the deployment of the 1P1D SGlang engine part. + +To allow our users to directly experience the model API, we still need a load balancer to handle sequential calls between prefill and decode. Different companies implement LBs differently, and the community will also officially release a new LB component written in Rust in the near future. + +Currently, we use a static K8S service + minilb approach to implement model API calls. + +### Creating Service for Prefill and Decode + +#### Create prefill k8s service +[p-svc.yaml](https://github.com/sgl-project/sglang/blob/main/docs/references/multi_node_deployment/lws_pd/lws-examples/p-svc.yaml) +```yaml Config +apiVersion: v1 +kind: Service +metadata: + name: deepseekr10528-prefill-main +spec: + selector: + leaderworkerset.sigs.k8s.io/name: deepseekr10528-prefill-main + role: leader + ports: + - protocol: TCP + port: 30000 + targetPort: 30000 +``` +Execute `kubectl apply -f p-svc.yaml` + +#### Create decode k8s service +[d-svc.yaml](https://github.com/sgl-project/sglang/blob/main/docs/references/multi_node_deployment/lws_pd/lws-examples/d-svc.yaml) +```yaml Config +apiVersion: v1 +kind: Service +metadata: + name: deepseekr10528-decode-main +spec: + selector: + leaderworkerset.sigs.k8s.io/name: deepseekr10528-decode-main + role: leader + ports: + - protocol: TCP + port: 30000 + targetPort: 30000 +``` +Execute `kubectl apply -f d-svc.yaml` + +#### Deploy minilb and lb service +[lb.yaml](https://github.com/sgl-project/sglang/blob/main/docs/references/multi_node_deployment/lws_pd/lws-examples/lb.yaml) +```yaml Config +apiVersion: apps/v1 +kind: Deployment +metadata: + name: deepseekr10528-lb-main + labels: + app: deepseekr10528-lb +spec: + replicas: 1 + selector: + matchLabels: + app: deepseekr10528-lb + template: + metadata: + labels: + app: deepseekr10528-lb + spec: + nodeSelector: + pd: "yes" + tolerations: + - key: pd + operator: Exists + - key: node-role + operator: Exists + containers: + - name: sgl-minilb + image: lmsysorg/sglang:deepep + command: + - python + - -m + - sglang_router.launch_router + - --pd-disaggregation + - --prefill + - http://deepseekr10528-prefill-main:30000 + - --decode + - http://deepseekr10528-decode-main:30000 + - --host + - 0.0.0.0 + - --port + - "8000" + ports: + - containerPort: 8000 +*** +apiVersion: v1 +kind: Service +metadata: + name: deepseekr10528-lb-service +spec: + type: NodePort + selector: + app: deepseekr10528-lb + ports: + - protocol: TCP + port: 8000 # Service Port(In-Cluster) + targetPort: 8000 # Exposed Container + nodePort: 30800 +``` +Execute `kubectl apply -f lb.yaml` + +After waiting for all model deployments to succeed, you will get the following output: + +```bash Command +[root@ecs-001]# kubectl get po +deepseekr10528-decode-main-0 1/1 Running 0 74m +deepseekr10528-decode-main-0-1 1/1 Running 0 74m +deepseekr10528-lb-main-9c5dbfc57-6lcbd 1/1 Running 0 22m +deepseekr10528-prefill-main-0 1/1 Running 0 74m +deepseekr10528-prefill-main-0-1 1/1 Running 0 74m +[root@ecs-cbm-x1-pd-cpu-001 main_doc]# kubectl get svc |grep dee +deepseekr10528-decode-main ClusterIP None 97m +deepseekr10528-lb-service NodePort 172.16.242.169 8000:30800/TCP 22m +deepseekr10528-prefill-main ClusterIP None 97m +``` + +At this point, select a nodePort:30800 to access: + +```bash Command +[root@ecs-001]# curl -X POST "http://{nodePort}:30800/v1/chat/completions" \ +> -H "Content-Type: application/json" \ +> -H "Authorization: Bearer None" \ +> -d '{ +> "rid":"ccccdd", +> "model": "r1", +> "messages": [ +> {"role": "system", "content": "0: You are a helpful AI assistant"}, +> {"role": "user", "content": "你是谁?."} +> ], +> "max_tokens":221 +> }' +{"id":"ccccdd","object":"chat.completion","created":1750252498,"model":"qwen2","choices":[{"index":0,"message":{"role":"assistant","content":"<think>\n嗯,用户问了一个很基础的自我介绍问题"你是谁?"。这可能是第一次互动时的常规开场白,也可能是想确认我的身份和功能范围。\n\n用户没有提供任何背景信息,语气简洁中性。这种场景下新用户的可能性较高,需要给出清晰友好的自我介绍,同时突出实用价值来降低陌生感。\n\n考虑到中文用户,应该用简体中文回复。重点要说明三点:身份归属(深度求索)、功能定位(AI助手)、服务范围(学习/工作/生活)。结尾用开放性问题引导对话很关键——既能了解需求,又能避免让用户面对空白输入框时不知所措。\n\n用波浪线结尾可以软化语气,那个笑脸表情😊刚好能中和AI的机械感。不过要控制表情符号数量,避免显得轻浮。\n</think>\n你好呀!我是你的AI助手,由深度求索公司(DeepSeek)开发的语言模型,名字叫 **DeepSeek-R1**。你可以把我当成一个知识丰富、随叫随到的小帮手~😊\n\n我的任务就是陪你聊天、解答问题、","reasoning_content":null,"tool_calls":null},"logprobs":null,"finish_reason":"length","matched_stop":null}],"usage":{"prompt_tokens":14,"total_tokens":235,"completion_tokens":221,"prompt_tokens_details":null}} + +``` +## FAQ + +1. The current deployment startup parameters may not be fully compatible with all RDMA scenarios. Different RDMA NCCL-related environment configurations may be needed in different network environments. + +2. Some preset, optimized configurations for EPLB are not used here. You can adjust them according to [6017](https://github.com/sgl-project/sglang/issues/6017) as needed. diff --git a/docs_new/docs/references/multi_node_deployment/multi_node.mdx b/docs_new/docs/references/multi_node_deployment/multi_node.mdx new file mode 100644 index 000000000..645203ea8 --- /dev/null +++ b/docs_new/docs/references/multi_node_deployment/multi_node.mdx @@ -0,0 +1,103 @@ +--- +title: "Multi-Node Deployment" +metatags: + description: "SGLang multi-node: Llama 405B on 2 nodes, DeepSeek V3/R1, SLURM cluster deployment examples." +--- +## Llama 3.1 405B + +**Run 405B (fp16) on Two Nodes** + +```bash Command +# replace 172.16.4.52:20000 with your own node ip address and port of the first node + +python3 -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-405B-Instruct \ + --tp 16 \ + --dist-init-addr 172.16.4.52:20000 \ + --nnodes 2 \ + --node-rank 0 + +python3 -m sglang.launch_server \ + --model-path meta-llama/Meta-Llama-3.1-405B-Instruct \ + --tp 16 \ + --dist-init-addr 172.16.4.52:20000 \ + --nnodes 2 \ + --node-rank 1 +``` + +Note that LLama 405B (fp8) can also be launched on a single node. + +```bash Command +python -m sglang.launch_server --model-path meta-llama/Meta-Llama-3.1-405B-Instruct-FP8 --tp 8 +``` + +## DeepSeek V3/R1 + +Please refer to [DeepSeek documents for reference](../../basic_usage/deepseek_v3#running-examples-on-multi-node). + +## Multi-Node Inference on SLURM + +This example showcases how to serve SGLang server across multiple nodes by SLURM. Submit the following job to the SLURM cluster. + +```bash Command +#!/bin/bash -l + +#SBATCH -o SLURM_Logs/%x_%j_master.out +#SBATCH -e SLURM_Logs/%x_%j_master.err +#SBATCH -D ./ +#SBATCH -J Llama-405B-Online-Inference-TP16-SGL + +#SBATCH --nodes=2 +#SBATCH --ntasks=2 +#SBATCH --ntasks-per-node=1 # Ensure 1 task per node +#SBATCH --cpus-per-task=18 +#SBATCH --mem=224GB +#SBATCH --partition="lmsys.org" +#SBATCH --gres=gpu:8 +#SBATCH --time=12:00:00 + +echo "[INFO] Activating environment on node $SLURM_PROCID" +if ! source ENV_FOLDER/bin/activate; then + echo "[ERROR] Failed to activate environment" >&2 + exit 1 +fi + +# Define parameters +model=MODEL_PATH +tp_size=16 + +echo "[INFO] Running inference" +echo "[INFO] Model: $model" +echo "[INFO] TP Size: $tp_size" + +# Set NCCL initialization address using the hostname of the head node +HEAD_NODE=$(scontrol show hostname "$SLURM_NODELIST" | head -n 1) +NCCL_INIT_ADDR="${HEAD_NODE}:8000" +echo "[INFO] NCCL_INIT_ADDR: $NCCL_INIT_ADDR" + +# Launch the model server on each node using SLURM +srun --ntasks=2 --nodes=2 --output="SLURM_Logs/%x_%j_node$SLURM_NODEID.out" \ + --error="SLURM_Logs/%x_%j_node$SLURM_NODEID.err" \ + python3 -m sglang.launch_server \ + --model-path "$model" \ + --grammar-backend "xgrammar" \ + --tp "$tp_size" \ + --dist-init-addr "$NCCL_INIT_ADDR" \ + --nnodes 2 \ + --node-rank "$SLURM_NODEID" & + +# Wait for the NCCL server to be ready on port 30000 +while ! nc -z "$HEAD_NODE" 30000; do + sleep 1 + echo "[INFO] Waiting for $HEAD_NODE:30000 to accept connections" +done + +echo "[INFO] $HEAD_NODE:30000 is ready to accept connections" + +# Keep the script running until the SLURM job times out +wait +``` + +Then, you can test the server by sending requests following other [documents](../../basic_usage/openai_api_completions). + +Thanks for [aflah02](https://github.com/aflah02) for providing the example, based on his [blog post](https://aflah02.substack.com/p/multi-node-llm-inference-with-sglang). diff --git a/docs_new/docs/references/multi_node_deployment/multi_node_index.mdx b/docs_new/docs/references/multi_node_deployment/multi_node_index.mdx new file mode 100644 index 000000000..eba1a2955 --- /dev/null +++ b/docs_new/docs/references/multi_node_deployment/multi_node_index.mdx @@ -0,0 +1,11 @@ +--- +title: "Multi-Node Deployment" +metatags: + description: "SGLang multi-node deployment index: K8s, LWS, RBG, PD disaggregation guides." +--- +- [Multi Node](./multi_node) +- [Deploy On K8S](./deploy_on_k8s) +- [Lws Pd Deploy](./lws_pd/lws_pd_deploy) +- [Deepseekv32 Pd](./rbg_pd/deepseekv32_pd) +- [Deploying DeepSeek with PD Disaggregation on 96 H100 GPUs](https://lmsys.org/blog/2025-05-05-large-scale-ep/) +- [Deploying Kimi K2 with PD Disaggregation on 128 H200 GPUs](https://lmsys.org/blog/2025-07-20-k2-large-scale-ep/) diff --git a/docs_new/docs/references/multi_node_deployment/multi_node_index.rst b/docs_new/docs/references/multi_node_deployment/multi_node_index.rst new file mode 100644 index 000000000..78636869e --- /dev/null +++ b/docs_new/docs/references/multi_node_deployment/multi_node_index.rst @@ -0,0 +1,14 @@ +Multi-Node Deployment +===================== + +.. toctree:: + :maxdepth: 1 + :caption: Multi-Node Deployment + + multi_node.md + deploy_on_k8s.md + lws_pd/lws_pd_deploy.md + rbg_pd/deepseekv32_pd.md + +- `Deploying DeepSeek with PD Disaggregation and Large-Scale Expert Parallelism on 96 H100 GPUs `_ +- `Deploying Kimi K2 with PD Disaggregation and Large-Scale Expert Parallelism on 128 H200 GPUs `_ diff --git a/docs_new/docs/references/multi_node_deployment/rbg_pd/deepseekv32_pd.mdx b/docs_new/docs/references/multi_node_deployment/rbg_pd/deepseekv32_pd.mdx new file mode 100644 index 000000000..fbc63eb1b --- /dev/null +++ b/docs_new/docs/references/multi_node_deployment/rbg_pd/deepseekv32_pd.mdx @@ -0,0 +1,570 @@ +--- +title: "DeepSeekV32-Exp RBG Based PD Deploy" +metatags: + description: "SGLang DeepSeek V3.2 RBG deployment: RoleBasedGroup PD disaggregation on Kubernetes." +--- +## 0. Prerequisites + +1. k8s >=1.26 +2. lws installed on k8s. +3. rbg installed on k8s. + +For RBG installation, please refer to: https://github.com/sgl-project/rbg + +## 1. Image Preparation + +`lmsysorg/sglang:latest` + + +### 2. All In One manifest file + +*Note: The NodeSelector section, model location section, and taint toleration section can be adjusted according to your actual deployment environment* + +rbg-dsv32.yml + +```yaml Config +apiVersion: workloads.x-k8s.io/v1alpha1 +kind: RoleBasedGroup +metadata: + name: deepseek-rbg-32exp + namespace: default +spec: + roles: + - name: prefill + replicas: 1 + workload: + apiVersion: leaderworkerset.x-k8s.io/v1 + kind: LeaderWorkerSet + restartPolicy: None + leaderWorkerSet: + size: 1 + patchLeaderTemplate: + metadata: + labels: + role: leader + pd_role: prefill + spec: + containers: + - command: + - python3 + - -m + - sglang.launch_server + - --model-path + - /work/models + - --port + - "30000" + - --trust-remote + - --host + - 0.0.0.0 + - --disaggregation-ib-device + - mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7 + - --disable-radix-cache + - --chunked-prefill-size + - "131072" + - --page-size + - "64" + # - --enable-eplb + - --ep-dispatch-algorithm + - dynamic + - --eplb-algorithm + - deepseek + - --enable-dp-lm-head + - --enable-dp-attention + - --dp-size + - "8" + - --moe-a2a-backend + - deepep + - --deepep-mode + - normal + - --disaggregation-mode + - prefill + - --mem-fraction-static + - "0.8" + - --max-prefill-tokens + - "32768" + - --context-length + - "32768" + - --tp + - "8" + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20102 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + - --ep-num-redundant-experts + - "32" + - --moe-dense-tp-size + - "1" + - --max-running-requests + - "1024" + env: + - name: LWS_WORKER_INDEX + valueFrom: + fieldRef: + fieldPath: metadata.labels['leaderworkerset.sigs.k8s.io/worker-index'] + livenessProbe: + failureThreshold: 3000 + httpGet: + path: /health + port: 30000 + initialDelaySeconds: 300 + periodSeconds: 60 + successThreshold: 1 + timeoutSeconds: 10 + readinessProbe: + failureThreshold: 20 + httpGet: + path: /health + port: 30000 + periodSeconds: 30 + successThreshold: 1 + timeoutSeconds: 10 + name: sglang + ports: + - containerPort: 30000 + name: sglang-http + protocol: TCP + + patchWorkerTemplate: {} + template: + metadata: + labels: + inference-framework: sglang + inference-stack.io/monitoring: "enabled" + spec: + containers: + - name: sglang + image: lmsysorg/sglang:latest + env: + - name: SGLANG_SKIP_SGL_KERNEL_VERSION_CHECK + value: "1" + - name: CUDA_LAUNCH_BLOCKING + value: "0" + - name: SGLANG_DISAGGREGATION_BOOTSTRAP_TIMEOUT + value: "1000000000" + - name: NVSHMEM_IB_TRAFFIC_CLASS + value: "16" + - name: NVSHMEM_DISABLE_P2P + value: "0" + - name: ENABLE_METRICS + value: "true" + - name: NVSHMEM_IB_GID_INDEX + value: "3" + - name: NVSHMEM_IB_SL + value: "5" + - name: SGLANG_SET_CPU_AFFINITY + value: "true" + - name: SGL_ENABLE_JIT_DEEPGEMM + value: "1" + - name: NCCL_IB_QPS_PER_CONNECTION + value: "8" + - name: NCCL_IB_SPLIT_DATA_ON_QPS + value: "1" + - name: NCCL_NET_PLUGIN + value: "none" + - name: NCCL_IB_TC + value: "136" + - name: NCCL_IB_SL + value: "5" + - name: NCCL_IB_TIMEOUT + value: "22" + - name: NCCL_IB_GID_INDEX + value: "3" + - name: NCCL_MIN_NCHANNELS + value: "4" + - name: NCCL_SOCKET_IFNAME + value: bond0 + - name: GLOO_SOCKET_IFNAME + value: bond0 + - name: NCCL_IB_HCA + value: ^=mlx5_0,mlx5_5,mlx5_6 + - name: NVSHMEM_BOOTSTRAP_UID_SOCK_IFNAME + value: "bond0" + - name: MC_TE_METRIC + value: "false" + resources: + limits: + nvidia.com/gpu: "8" + securityContext: + capabilities: + add: + - IPC_LOCK + privileged: true + volumeMounts: + - mountPath: /root/.cache + name: sgl-cache + - mountPath: /dev/shm + name: dshm + - mountPath: /work/models + name: model + - mountPath: /dev/infiniband + name: ib + - mountPath: /sgl-workspace/sglang + name: src + + dnsPolicy: ClusterFirstWithHostNet + hostIPC: true + hostNetwork: true + nodeSelector: + pd: "yes" + tolerations: + - key: pd + operator: Exists + volumes: + - hostPath: + path: /var/run/sys-topology + name: topo + - hostPath: + path: /data1/sgl_cache4 + type: DirectoryOrCreate + name: sgl-cache + - emptyDir: + medium: Memory + name: dshm + - hostPath: + path: /data/DeepSeek-V3.2-Exp + name: model + - hostPath: + path: /dev/infiniband + name: ib + - hostPath: + path: /data/src/sglang + type: DirectoryOrCreate + name: src + + - name: decode + replicas: 1 + workload: + apiVersion: leaderworkerset.x-k8s.io/v1 + kind: LeaderWorkerSet + leaderWorkerSet: + size: 1 + patchLeaderTemplate: + metadata: + labels: + role: leader + pd_role: decode + spec: + containers: + - command: + - python3 + - -m + - sglang.launch_server + - --model-path + - /work/models + - --port + - "30000" + - --trust-remote + - --host + - 0.0.0.0 + - --disaggregation-ib-device + - mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7 + - --chunked-prefill-size + - "131072" + - --eplb-rebalance-layers-per-chunk + - "29" + - --page-size + - "64" + - --enable-dp-attention + - --enable-dp-lm-head + - --dp-size + - "8" + - --moe-a2a-backend + - deepep + - --deepep-mode + - low_latency + - --disaggregation-mode + - decode + - --mem-fraction-static + - "0.8" + - --context-length + - "32768" + - --max-running-requests + - "2048" + - --tp-size + - "8" # Size of Tensor Parallelism + - --cuda-graph-max-bs + - "16" + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20102 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + - --ep-num-redundant-experts + - "32" + - --moe-dense-tp-size + - "1" + env: + - name: LWS_WORKER_INDEX + valueFrom: + fieldRef: + fieldPath: metadata.labels['leaderworkerset.sigs.k8s.io/worker-index'] + livenessProbe: + failureThreshold: 30000 + httpGet: + path: /health + port: 30000 + initialDelaySeconds: 300 + periodSeconds: 60 + successThreshold: 1 + timeoutSeconds: 10 + name: sglang + readinessProbe: + failureThreshold: 20 + httpGet: + path: /health + port: 30000 + periodSeconds: 30 + successThreshold: 1 + timeoutSeconds: 10 + patchWorkerTemplate: + spec: + containers: + - command: + - python3 + - -m + - sglang.launch_server + - --model-path + - /work/models + - --crash-dump-folder + - /log + - --chunked-prefill-size + - "262144" + - --eplb-rebalance-layers-per-chunk + - "29" + - --page-size + - "64" + - --enable-dp-attention + - --enable-dp-lm-head + - --dp-size + - "32" + - --moe-a2a-backend + - "deepep" + - --deepep-mode + - low_latency + - --disaggregation-mode + - decode + - --mem-fraction-static + - "0.849" + - --context-length + - "32768" + - --disaggregation-ib-device + - mlx5_0,mlx5_1,mlx5_2,mlx5_3,mlx5_4,mlx5_5,mlx5_6,mlx5_7 + - --max-running-requests + - "4096" + - --cuda-graph-max-bs + - "16" + - --tp-size + - "8" # Size of Tensor Parallelism + - --dist-init-addr + - $(LWS_LEADER_ADDRESS):20102 + - --nnodes + - $(LWS_GROUP_SIZE) + - --node-rank + - $(LWS_WORKER_INDEX) + - --trust-remote-code + - --ep-num-redundant-experts + - "32" + - --moe-dense-tp-size + - "1" + env: + - name: LWS_WORKER_INDEX + valueFrom: + fieldRef: + fieldPath: metadata.labels['leaderworkerset.sigs.k8s.io/worker-index'] + name: sglang + template: + metadata: + labels: + inference-framework: sglang-unuse + inference-stack.io/monitoring: "enabled" + spec: + containers: + - image: lmsysorg/sglang:latest + name: sglang + resources: + limits: + nvidia.com/gpu: "8" + securityContext: + capabilities: + add: + - IPC_LOCK + privileged: true + volumeMounts: + - mountPath: /root/.cache + name: sgl-cache + - mountPath: /dev/shm + name: dshm + - mountPath: /work/models + name: model + - mountPath: /dev/infiniband + name: ib + - mountPath: /sgl-workspace/sglang + name: src + env: + - name: SGLANG_SKIP_SGL_KERNEL_VERSION_CHECK + value: "1" + - name: SGLANG_DISAGGREGATION_WAITING_TIMEOUT + value: "100000000" + - name: NVSHMEM_DISABLE_P2P + value: "0" + - name: NVSHMEM_IB_TRAFFIC_CLASS + value: "16" + - name: NVSHMEM_IB_SL + value: "5" + - name: ENABLE_METRICS + value: "true" + - name: CUDA_LAUNCH_BLOCKING + value: "0" + - name: NVSHMEM_IB_GID_INDEX + value: "3" + - name: NCCL_IB_QPS_PER_CONNECTION + value: "8" + - name: NCCL_IB_SPLIT_DATA_ON_QPS + value: "1" + - name: NCCL_NET_PLUGIN + value: "none" + - name: NCCL_IB_TC + value: "136" + - name: NCCL_IB_SL + value: "5" + - name: NCCL_IB_TIMEOUT + value: "22" + - name: NCCL_IB_GID_INDEX + value: "3" + - name: NCCL_MIN_NCHANNELS + value: "4" + - name: NCCL_SOCKET_IFNAME + value: bond0 + - name: GLOO_SOCKET_IFNAME + value: bond0 + - name: NVSHMEM_BOOTSTRAP_UID_SOCK_IFNAME + value: "bond0" + - name: NCCL_IB_HCA + value: ^=mlx5_0,mlx5_5,mlx5_6 + - name: MC_TE_METRIC + value: "false" + - name: SGL_ENABLE_JIT_DEEPGEMM + value: "1" + dnsPolicy: ClusterFirstWithHostNet + hostIPC: true + hostNetwork: true + nodeSelector: + pd: "yes" + tolerations: + - key: pd + operator: Exists + volumes: + - hostPath: + path: /var/run/sys-topology + name: topo + - hostPath: + path: /data1/sgl_cache4 + type: DirectoryOrCreate + name: sgl-cache + - hostPath: + path: /data/src/sglang + type: DirectoryOrCreate + name: src + - emptyDir: + medium: Memory + name: dshm + - hostPath: + path: /data/DeepSeek-V3.2-Exp + name: model + - hostPath: + path: /dev/infiniband + name: ib + - name: router + replicas: 1 + dependencies: [ "decode", "prefill" ] + template: + spec: + containers: + - name: scheduler + image: lmsysorg/sglang:latest + command: + - sh + - -c + - > + python3 -m sglang_router.launch_router + --host 0.0.0.0 + --port 8080 + --pd-disaggregation + --policy random + --service-discovery + --service-discovery-namespace ${NAMESPACE} + --service-discovery-port 30000 + --prefill-selector pd_role=prefill + --decode-selector pd_role=decode + --max-payload-size 2147483648 + --worker-startup-timeout-secs 1200 + env: + - name: NAMESPACE + valueFrom: + fieldRef: + apiVersion: v1 + fieldPath: metadata.namespace +*** +apiVersion: v1 +kind: Service +metadata: + labels: + app: deepseek-rbg-32exp + name: deepseek-rbg-32exp + namespace: default +spec: + ports: + - name: http + port: 8080 + protocol: TCP + targetPort: 8080 + nodePort: 30080 + + selector: + rolebasedgroup.workloads.x-k8s.io/name: deepseek-rbg-32exp + rolebasedgroup.workloads.x-k8s.io/role: router + type: NodePort + +``` + +```bash Command +[root@ecs-001]# kubectl get po -n default +deepseek-rbg-32exp-decode-main-0 1/1 Running 0 74m +deepseek-rbg-32exp-decode-0-1 1/1 Running 0 74m +deepseek-rbg-32exp-router-9c5dbfc57 1/1 Running 0 22m +deepseek-rbg-32exp-prefill-0 1/1 Running 0 74m + +[root@ecs-cbm-x1-pd-cpu-001 main_doc]# kubectl get svc |grep dee +deepseek-rbg-32exp-decode ClusterIP None 97m +deepseek-rbg-32exp-router-service NodePort 172.16.242.169 8000:30800/TCP 22m +deepseek-rbg-32exp-prefill ClusterIP None 97m +``` + +At this point, select a nodePort:30800 to access: + +```bash Command +[root@ecs-001]# curl -X POST "http://{nodePort}:30800/v1/chat/completions" \ +> -H "Content-Type: application/json" \ +> -H "Authorization: Bearer None" \ +> -d '{ +> "rid":"ccccdd", +> "model": "dsv32", +> "messages": [ +> {"role": "system", "content": "0: You are a helpful AI assistant"}, +> {"role": "user", "content": "你是谁?."} +> ], +> "max_tokens":221 +> }' +{"id":"ccccdd","object":"chat.completion","created":1750252498,"model":"qwen2","choices":[{"index":0,"message":{"role":"assistant","content":"<think>\n嗯,用户问了一个很基础的自我介绍问题"你是谁?"。这可能是第一次互动时的常规开场白,也可能是想确认我的身份和功能范围。\n\n用户没有提供任何背景信息,语气简洁中性。这种场景下新用户的可能性较高,需要给出清晰友好的自我介绍,同时突出实用价值来降低陌生感。\n\n考虑到中文用户,应该用简体中文回复。重点要说明三点:身份归属(深度求索)、功能定位(AI助手)、服务范围(学习/工作/生活)。结尾用开放性问题引导对话很关键——既能了解需求,又能避免让用户面对空白输入框时不知所措。\n\n用波浪线结尾可以软化语气,那个笑脸表情😊刚好能中和AI的机械感。不过要控制表情符号数量,避免显得轻浮。\n</think>\n你好呀!我是你的AI助手,由深度求索公司(DeepSeek)开发的语言模型,名字叫 **DeepSeek-V32**。你可以把我当成一个知识丰富、随叫随到的小帮手~😊\n\n我的任务就是陪你聊天、解答问题、","reasoning_content":null,"tool_calls":null},"logprobs":null,"finish_reason":"length","matched_stop":null}],"usage":{"prompt_tokens":14,"total_tokens":235,"completion_tokens":221,"prompt_tokens_details":null}} + +``` +## FAQ + +1. The current deployment startup parameters may not be fully compatible with all RDMA scenarios. Different RDMA NCCL-related environment configurations may be needed in different network environments. + +2. Please ensure that the sglang code in the image has incorporated the changes from [PR #10912](https://github.com/sgl-project/sglang/pull/10912). diff --git a/docs_new/docs/references/overview.mdx b/docs_new/docs/references/overview.mdx new file mode 100644 index 000000000..60af63453 --- /dev/null +++ b/docs_new/docs/references/overview.mdx @@ -0,0 +1,13 @@ +--- +title: References +description: FAQ, environment variables, production metrics, deployment guides, and more. +--- + +- [FAQ](./faq) +- [Environment Variables](./environment_variables) +- [Production Metrics](./production_metrics) +- [Production Request Trace](./production_request_trace) +- [Multi-Node Deployment](./multi_node_deployment/multi_node) +- [Custom Chat Template](./custom_chat_template) +- [Frontend Language](./frontend/frontend_tutorial) +- [Post-Training Integration](./post_training_integration) diff --git a/docs_new/docs/references/post_training_integration.mdx b/docs_new/docs/references/post_training_integration.mdx new file mode 100644 index 000000000..d4544fd0f --- /dev/null +++ b/docs_new/docs/references/post_training_integration.mdx @@ -0,0 +1,34 @@ +--- +title: "Post-Training Integration" +metatags: + description: "SGLang post-training: RLHF integration with Miles, slime, AReaL, ROLL, verl, Unsloth, LLaMA Factory." +--- +SGLang has become the de facto inference backend for modern LLM training frameworks, powering state-of-the-art models across the industry. From GLM-4.6 to Qwen3, leading models leverage SGLang's high-performance inference during reinforcement learning and post-training workflows. + +What makes SGLang essential for post-training? + +- Open-To-Use Refit Functionality: diverse method for colocate or disaggregate +- Easy To Postpone Generation: enable partial rollout and dedicated rollout control +- Fine-Grained Engine Sleep And Wake Up: facilitate maxium-powered rollout and training +- Training Serving Alignment: ensure the performance consistency in training and serving +- Load Balancing Router: cache-aware load-balancing for high-throughput rollout +- Deterministic Inference: ensure zero kl divergence between rollout and training + +These capabilities, combined with native integration support across major frameworks, have established SGLang as the infrastructure backbone for modern LLM/VLMs post-training. We also share our latest work in this slide, [Optimizing Large-Scale RL with SGLang](https://gamma.app/docs/Optimizing-RL-with-SGLang-y0kqgj877k34779). + +## Adoption + +- [**Miles**](https://github.com/radixark/miles): Enterprise-scale RL framework for large MoE models with SGLang-native rollout, speculative training, and production-grade stability +- [**slime**](https://github.com/THUDM/slime): Post-training framework combining Megatron and SGLang, used to train GLM-4.6 +- [**AReaL**](https://github.com/inclusionAI/AReaL): Fully asynchronous RL system achieving 2.77x speedup with SGLang backend for continuous rollout generation +- [**ROLL**](https://github.com/alibaba/ROLL): ROLL is an efficient and user-friendly RL library designed for Large Language Models utilizing Large Scale GPU resources +- [**verl**](https://github.com/volcengine/verl): Full-stack RLHF framework supporting PPO, GRPO, and ReMax with modular SGLang integration +- [**Unsloth**](https://docs.unsloth.ai/basics/inference-and-deployment/sglang-guide): 2x faster fine-tuning with optimized kernels, deploys seamlessly with SGLang inference +- [**LLaMA Factory**](https://github.com/hiyouga/LLaMA-Factory): Unified framework for training 100+ LLMs with LoRA, QLoRA, and full fine-tuning methods +- [**Tunix**](https://github.com/google/tunix): Google's JAX-native library for LLM post-training with SFT, DPO, PPO, and GRPO support +- [**RL2**](https://github.com/ChenmienTan/RL2): Ray Less Reinforcement Learning, a concise library of post-training for large language models + + +## Collaboration + +Due to the privacy of the design parternes, we cannot list the companies that adopt SGLang for post-training. However, we are happy to share the details with you if you are interested and trust the choice among 10+ top companies and frontier labs across US and China. If you are interested in integrating SGLang with your training framework or need technical support, we're here to help! Reach out to us at **rl_team@lmsys.org** for partnerships, integration guidance, and custom feature development. diff --git a/docs_new/docs/references/production_metrics.mdx b/docs_new/docs/references/production_metrics.mdx new file mode 100644 index 000000000..96ff6c899 --- /dev/null +++ b/docs_new/docs/references/production_metrics.mdx @@ -0,0 +1,234 @@ +--- +title: "Production Metrics" +metatags: + description: "SGLang Prometheus metrics: TTFT, TPOT, throughput, cache hit rate. Grafana dashboard setup guide." +--- +SGLang exposes the following metrics via Prometheus. You can enable it by adding `--enable-metrics` when you launch the server. + +An example of the monitoring dashboard is available in [examples/monitoring/grafana.json](https://github.com/sgl-project/sglang/blob/main/examples/monitoring/grafana/dashboards/json/sglang-dashboard.json). + +Here is an example of the metrics: + +```text Output +$ curl http://localhost:30000/metrics +# HELP sglang:prompt_tokens_total Number of prefill tokens processed. +# TYPE sglang:prompt_tokens_total counter +sglang:prompt_tokens_total{model_name="meta-llama/Llama-3.1-8B-Instruct"} 8.128902e+06 +# HELP sglang:generation_tokens_total Number of generation tokens processed. +# TYPE sglang:generation_tokens_total counter +sglang:generation_tokens_total{model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.557572e+06 +# HELP sglang:token_usage The token usage +# TYPE sglang:token_usage gauge +sglang:token_usage{model_name="meta-llama/Llama-3.1-8B-Instruct"} 0.28 +# HELP sglang:cache_hit_rate The cache hit rate +# TYPE sglang:cache_hit_rate gauge +sglang:cache_hit_rate{model_name="meta-llama/Llama-3.1-8B-Instruct"} 0.007507552643049313 +# HELP sglang:time_to_first_token_seconds Histogram of time to first token in seconds. +# TYPE sglang:time_to_first_token_seconds histogram +sglang:time_to_first_token_seconds_sum{model_name="meta-llama/Llama-3.1-8B-Instruct"} 2.3518979474117756e+06 +sglang:time_to_first_token_seconds_bucket{le="0.001",model_name="meta-llama/Llama-3.1-8B-Instruct"} 0.0 +sglang:time_to_first_token_seconds_bucket{le="0.005",model_name="meta-llama/Llama-3.1-8B-Instruct"} 0.0 +sglang:time_to_first_token_seconds_bucket{le="0.01",model_name="meta-llama/Llama-3.1-8B-Instruct"} 0.0 +sglang:time_to_first_token_seconds_bucket{le="0.02",model_name="meta-llama/Llama-3.1-8B-Instruct"} 0.0 +sglang:time_to_first_token_seconds_bucket{le="0.04",model_name="meta-llama/Llama-3.1-8B-Instruct"} 1.0 +sglang:time_to_first_token_seconds_bucket{le="0.06",model_name="meta-llama/Llama-3.1-8B-Instruct"} 3.0 +sglang:time_to_first_token_seconds_bucket{le="0.08",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:time_to_first_token_seconds_bucket{le="0.1",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:time_to_first_token_seconds_bucket{le="0.25",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:time_to_first_token_seconds_bucket{le="0.5",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:time_to_first_token_seconds_bucket{le="0.75",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:time_to_first_token_seconds_bucket{le="1.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 27.0 +sglang:time_to_first_token_seconds_bucket{le="2.5",model_name="meta-llama/Llama-3.1-8B-Instruct"} 140.0 +sglang:time_to_first_token_seconds_bucket{le="5.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 314.0 +sglang:time_to_first_token_seconds_bucket{le="7.5",model_name="meta-llama/Llama-3.1-8B-Instruct"} 941.0 +sglang:time_to_first_token_seconds_bucket{le="10.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 1330.0 +sglang:time_to_first_token_seconds_bucket{le="15.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 1970.0 +sglang:time_to_first_token_seconds_bucket{le="20.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 2326.0 +sglang:time_to_first_token_seconds_bucket{le="25.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 2417.0 +sglang:time_to_first_token_seconds_bucket{le="30.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 2513.0 +sglang:time_to_first_token_seconds_bucket{le="+Inf",model_name="meta-llama/Llama-3.1-8B-Instruct"} 11008.0 +sglang:time_to_first_token_seconds_count{model_name="meta-llama/Llama-3.1-8B-Instruct"} 11008.0 +# HELP sglang:e2e_request_latency_seconds Histogram of End-to-end request latency in seconds +# TYPE sglang:e2e_request_latency_seconds histogram +sglang:e2e_request_latency_seconds_sum{model_name="meta-llama/Llama-3.1-8B-Instruct"} 3.116093850019932e+06 +sglang:e2e_request_latency_seconds_bucket{le="0.3",model_name="meta-llama/Llama-3.1-8B-Instruct"} 0.0 +sglang:e2e_request_latency_seconds_bucket{le="0.5",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:e2e_request_latency_seconds_bucket{le="0.8",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:e2e_request_latency_seconds_bucket{le="1.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:e2e_request_latency_seconds_bucket{le="1.5",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:e2e_request_latency_seconds_bucket{le="2.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:e2e_request_latency_seconds_bucket{le="2.5",model_name="meta-llama/Llama-3.1-8B-Instruct"} 6.0 +sglang:e2e_request_latency_seconds_bucket{le="5.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.0 +sglang:e2e_request_latency_seconds_bucket{le="10.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 10.0 +sglang:e2e_request_latency_seconds_bucket{le="15.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 11.0 +sglang:e2e_request_latency_seconds_bucket{le="20.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 14.0 +sglang:e2e_request_latency_seconds_bucket{le="30.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 247.0 +sglang:e2e_request_latency_seconds_bucket{le="40.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 486.0 +sglang:e2e_request_latency_seconds_bucket{le="50.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 845.0 +sglang:e2e_request_latency_seconds_bucket{le="60.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 1513.0 +sglang:e2e_request_latency_seconds_bucket{le="+Inf",model_name="meta-llama/Llama-3.1-8B-Instruct"} 11228.0 +sglang:e2e_request_latency_seconds_count{model_name="meta-llama/Llama-3.1-8B-Instruct"} 11228.0 +# HELP sglang:time_per_output_token_seconds Histogram of time per output token in seconds. +# TYPE sglang:time_per_output_token_seconds histogram +sglang:time_per_output_token_seconds_sum{model_name="meta-llama/Llama-3.1-8B-Instruct"} 866964.5791549598 +sglang:time_per_output_token_seconds_bucket{le="0.005",model_name="meta-llama/Llama-3.1-8B-Instruct"} 1.0 +sglang:time_per_output_token_seconds_bucket{le="0.01",model_name="meta-llama/Llama-3.1-8B-Instruct"} 73.0 +sglang:time_per_output_token_seconds_bucket{le="0.015",model_name="meta-llama/Llama-3.1-8B-Instruct"} 382.0 +sglang:time_per_output_token_seconds_bucket{le="0.02",model_name="meta-llama/Llama-3.1-8B-Instruct"} 593.0 +sglang:time_per_output_token_seconds_bucket{le="0.025",model_name="meta-llama/Llama-3.1-8B-Instruct"} 855.0 +sglang:time_per_output_token_seconds_bucket{le="0.03",model_name="meta-llama/Llama-3.1-8B-Instruct"} 1035.0 +sglang:time_per_output_token_seconds_bucket{le="0.04",model_name="meta-llama/Llama-3.1-8B-Instruct"} 1815.0 +sglang:time_per_output_token_seconds_bucket{le="0.05",model_name="meta-llama/Llama-3.1-8B-Instruct"} 11685.0 +sglang:time_per_output_token_seconds_bucket{le="0.075",model_name="meta-llama/Llama-3.1-8B-Instruct"} 433413.0 +sglang:time_per_output_token_seconds_bucket{le="0.1",model_name="meta-llama/Llama-3.1-8B-Instruct"} 4.950195e+06 +sglang:time_per_output_token_seconds_bucket{le="0.15",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.039435e+06 +sglang:time_per_output_token_seconds_bucket{le="0.2",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.171662e+06 +sglang:time_per_output_token_seconds_bucket{le="0.3",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.266055e+06 +sglang:time_per_output_token_seconds_bucket{le="0.4",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.296752e+06 +sglang:time_per_output_token_seconds_bucket{le="0.5",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.312226e+06 +sglang:time_per_output_token_seconds_bucket{le="0.75",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.339675e+06 +sglang:time_per_output_token_seconds_bucket{le="1.0",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.357747e+06 +sglang:time_per_output_token_seconds_bucket{le="2.5",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.389414e+06 +sglang:time_per_output_token_seconds_bucket{le="+Inf",model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.400757e+06 +sglang:time_per_output_token_seconds_count{model_name="meta-llama/Llama-3.1-8B-Instruct"} 7.400757e+06 +# HELP sglang:func_latency_seconds Function latency in seconds +# TYPE sglang:func_latency_seconds histogram +sglang:func_latency_seconds_sum{name="generate_request"} 4.514771912145079 +sglang:func_latency_seconds_bucket{le="0.05",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="0.07500000000000001",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="0.1125",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="0.16875",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="0.253125",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="0.3796875",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="0.56953125",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="0.8542968750000001",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="1.2814453125",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="1.9221679687500002",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="2.8832519531250003",name="generate_request"} 14006.0 +sglang:func_latency_seconds_bucket{le="4.3248779296875",name="generate_request"} 14007.0 +sglang:func_latency_seconds_bucket{le="6.487316894531251",name="generate_request"} 14007.0 +sglang:func_latency_seconds_bucket{le="9.730975341796876",name="generate_request"} 14007.0 +sglang:func_latency_seconds_bucket{le="14.596463012695313",name="generate_request"} 14007.0 +sglang:func_latency_seconds_bucket{le="21.89469451904297",name="generate_request"} 14007.0 +sglang:func_latency_seconds_bucket{le="32.84204177856446",name="generate_request"} 14007.0 +sglang:func_latency_seconds_bucket{le="49.26306266784668",name="generate_request"} 14007.0 +sglang:func_latency_seconds_bucket{le="+Inf",name="generate_request"} 14007.0 +sglang:func_latency_seconds_count{name="generate_request"} 14007.0 +# HELP sglang:num_running_reqs The number of running requests +# TYPE sglang:num_running_reqs gauge +sglang:num_running_reqs{model_name="meta-llama/Llama-3.1-8B-Instruct"} 162.0 +# HELP sglang:num_used_tokens The number of used tokens +# TYPE sglang:num_used_tokens gauge +sglang:num_used_tokens{model_name="meta-llama/Llama-3.1-8B-Instruct"} 123859.0 +# HELP sglang:gen_throughput The generate throughput (token/s) +# TYPE sglang:gen_throughput gauge +sglang:gen_throughput{model_name="meta-llama/Llama-3.1-8B-Instruct"} 86.50814177726902 +# HELP sglang:num_queue_reqs The number of requests in the waiting queue +# TYPE sglang:num_queue_reqs gauge +sglang:num_queue_reqs{model_name="meta-llama/Llama-3.1-8B-Instruct"} 2826.0 +``` + +## Setup Guide + +This section describes how to set up the monitoring stack (Prometheus + Grafana) provided in the `examples/monitoring` directory. + +### Prerequisites + +- Docker and Docker Compose installed +- SGLang server running with metrics enabled + +### Usage + +1. **Start your SGLang server with metrics enabled:** + + ```bash Command + python -m sglang.launch_server \ + --model-path \ + --port 30000 \ + --enable-metrics + ``` + Replace `` with the actual path to your model (e.g., `meta-llama/Meta-Llama-3.1-8B-Instruct`). Ensure the server is accessible from the monitoring stack (you might need `--host 0.0.0.0` if running in Docker). By default, the metrics endpoint will be available at `http://:30000/metrics`. + +2. **Navigate to the monitoring example directory:** + ```bash Command + cd examples/monitoring + ``` + +3. **Start the monitoring stack:** + ```bash Command + docker compose up -d + ``` + This command will start Prometheus and Grafana in the background. + +4. **Access the monitoring interfaces:** + * **Grafana:** Open your web browser and go to [http://localhost:3000](http://localhost:3000). + * **Prometheus:** Open your web browser and go to [http://localhost:9090](http://localhost:9090). + +5. **Log in to Grafana:** + * Default Username: `admin` + * Default Password: `admin` + You will be prompted to change the password upon your first login. + +6. **View the Dashboard:** + The SGLang dashboard is pre-configured and should be available automatically. Navigate to `Dashboards` -> `Browse` -> `SGLang Monitoring` folder -> `SGLang Dashboard`. + +### Troubleshooting + +* **Port Conflicts:** If you encounter errors like "port is already allocated," check if other services (including previous instances of Prometheus/Grafana) are using ports `9090` or `3000`. Use `docker ps` to find running containers and `docker stop ` to stop them, or use `lsof -i :` to find other processes using the ports. You might need to adjust the ports in the `docker-compose.yaml` file if they permanently conflict with other essential services on your system. + +To modify Grafana's port to the other one(like 3090) in your Docker Compose file, you need to explicitly specify the port mapping under the grafana service. + + Option 1: Add GF_SERVER_HTTP_PORT to the environment section: + ```text Output + environment: + - GF_AUTH_ANONYMOUS_ENABLED=true + - GF_SERVER_HTTP_PORT=3090 # <-- Add this line + ``` + Option 2: Use port mapping: + ```text Output + grafana: + image: grafana/grafana:latest + container_name: grafana + ports: + - "3090:3000" # <-- Host:Container port mapping + ``` +* **Connection Issues:** + * Ensure both Prometheus and Grafana containers are running (`docker ps`). + * Verify the Prometheus data source configuration in Grafana (usually auto-configured via `grafana/datasources/datasource.yaml`). Go to `Connections` -> `Data sources` -> `Prometheus`. The URL should point to the Prometheus service (e.g., `http://prometheus:9090`). + * Confirm that your SGLang server is running and the metrics endpoint (`http://:30000/metrics`) is accessible *from the Prometheus container*. If SGLang is running on your host machine and Prometheus is in Docker, use `host.docker.internal` (on Docker Desktop) or your machine's network IP instead of `localhost` in the `prometheus.yaml` scrape configuration. +* **No Data on Dashboard:** + * Generate some traffic to your SGLang server to produce metrics. For example, run a benchmark: + ```bash Command + python3 -m sglang.bench_serving --backend sglang --dataset-name random --num-prompts 100 --random-input 128 --random-output 128 + ``` + * Check the Prometheus UI (`http://localhost:9090`) under `Status` -> `Targets` to see if the SGLang endpoint is being scraped successfully. + * Verify the `model_name` and `instance` labels in your Prometheus metrics match the variables used in the Grafana dashboard. You might need to adjust the Grafana dashboard variables or the labels in your Prometheus configuration. + +### Configuration Files + +The monitoring setup is defined by the following files within the `examples/monitoring` directory: + +* `docker-compose.yaml`: Defines the Prometheus and Grafana services. +* `prometheus.yaml`: Prometheus configuration, including scrape targets. +* `grafana/datasources/datasource.yaml`: Configures the Prometheus data source for Grafana. +* `grafana/dashboards/config/dashboard.yaml`: Tells Grafana to load dashboards from the specified path. +* `grafana/dashboards/json/sglang-dashboard.json`: The actual Grafana dashboard definition in JSON format. + +You can customize the setup by modifying these files. For instance, you might need to update the `static_configs` target in `prometheus.yaml` if your SGLang server runs on a different host or port. + +#### Check if the metrics are being collected + +Run: +```text Output +python3 -m sglang.bench_serving \ + --backend sglang \ + --dataset-name random \ + --num-prompts 3000 \ + --random-input 1024 \ + --random-output 1024 \ + --random-range-ratio 0.5 +``` + +to generate some requests. + +Then you should be able to see the metrics in the Grafana dashboard. diff --git a/docs_new/docs/references/production_request_trace.mdx b/docs_new/docs/references/production_request_trace.mdx new file mode 100644 index 000000000..53f000ac1 --- /dev/null +++ b/docs_new/docs/references/production_request_trace.mdx @@ -0,0 +1,164 @@ +--- +title: "Production Request Tracing" +metatags: + description: "SGLang OpenTelemetry tracing: Jaeger visualization, trace context propagation, PD disaggregation support." +--- +SGlang exports request trace data based on the OpenTelemetry Collector. You can enable tracing by adding the `--enable-trace` and configure the OpenTelemetry Collector endpoint using `--otlp-traces-endpoint` when launching the server. + +You can find example screenshots of the visualization in https://github.com/sgl-project/sglang/issues/8965. + +## Setup Guide +This section explains how to configure the request tracing and export the trace data. +1. Install the required packages and tools + * install Docker and Docker Compose + * install the dependencies + ```bash Command + # enter the SGLang root directory + pip install -e "python[tracing]" + + # or manually install the dependencies using pip + pip install opentelemetry-sdk opentelemetry-api opentelemetry-exporter-otlp opentelemetry-exporter-otlp-proto-grpc + ``` + +2. launch opentelemetry collector and jaeger + ```bash Command + docker compose -f examples/monitoring/tracing_compose.yaml up -d + ``` + +3. start your SGLang server with tracing enabled + ```bash Command + # set env variables + export SGLANG_OTLP_EXPORTER_SCHEDULE_DELAY_MILLIS=500 + export SGLANG_OTLP_EXPORTER_MAX_EXPORT_BATCH_SIZE=64 + # start the prefill and decode server + python -m sglang.launch_server --enable-trace --otlp-traces-endpoint 0.0.0.0:4317 + # start the mini lb + python -m sglang_router.launch_router --enable-trace --otlp-traces-endpoint 0.0.0.0:4317 + ``` + + Replace `0.0.0.0:4317` with the actual endpoint of the opentelemetry collector. If you launched the openTelemetry collector with tracing_compose.yaml, the default receiving port is 4317. + + To use the HTTP/protobuf span exporter, set the following environment variable and point to an HTTP endpoint, for example, `http://0.0.0.0:4318/v1/traces`. + ```bash Command + export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http/protobuf + ``` + + +4. raise some requests +5. Observe whether trace data is being exported + * Access port 16686 of Jaeger using a web browser to visualize the request traces. + * The OpenTelemetry Collector also exports trace data in JSON format to /tmp/otel_trace.json. In a follow-up patch, we will provide a tool to convert this data into a Perfetto-compatible format, enabling visualization of requests in the Perfetto UI. + +## How to add Tracing for slices you're interested in? +We have already inserted instrumentation points in the tokenizer and scheduler main threads. If you wish to trace additional request execution segments or perform finer-grained tracing, please use the APIs from the tracing package as described below. + +1. initialization + + Every process involved in tracing during the initialization phase should execute: + ```python Example + process_tracing_init(otlp_traces_endpoint, server_name) + ``` + The otlp_traces_endpoint is obtained from the arguments, and you can set server_name freely, but it should remain consistent across all processes. + + Every thread involved in tracing during the initialization phase should execute: + ```python Example + trace_set_thread_info("thread label", tp_rank, dp_rank) + ``` + The "thread label" can be regarded as the name of the thread, used to distinguish different threads in the visualization view. + +2. Mark the beginning and end of a request + ```text Output + trace_req_start(rid, bootstrap_room) + trace_req_finish(rid) + ``` + These two APIs must be called within the same process, for example, in the tokenizer. + +3. Add tracing for slice + + * Add slice tracing normally: + ```python Example + trace_slice_start("slice A", rid) + trace_slice_end("slice A", rid) + ``` + + - Use the "anonymous" flag to not specify a slice name at the start of the slice, allowing the slice name to be determined by trace_slice_end. + +Note: Anonymous slices must not be nested. + ```python Example + trace_slice_start("", rid, anonymous = True) + trace_slice_end("slice A", rid) + ``` + + - In trace_slice_end, use auto_next_anon to automatically create the next anonymous slice, which can reduce the number of instrumentation points needed. + ```python Example + trace_slice_start("", rid, anonymous = True) + trace_slice_end("slice A", rid, auto_next_anon = True) + trace_slice_end("slice B", rid, auto_next_anon = True) + trace_slice_end("slice C", rid, auto_next_anon = True) + trace_slice_end("slice D", rid) + ``` + - The end of the last slice in a thread must be marked with thread_finish_flag=True; otherwise, the thread's span will not be properly generated. + ```python Example + trace_slice_end("slice D", rid, thread_finish_flag = True) + ``` + +4. When the request execution flow transfers to another thread, the trace context needs to be explicitly propagated. + - sender: Execute the following code before sending the request to another thread via ZMQ + ```python Example + trace_context = trace_get_proc_propagate_context(rid) + req.trace_context = trace_context + ``` + - receiver: Execute the following code after receiving the request via ZMQ + ```python Example + trace_set_proc_propagate_context(rid, req.trace_context) + ``` + +5. When the request execution flow transfers to another node(PD disaggregation), the trace context needs to be explicitly propagated. + - sender: Execute the following code before sending the request to node thread via http + ```python Example + trace_context = trace_get_remote_propagate_context(bootstrap_room_list) + headers = {"trace_context": trace_context} + session.post(url, headers=headers) + ``` + - receiver: Execute the following code after receiving the request via http + ```python Example + trace_set_remote_propagate_context(request.headers['trace_context']) + ``` + +## How to Extend the Tracing Framework to Support Complex Tracing Scenarios + +The currently provided tracing package still has potential for further development. If you wish to build more advanced features upon it, you must first understand its existing design principles. + +The core of the tracing framework's implementation lies in the design of the span structure and the trace context. To aggregate scattered slices and enable concurrent tracking of multiple requests, we have designed a two-level trace context structure and a four-level span structure: `SglangTraceReqContext`, `SglangTraceThreadContext`. Their relationship is as follows: +```text Output +SglangTraceReqContext (req_id="req-123") ++-- SglangTraceThreadContext(thread_label="scheduler", tp_rank=0) +| ++-- SglangTraceThreadContext(thread_label="scheduler", tp_rank=1) +``` + +Each traced request maintains a global `SglangTraceReqContext`. For every thread processing the request, a corresponding `SglangTraceThreadContext` is recorded and composed within the `SglangTraceReqContext`. Within each thread, every currently traced slice (possibly nested) is stored in a list. + +In addition to the above hierarchy, each slice also records its previous slice via Span.add_link(), which can be used to trace the execution flow. + +When the request execution flow transfers to a new thread, the trace context needs to be explicitly propagated. In the framework, this is represented by `SglangTracePropagateContext`, which contains the context of the request span and the previous slice span. + + +We designed a four-level span structure, consisting of `bootstrap_room_span`, `req_root_span`, `thread_span`, and `slice_span`. Among them, `req_root_span` and `thread_span` correspond to `SglangTraceReqContext` and `SglangTraceThreadContext`, respectively, and `slice_span` is stored within the `SglangTraceThreadContext`. The `bootstrap_room_span` is designed to accommodate the separation of PD-disaggregation. On different nodes, we may want to add certain attributes to the `req_root_span`. However, if the `req_root_span` is shared across all nodes, the Prefill and Decode nodes would not be allowed to add attributes due to the constraints imposed by OpenTelemetry's design. + +```text Output +bootstrap room span ++-- router req root span +| +-- router thread span +| +-- slice span ++-- prefill req root span +| +-- tokenizer thread span +| | +-- slice span +| +-- scheduler thread span +| +-- slice span ++-- decode req root span + +-- tokenizer thread span + | +-- slice span + +-- scheduler thread span + +-- slice span +``` diff --git a/docs_new/docs/references/torch_compile_cache.mdx b/docs_new/docs/references/torch_compile_cache.mdx new file mode 100644 index 000000000..0e3c850ca --- /dev/null +++ b/docs_new/docs/references/torch_compile_cache.mdx @@ -0,0 +1,16 @@ +--- +title: "Enabling cache for torch.compile" +metatags: + description: "SGLang torch.compile cache: TORCHINDUCTOR_CACHE_DIR for faster deployment across multiple machines." +--- +SGLang uses `max-autotune-no-cudagraphs` mode of torch.compile. The auto-tuning can be slow. +If you want to deploy a model on many different machines, you can ship the torch.compile cache to these machines and skip the compilation steps. + +This is based on https://pytorch.org/tutorials/recipes/torch_compile_caching_tutorial.html + + +1. Generate the cache by setting TORCHINDUCTOR_CACHE_DIR and running the model once. +```text Output +TORCHINDUCTOR_CACHE_DIR=/root/inductor_root_cache python3 -m sglang.launch_server --model meta-llama/Llama-3.1-8B-Instruct --enable-torch-compile +``` +2. Copy the cache folder to other machines and launch the server with `TORCHINDUCTOR_CACHE_DIR`. diff --git a/docs_new/docs/sglang-diffusion/api/cli.mdx b/docs_new/docs/sglang-diffusion/api/cli.mdx new file mode 100644 index 000000000..73f913ffd --- /dev/null +++ b/docs_new/docs/sglang-diffusion/api/cli.mdx @@ -0,0 +1,366 @@ +--- +title: CLI reference +sidebarTitle: CLI +description: Run one-off generation tasks and launch the HTTP server from the command line. +--- + +The `sglang` CLI provides two main subcommands for diffusion inference: + +- **`sglang generate`** -- run a one-off generation without a persistent server +- **`sglang serve`** -- launch the OpenAI-compatible HTTP server + +## Prerequisites + +A working SGLang Diffusion installation with the `sglang` CLI available in your `$PATH`. See the [installation guide](../installation) for setup instructions. + +## Generate + +Run a one-off generation task without launching a persistent server. Pass both server arguments and sampling parameters after the `generate` subcommand: + +```bash +SERVER_ARGS=( + --model-path Wan-AI/Wan2.2-T2V-A14B-Diffusers + --text-encoder-cpu-offload + --pin-cpu-memory + --num-gpus 4 + --ulysses-degree=2 + --ring-degree=2 +) + +SAMPLING_ARGS=( + --prompt "A curious raccoon" + --save-output + --output-path outputs + --output-file-name "A curious raccoon.mp4" +) + +sglang generate "${SERVER_ARGS[@]}" "${SAMPLING_ARGS[@]}" +``` + +You can also enable Cache-DiT acceleration via an environment variable: + +```bash +SGLANG_CACHE_DIT_ENABLED=true sglang generate "${SERVER_ARGS[@]}" "${SAMPLING_ARGS[@]}" +``` + + +HTTP server-related arguments are ignored in `generate` mode. The process shuts down automatically once generation completes. + + +## Serve + +Launch the SGLang Diffusion HTTP server and interact through the OpenAI-compatible API. + +```bash +SERVER_ARGS=( + --model-path Wan-AI/Wan2.1-T2V-1.3B-Diffusers + --text-encoder-cpu-offload + --pin-cpu-memory + --num-gpus 4 + --ulysses-degree=2 + --ring-degree=2 +) + +sglang serve "${SERVER_ARGS[@]}" +``` + +- `--model-path` -- which model to load (e.g. `Wan-AI/Wan2.1-T2V-1.3B-Diffusers`) +- `--port` -- HTTP port to listen on (default: `30010`) + +For full API usage including image/video generation and LoRA management, see the [OpenAI API documentation](./openai-api). + +--- + +## Supported arguments + +### Server arguments + + + +| Argument | Description | +|:--|:--| +| `--model-path MODEL_PATH` | Path to the model or HuggingFace model ID | +| `--lora-path LORA_PATH` | Path to a LoRA adapter (local or HuggingFace ID). If omitted, LoRA is not applied | +| `--lora-nickname NAME` | Nickname for the LoRA adapter (default: `default`) | +| `--num-gpus NUM` | Number of GPUs to use | +| `--tp-size SIZE` | Tensor parallelism size (encoder only; keep at most 1 when text encoder offload is enabled) | +| `--sp-degree SIZE` | Sequence parallelism size (typically should match the number of GPUs) | +| `--ulysses-degree SIZE` | DeepSpeed-Ulysses-style SP degree in USP | +| `--ring-degree SIZE` | Ring attention-style SP degree in USP | +| `--attention-backend BACKEND` | Attention backend. Native pipelines: `fa`, `torch_sdpa`, `sage_attn`, etc. Diffusers pipelines: `flash`, `_flash_3_hub`, `sage`, `xformers` | +| `--attention-backend-config CONFIG` | Config for the attention backend. Accepts a JSON string, a JSON/YAML file path, or `key=value` pairs | +| `--cache-dit-config PATH` | Path to a Cache-DiT YAML/JSON config (diffusers backend only) | +| `--dit-precision DTYPE` | Precision for the DiT model (`fp32`, `fp16`, `bf16`) | +| `--text-encoder-cpu-offload` | Offload text encoders to CPU | +| `--pin-cpu-memory` | Pin CPU memory for faster transfers | + + + +### Sampling parameters + + + +| Argument | Description | +|:--|:--| +| `--prompt PROMPT` | Text description for the image or video to generate | +| `--negative-prompt PROMPT` | Negative prompt to guide generation away from certain concepts | +| `--num-inference-steps STEPS` | Number of denoising steps | +| `--seed SEED` | Random seed for reproducible generation | + + + + + +| Argument | Description | +|:--|:--| +| `--height HEIGHT` | Height of the generated output | +| `--width WIDTH` | Width of the generated output | +| `--num-frames NUM` | Number of frames to generate (video only) | +| `--fps FPS` | Frames per second for the saved output (video only) | + + + + + +| Argument | Description | +|:--|:--| +| `--save-output` | Save the image or video to disk | +| `--output-path PATH` | Directory to save the generated output | +| `--output-file-name NAME` | File name for the saved output | +| `--return-frames` | Return the raw frames instead of saving | + + + +### Frame interpolation (video only) + +Frame interpolation is a post-processing step that synthesizes new frames between each pair of consecutive generated frames, producing smoother motion without re-running the diffusion model. + +The `--frame-interpolation-exp` flag controls how many rounds of interpolation to apply: each round inserts one new frame into every gap between adjacent frames, so the output frame count follows the formula: + +$$ +\text{output frames} = (N - 1) \times 2^{\text{exp}} + 1 +$$ + +For example, 5 original frames with `exp=1` -> 4 gaps x 1 new frame + 5 originals = **9 frames**; with `exp=2` -> **17 frames**. + +| Argument | Description | +|:--|:--| +| `--enable-frame-interpolation` | Enable frame interpolation. Model weights are downloaded automatically on first use | +| `--frame-interpolation-exp EXP` | Interpolation exponent -- `1` = 2x temporal resolution, `2` = 4x, etc. (default: `1`) | +| `--frame-interpolation-scale SCALE` | RIFE inference scale; use `0.5` for high-resolution inputs to save memory (default: `1.0`) | +| `--frame-interpolation-model-path PATH` | Local directory or HuggingFace repo ID containing RIFE `flownet.pkl` weights (default: `elfgum/RIFE-4.22.lite`, downloaded automatically) | + +**Example** -- generate a 5-frame video and interpolate to 9 frames ($(5 - 1) \times 2^1 + 1 = 9$): + +```bash +sglang generate \ + --model-path Wan-AI/Wan2.2-T2V-A14B-Diffusers \ + --prompt "A dog running through a park" \ + --num-frames 5 \ + --enable-frame-interpolation \ + --frame-interpolation-exp 1 \ + --save-output +``` + +--- + +## Configuration files + +Instead of passing every parameter on the command line, you can use a JSON or YAML config file. Command-line arguments take precedence over config values. + +```bash +sglang generate --config config.json +``` + + + + ```json config.json + { + "model_path": "FastVideo/FastHunyuan-diffusers", + "prompt": "A beautiful woman in a red dress walking down a street", + "output_path": "outputs/", + "num_gpus": 2, + "sp_size": 2, + "tp_size": 1, + "num_frames": 45, + "height": 720, + "width": 1280, + "num_inference_steps": 6, + "seed": 1024, + "fps": 24, + "precision": "bf16", + "vae_precision": "fp16", + "vae_tiling": true, + "vae_sp": true, + "vae_config": { + "load_encoder": false, + "load_decoder": true, + "tile_sample_min_height": 256, + "tile_sample_min_width": 256 + }, + "text_encoder_precisions": ["fp16", "fp16"], + "mask_strategy_file_path": null, + "enable_torch_compile": false + } + ``` + + + ```yaml config.yaml + model_path: "FastVideo/FastHunyuan-diffusers" + prompt: "A beautiful woman in a red dress walking down a street" + output_path: "outputs/" + num_gpus: 2 + sp_size: 2 + tp_size: 1 + num_frames: 45 + height: 720 + width: 1280 + num_inference_steps: 6 + seed: 1024 + fps: 24 + precision: "bf16" + vae_precision: "fp16" + vae_tiling: true + vae_sp: true + vae_config: + load_encoder: false + load_decoder: true + tile_sample_min_height: 256 + tile_sample_min_width: 256 + text_encoder_precisions: + - "fp16" + - "fp16" + mask_strategy_file_path: null + enable_torch_compile: false + ``` + + + +To see all available options: + +```bash +sglang generate --help +``` + +--- + +## Component path overrides + +You can override any pipeline component (e.g. `vae`, `transformer`, `text_encoder`) by specifying a custom checkpoint path with `---path`, where `` matches the key in the model's `model_index.json`. + +### Example: FLUX.2-dev with Tiny AutoEncoder + +Replace the default VAE with a distilled tiny autoencoder for ~3x faster decoding: + +```bash +sglang serve \ + --model-path=black-forest-labs/FLUX.2-dev \ + --vae-path=fal/FLUX.2-Tiny-AutoEncoder +``` + +You can also use a local path: + +```bash +sglang serve \ + --model-path=black-forest-labs/FLUX.2-dev \ + --vae-path=~/.cache/huggingface/hub/models--fal--FLUX.2-Tiny-AutoEncoder/snapshots/.../vae +``` + + +The component key must match the one in the model's `model_index.json` (e.g. `vae`). +The path must be either a HuggingFace repo ID or point to a complete component folder containing `config.json` and safetensors files. + + +--- + +## Diffusers backend + +SGLang Diffusion supports a diffusers backend that runs any diffusers-compatible model through SGLang's infrastructure using vanilla diffusers pipelines. This is useful for models without native SGLang implementations or models with custom pipeline classes. + +### Backend arguments + +| Argument | Values | Description | +|:--|:--|:--| +| `--backend` | `auto` (default), `sglang`, `diffusers` | `auto`: prefer native SGLang, fallback to diffusers. `sglang`: force native (fails if unavailable). `diffusers`: force vanilla diffusers pipeline | +| `--diffusers-attention-backend` | `flash`, `_flash_3_hub`, `sage`, `xformers`, `native` | Attention backend for diffusers pipelines | +| `--trust-remote-code` | flag | Required for models with custom pipeline classes | +| `--vae-tiling` | flag | Enable VAE tiling for large image support (decodes tile-by-tile) | +| `--vae-slicing` | flag | Enable VAE slicing for lower memory usage (decodes slice-by-slice) | +| `--dit-precision` | `fp16`, `bf16`, `fp32` | Precision for the diffusion transformer | +| `--vae-precision` | `fp16`, `bf16`, `fp32` | Precision for the VAE | + +### Example: running Ovis-Image-7B + +[Ovis-Image-7B](https://huggingface.co/AIDC-AI/Ovis-Image-7B) is a 7B text-to-image model optimized for high-quality text rendering. + +```bash +sglang generate \ + --model-path AIDC-AI/Ovis-Image-7B \ + --backend diffusers \ + --trust-remote-code \ + --diffusers-attention-backend flash \ + --prompt "A serene Japanese garden with cherry blossoms" \ + --height 1024 \ + --width 1024 \ + --num-inference-steps 30 \ + --save-output \ + --output-path outputs \ + --output-file-name ovis_garden.png +``` + +### Extra diffusers arguments + +For pipeline-specific parameters not exposed via CLI, use `diffusers_kwargs` in a config file: + +```json config.json +{ + "model_path": "AIDC-AI/Ovis-Image-7B", + "backend": "diffusers", + "prompt": "A beautiful landscape", + "diffusers_kwargs": { + "cross_attention_kwargs": {"scale": 0.5} + } +} +``` + +```bash +sglang generate --config config.json +``` + +### Cache-DiT acceleration + +Users on the diffusers backend can leverage Cache-DiT acceleration by loading custom cache configs from a YAML file. See the [Cache-DiT documentation](../cache-dit) for details. + +--- + +## Cloud storage support + +The server supports automatically uploading generated artifacts to S3-compatible cloud storage (AWS S3, MinIO, Alibaba Cloud OSS, Tencent Cloud COS). + +The workflow is: **Generate -> Upload -> Delete local file**. The API response returns the public URL of the uploaded object. + +1. **Install boto3** + +```bash +pip install boto3 +``` + +2. **Set environment variables** + +```bash +export SGLANG_CLOUD_STORAGE_TYPE=s3 +export SGLANG_S3_BUCKET_NAME=my-bucket +export SGLANG_S3_ACCESS_KEY_ID=your-access-key +export SGLANG_S3_SECRET_ACCESS_KEY=your-secret-key + +# Optional: custom endpoint for MinIO/OSS/COS +export SGLANG_S3_ENDPOINT_URL=https://minio.example.com +``` + +3. **Launch the server** + +```bash +sglang serve --model-path MODEL_PATH +``` + +See the [environment variables reference](../environment-variables) for all storage-related variables. diff --git a/docs_new/docs/sglang-diffusion/api/openai-api.mdx b/docs_new/docs/sglang-diffusion/api/openai-api.mdx new file mode 100644 index 000000000..15642149c --- /dev/null +++ b/docs_new/docs/sglang-diffusion/api/openai-api.mdx @@ -0,0 +1,421 @@ +--- +title: OpenAI API +sidebarTitle: OpenAI API +description: Image and video generation endpoints with LoRA adapter management. +--- + +The SGLang Diffusion HTTP server implements an OpenAI-compatible API for image and video generation, as well as dynamic LoRA adapter management. + +## Prerequisites + +- Python 3.11+ if you plan to use the OpenAI Python SDK. +- A running SGLang Diffusion server (see the [CLI reference](./cli) for launch instructions). + +## Start the server + +```bash +SERVER_ARGS=( + --model-path Wan-AI/Wan2.1-T2V-1.3B-Diffusers + --text-encoder-cpu-offload + --pin-cpu-memory + --num-gpus 4 + --ulysses-degree=2 + --ring-degree=2 + --port 30010 +) + +sglang serve "${SERVER_ARGS[@]}" +``` + +- `--model-path` -- path to the model or HuggingFace model ID +- `--port` -- HTTP port to listen on (default: `30000`) + +### Get model information + +**Endpoint:** `GET /models` + +Returns model path, task type, pipeline configuration, and precision settings. + + +```bash curl +curl -sS -X GET "http://localhost:30010/models" +``` + + +**Response:** + +```json +{ + "model_path": "Wan-AI/Wan2.1-T2V-1.3B-Diffusers", + "task_type": "T2V", + "pipeline_name": "wan_pipeline", + "pipeline_class": "WanPipeline", + "num_gpus": 4, + "dit_precision": "bf16", + "vae_precision": "fp16" +} +``` + +--- + +## Image generation + +The server implements an OpenAI-compatible Images API under the `/v1/images` namespace. + +### Create an image + +**Endpoint:** `POST /v1/images/generations` + + +```python Python +import base64 +from openai import OpenAI + +client = OpenAI(api_key="sk-proj-1234567890", base_url="http://localhost:30010/v1") + +img = client.images.generate( + prompt="A calico cat playing a piano on stage", + size="1024x1024", + n=1, + response_format="b64_json", +) + +image_bytes = base64.b64decode(img.data[0].b64_json) +with open("output.png", "wb") as f: + f.write(image_bytes) +``` + +```bash curl +curl -sS -X POST "http://localhost:30010/v1/images/generations" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer sk-proj-1234567890" \ + -d '{ + "prompt": "A calico cat playing a piano on stage", + "size": "1024x1024", + "n": 1, + "response_format": "b64_json" + }' +``` + + + +If `response_format=url` is used and cloud storage is not configured, the API returns a relative URL like `/v1/images//content`. + + +### Edit an image + +**Endpoint:** `POST /v1/images/edits` + +Accepts a multipart form upload with input images and a text prompt. Returns either a base64-encoded image or a URL. + + + + ```bash + curl -sS -X POST "http://localhost:30010/v1/images/edits" \ + -H "Authorization: Bearer sk-proj-1234567890" \ + -F "image=@local_input_image.png" \ + -F "url=image_url.jpg" \ + -F "prompt=A calico cat playing a piano on stage" \ + -F "size=1024x1024" \ + -F "response_format=b64_json" + ``` + + + ```bash + curl -sS -X POST "http://localhost:30010/v1/images/edits" \ + -H "Authorization: Bearer sk-proj-1234567890" \ + -F "image=@local_input_image.png" \ + -F "url=image_url.jpg" \ + -F "prompt=A calico cat playing a piano on stage" \ + -F "size=1024x1024" \ + -F "response_format=url" + ``` + + + +### Download image content + +When `response_format=url` is used, the API returns a relative URL like `/v1/images//content`. + +**Endpoint:** `GET /v1/images/{image_id}/content` + +```bash +curl -sS -L "http://localhost:30010/v1/images//content" \ + -H "Authorization: Bearer sk-proj-1234567890" \ + -o output.png +``` + +--- + +## Video generation + +The server implements a subset of the OpenAI Videos API under the `/v1/videos` namespace. + +### Create a video + +**Endpoint:** `POST /v1/videos` + + +```python Python +from openai import OpenAI + +client = OpenAI(api_key="sk-proj-1234567890", base_url="http://localhost:30010/v1") + +video = client.videos.create( + prompt="A calico cat playing a piano on stage", + size="1280x720" +) +print(f"Video ID: {video.id}, Status: {video.status}") +``` + +```bash curl +curl -sS -X POST "http://localhost:30010/v1/videos" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer sk-proj-1234567890" \ + -d '{ + "prompt": "A calico cat playing a piano on stage", + "size": "1280x720" + }' +``` + + +### List videos + +**Endpoint:** `GET /v1/videos` + + +```python Python +videos = client.videos.list() +for item in videos.data: + print(item.id, item.status) +``` + +```bash curl +curl -sS -X GET "http://localhost:30010/v1/videos" \ + -H "Authorization: Bearer sk-proj-1234567890" +``` + + +### Download video content + +**Endpoint:** `GET /v1/videos/{video_id}/content` + + +```python Python +import time + +# Poll for completion +while True: + page = client.videos.list() + item = next((v for v in page.data if v.id == video_id), None) + if item and item.status == "completed": + break + time.sleep(5) + +# Download content +resp = client.videos.download_content(video_id=video_id) +with open("output.mp4", "wb") as f: + f.write(resp.read()) +``` + +```bash curl +curl -sS -L "http://localhost:30010/v1/videos//content" \ + -H "Authorization: Bearer sk-proj-1234567890" \ + -o output.mp4 +``` + + +--- + +## LoRA management + +The server supports dynamic loading, merging, and unmerging of LoRA adapters. + + +- **Mutual exclusion:** Only one LoRA can be merged (active) at a time. +- **Switching:** To switch LoRAs, you must first unmerge the current one, then set the new one. +- **Caching:** The server caches loaded LoRA weights in memory. Switching back to a previously loaded LoRA (same path) has negligible cost. + + +### Set LoRA adapter + +Loads one or more LoRA adapters and merges their weights into the model. Supports both single LoRA (backward compatible) and multiple LoRA adapters. + +**Endpoint:** `POST /v1/set_lora` + +**Parameters:** + +| Parameter | Type | Description | +|:--|:--|:--| +| `lora_nickname` | string or list | A unique identifier for the LoRA adapter(s). Required | +| `lora_path` | string or list | Path to `.safetensors` file(s) or HuggingFace repo ID(s). Required for first load; optional when re-activating a cached nickname | +| `target` | string or list | Which transformer(s) to apply the LoRA to: `"all"` (default), `"transformer"`, `"transformer_2"`, `"critic"` | +| `strength` | float or list | LoRA strength for merge (default: `1.0`). Values < 1.0 reduce the effect, > 1.0 amplify it | + + + + ```bash + curl -X POST http://localhost:30010/v1/set_lora \ + -H "Content-Type: application/json" \ + -d '{ + "lora_nickname": "lora_name", + "lora_path": "/path/to/lora.safetensors", + "target": "all", + "strength": 0.8 + }' + ``` + + + ```bash + curl -X POST http://localhost:30010/v1/set_lora \ + -H "Content-Type: application/json" \ + -d '{ + "lora_nickname": ["lora_1", "lora_2"], + "lora_path": ["/path/to/lora1.safetensors", "/path/to/lora2.safetensors"], + "target": ["transformer", "transformer_2"], + "strength": [0.8, 1.0] + }' + ``` + + + ```bash + curl -X POST http://localhost:30010/v1/set_lora \ + -H "Content-Type: application/json" \ + -d '{ + "lora_nickname": ["style_lora", "character_lora"], + "lora_path": ["/path/to/style.safetensors", "/path/to/character.safetensors"], + "target": "all", + "strength": [0.7, 0.9] + }' + ``` + + + + +When using multiple LoRAs: +- All list parameters (`lora_nickname`, `lora_path`, `target`, `strength`) must have the same length. +- If `target` or `strength` is a single value, it will be applied to all LoRAs. +- Multiple LoRAs applied to the same target will be merged in order. + + +### Merge LoRA weights + +Manually merges the currently set LoRA weights into the base model. + +**Endpoint:** `POST /v1/merge_lora_weights` + +| Parameter | Type | Description | +|:--|:--|:--| +| `target` | string | Which transformer(s) to merge: `"all"` (default), `"transformer"`, `"transformer_2"`, `"critic"` | +| `strength` | float | LoRA strength for merge (default: `1.0`) | + +```bash +curl -X POST http://localhost:30010/v1/merge_lora_weights \ + -H "Content-Type: application/json" \ + -d '{"strength": 0.8}' +``` + + +`set_lora` automatically performs a merge, so this endpoint is typically only needed if you have manually unmerged but want to re-apply the same LoRA without calling `set_lora` again. + + +### Unmerge LoRA weights + +Unmerges the currently active LoRA weights from the base model, restoring it to its original state. Call this before setting a different LoRA. + +**Endpoint:** `POST /v1/unmerge_lora_weights` + +```bash +curl -X POST http://localhost:30010/v1/unmerge_lora_weights \ + -H "Content-Type: application/json" +``` + +### List LoRA adapters + +Returns loaded LoRA adapters and current application status per module. + +**Endpoint:** `GET /v1/list_loras` + +```bash +curl -sS -X GET "http://localhost:30010/v1/list_loras" +``` + +**Response:** + +```json +{ + "loaded_adapters": [ + { "nickname": "lora_a", "path": "/weights/lora_a.safetensors" }, + { "nickname": "lora_b", "path": "/weights/lora_b.safetensors" } + ], + "active": { + "transformer": [ + { + "nickname": "lora2", + "path": "tarn59/pixel_art_style_lora_z_image_turbo", + "merged": true, + "strength": 1.0 + } + ] + } +} +``` + +### Example: switching LoRAs + +1. **Set LoRA A** + +```bash +curl -X POST http://localhost:30010/v1/set_lora \ + -d '{"lora_nickname": "lora_a", "lora_path": "path/to/A"}' +``` + +2. **Generate with LoRA A** + +Run your image or video generation requests. + +3. **Unmerge LoRA A** + +```bash +curl -X POST http://localhost:30010/v1/unmerge_lora_weights +``` + +4. **Set LoRA B** + +```bash +curl -X POST http://localhost:30010/v1/set_lora \ + -d '{"lora_nickname": "lora_b", "lora_path": "path/to/B"}' +``` + +5. **Generate with LoRA B** + +Run your image or video generation requests with the new adapter. + +--- + +## Output quality + +Control output quality and compression for both image and video generation through the `output-quality` and `output-compression` parameters. + +### Parameters + +| Parameter | Type | Description | +|:--|:--|:--| +| `output-quality` | string | Preset quality level. Default: `"default"` | +| `output-compression` | integer | Direct compression level override (0-100). When provided, takes precedence over `output-quality` | + +**Quality presets:** + +| Preset | Compression value | +|:--|:--| +| `"maximum"` | 100 | +| `"high"` | 90 | +| `"medium"` | 55 | +| `"low"` | 35 | +| `"default"` | Auto (50 for video, 75 for image) | + + +- When both `output-quality` and `output-compression` are provided, `output-compression` takes precedence. +- Quality settings apply to JPEG and video formats. PNG uses lossless compression and ignores these settings. +- Lower compression values (or `"low"` quality preset) produce smaller files but may show visible artifacts. + diff --git a/docs_new/docs/sglang-diffusion/attention-backends.mdx b/docs_new/docs/sglang-diffusion/attention-backends.mdx new file mode 100644 index 000000000..d8a6c21c1 --- /dev/null +++ b/docs_new/docs/sglang-diffusion/attention-backends.mdx @@ -0,0 +1,405 @@ +--- +title: "Attention Backends" +description: "Select and configure attention backends for SGLang diffusion pipelines." +--- + +This document describes the attention backends available in sglang diffusion (`sglang.multimodal_gen`) and how to select them. + +## Overview + +Attention backends are defined by `AttentionBackendEnum` (`sglang.multimodal_gen.runtime.platforms.interface.AttentionBackendEnum`) and selected via the CLI flag `--attention-backend`. + +Backend selection is performed by the shared attention layers (e.g. `LocalAttention` / `USPAttention` / `UlyssesAttention` in `sglang.multimodal_gen.runtime.layers.attention.layer`) and therefore applies to any model component using these layers (e.g. diffusion transformer / DiT and encoders). + +When using the diffusers backend, `--attention-backend` is passed through to diffusers' +`set_attention_backend` (e.g., `flash`, `_flash_3_hub`, `sage`, `xformers`, `native`). + +- **CUDA**: prefers FlashAttention (FA3/FA4) when supported; otherwise falls back to PyTorch SDPA. +- **ROCm**: uses FlashAttention when available; otherwise falls back to PyTorch SDPA. +- **MPS**: always uses PyTorch SDPA. +- **NPU**: always uses PyTorch SDPA. + +## Backend options + +For SGLang-native pipelines, the CLI accepts the lowercase names of `AttentionBackendEnum`. The table below lists the backends implemented by the built-in platforms. `fa3`/`fa4` are accepted as aliases for `fa`. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CLI valueEnum valueNotes
`fa` / `fa3` / `fa4``FA`FlashAttention. `fa3/fa4` are normalized to `fa` during argument parsing (`ServerArgs.__post_init__`).
`torch_sdpa``TORCH_SDPA`PyTorch `scaled_dot_product_attention`.
`sliding_tile_attn``SLIDING_TILE_ATTN`Sliding Tile Attention (STA). Requires `st_attn`. Configure via `--attention-backend-config`.
`sage_attn``SAGE_ATTN`Requires `sageattention`. Upstream SageAttention CUDA extensions target SM80/SM86/SM89/SM90/SM120 (compute capability 8.0/8.6/8.9/9.0/12.0); see upstream `setup.py`: https://github.com/thu-ml/SageAttention/blob/main/setup.py.
`sage_attn_3``SAGE_ATTN_3`Requires SageAttention3 installed per upstream instructions.
`video_sparse_attn``VIDEO_SPARSE_ATTN`Requires `vsa`. Configure `sparsity` via `--attention-backend-config`.
`vmoba_attn``VMOBA_ATTN`Requires `kernel.attn.vmoba_attn.vmoba`. Configure via `--attention-backend-config`.
`aiter``AITER`Requires `aiter`.
`sparse_video_gen_2_attn``SPARSE_VIDEO_GEN_2_ATTN`Requires `svg`. See installation instructions at https://github.com/svg-project/Sparse-VideoGen.
+ +## Selection priority + +The selection order in `runtime/layers/attention/selector.py` is: + +1. `global_force_attn_backend(...)` / `global_force_attn_backend_context_manager(...)` +2. CLI `--attention-backend` (`ServerArgs.attention_backend`) +3. Auto selection (platform capability, dtype, and installed packages) + +## Configuration + +Some backends require additional configuration. You can pass these parameters via `--attention-backend-config`. This argument accepts: +- A path to a JSON or YAML configuration file. +- A JSON string (e.g., `'{"sparsity": 0.5}'`). +- Key-value pairs (e.g., `"sparsity=0.5,enable_x=true"`). + +### Supported Configuration Parameters + +**Sliding Tile Attention (`sliding_tile_attn`)** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescriptionDefault
`mask_strategy_file_path``str`**Required.** Path to the mask strategy JSON file.-
`sta_mode``str`Mode of STA.``STA_inference``
`skip_time_steps``int`Number of steps to use full attention before switching to sparse attention.`15`
+ +**Video Sparse Attention (`video_sparse_attn`)** + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescriptionDefault
`sparsity``float`Validation sparsity (0.0 - 1.0).`0.0`
+ +**V-MoBA (`vmoba_attn`)** + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescriptionDefault
`temporal_chunk_size``int`Chunk size for temporal dimension.-
`temporal_topk``int`Top-K tokens to select in temporal dimension.-
`spatial_chunk_size``list[int]`Chunk size for spatial dimension (H, W).-
`spatial_topk``int`Top-K tokens to select in spatial dimension.-
`st_chunk_size``list[int]`Chunk size for spatiotemporal dimension (T, H, W).-
`st_topk``int`Top-K tokens to select in spatiotemporal dimension.-
`moba_select_mode``str`Selection mode (e.g., `threshold`).`threshold`
`moba_threshold``float`Threshold value for selection.`0.25`
`moba_threshold_type``str`Type of thresholding (e.g., `query_head`).`query_head`
`first_full_step``int`Number of initial steps to use full attention.`12`
`first_full_layer``int`Number of initial layers to use full attention.`0`
`temporal_layer``int`Number of temporal layers.`1`
`spatial_layer``int`Number of spatial layers.`1`
`st_layer``int`Number of spatiotemporal layers.`1`
+ +## Platform support matrix + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BackendCUDAROCmMPSNPUNotes
`fa`YesYesNoNoCUDA requires SM80+ and fp16/bf16. FlashAttention is only used when the required runtime is installed; otherwise it falls back to `torch_sdpa`.
`torch_sdpa`YesYesYesYesMost compatible option across platforms.
`sliding_tile_attn`YesNoNoNoCUDA-only. Requires `st_attn`. Configure via `--attention-backend-config`.
`sage_attn`YesNoNoNoCUDA-only (optional dependency).
`sage_attn_3`YesNoNoNoCUDA-only (optional dependency).
`video_sparse_attn`YesNoNoNoCUDA-only. Requires `vsa`. Configure `sparsity` via `--attention-backend-config`.
`vmoba_attn`YesNoNoNoCUDA-only. Requires `kernel.attn.vmoba_attn.vmoba`. Configure via `--attention-backend-config`.
`aiter`YesNoNoNoRequires `aiter`.
`sparse_video_gen_2_attn`YesNoNoNoCUDA-only. Requires `svg`.
+ +## Usage + +### Select a backend via CLI + +```bash +sglang generate \ + --model-path \ + --prompt "..." \ + --attention-backend fa +``` + +```bash +sglang generate \ + --model-path \ + --prompt "..." \ + --attention-backend torch_sdpa +``` + +### Using Sliding Tile Attention (STA) + +```bash +# Pass the mask strategy file path via config +sglang generate \ + --model-path \ + --prompt "..." \ + --attention-backend sliding_tile_attn \ + --attention-backend-config "mask_strategy_file_path=/abs/path/to/mask_strategy.json" +``` + +### Notes for ROCm / MPS + +- ROCm: use `--attention-backend torch_sdpa` or `fa` depending on what is available in your environment. +- MPS: the platform implementation always uses `torch_sdpa`. diff --git a/docs_new/docs/sglang-diffusion/cache-dit.mdx b/docs_new/docs/sglang-diffusion/cache-dit.mdx new file mode 100644 index 000000000..59bc388d3 --- /dev/null +++ b/docs_new/docs/sglang-diffusion/cache-dit.mdx @@ -0,0 +1,433 @@ +--- +title: "Cache-DiT Acceleration" +description: "Configure Cache-DiT acceleration for diffusion inference." +--- + +SGLang integrates [Cache-DiT](https://github.com/vipshop/cache-dit), a caching acceleration engine for Diffusion Transformers (DiT), to achieve up to **1.69x inference speedup** with minimal quality loss. + +## Overview + +**Cache-DiT** uses intelligent caching strategies to skip redundant computation in the denoising loop: + +- **DBCache (Dual Block Cache)**: Dynamically decides when to cache transformer blocks based on residual differences +- **TaylorSeer**: Uses Taylor expansion for calibration to optimize caching decisions +- **SCM (Step Computation Masking)**: Step-level caching control for additional speedup + +## Basic Usage + +Enable Cache-DiT by exporting the environment variable and using `sglang generate` or `sglang serve` : + +```bash +SGLANG_CACHE_DIT_ENABLED=true \ +sglang generate --model-path Qwen/Qwen-Image \ + --prompt "A beautiful sunset over the mountains" +``` + +## Diffusers Backend + +Cache-DiT supports loading acceleration configs from a custom YAML file. For +diffusers pipelines (`diffusers` backend), pass the YAML/JSON path via `--cache-dit-config`. This +flow requires cache-dit >= 1.2.0 (`cache_dit.load_configs`). + +### Single GPU inference + +Define a `cache.yaml` file that contains: + +```yaml +cache_config: + max_warmup_steps: 8 + warmup_interval: 2 + max_cached_steps: -1 + max_continuous_cached_steps: 2 + Fn_compute_blocks: 1 + Bn_compute_blocks: 0 + residual_diff_threshold: 0.12 + enable_taylorseer: true + taylorseer_order: 1 +``` + +Then apply the config with: + +```bash +sglang generate \ + --backend diffusers \ + --model-path Qwen/Qwen-Image \ + --cache-dit-config cache.yaml \ + --prompt "A beautiful sunset over the mountains" +``` + +### Distributed inference + +- 1D Parallelism + +Define a parallelism only config yaml `parallel.yaml` file that contains: + +```yaml +parallelism_config: + ulysses_size: auto + parallel_kwargs: + attention_backend: native + extra_parallel_modules: ["text_encoder", "vae"] +``` + +Then, apply the distributed inference acceleration config from yaml. `ulysses_size: auto` means that cache-dit will auto detect the `world_size` as the ulysses_size. Otherwise, you should manually set it as specific int number, e.g, 4. + +Then apply the distributed config with: (Note: please add `--num-gpus N` to specify the number of gpus for distributed inference) + +```bash +sglang generate \ + --backend diffusers \ + --num-gpus 4 \ + --model-path Qwen/Qwen-Image \ + --cache-dit-config parallel.yaml \ + --prompt "A futuristic cityscape at sunset" +``` + +- 2D Parallelism + +You can also define a 2D parallelism config yaml `parallel_2d.yaml` file that contains: + +```yaml +parallelism_config: + ulysses_size: auto + tp_size: 2 + parallel_kwargs: + attention_backend: native + extra_parallel_modules: ["text_encoder", "vae"] +``` +Then, apply the 2D parallelism config from yaml. Here `tp_size: 2` means using tensor parallelism with size 2. The `ulysses_size: auto` means that cache-dit will auto detect the `world_size // tp_size` as the ulysses_size. + +- 3D Parallelism + +You can also define a 3D parallelism config yaml `parallel_3d.yaml` file that contains: + +```yaml +parallelism_config: + ulysses_size: 2 + ring_size: 2 + tp_size: 2 + parallel_kwargs: + attention_backend: native + extra_parallel_modules: ["text_encoder", "vae"] +``` +Then, apply the 3D parallelism config from yaml. Here `ulysses_size: 2`, `ring_size: 2`, `tp_size: 2` means using ulysses parallelism with size 2, ring parallelism with size 2 and tensor parallelism with size 2. + +### Hybrid Cache and Parallelism + +Define a hybrid cache and parallel acceleration config yaml `hybrid.yaml` file that contains: + +```yaml +cache_config: + max_warmup_steps: 8 + warmup_interval: 2 + max_cached_steps: -1 + max_continuous_cached_steps: 2 + Fn_compute_blocks: 1 + Bn_compute_blocks: 0 + residual_diff_threshold: 0.12 + enable_taylorseer: true + taylorseer_order: 1 +parallelism_config: + ulysses_size: auto + parallel_kwargs: + attention_backend: native + extra_parallel_modules: ["text_encoder", "vae"] +``` + +Then, apply the hybrid cache and parallel acceleration config from yaml. + +```bash +sglang generate \ + --backend diffusers \ + --num-gpus 4 \ + --model-path Qwen/Qwen-Image \ + --cache-dit-config hybrid.yaml \ + --prompt "A beautiful sunset over the mountains" +``` + +## Advanced Configuration + +### DBCache Parameters + +DBCache controls block-level caching behavior: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Fn`SGLANG_CACHE_DIT_FN`1Number of first blocks to always compute
Bn`SGLANG_CACHE_DIT_BN`0Number of last blocks to always compute
W`SGLANG_CACHE_DIT_WARMUP`4Warmup steps before caching starts
R`SGLANG_CACHE_DIT_RDT`0.24Residual difference threshold
MC`SGLANG_CACHE_DIT_MC`3Maximum continuous cached steps
+ +### TaylorSeer Configuration + +TaylorSeer improves caching accuracy using Taylor expansion: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterEnv VariableDefaultDescription
Enable`SGLANG_CACHE_DIT_TAYLORSEER`falseEnable TaylorSeer calibrator
Order`SGLANG_CACHE_DIT_TS_ORDER`1Taylor expansion order (1 or 2)
+ +### Combined Configuration Example + +DBCache and TaylorSeer are complementary strategies that work together, you can configure both sets of parameters +simultaneously: + +```bash +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 generate --model-path black-forest-labs/FLUX.1-dev \ + --prompt "A curious raccoon in a forest" +``` + +### SCM (Step Computation Masking) + +SCM provides step-level caching control for additional speedup. It decides which denoising steps to compute fully and +which to use cached results. + +**SCM Presets** + +SCM is configured with presets: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PresetCompute RatioSpeedQuality
`none`100%BaselineBest
`slow`~75%~1.3xHigh
`medium`~50%~2xGood
`fast`~35%~3xAcceptable
`ultra`~25%~4xLower
+ +**Usage** + +```bash +SGLANG_CACHE_DIT_ENABLED=true \ +SGLANG_CACHE_DIT_SCM_PRESET=medium \ +sglang generate --model-path Qwen/Qwen-Image \ + --prompt "A futuristic cityscape at sunset" +``` + +**Custom SCM Bins** + +For fine-grained control over which steps to compute vs cache: + +```bash +SGLANG_CACHE_DIT_ENABLED=true \ +SGLANG_CACHE_DIT_SCM_COMPUTE_BINS="8,3,3,2,2" \ +SGLANG_CACHE_DIT_SCM_CACHE_BINS="1,2,2,2,3" \ +sglang generate --model-path Qwen/Qwen-Image \ + --prompt "A futuristic cityscape at sunset" +``` + +**SCM Policy** + + + + + + + + + + + + + + + + + + + + + + + + + + +
PolicyEnv VariableDescription
`dynamic``SGLANG_CACHE_DIT_SCM_POLICY=dynamic`Adaptive caching based on content (default)
`static``SGLANG_CACHE_DIT_SCM_POLICY=static`Fixed caching pattern
+ +## Environment Variables + +All Cache-DiT parameters can be configured via environment variables. +See [Environment variables](./environment-variables) for the complete list. + +## Supported Models + +SGLang Diffusion x Cache-DiT supports almost all models originally supported in SGLang Diffusion: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model FamilyExample Models
WanWan2.1, Wan2.2
FluxFLUX.1-dev, FLUX.2-dev
Z-ImageZ-Image-Turbo
QwenQwen-Image, Qwen-Image-Edit
HunyuanHunyuanVideo
+ +## Performance Tips + +1. **Start with defaults**: The default parameters work well for most models +2. **Use TaylorSeer**: It typically improves both speed and quality +3. **Tune R threshold**: Lower values = better quality, higher values = faster +4. **SCM for extra speed**: Use `medium` preset for good speed/quality balance +5. **Warmup matters**: Higher warmup = more stable caching decisions + +## Limitations + +- **SGLang-native pipelines**: Distributed support (TP/SP) is not yet validated; Cache-DiT will be automatically + disabled when `world_size > 1`. +- **SCM minimum steps**: SCM requires >= 8 inference steps to be effective +- **Model support**: Only models registered in Cache-DiT's BlockAdapterRegister are supported + +## Troubleshooting + +### SCM disabled for low step count + +For models with < 8 inference steps (e.g., DMD distilled models), SCM will be automatically disabled. DBCache +acceleration still works. + +## References + +- [Cache-DiT](https://github.com/vipshop/cache-dit) +- [SGLang diffusion](../../sglang-diffusion/intro) diff --git a/docs_new/docs/sglang-diffusion/caching-acceleration.mdx b/docs_new/docs/sglang-diffusion/caching-acceleration.mdx new file mode 100644 index 000000000..0c95559b2 --- /dev/null +++ b/docs_new/docs/sglang-diffusion/caching-acceleration.mdx @@ -0,0 +1,88 @@ +--- +title: "Caching Acceleration" +description: "Compare caching acceleration strategies for diffusion models." +--- + +SGLang provides multiple caching acceleration strategies for Diffusion Transformer (DiT) models. These strategies can significantly reduce inference time by skipping redundant computation. + +## Overview + +SGLang supports two complementary caching approaches: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
StrategyScopeMechanismBest For
Cache-DiTBlock-levelSkip individual transformer blocks dynamicallyAdvanced, higher speedup
TeaCacheTimestep-levelSkip entire denoising steps based on L1 similaritySimple, built-in
+ + +## Cache-DiT + +[Cache-DiT](https://github.com/vipshop/cache-dit) provides block-level caching with +advanced strategies like DBCache and TaylorSeer. It can achieve up to **1.69x speedup**. + +See [Cache-DiT](./cache-dit) for detailed configuration. + +### Quick Start + +```bash +SGLANG_CACHE_DIT_ENABLED=true \ +sglang generate --model-path Qwen/Qwen-Image \ + --prompt "A beautiful sunset over the mountains" +``` + +### Key Features + +- **DBCache**: Dynamic block-level caching based on residual differences +- **TaylorSeer**: Taylor expansion-based calibration for optimized caching +- **SCM**: Step-level computation masking for additional speedup + +## TeaCache + +TeaCache (Temporal similarity-based caching) accelerates diffusion inference by detecting when consecutive denoising steps are similar enough to skip computation entirely. + +See [TeaCache](./tea-cache) for detailed documentation. + +### Quick Overview + +- Tracks L1 distance between modulated inputs across timesteps +- When accumulated distance is below threshold, reuses cached residual +- Supports CFG with separate positive/negative caches + +### Supported Models + +- Wan (wan2.1, wan2.2) +- Hunyuan (HunyuanVideo) +- Z-Image + +For Flux and Qwen models, TeaCache is automatically disabled when CFG is enabled. + +## References + +- [Cache-DiT Repository](https://github.com/vipshop/cache-dit) +- [TeaCache Paper](https://arxiv.org/abs/2411.14324) diff --git a/docs_new/docs/sglang-diffusion/ci-performance.mdx b/docs_new/docs/sglang-diffusion/ci-performance.mdx new file mode 100644 index 000000000..7d2f62ecd --- /dev/null +++ b/docs_new/docs/sglang-diffusion/ci-performance.mdx @@ -0,0 +1,32 @@ +--- +title: "CI Performance Baselines" +description: "Generate and update diffusion performance baselines used in CI." +--- + +`python/sglang/multimodal_gen/test/scripts/gen_perf_baselines.py` starts a local diffusion server, issues requests for selected test cases, aggregates stage/denoise-step/E2E timings from the perf log, and writes the results back to the `scenarios` section of `perf_baselines.json`. + +## Usage + +Update a single case: + +```bash +python python/sglang/multimodal_gen/test/scripts/gen_perf_baselines.py --case qwen_image_t2i +``` + +Select by regex: + +```bash +python python/sglang/multimodal_gen/test/scripts/gen_perf_baselines.py --match 'qwen_image_.*' +``` + +Run all keys from the baseline file `scenarios`: + +```bash +python python/sglang/multimodal_gen/test/scripts/gen_perf_baselines.py --all-from-baseline +``` + +Specify input/output paths and timeout: + +```bash +python python/sglang/multimodal_gen/test/scripts/gen_perf_baselines.py --baseline python/sglang/multimodal_gen/test/server/perf_baselines.json --out /tmp/perf_baselines.json --timeout 600 +``` diff --git a/docs_new/docs/sglang-diffusion/environment-variables.mdx b/docs_new/docs/sglang-diffusion/environment-variables.mdx new file mode 100644 index 000000000..603c68405 --- /dev/null +++ b/docs_new/docs/sglang-diffusion/environment-variables.mdx @@ -0,0 +1,140 @@ +--- +title: "Environment Variables" +description: "Configure SGLang diffusion behavior with environment variables." +--- + +These variables configure caching acceleration for Diffusion Transformer (DiT) models. +SGLang supports multiple caching strategies - see [performance optimization documentation](./performance-optimization) for an overview. + +See [Environment Variables](../references/environment_variables) for a list of all environment variables. + +## Cache-DiT configuration + +See [Cache-DiT documentation](./cache-dit) for detailed configuration. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDefaultDescription
`SGLANG_CACHE_DIT_ENABLED`falseEnable Cache-DiT acceleration
`SGLANG_CACHE_DIT_FN`1First N blocks to always compute
`SGLANG_CACHE_DIT_BN`0Last N blocks to always compute
`SGLANG_CACHE_DIT_WARMUP`4Warmup steps before caching
`SGLANG_CACHE_DIT_RDT`0.24Residual difference threshold
`SGLANG_CACHE_DIT_MC`3Max continuous cached steps
`SGLANG_CACHE_DIT_TAYLORSEER`falseEnable TaylorSeer calibrator
`SGLANG_CACHE_DIT_TS_ORDER`1TaylorSeer order (1 or 2)
`SGLANG_CACHE_DIT_SCM_PRESET`noneSCM preset (none/slow/medium/fast/ultra)
`SGLANG_CACHE_DIT_SCM_POLICY`dynamicSCM caching policy
`SGLANG_CACHE_DIT_SCM_COMPUTE_BINS`not setCustom SCM compute bins
`SGLANG_CACHE_DIT_SCM_CACHE_BINS`not setCustom SCM cache bins
+ +## Cloud Storage + +These variables configure S3-compatible cloud storage for automatically uploading generated images and videos. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Environment VariableDefaultDescription
`SGLANG_CLOUD_STORAGE_TYPE`not setSet to `s3` to enable cloud storage
`SGLANG_S3_BUCKET_NAME`not setThe name of the S3 bucket
`SGLANG_S3_ENDPOINT_URL`not setCustom endpoint URL (for MinIO, OSS, etc.)
`SGLANG_S3_REGION_NAME`us-east-1AWS region name
`SGLANG_S3_ACCESS_KEY_ID`not setAWS Access Key ID
`SGLANG_S3_SECRET_ACCESS_KEY`not setAWS Secret Access Key
diff --git a/docs_new/docs/sglang-diffusion/index.mdx b/docs_new/docs/sglang-diffusion/index.mdx new file mode 100644 index 000000000..5e4a54d73 --- /dev/null +++ b/docs_new/docs/sglang-diffusion/index.mdx @@ -0,0 +1,65 @@ +--- +title: SGLang Diffusion +description: Accelerated image and video generation with diffusion models. +--- + +SGLang Diffusion is an inference framework for accelerated image and video generation using diffusion models. It provides an end-to-end unified pipeline with optimized kernels and an efficient scheduler loop. + +## Key features + +* **Broad model support:** Wan series, FastWan series, Hunyuan, Qwen-Image, Qwen-Image-Edit, Flux, Z-Image, GLM-Image, and more +* **Fast inference:** optimized kernels, efficient scheduler loop, and Cache-DiT acceleration +* **Ease of use:** OpenAI-compatible API, CLI, and Python SDK +* **Multi-platform:** NVIDIA GPUs (H100, H200, A100, B200, 4090), AMD GPUs (MI300X, MI325X), and Ascend NPU (A2, A3) + +## Quick start + +1. **Install SGLang Diffusion** + +```bash +uv pip install "sglang[diffusion]" --prerelease=allow +``` + +See the [installation guide](./installation) for more installation methods and ROCm-specific instructions. + +2. **Run a one-off generation** + +```bash +sglang generate --model-path Qwen/Qwen-Image \ + --prompt "A beautiful sunset over the mountains" \ + --save-output +``` + +3. **Serve with the OpenAI-compatible API** + +```bash +sglang serve --model-path Qwen/Qwen-Image --port 30010 +``` + +## CLI quick reference + +### Generate (one-off generation) + +```bash +sglang generate --model-path --prompt "" --save-output +``` + +### Serve (HTTP server) + +```bash +sglang serve --model-path --port 30010 +``` + +### Enable Cache-DiT acceleration + +```bash +SGLANG_CACHE_DIT_ENABLED=true sglang generate --model-path --prompt "" +``` + +## References + +* [SGLang GitHub](https://github.com/sgl-project/sglang) +* [Cache-DiT](https://github.com/vipshop/cache-dit) +* [FastVideo](https://github.com/hao-ai-lab/FastVideo) +* [xDiT](https://github.com/xdit-project/xDiT) +* [Diffusers](https://github.com/huggingface/diffusers) diff --git a/docs_new/docs/sglang-diffusion/installation.mdx b/docs_new/docs/sglang-diffusion/installation.mdx new file mode 100644 index 000000000..da8d12cec --- /dev/null +++ b/docs_new/docs/sglang-diffusion/installation.mdx @@ -0,0 +1,110 @@ +--- +title: Install SGLang Diffusion +description: Install SGLang Diffusion on NVIDIA, AMD, MUSA, and Ascend platforms. +--- + +You can install SGLang Diffusion using one of the methods below. + +## Standard installation (NVIDIA GPUs) + +**Platform:** NVIDIA GPUs (CUDA) + + + + Use `uv` for faster installation: + + ```bash + pip install --upgrade pip + pip install uv + uv pip install "sglang[diffusion]" --prerelease=allow + ``` + + + + ```bash + git clone https://github.com/sgl-project/sglang.git + cd sglang + pip install --upgrade pip + pip install -e "python[diffusion]" + ``` + + Or with `uv`: + + ```bash + uv pip install -e "python[diffusion]" --prerelease=allow + ``` + + + + The Docker images are available on Docker Hub at [lmsysorg/sglang](https://hub.docker.com/r/lmsysorg/sglang/tags), built from the [Dockerfile](https://github.com/sgl-project/sglang/blob/main/docker/Dockerfile). Replace `` below with your HuggingFace Hub [token](https://huggingface.co/docs/hub/en/security-tokens). + + ```bash + docker run --gpus all \ + --shm-size 32g \ + -p 30000:30000 \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --env "HF_TOKEN=" \ + --ipc=host \ + lmsysorg/sglang:dev \ + zsh -c '\ + echo "Installing diffusion dependencies..." && \ + pip install -e "python[diffusion]" && \ + echo "Starting SGLang-Diffusion..." && \ + sglang generate \ + --model-path black-forest-labs/FLUX.1-dev \ + --prompt "A logo With Bold Large text: SGL Diffusion" \ + --save-output \ + ' + ``` + + + +## Platform-specific installs + +Use the tab that matches your accelerator. + + + + **Platform:** AMD Instinct GPUs (ROCm) + + For AMD Instinct GPUs (for example, MI300X), use the ROCm-enabled Docker image: + + ```bash + docker run --device=/dev/kfd --device=/dev/dri --ipc=host \ + -v ~/.cache/huggingface:/root/.cache/huggingface \ + --env HF_TOKEN= \ + lmsysorg/sglang:v0.5.9-rocm700-mi30x \ + sglang generate --model-path black-forest-labs/FLUX.1-dev --prompt "A logo With Bold Large text: SGL Diffusion" --save-output + ``` + + For detailed ROCm system configuration and installation from source, see [AMD GPUs](../hardware-platforms/amd-gpus). + + + + **Platform:** Moore Threads GPUs (MUSA) + + For Moore Threads GPUs (MTGPU) with the MUSA software stack: + + ```bash + git clone https://github.com/sgl-project/sglang.git + cd sglang + pip install --upgrade pip + rm -f python/pyproject.toml && mv python/pyproject_other.toml python/pyproject.toml + pip install -e "python[all_musa]" + ``` + + + + **Platform:** Ascend NPU + + For Ascend NPU, follow the [NPU installation guide](../hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support). + + Quick test: + + ```bash + sglang generate --model-path black-forest-labs/FLUX.1-dev \ + --prompt "A logo With Bold Large text: SGL Diffusion" \ + --save-output + ``` + + diff --git a/docs_new/docs/sglang-diffusion/performance-optimization.mdx b/docs_new/docs/sglang-diffusion/performance-optimization.mdx new file mode 100644 index 000000000..a578a3bea --- /dev/null +++ b/docs_new/docs/sglang-diffusion/performance-optimization.mdx @@ -0,0 +1,105 @@ +--- +title: "Performance Optimization" +description: "Optimize SGLang diffusion performance with caching, kernels, and profiling." +--- + +SGLang-Diffusion provides multiple performance optimization strategies to accelerate inference. This section covers all available performance tuning options. + +## Overview + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OptimizationTypeDescription
Cache-DiTCachingBlock-level caching with DBCache, TaylorSeer, and SCM
TeaCacheCachingTimestep-level caching using L1 similarity
Attention BackendsKernelOptimized attention implementations (FlashAttention, SageAttention, etc.)
ProfilingDiagnosticsPyTorch Profiler and Nsight Systems guidance
+ +## Caching Strategies + +SGLang supports two complementary caching approaches: + +### Cache-DiT + +[Cache-DiT](https://github.com/vipshop/cache-dit) provides block-level caching with advanced strategies. It can achieve up to **1.69x speedup**. + +**Quick Start:** +```bash +SGLANG_CACHE_DIT_ENABLED=true \ +sglang generate --model-path Qwen/Qwen-Image \ + --prompt "A beautiful sunset over the mountains" +``` + +**Key Features:** +- **DBCache**: Dynamic block-level caching based on residual differences +- **TaylorSeer**: Taylor expansion-based calibration for optimized caching +- **SCM**: Step-level computation masking for additional speedup + +See [Cache-DiT documentation](./cache-dit) for detailed configuration. + +### TeaCache + +TeaCache (Temporal similarity-based caching) accelerates diffusion inference by detecting when consecutive denoising steps are similar enough to skip computation entirely. + +**Quick Overview:** +- Tracks L1 distance between modulated inputs across timesteps +- When accumulated distance is below threshold, reuses cached residual +- Supports CFG with separate positive/negative caches + +**Supported Models:** Wan (wan2.1, wan2.2), Hunyuan (HunyuanVideo), Z-Image + +See [TeaCache documentation](./tea-cache) for detailed configuration. + +## Attention Backends + +Different attention backends offer varying performance characteristics depending on your hardware and model: + +- **FlashAttention**: Fastest on NVIDIA GPUs with fp16/bf16 +- **SageAttention**: Alternative optimized implementation +- **xformers**: Memory-efficient attention +- **SDPA**: PyTorch native scaled dot-product attention + +See [Attention backends](./attention-backends) for platform support and configuration options. + +## Profiling + +To diagnose performance bottlenecks, SGLang-Diffusion supports profiling tools: + +- **PyTorch Profiler**: Built-in Python profiling +- **Nsight Systems**: GPU kernel-level analysis + +See [Profiling guide](./profiling) for detailed instructions. + +## References + +- [Cache-DiT Repository](https://github.com/vipshop/cache-dit) +- [TeaCache Paper](https://arxiv.org/abs/2411.14324) diff --git a/docs_new/docs/sglang-diffusion/profiling.mdx b/docs_new/docs/sglang-diffusion/profiling.mdx new file mode 100644 index 000000000..767a6cfab --- /dev/null +++ b/docs_new/docs/sglang-diffusion/profiling.mdx @@ -0,0 +1,139 @@ +--- +title: "Profiling" +description: "Profile SGLang diffusion workloads with PyTorch Profiler and Nsight Systems." +--- + +This guide covers profiling techniques for multimodal generation pipelines in SGLang. + +## PyTorch Profiler + +PyTorch Profiler provides detailed kernel execution time, call stack, and GPU utilization metrics. + +### Denoising Stage Profiling + +Profile the denoising stage with sampled timesteps (default: 5 steps after 1 warmup step): + +```bash +sglang generate \ + --model-path Qwen/Qwen-Image \ + --prompt "A Logo With Bold Large Text: SGL Diffusion" \ + --seed 0 \ + --profile +``` + +**Parameters:** +- `--profile`: Enable profiling for the denoising stage +- `--num-profiled-timesteps N`: Number of timesteps to profile after warmup (default: 5) + - Smaller values reduce trace file size + - Example: `--num-profiled-timesteps 10` profiles 10 steps after 1 warmup step + +### Full Pipeline Profiling + +Profile all pipeline stages (text encoding, denoising, VAE decoding, etc.): + +```bash +sglang generate \ + --model-path Qwen/Qwen-Image \ + --prompt "A Logo With Bold Large Text: SGL Diffusion" \ + --seed 0 \ + --profile \ + --profile-all-stages +``` + +**Parameters:** +- `--profile-all-stages`: Used with `--profile`, profile all pipeline stages instead of just denoising + +### Output Location + +By default, trace files are saved in the ./logs/ directory. + +The exact output file path will be shown in the console output, for example: + +```bash +[mm-dd hh:mm:ss] Saved profiler traces to: /sgl-workspace/sglang/logs/mocked_fake_id_for_offline_generate-5_steps-global-rank0.trace.json.gz +``` + +### View Traces + +Load and visualize trace files at: +- https://ui.perfetto.dev/ (recommended) +- chrome://tracing (Chrome only) + +For large trace files, reduce `--num-profiled-timesteps` or avoid using `--profile-all-stages`. + + +### `--perf-dump-path` (Stage/Step Timing Dump) + +Besides profiler traces, you can also dump a lightweight JSON report that contains: +- stage-level timing breakdown for the full pipeline +- step-level timing breakdown for the denoising stage (per diffusion step) + +This is useful to quickly identify which stage dominates end-to-end latency, and whether denoising steps have uniform runtimes (and if not, which step has an abnormal spike). + +The dumped JSON contains a `denoise_steps_ms` field formatted as an array of objects, each with a `step` key (the step index) and a `duration_ms` key. + +Example: + +```bash +sglang generate \ + --model-path \ + --prompt "" \ + --perf-dump-path perf.json +``` + +## Nsight Systems + +Nsight Systems provides low-level CUDA profiling with kernel details, register usage, and memory access patterns. + +### Installation + +See the [SGLang profiling guide](../developer_guide/benchmark_and_profiling#profile-with-nsight) for installation instructions. + +### Basic Profiling + +Profile the entire pipeline execution: + +```bash +nsys profile \ + --trace-fork-before-exec=true \ + --cuda-graph-trace=node \ + --force-overwrite=true \ + -o QwenImage \ + sglang generate \ + --model-path Qwen/Qwen-Image \ + --prompt "A Logo With Bold Large Text: SGL Diffusion" \ + --seed 0 +``` + +### Targeted Stage Profiling + +Use `--delay` and `--duration` to capture specific stages and reduce file size: + +```bash +nsys profile \ + --trace-fork-before-exec=true \ + --cuda-graph-trace=node \ + --force-overwrite=true \ + --delay 10 \ + --duration 30 \ + -o QwenImage_denoising \ + sglang generate \ + --model-path Qwen/Qwen-Image \ + --prompt "A Logo With Bold Large Text: SGL Diffusion" \ + --seed 0 +``` + +**Parameters:** +- `--delay N`: Wait N seconds before starting capture (skip initialization overhead) +- `--duration N`: Capture for N seconds (focus on specific stages) +- `--force-overwrite`: Overwrite existing output files + +## Notes + +- **Reduce trace size**: Use `--num-profiled-timesteps` with smaller values or `--delay`/`--duration` with Nsight Systems +- **Stage-specific analysis**: Use `--profile` alone for denoising stage, add `--profile-all-stages` for full pipeline +- **Multiple runs**: Profile with different prompts and resolutions to identify bottlenecks across workloads + +## FAQ + +- If you are profiling `sglang generate` with Nsight Systems and find that the generated profiler file did not capture any CUDA kernels, you can resolve this issue by increasing the model's inference steps to extend the execution time. diff --git a/docs_new/docs/sglang-diffusion/supported-models.mdx b/docs_new/docs/sglang-diffusion/supported-models.mdx new file mode 100644 index 000000000..3af2f89ad --- /dev/null +++ b/docs_new/docs/sglang-diffusion/supported-models.mdx @@ -0,0 +1,350 @@ +--- +title: "Supported Models" +description: "Check model compatibility across diffusion optimizations and backends." +--- + +The table below shows every supported model and the optimizations supported for them. + +Key: + +- `Yes` = Compatible +- `No` = Incompatible +- `N/A` = Not applicable + +## Models x Optimization + +The `HuggingFace Model ID` can be passed directly to `from_pretrained()` methods, and sglang-diffusion will use the optimal default parameters when initializing and generating videos. + +### Video Generation Models + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model NameHuggingFace Model IDResolutionsTeaCacheSliding Tile AttnSage AttnVideo Sparse Attention (VSA)Sparse Linear Attention (SLA)Sage Sparse Linear Attention (SageSLA)Sparse Video Gen 2 (SVG2)
FastWan2.1 T2V 1.3B`FastVideo/FastWan2.1-T2V-1.3B-Diffusers`480pN/AN/AN/AYesNoNoNo
FastWan2.2 TI2V 5B Full Attn`FastVideo/FastWan2.2-TI2V-5B-FullAttn-Diffusers`720pN/AN/AN/AYesNoNoNo
Wan2.2 TI2V 5B`Wan-AI/Wan2.2-TI2V-5B-Diffusers`720pN/AN/AYesN/ANoNoNo
Wan2.2 T2V A14B`Wan-AI/Wan2.2-T2V-A14B-Diffusers`480p, 720pNoNoYesN/ANoNoNo
Wan2.2 I2V A14B`Wan-AI/Wan2.2-I2V-A14B-Diffusers`480p, 720pNoNoYesN/ANoNoNo
HunyuanVideo`hunyuanvideo-community/HunyuanVideo`720x1280, 544x960NoYesYesN/ANoNoYes
FastHunyuan`FastVideo/FastHunyuan-diffusers`720x1280, 544x960NoYesYesN/ANoNoYes
Wan2.1 T2V 1.3B`Wan-AI/Wan2.1-T2V-1.3B-Diffusers`480pYesYesYesN/ANoNoYes
Wan2.1 T2V 14B`Wan-AI/Wan2.1-T2V-14B-Diffusers`480p, 720pYesYesYesN/ANoNoYes
Wan2.1 I2V 480P`Wan-AI/Wan2.1-I2V-14B-480P-Diffusers`480pYesYesYesN/ANoNoYes
Wan2.1 I2V 720P`Wan-AI/Wan2.1-I2V-14B-720P-Diffusers`720pYesYesYesN/ANoNoYes
TurboWan2.1 T2V 1.3B`IPostYellow/TurboWan2.1-T2V-1.3B-Diffusers`480pYesNoNoNoYesYesN/A
TurboWan2.1 T2V 14B`IPostYellow/TurboWan2.1-T2V-14B-Diffusers`480pYesNoNoNoYesYesN/A
TurboWan2.1 T2V 14B 720P`IPostYellow/TurboWan2.1-T2V-14B-720P-Diffusers`720pYesNoNoNoYesYesN/A
TurboWan2.2 I2V A14B`IPostYellow/TurboWan2.2-I2V-A14B-Diffusers`720pYesNoNoNoYesYesN/A
+ + +1. Wan2.2 TI2V 5B has known quality issues for some I2V workloads. +2. SageSLA is based on SpargeAttn. Install SpargeAttn first with `pip install git+https://github.com/thu-ml/SpargeAttn.git --no-build-isolation`. + + +### Image Generation Models + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model NameHuggingFace Model IDResolutions
FLUX.1-dev`black-forest-labs/FLUX.1-dev`Any resolution
FLUX.2-dev`black-forest-labs/FLUX.2-dev`Any resolution
FLUX.2-Klein`black-forest-labs/FLUX.2-klein-4B`Any resolution
Z-Image-Turbo`Tongyi-MAI/Z-Image-Turbo`Any resolution
GLM-Image`zai-org/GLM-Image`Any resolution
Qwen Image`Qwen/Qwen-Image`Any resolution
Qwen Image 2512`Qwen/Qwen-Image-2512`Any resolution
Qwen Image Edit`Qwen/Qwen-Image-Edit`Any resolution
+ +## Verified LoRA Examples + +This section lists example LoRAs that have been explicitly tested and verified with each base model in the **SGLang Diffusion** pipeline. + + +LoRAs that are not listed here are not necessarily incompatible. +In practice, most standard LoRAs are expected to work, especially those following common Diffusers or SD-style conventions. +The entries below simply reflect configurations that have been manually validated by the SGLang team. + + +### Verified LoRAs by Base Model + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Base ModelSupported LoRAs
Wan2.2`lightx2v/Wan2.2-Distill-Loras`
`Cseti/wan2.2-14B-Arcane_Jinx-lora-v1`
Wan2.1`lightx2v/Wan2.1-Distill-Loras`
Z-Image-Turbo`tarn59/pixel_art_style_lora_z_image_turbo`
`wcde/Z-Image-Turbo-DeJPEG-Lora`
Qwen-Image`lightx2v/Qwen-Image-Lightning`
`flymy-ai/qwen-image-realism-lora`
`prithivMLmods/Qwen-Image-HeadshotX`
`starsfriday/Qwen-Image-EVA-LoRA`
Qwen-Image-Edit`ostris/qwen_image_edit_inpainting`
`lightx2v/Qwen-Image-Edit-2511-Lightning`
Flux`dvyio/flux-lora-simple-illustration`
`XLabs-AI/flux-furry-lora`
`XLabs-AI/flux-RealismLora`
+ +## Special requirements + +### Sliding Tile Attention + +- Currently, only Hopper GPUs (H100s) are supported. diff --git a/docs_new/docs/sglang-diffusion/tea-cache.mdx b/docs_new/docs/sglang-diffusion/tea-cache.mdx new file mode 100644 index 000000000..78b4d3714 --- /dev/null +++ b/docs_new/docs/sglang-diffusion/tea-cache.mdx @@ -0,0 +1,143 @@ +--- +title: "TeaCache Acceleration" +description: "Configure TeaCache for temporal similarity-based diffusion acceleration." +--- + +> **Note**: This is one of two caching strategies available in SGLang. +> For an overview of all caching options, see [SGLang diffusion overview](../../sglang-diffusion/intro). + +TeaCache (Temporal similarity-based caching) accelerates diffusion inference by detecting when consecutive denoising steps are similar enough to skip computation entirely. + +## Overview + +TeaCache works by: +1. Tracking the L1 distance between modulated inputs across consecutive timesteps +2. Accumulating the rescaled L1 distance over steps +3. When accumulated distance is below a threshold, reusing the cached residual +4. Supporting CFG (Classifier-Free Guidance) with separate positive/negative caches + +## How It Works + +### L1 Distance Tracking + +At each denoising step, TeaCache computes the relative L1 distance between the current and previous modulated inputs: + +```text +rel_l1 = |current - previous|.mean() / |previous|.mean() +``` + +This distance is then rescaled using polynomial coefficients and accumulated: + +```text +accumulated += poly(coefficients)(rel_l1) +``` + +### Cache Decision + +- If `accumulated >= threshold`: Force computation, reset accumulator +- If `accumulated < threshold`: Skip computation, use cached residual + +### CFG Support + +For models that support CFG cache separation (Wan, Hunyuan, Z-Image), TeaCache maintains separate caches for positive and negative branches: +- `previous_modulated_input` / `previous_residual` for positive branch +- `previous_modulated_input_negative` / `previous_residual_negative` for negative branch + +For models that don't support CFG separation (Flux, Qwen), TeaCache is automatically disabled when CFG is enabled. + +## Configuration + +TeaCache is configured via `TeaCacheParams` in the sampling parameters: + +```python +from sglang.multimodal_gen.configs.sample.teacache import TeaCacheParams + +params = TeaCacheParams( + teacache_thresh=0.1, # Threshold for accumulated L1 distance + coefficients=[1.0, 0.0, 0.0], # Polynomial coefficients for L1 rescaling +) +``` + +### Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterTypeDescription
`teacache_thresh`floatThreshold for accumulated L1 distance. Lower = more caching, faster but potentially lower quality
`coefficients`list[float]Polynomial coefficients for L1 rescaling. Model-specific tuning
+ +### Model-Specific Configurations + +Different models may have different optimal configurations. The coefficients are typically tuned per-model to balance speed and quality. + +## Supported Models + +TeaCache is built into the following model families: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model FamilyCFG Cache SeparationNotes
Wan (wan2.1, wan2.2)YesFull support
Hunyuan (HunyuanVideo)YesTo be supported
Z-ImageYesTo be supported
FluxNoTo be supported
QwenNoTo be supported
+ + +## References + +- [TeaCache: Accelerating Diffusion Models with Temporal Similarity](https://arxiv.org/abs/2411.14324) diff --git a/docs_new/docs/supported-models.mdx b/docs_new/docs/supported-models.mdx new file mode 100644 index 000000000..d4f2ea757 --- /dev/null +++ b/docs_new/docs/supported-models.mdx @@ -0,0 +1,87 @@ +--- +title: Supported models +description: See which families of SGLang-compatible models are actively maintained. +mode: wide +--- + +SGLang supports model families across text generation, retrieval, and reward workflows. Browse the sections below for the primary product paths and jump to the detail pages when you are ready to explore a specific class. + +### Text generation + + + + Production-tuned Llama and Qwen families validated for high-throughput + serving. + + + Vision-text hybrids that stay responsive on multi-GPU setups. + + + Score-based and diffusion backbones for structured text generation + workflows. + + + +### Retrieval and ranking + + + + Dense and sparse embeddings optimized with FlashInfer kernels. + + + Low-latency rerankers for multi-stage retrieval pipelines. + + + Lightweight classifiers covering safety, intent, and context filters. + + + +### Specialized models + + + + RLHF and reward scoring pipelines optimized for production latency. + + diff --git a/docs_new/docs/supported-models/classification-models.mdx b/docs_new/docs/supported-models/classification-models.mdx new file mode 100644 index 000000000..510effe2f --- /dev/null +++ b/docs_new/docs/supported-models/classification-models.mdx @@ -0,0 +1,323 @@ +--- +title: Classification Models +--- + +This document describes the `/v1/classify` API endpoint in SGLang, which is compatible with vLLM's classification API format. + +## Overview + +The classification API allows you to classify text inputs using classification models. This implementation follows the same format as vLLM's 0.7.0 classification API. + +## API endpoint + +```text Output +POST /v1/classify +``` + +## Request format + +```json Config +{ + "model": "model_name", + "input": "text to classify" +} +``` + +### Parameters + + + The name of the classification model to use. + + + + The text to classify. + + + + User identifier for tracking. + + + + Request ID for tracking. + + + + Request priority. + + +## Response format + +```json Config +{ + "id": "classify-9bf17f2847b046c7b2d5495f4b4f9682", + "object": "list", + "created": 1745383213, + "model": "jason9693/Qwen2.5-1.5B-apeach", + "data": [ + { + "index": 0, + "label": "Default", + "probs": [0.565970778465271, 0.4340292513370514], + "num_classes": 2 + } + ], + "usage": { + "prompt_tokens": 10, + "total_tokens": 10, + "completion_tokens": 0, + "prompt_tokens_details": null + } +} +``` + +### Response fields + + + Unique identifier for the classification request. + + + + Always `"list"`. + + + + Unix timestamp when the request was created. + + + + The model used for classification. + + + + Array of classification results. + + + + Index of the result. + + + + Predicted class label. + + + + Array of probabilities for each class. + + + + Total number of classes. + + + + + + + Token usage information. + + + + Number of input tokens. + + + + Total number of tokens. + + + + Number of completion tokens (always `0` for classification). + + + + Additional token details (optional). + + + + + +## Example usage + + + + ```bash Command + curl -v "http://127.0.0.1:8000/v1/classify" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "jason9693/Qwen2.5-1.5B-apeach", + "input": "Loved the new café—coffee was great." + }' + ``` + + + ```python Example + import requests + import json + + # Make classification request + response = requests.post( + "http://127.0.0.1:8000/v1/classify", + headers={"Content-Type": "application/json"}, + json={ + "model": "jason9693/Qwen2.5-1.5B-apeach", + "input": "Loved the new café—coffee was great." + } + ) + + # Parse response + result = response.json() + print(json.dumps(result, indent=2)) + ``` + + + + +## Supported models + +The classification API works with any classification model supported by SGLang, including: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelType
`LlamaForSequenceClassification`Multi-class classification
`Qwen2ForSequenceClassification`Multi-class classification
`Qwen3ForSequenceClassification`Multi-class classification
`BertForSequenceClassification`Multi-class classification
`Gemma2ForSequenceClassification`Multi-class classification
+ + + The API automatically uses the `id2label` mapping from the model's `config.json` file to provide meaningful label names instead of generic class names. If `id2label` is not available, it falls back to `LABEL_0`, `LABEL_1`, etc., or `Class_0`, `Class_1` as a last resort. + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelType
`InternLM2ForRewardModel`Single reward score
`Qwen2ForRewardModel`Single reward score
`LlamaForSequenceClassificationWithNormal_Weights`Special reward model
+ + + The `/classify` endpoint in SGLang was originally designed for reward models but now supports all non-generative models. The `/v1/classify` endpoint provides a standardized vLLM-compatible interface for classification tasks. + + +
+
+ +## Error handling + +The API returns appropriate HTTP status codes and error messages: + + + + + + + + + + + + + + + + + + + + + + +
Status codeMeaning
`400 Bad Request`Invalid request format or missing required fields
`500 Internal Server Error`Server-side processing error
+ +Error response format: + +```json Config +{ + "error": "Error message", + "type": "error_type", + "code": 400 +} +``` + +## Implementation details + + + Handles routing and request/response models in + `sgl-model-gateway/src/protocols/spec.rs`. + + + + Implements the actual endpoint in + `python/sglang/srt/entrypoints/http_server.py`. + + + + Handles the classification logic in + `python/sglang/srt/entrypoints/openai/serving_classify.py`. + + +## Testing + +Use the provided test script to verify the implementation: + + +```bash Command +python test_classify_api.py +``` + + +## Compatibility + + + This implementation is compatible with vLLM's classification API format, + allowing seamless migration from vLLM to SGLang for classification tasks. + diff --git a/docs_new/docs/supported-models/diffusion-language-models.mdx b/docs_new/docs/supported-models/diffusion-language-models.mdx new file mode 100644 index 000000000..e3adf769b --- /dev/null +++ b/docs_new/docs/supported-models/diffusion-language-models.mdx @@ -0,0 +1,13 @@ +--- +title: Diffusion language models +--- + +For detailed documentation on diffusion models in SGLang, see the [SGLang Diffusion](/docs/sglang-diffusion/index) section under Docs. + + + Learn about score-based diffusion backbones, supported models, and usage patterns. + diff --git a/docs_new/docs/supported-models/embedding-models.mdx b/docs_new/docs/supported-models/embedding-models.mdx new file mode 100644 index 000000000..1383440f1 --- /dev/null +++ b/docs_new/docs/supported-models/embedding-models.mdx @@ -0,0 +1,173 @@ +--- +title: Embedding models +description: Dense and sparse embedding models with FlashInfer acceleration and SGLang's batching infrastructure. +--- + +SGLang provides robust support for embedding models by integrating efficient serving mechanisms with its flexible programming interface. This integration allows for streamlined handling of embedding tasks, facilitating faster and more accurate retrieval and semantic search operations. SGLang's architecture enables better resource utilization and reduced latency in embedding model deployment. + + + Embedding models must be launched with the `--is-embedding` flag. Some models + may also require `--trust-remote-code`. + + +## Quick start + +1. **Launch the server** + +```bash +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-Embedding-4B \ + --is-embedding \ + --host 0.0.0.0 \ + --port 30000 +``` + +2. **Send a client request** + +```python +import requests + +url = "http://127.0.0.1:30000" + +payload = { + "model": "Qwen/Qwen3-Embedding-4B", + "input": "What is the capital of France?", + "encoding_format": "float" +} + +response = requests.post(url + "/v1/embeddings", json=payload).json() +print("Embedding:", response["data"][0]["embedding"]) +``` + +## Multimodal embedding example + +For multimodal models like GME that support both text and images: + +1. **Launch the server with a multimodal model** + +```bash +python3 -m sglang.launch_server \ + --model-path Alibaba-NLP/gme-Qwen2-VL-2B-Instruct \ + --is-embedding \ + --chat-template gme-qwen2-vl \ + --host 0.0.0.0 \ + --port 30000 +``` + +2. **Send a multimodal request** + +```python +import requests + +url = "http://127.0.0.1:30000" + +text_input = "Represent this image in embedding space." +image_path = "https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild/resolve/main/images/023.jpg" + +payload = { + "model": "gme-qwen2-vl", + "input": [ + {"text": text_input}, + {"image": image_path} + ], +} + +response = requests.post(url + "/v1/embeddings", json=payload).json() +print("Embeddings:", [x.get("embedding") for x in response.get("data", [])]) +``` + +## Matryoshka embedding example + +[Matryoshka Embeddings](https://sbert.net/examples/sentence_transformer/training/matryoshka/README.html#matryoshka-embeddings) or [Matryoshka Representation Learning (MRL)](https://arxiv.org/abs/2205.13147) is a technique used in training embedding models. It allows users to trade off between performance and cost. + +1. **Launch a Matryoshka-capable model** + +If the model config already includes `matryoshka_dimensions` or `is_matryoshka` then no override is needed. Otherwise, use `--json-model-override-args` as below: + +```bash +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-Embedding-0.6B \ + --is-embedding \ + --host 0.0.0.0 \ + --port 30000 \ + --json-model-override-args '{"matryoshka_dimensions": [128, 256, 512, 1024, 1536]}' +``` + + + Setting `"is_matryoshka": true` allows truncating to any dimension. Otherwise, the server validates that the specified dimension in the request is one of `matryoshka_dimensions`. Omitting `dimensions` in a request returns the full vector. + + +2. **Make requests with different output dimensions** + +```python +import requests + +url = "http://127.0.0.1:30000" + +# Request a truncated (Matryoshka) embedding by specifying a supported dimension. +payload = { + "model": "Qwen/Qwen3-Embedding-0.6B", + "input": "Explain diffusion models simply.", + "dimensions": 512 # change to 128 / 1024 / omit for full size +} + +response = requests.post(url + "/v1/embeddings", json=payload).json() +print("Embedding:", response["data"][0]["embedding"]) +``` + +## Supported models + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelExample HF modelChat templateNotes
E5 (Llama/Mistral based)`intfloat/e5-mistral-7b-instruct`N/AHigh-quality text embeddings based on Mistral/Llama architectures
GTE-Qwen2`Alibaba-NLP/gte-Qwen2-7B-instruct`N/AAlibaba's text embedding model with multilingual support
Qwen3-Embedding`Qwen/Qwen3-Embedding-4B`N/ALatest Qwen3-based text embedding model for semantic representation
BGE`BAAI/bge-large-en-v1.5`N/ABAAI's text embeddings (requires `--attention-backend triton` or `torch_native`)
GME (Multimodal)`Alibaba-NLP/gme-Qwen2-VL-2B-Instruct``gme-qwen2-vl`Multimodal embedding for text and image cross-modal tasks
CLIP`openai/clip-vit-large-patch14-336`N/AOpenAI's CLIP for image and text embeddings
diff --git a/docs_new/docs/supported-models/large-language-models.mdx b/docs_new/docs/supported-models/large-language-models.mdx new file mode 100644 index 000000000..8af620259 --- /dev/null +++ b/docs_new/docs/supported-models/large-language-models.mdx @@ -0,0 +1,265 @@ +--- +title: Large Language Models +--- + +These models accept text input and produce text output (e.g., chat completions). They are primarily large language models (LLMs), some with mixture-of-experts (MoE) architectures for scaling. + +## Example launch Command + + +```shell Command +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.2-1B-Instruct \ # example HF/local path + --host 0.0.0.0 \ + --port 30000 \ +``` + + +## Supported models + +Below the supported models are summarized in a table. + +If you are unsure if a specific architecture is implemented, you can search for it via GitHub. For example, to search for `Qwen3ForCausalLM`, use the expression: + +```text Output +repo:sgl-project/sglang path:/^python\/sglang\/srt\/models\// Qwen3ForCausalLM +``` + +in the GitHub search bar. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model Family (Variants)Example HuggingFace IdentifierDescription
**DeepSeek** (v1, v2, v3/R1)`deepseek-ai/DeepSeek-R1`Series of advanced reasoning-optimized models (including a 671B MoE) trained with reinforcement learning; top performance on complex reasoning, math, and code tasks. [SGLang provides Deepseek v3/R1 model-specific optimizations](../basic_usage/deepseek_v3) and [Reasoning Parser](../advanced_features/separate_reasoning.ipynb)
**Kimi K2** (Thinking, Instruct)`moonshotai/Kimi-K2-Instruct`Moonshot AI's 1 trillion parameter MoE model (32B active) with 128K–256K context; state-of-the-art agentic intelligence with stable long-horizon agency across 200–300 sequential tool calls. Features MLA attention and native INT4 quantization. [See Reasoning Parser docs](../advanced_features/separate_reasoning.ipynb)
**Kimi Linear** (48B-A3B)`moonshotai/Kimi-Linear-48B-A3B-Instruct`Moonshot AI's hybrid linear attention model (48B total, 3B active) with 1M token context; features Kimi Delta Attention (KDA) for up to 6× faster decoding and 75% KV cache reduction vs full attention.
**GPT-OSS**`openai/gpt-oss-20b`, `openai/gpt-oss-120b`OpenAI’s latest GPT-OSS series for complex reasoning, agentic tasks, and versatile developer use cases.
**Qwen** (3, 3MoE, 3Next, 2.5, 2 series)`Qwen/Qwen3-0.6B`, `Qwen/Qwen3-30B-A3B` `Qwen/Qwen3-Next-80B-A3B-Instruct `Alibaba’s latest Qwen3 series for complex reasoning, language understanding, and generation tasks; Support for MoE variants along with previous generation 2.5, 2, etc. [SGLang provides Qwen3 specific reasoning parser](../advanced_features/separate_reasoning.ipynb)
**Llama** (2, 3.x, 4 series)`meta-llama/Llama-4-Scout-17B-16E-Instruct`Meta's open LLM series, spanning 7B to 400B parameters (Llama 2, 3, and new Llama 4) with well-recognized performance. [SGLang provides Llama-4 model-specific optimizations](../basic_usage/llama4.md)
**Mistral** (Mixtral, NeMo, Small3)`mistralai/Mistral-7B-Instruct-v0.2`Open 7B LLM by Mistral AI with strong performance; extended into MoE (“Mixtral”) and NeMo Megatron variants for larger scale.
**Gemma** (v1, v2, v3)`google/gemma-3-1b-it`Google’s family of efficient multilingual models (1B–27B); Gemma 3 offers a 128K context window, and its larger (4B+) variants support vision input.
**Phi** (Phi-1.5, Phi-2, Phi-3, Phi-4, Phi-MoE series)`microsoft/Phi-4-multimodal-instruct`, `microsoft/Phi-3.5-MoE-instruct`Microsoft’s Phi family of small models (1.3B–5.6B); Phi-4-multimodal (5.6B) processes text, images, and speech, Phi-4-mini is a high-accuracy text model and Phi-3.5-MoE is a mixture-of-experts model.
**MiniCPM** (v3, 4B)`openbmb/MiniCPM3-4B`OpenBMB’s series of compact LLMs for edge devices; MiniCPM 3 (4B) achieves GPT-3.5-level results in text tasks.
**OLMo** (2, 3)`allenai/OLMo-3-1125-32B`, `allenai/OLMo-3-32B-Think`, `allenai/OLMo-2-1124-7B-Instruct`Allen AI’s series of Open Language Models designed to enable the science of language models.
**OLMoE** (Open MoE)`allenai/OLMoE-1B-7B-0924`Allen AI’s open Mixture-of-Experts model (7B total, 1B active parameters) delivering state-of-the-art results with sparse expert activation.
**MiniMax-M2** (M2, M2.1)`minimax/MiniMax-M2`, `minimax/MiniMax-M2.1`MiniMax’s SOTA LLM for coding & agentic workflows.
**StableLM** (3B, 7B)`stabilityai/stablelm-tuned-alpha-7b`StabilityAI’s early open-source LLM (3B & 7B) for general text generation; a demonstration model with basic instruction-following ability.
**Command-(R,A)** (Cohere)`CohereLabs/c4ai-command-r-v01`, `CohereLabs/c4ai-command-r7b-12-2024`, `CohereLabs/c4ai-command-a-03-2025`Cohere’s open conversational LLM (Command series) optimized for long context, retrieval-augmented generation, and tool use.
**DBRX** (Databricks)`databricks/dbrx-instruct`Databricks’ 132B-parameter MoE model (36B active) trained on 12T tokens; competes with GPT-3.5 quality as a fully open foundation model.
**Grok** (xAI)`xai-org/grok-1`xAI’s grok-1 model known for vast size(314B parameters) and high quality; integrated in SGLang for high-performance inference.
**ChatGLM** (GLM-130B family)`THUDM/chatglm2-6b`Zhipu AI’s bilingual chat model (6B) excelling at Chinese-English dialogue; fine-tuned for conversational quality and alignment.
**InternLM 2** (7B, 20B)`internlm/internlm2-7b`Next-gen InternLM (7B and 20B) from SenseTime, offering strong reasoning and ultra-long context support (up to 200K tokens).
**ExaONE 3** (Korean-English)`LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct`LG AI Research’s Korean-English model (7.8B) trained on 8T tokens; provides high-quality bilingual understanding and generation.
**Baichuan 2** (7B, 13B)`baichuan-inc/Baichuan2-13B-Chat`BaichuanAI’s second-generation Chinese-English LLM (7B/13B) with improved performance and an open commercial license.
**XVERSE** (MoE)`xverse/XVERSE-MoE-A36B`Yuanxiang’s open MoE LLM (XVERSE-MoE-A36B: 255B total, 36B active) supporting ~40 languages; delivers 100B+ dense-level performance via expert routing.
**SmolLM** (135M–1.7B)`HuggingFaceTB/SmolLM-1.7B`Hugging Face’s ultra-small LLM series (135M–1.7B params) offering surprisingly strong results, enabling advanced AI on mobile/edge devices.
**GLM-4** (Multilingual 9B)`ZhipuAI/glm-4-9b-chat`Zhipu’s GLM-4 series (up to 9B parameters) – open multilingual models with support for 1M-token context and even a 5.6B multimodal variant (Phi-4V).
**MiMo** (7B series)`XiaomiMiMo/MiMo-7B-RL`Xiaomi's reasoning-optimized model series, leverages Multiple-Token Prediction for faster inference.
**ERNIE-4.5** (4.5, 4.5MoE series)`baidu/ERNIE-4.5-21B-A3B-PT`Baidu's ERNIE-4.5 series which consists of MoE with 47B and 3B active parameters, with the largest model having 424B total parameters, as well as a 0.3B dense model.
**Arcee AFM-4.5B**`arcee-ai/AFM-4.5B-Base`Arcee's foundational model series for real world reliability and edge deployments.
**Persimmon** (8B)`adept/persimmon-8b-chat`Adept’s open 8B model with a 16K context window and fast inference; trained for broad usability and licensed under Apache 2.0.
**Solar** (10.7B)`upstage/SOLAR-10.7B-Instruct-v1.0`Upstage's 10.7B parameter model, optimized for instruction-following tasks. This architecture incorporates a depth-up scaling methodology, enhancing model performance.
**Tele FLM** (52B-1T)`CofeAI/Tele-FLM`BAAI & TeleAI's multilingual model, available in 52-billion and 1-trillion parameter variants. It is a decoder-only transformer trained on ~2T tokens
**Ling** (16.8B–290B)`inclusionAI/Ling-lite`, `inclusionAI/Ling-plus`InclusionAI’s open MoE models. Ling-Lite has 16.8B total / 2.75B active parameters, and Ling-Plus has 290B total / 28.8B active parameters. They are designed for high performance on NLP and complex reasoning tasks.
**Granite 3.0, 3.1** (IBM)`ibm-granite/granite-3.1-8b-instruct`IBM's open dense foundation models optimized for reasoning, code, and business AI use cases. Integrated with Red Hat and watsonx systems.
**Granite 3.0 MoE** (IBM)`ibm-granite/granite-3.0-3b-a800m-instruct`IBM’s Mixture-of-Experts models offering strong performance with cost-efficiency. MoE expert routing designed for enterprise deployment at scale.
**GPT-J** (6B)`EleutherAI/gpt-j-6b`EleutherAI's GPT-2-like causal language model (6B) trained on the [Pile](https://pile.eleuther.ai/) dataset.
**Orion** (14B)`OrionStarAI/Orion-14B-Base`A series of open-source multilingual large language models by OrionStarAI, pretrained on a 2.5T token multilingual corpus including Chinese, English, Japanese, Korean, etc, and it exhibits superior performance in these languages.
**Llama Nemotron Super** (v1, v1.5, NVIDIA)`nvidia/Llama-3_3-Nemotron-Super-49B-v1`, `nvidia/Llama-3_3-Nemotron-Super-49B-v1_5`The [NVIDIA Nemotron](https://www.nvidia.com/en-us/ai-data-science/foundation-models/nemotron/) family of multimodal models provides state-of-the-art reasoning models specifically designed for enterprise-ready AI agents.
**Llama Nemotron Ultra** (v1, NVIDIA)`nvidia/Llama-3_1-Nemotron-Ultra-253B-v1`The [NVIDIA Nemotron](https://www.nvidia.com/en-us/ai-data-science/foundation-models/nemotron/) family of multimodal models provides state-of-the-art reasoning models specifically designed for enterprise-ready AI agents.
**NVIDIA Nemotron Nano 2.0**`nvidia/NVIDIA-Nemotron-Nano-9B-v2`The [NVIDIA Nemotron](https://www.nvidia.com/en-us/ai-data-science/foundation-models/nemotron/) family of multimodal models provides state-of-the-art reasoning models specifically designed for enterprise-ready AI agents. `Nemotron-Nano-9B-v2` is a hybrid Mamba-Transformer language model designed to increase throughput for reasoning workloads while achieving state-of-the-art accuracy compared to similarly-sized models.
**StarCoder2** (3B-15B)`bigcode/starcoder2-7b`StarCoder2 is a family of open large language models (LLMs) specialized for code generation and understanding. It is the successor to StarCoder, jointly developed by the BigCode project (a collaboration between Hugging Face, ServiceNow Research, and other contributors).
**Jet-Nemotron**`jet-ai/Jet-Nemotron-2B`Jet-Nemotron is a new family of hybrid-architecture language models that surpass state-of-the-art open-source full-attention language models, while achieving significant efficiency gains.
**Trinity** (Nano, Mini)`arcee-ai/Trinity-Mini`Arcee's foundational MoE Trinity family of models, open weights under Apache 2.0.
**Falcon-H1** (0.5B–34B)`tiiuae/Falcon-H1-34B-Instruct`TII's hybrid Mamba-Transformer architecture combining attention and state-space models for efficient long-context inference.
**Hunyuan-Large** (389B, MoE)`tencent/Tencent-Hunyuan-Large`Tencent's open-source MoE model with 389B total / 52B active parameters, featuring Cross-Layer Attention (CLA) for improved efficiency.
**IBM Granite 4.0 (Hybrid, Dense)**`ibm-granite/granite-4.0-h-micro`, `ibm-granite/granite-4.0-micro`IBM Granite 4.0 micro models: hybrid Mamba–MoE (`h-micro`) and dense (`micro`) variants. Enterprise-focused reasoning models
diff --git a/docs_new/docs/supported-models/mindspore-models.mdx b/docs_new/docs/supported-models/mindspore-models.mdx new file mode 100644 index 000000000..f94987038 --- /dev/null +++ b/docs_new/docs/supported-models/mindspore-models.mdx @@ -0,0 +1,167 @@ +--- +title: "MindSpore Models" +--- + +MindSpore is a high-performance AI framework optimized for [Ascend NPUs](../hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support). This doc guides users to run MindSpore models in SGLang. + +## Requirements + +MindSpore currently only supports Ascend NPU devices. Users need to first install Ascend CANN software packages. The CANN software packages can be downloaded from the [Ascend Official Website](https://www.hiascend.com). The recommended version is 8.3.RC2. + +## Supported Models + +Currently, the following models are supported: + + + + Dense and MoE models + + + DeepSeek V3 and R1 models + + + Additional models are on the way + + + +## Installation + +Currently, MindSpore models are provided by an independent package `sgl-mindspore`. Support for MindSpore is built upon current SGLang support for Ascend NPU platform. Please first [install SGLang for Ascend NPU](../hardware-platforms/ascend-npus/SGLang-installation-with-NPUs-support) and then install `sgl-mindspore`. + + +```bash Install +git clone https://github.com/mindspore-lab/sgl-mindspore.git +cd sgl-mindspore +pip install -e . +``` + + +## Run Model + +Current SGLang-MindSpore supports Qwen3 and DeepSeek V3/R1 models. This doc uses Qwen3-8B as an example. + +### Offline Infer + +Use the following script for offline infer: + + +```python Offline Infer +import sglang as sgl + +# Initialize the engine with MindSpore backend +llm = sgl.Engine( + model_path="/path/to/your/model", # Local model path + device="npu", # Use NPU device + model_impl="mindspore", # MindSpore implementation + attention_backend="ascend", # Attention backend + tp_size=1, # Tensor parallelism size + dp_size=1 # Data parallelism size +) + +# Generate text +prompts = [ + "Hello, my name is", + "The capital of France is", + "The future of AI is" +] + +sampling_params = {"temperature": 0, "top_p": 0.9} +outputs = llm.generate(prompts, sampling_params) + +for prompt, output in zip(prompts, outputs): + print(f"Prompt: {prompt}") + print(f"Generated: {output['text']}") + print("---") +``` + + +### Start Server + + +```bash Single Node +python3 -m sglang.launch_server \ + --model-path /path/to/your/model \ + --host 0.0.0.0 \ + --device npu \ + --model-impl mindspore \ + --attention-backend ascend \ + --tp-size 1 \ + --dp-size 1 +``` +```bash Multi-Node Distributed +python3 -m sglang.launch_server \ + --model-path /path/to/your/model \ + --host 0.0.0.0 \ + --device npu \ + --model-impl mindspore \ + --attention-backend ascend \ + --dist-init-addr 127.0.0.1:29500 \ + --nnodes 2 \ + --node-rank 0 \ + --tp-size 4 \ + --dp-size 2 +``` + + +## Troubleshooting + +### Debug Mode + +Enable sglang debug logging by log-level argument: + + +```bash Debug Mode +python3 -m sglang.launch_server \ + --model-path /path/to/your/model \ + --host 0.0.0.0 \ + --device npu \ + --model-impl mindspore \ + --attention-backend ascend \ + --log-level DEBUG +``` + + +Enable MindSpore info and debug logging by setting environments: + + +```bash INFO +export GLOG_v=1 +``` +```bash DEBUG +export GLOG_v=0 +``` + + +### Explicitly Select Devices + +Use the following environment variable to explicitly select the devices to use: + + +```bash Select Devices +export ASCEND_RT_VISIBLE_DEVICES=4,5,6,7 +``` + + +### Some Communication Environment Issues + +In case of some environment with special communication environment, users need to set some environment variables: + + +```bash Disable LCCL +export MS_ENABLE_LCCL=off # current not support LCCL communication mode in SGLang-MindSpore +``` + + +### Some Dependencies of Protobuf + +In case of some environment with special protobuf version, users need to set some environment variables to avoid binary version mismatch: + + +```bash Fix Protobuf +export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python +``` + + +## Support + +For MindSpore-specific issues, refer to the [MindSpore documentation](https://www.mindspore.cn/). diff --git a/docs_new/docs/supported-models/modelscope.mdx b/docs_new/docs/supported-models/modelscope.mdx new file mode 100644 index 000000000..b9e20936a --- /dev/null +++ b/docs_new/docs/supported-models/modelscope.mdx @@ -0,0 +1,32 @@ +--- +title: "Use Models From ModelScope" +--- + +To use a model from [ModelScope](https://www.modelscope.cn), set the environment variable `SGLANG_USE_MODELSCOPE`. + + +```bash Set Environment Variable +export SGLANG_USE_MODELSCOPE=true +``` + + +We take [Qwen2-7B-Instruct](https://www.modelscope.cn/models/qwen/qwen2-7b-instruct) as an example. + +## Launch the Server + + +```bash Python +python -m sglang.launch_server --model-path qwen/Qwen2-7B-Instruct --port 30000 +``` +```bash Docker +docker run --gpus all \ + -p 30000:30000 \ + -v ~/.cache/modelscope:/root/.cache/modelscope \ + --env "SGLANG_USE_MODELSCOPE=true" \ + --ipc=host \ + lmsysorg/sglang:latest \ + python3 -m sglang.launch_server --model-path Qwen/Qwen2.5-7B-Instruct --host 0.0.0.0 --port 30000 +``` + + +ModelScope uses a different cache directory than Hugging Face. You may need to set it manually to avoid running out of disk space. diff --git a/docs_new/docs/supported-models/new-model-support.mdx b/docs_new/docs/supported-models/new-model-support.mdx new file mode 100644 index 000000000..cbaaedfca --- /dev/null +++ b/docs_new/docs/supported-models/new-model-support.mdx @@ -0,0 +1,307 @@ +--- +title: "How to Support New Models" +description: "This document explains how to add support for new language models and multimodal large language models (MLLMs) in SGLang. It also covers how to test new models and register external implementations." +--- + +## How to Support a New Language Model + +To support a new model in SGLang, you only need to add a single file under the [SGLang Models Directory](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/models). You can learn from existing model implementations and create a new file for your model. For most models, you should be able to find a similar model to start with (e.g., starting from Llama). Also refer how to [port a Model from vLLM to SGLang](#port-a-model-from-vllm-to-sglang). + +## How to Support a New Multimodal Large Language Model + +To support a new multimodal large language model (MLLM) in SGLang, there are several key components in addition to the standard LLM support: + +1. **Register your new model as multimodal:** +Extend `is_multimodal_model` in [model\_config.py](https://github.com/sgl-project/sglang/blob/0ab3f437aba729b348a683ab32b35b214456efc7/python/sglang/srt/configs/model_config.py#L561) to return `True` for your model. + +2. **Register a new chat-template:** +Only when your default chat-template is unable to accept images as input, register a new chat template in [conversation.py](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/conversation.py) and the corresponding matching function. + +3. **Add a multimodal data processor:** +Define a new `Processor` class that inherits from `BaseMultimodalProcessor` and register this processor as your model's dedicated processor. See [multimodal\_processor.py](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/multimodal/processors) for more details. + +4. **Handle multimodal tokens:** +Implement a `pad_input_ids` function for your new model. In this function, multimodal tokens in the prompt should be expanded (if necessary) and padded with multimodal-data-hashes so that SGLang can recognize different multimodal data with `RadixAttention`. + +5. **Handle image feature extraction:** +Implement a `get_image_feature` function for your new model, which extracts image features from raw image data and converts them into the embeddings used by the language model. + +6. **Adapt to vision attention:** +Adapt the multi-headed `Attention` of ViT with SGLang's `VisionAttention`. + +You can refer to [Qwen2VL](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/models/qwen2_vl.py) or other mllm implementations. These models demonstrate how to correctly handle both multimodal and textual inputs. + +## Testing and Debugging + +Please note all your testing and benchmarking results in PR description. + +### Interactive Debugging + +For interactive debugging, compare the outputs of Hugging Face/Transformers and SGLang. The following two commands should give the same text output and very similar prefill logits: + + +```bash Get reference output +python3 scripts/playground/reference_hf.py --model-path [new model] --model-type {text,mllm} +``` +```bash Get SGLang output +python3 -m sglang.bench_one_batch --correct --model [new model] +``` + + +### Add the Model to the Test Suite + +To ensure the new model is well maintained, add it to the test suite by including it in the `ALL_OTHER_MODELS` list in the [test\_generation\_models.py](https://github.com/sgl-project/sglang/blob/main/test/srt/models/test_generation_models.py) file, test the new model on your local machine and report the results on demonstrative benchmarks (GSM8K, MMLU, MMMU, MMMU-Pro, etc.) in your PR. + +For VLMs, also include a test in `test_vision_openai_server_{x}.py` (e.g. [test\_vision\_openai\_server\_a.py](https://github.com/sgl-project/sglang/blob/main/test/srt/test_vision_openai_server_a.py), [test\_vision\_openai\_server\_b.py](https://github.com/sgl-project/sglang/blob/main/test/srt/test_vision_openai_server_b.py)). + +This is an example command to run to test a new model on your local machine: + + +```bash Run Test +ONLY_RUN=Qwen/Qwen2-1.5B python3 -m unittest test_generation_models.TestGenerationModels.test_others +``` + + +### Benchmark + + + + Follow the MMMU benchmark [README](https://github.com/sgl-project/sglang/blob/main/benchmark/mmmu/README) to get SGLang vs. HF Transformer accuracy comparison. The accuracy score from SGLang run should not be much lower than that from HF Transformer run. Similarly, follow the [benchmark and profiling guide](../developer_guide/benchmark_and_profiling) to get performance comparison: TTFT and throughput must meet or exceed baselines (e.g., HF Transformer). + + + If you ran other evals, please note the results in PR description. + + + +## Port a Model from vLLM to SGLang + +The [vLLM Models Directory](https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/models) is a valuable resource, as vLLM covers many models. SGLang reuses vLLM's interface and some layers, making it easier to port models from vLLM to SGLang. + +To port a model from vLLM to SGLang: + +- Compare these two files for guidance: + - [SGLang Llama Implementation](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/models/llama.py) + - [vLLM Llama Implementation](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/models/llama.py) +- The major differences include: + - **Replace vLLM's `Attention` with `RadixAttention`** (ensure you pass `layer_id` to `RadixAttention`). + - **Replace vLLM's `LogitsProcessor` with SGLang's `LogitsProcessor`.** + - **Replace the multi-headed `Attention` of ViT with SGLang's `VisionAttention`.** + - **Replace other vLLM layers** (such as `RMSNorm`, `SiluAndMul`) with SGLang layers. + - **Remove `Sample`.** + - **Change the `forward()` functions** and add a `forward_batch()` method. + - **Add `EntryClass`** at the end. + - **Ensure that the new implementation uses only SGLang components** and does not rely on any vLLM components. + +Make sure you add your new model to the supported models list in the supported models documentation. + +## Registering an External Model Implementation + +In addition to the methods above, you can register your new model with the `ModelRegistry` before launching the server. This allows you to integrate your model without modifying the source code. + +For example: + + +```python Register Model +from sglang.srt.models.registry import ModelRegistry +from sglang.srt.entrypoints.http_server import launch_server + +# For a single model, add it to the registry: +ModelRegistry.models[model_name] = model_class + +# For multiple models, you can imitate the import_model_classes() function: +from functools import lru_cache + +@lru_cache() +def import_new_model_classes(): + model_arch_name_to_cls = {} + # Populate model_arch_name_to_cls with your new model classes. + ... + return model_arch_name_to_cls + +ModelRegistry.models.update(import_new_model_classes()) + +# Launch the server with your server arguments: +launch_server(server_args) +``` + + +## Example: Implementing and Serving a Llama Wrapper Model + +Below is an introductory, step-by-step walkthrough on how to implement a new model end-to-end in SGLang and then run it via the [Offline Engine](../basic_usage/offline_engine_api). + +### Implementing Our Model + +To keep things simple, this new model will be a simple wrapper around [Llama 3.1-8B-Instruct](https://huggingface.co/meta-llama/Llama-3.1-8B-Instruct), and our goal will be just to bias the output logits for each `forward` call by taking the square root of each individual logit. + +Let's start by defining our model in a file called `llama_wrapper.py`. The first step is to import the necessary libraries from SRT, which is SGLang's internal backend. + +```python llama_wrapper.py +import torch +from transformers import LlamaConfig +from typing import Optional +from sglang.srt.layers.logits_processor import LogitsProcessorOutput +from sglang.srt.layers.quantization.base_config import QuantizationConfig +from sglang.srt.model_executor.forward_batch_info import ForwardBatch, PPProxyTensors + +from sglang.srt.models.llama import LlamaForCausalLM +``` + +Next, we declare a new `class` for our model and have it inherit from `LlamaForCausalLM`, which allows our model to access `LlamaForCausalLM`'s predefined modules and layers, such as `LlamaAttention` and `LlamaMLP`. Note that almost all model implementations take in `config` and `quant_config` as arguments for their `__init__` method; `config` and `quant_config` are passed in via [`model_loader/loader.py`](https://github.com/sgl-project/sglang/blob/bf72b80122fd888bf619d17b96fa3e323ab809fc/python/sglang/srt/model_loader/loader.py#L219). Because we have inherited from `LlamaForCausalLM`, we can pass our parameters directly to its constructor, which will set the member variables for us. + + +```python Class Definition +class LlamaWrapper(LlamaForCausalLM): + def __init__( + self, + config: LlamaConfig, + quant_config: Optional[QuantizationConfig] = None, + prefix: str = "", + ) -> None: + super().__init__(config=config, quant_config=quant_config, prefix=prefix) +``` + + +Now, we want to define the `forward` method, which is what will be called at inference time. Note that the signature for `forward` is essentially the same for any model; you can take a look at the other models defined in the [`models` directory](https://github.com/sgl-project/sglang/tree/main/python/sglang/srt/models/) for references. To see where exactly `forward` is called in the SGLang runtime's internals, take a look at [`forward_decode`](https://github.com/sgl-project/sglang/blob/bf72b80122fd888bf619d17b96fa3e323ab809fc/python/sglang/srt/model_executor/model_runner.py#L1705) and [`forward_extend`](https://github.com/sgl-project/sglang/blob/bf72b80122fd888bf619d17b96fa3e323ab809fc/python/sglang/srt/model_executor/model_runner.py#L1724) in the [`ModelRunner` class](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/model_executor/model_runner.py). + + +```python Forward Method Signature + @torch.no_grad() + def forward( + self, + input_ids: torch.Tensor, + positions: torch.Tensor, + forward_batch: ForwardBatch, + pp_proxy_tensors: Optional[PPProxyTensors] = None, + input_embeds: Optional[torch.Tensor] = None, + get_embedding: bool = False, + ) -> LogitsProcessorOutput: +``` + + +We now call the `__call__` method for `self.model` (which is a member variable that `LlamaForCausalLM` defines in its `__init__` method), which eventually calls `LlamaForCausalLM`'s `forward` method. After that, we feed the `hidden_states` into our model's `LogitsProcessor` (again defined in `LlamaForCausalLM`). + + +```python Call Model and LogitsProcessor + hidden_states = self.model( + input_ids, + positions, + forward_batch, + input_embeds, + pp_proxy_tensors=pp_proxy_tensors, + ) + + res: LogitsProcessorOutput = self.logits_processor( + input_ids, + hidden_states, + self.lm_head, + forward_batch, + ) +``` + + +After receiving the logits for the next token, we can finally perform our biasing step. + + +```python Logit Biasing + orig_logits = res.next_token_logits + res.next_token_logits = torch.where( + orig_logits > 0, + orig_logits.sqrt(), + orig_logits + ) + + return res +``` + + +Now, our `LlamaWrapper` model is created and ready to be served! + +### Serving Our Model Via SGLang's Offline Engine + +The next step of this walkthrough involves hosting our new model offline, so that it can be served locally and without an HTTP server. + +First, create a new file called `run.py`. Now, we must ensure that SGLang's `ModelRegistry` can find our model. To do this, we first download the model's configuration and weights from Huggingface. + +```python run.py +import asyncio +from functools import lru_cache +from huggingface_hub import snapshot_download +from llama_wrapper import LlamaWrapper # Make sure to import our new model! +import sglang as sgl +from sglang.srt.models.registry import ModelRegistry + +# Make sure to request access to this model on Huggingface, then export your +# `HF_TOKEN` to download the model snapshot +llama_dir = snapshot_download( + repo_id="meta-llama/Llama-3.1-8B-Instruct", + local_dir="./llama_ckpt", +) +``` + +Now that we have our model on disk, we want to point it to `LlamaWrapper` by changing the `architectures` field in `./llama_ckpt/config.json` to be `LlamaWrapper`. That way, when we pass in the path of our model checkpoint to SGLang, it will know that we want to use "LlamaWrapper" instead of "LlamaForCausalLM" as our model. + +```json ./llama_ckpt/config.json +{ + "architectures": [ + # "LlamaForCausalLM" + "LlamaWrapper" + ], + ... +} +``` + +However, if we don't link our `LlamaWrapper` class to the "LlamaWrapper" registry keyword, then SGLang won't be able to find our model. Thus, to register our `LlamaWrapper`, we want to follow the steps in the above section titled "Registering an External Model Implementation". + + +```python Register LlamaWrapper +@lru_cache() +def import_new_model_classes(): + model_arch_name_to_cls = {"LlamaWrapper": LlamaWrapper} + return model_arch_name_to_cls + +ModelRegistry.models.update(import_new_model_classes()) +``` + + +Lastly, when we create our `Engine`, we just pass in the path to the local model directory. Then, our `LlamaWrapper` is ready to be served; for this walkthrough, we will use SGLang `Engine`'s non-streaming asynchronous generation endpoint. + + +```python Run Model +def main(): + llm = sgl.Engine(model_path="./llama_ckpt") + sampling_params = {"temperature": 0.2, "top_k": 5} + prompts = [ + "Write a short, neutral self-introduction for a fictional character. Hello, my name is", + "Provide a concise factual statement about France's capital city. The capital of France is", + "Explain possible future trends in artificial intelligence. The future of AI is", + ] + + asyncio.run(run_llm(llm, sampling_params, prompts)) + + llm.shutdown() + +async def run_llm( + llm, + sampling_params, + prompts, +) -> None: + outputs = await llm.async_generate(prompts, sampling_params) + + for prompt, output in zip(prompts, outputs): + print(f"\nPrompt: {prompt}") + print(f"Generated text: {output['text']}") + +if __name__ == "__main__": + main() +``` + + +Now, when we call `python run.py`, we will get the outputs of our newly created model! + +## Documentation + +Add to table of supported models in [generative\_models](/docs/supported-models/large-language-models) or [multimodal\_language\_models](/docs/supported-models/vision-language-models). + +--- + +By following these guidelines, you can add support for new language models and multimodal large language models in SGLang and ensure they are thoroughly tested and easily integrated into the system. diff --git a/docs_new/docs/supported-models/rerank-models.mdx b/docs_new/docs/supported-models/rerank-models.mdx new file mode 100644 index 000000000..dab840c6c --- /dev/null +++ b/docs_new/docs/supported-models/rerank-models.mdx @@ -0,0 +1,311 @@ +--- +title: Rerank models +--- + +SGLang offers comprehensive support for rerank models by incorporating optimized serving frameworks with a flexible programming interface. This setup enables efficient processing of cross-encoder reranking tasks, improving the accuracy and relevance of search result ordering. SGLang’s design ensures high throughput and low latency during reranker model deployment, making it ideal for semantic-based result refinement in large-scale retrieval systems. + +Rerank models in SGLang fall into two categories: + +- **Cross-encoder rerank models**: run with `--is-embedding` (embedding runner). +- **Decoder-only rerank models**: run **without** `--is-embedding` and use next-token logprob scoring (yes/no). + - Text-only (e.g. Qwen3-Reranker) + - Multimodal (e.g. Qwen3-VL-Reranker): also supports image/video content + +Some models may require `--trust-remote-code`. + + +## Supported rerank models + +| Model Family (Rerank) | Example HuggingFace Identifier | Chat Template | Description | +|------------------------------------------------|--------------------------------------|---------------|----------------------------------------------------------------------------------------------------------------------------------| +| **BGE-Reranker (BgeRerankModel)** | `BAAI/bge-reranker-v2-m3` | N/A | Currently only support `attention-backend` `triton` and `torch_native`. High-performance cross-encoder reranker model from BAAI. Suitable for reranking search results based on semantic relevance. | +| **Qwen3-Reranker (decoder-only yes/no)** | `Qwen/Qwen3-Reranker-8B` | `examples/chat_template/qwen3_reranker.jinja` | Decoder-only reranker using next-token logprob scoring for labels (yes/no). Launch **without** `--is-embedding`. | +| **Qwen3-VL-Reranker (multimodal yes/no)** | `Qwen/Qwen3-VL-Reranker-2B` | `examples/chat_template/qwen3_vl_reranker.jinja` | Multimodal decoder-only reranker supporting text, images, and videos. Uses yes/no logprob scoring. Launch **without** `--is-embedding`. | + + +## Cross-Encoder Rerank (embedding runner) + +### Launch Command + +```shell +python3 -m sglang.launch_server \ + --model-path BAAI/bge-reranker-v2-m3 \ + --host 0.0.0.0 \ + --disable-radix-cache \ + --chunked-prefill-size -1 \ + --attention-backend triton \ + --is-embedding \ + --port 30000 +``` + +### Example Client Request + +```python +import requests + +url = "http://127.0.0.1:30000/v1/rerank" + +payload = { + "model": "BAAI/bge-reranker-v2-m3", + "query": "what is panda?", + "documents": [ + "hi", + "The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China." + ], + "top_n": 1, + "return_documents": True +} + +response = requests.post(url, json=payload) +response_json = response.json() + +for item in response_json: + if item.get("document"): + print(f"Score: {item['score']:.2f} - Document: '{item['document']}'") + else: + print(f"Score: {item['score']:.2f} - Index: {item['index']}") +``` + +**Request Parameters:** + +- `query` (required): The query text to rank documents against +- `documents` (required): List of documents to be ranked +- `model` (required): Model to use for reranking +- `top_n` (optional): Maximum number of documents to return. Defaults to returning all documents. If specified value is greater than the total number of documents, all documents will be returned. +- `return_documents` (optional): Whether to return documents in the response. Defaults to `True`. + +## Qwen3-Reranker (decoder-only yes/no rerank) + +### Launch Command + +```shell +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-Reranker-0.6B \ + --trust-remote-code \ + --disable-radix-cache \ + --host 0.0.0.0 \ + --port 8001 \ + --chat-template examples/chat_template/qwen3_reranker.jinja +``` + +Qwen3-Reranker uses decoder-only logprob scoring (yes/no). Do NOT launch it with `--is-embedding`. + +### Example Client Request (supports optional instruct, top_n, and return_documents) + +```shell +curl -X POST http://127.0.0.1:8001/v1/rerank \ + -H "Content-Type: application/json" \ + -d '{ + "model": "Qwen3-Reranker-0.6B", + "query": "法国首都是哪里?", + "documents": [ + "法国的首都是巴黎。", + "德国的首都是柏林。", + "香蕉是黄色的水果。" + ], + "instruct": "Given a web search query, retrieve relevant passages that answer the query.", + "top_n": 2, + "return_documents": true + }' +``` + +**Request Parameters:** + +- `query` (required): The query text to rank documents against +- `documents` (required): List of documents to be ranked +- `model` (required): Model to use for reranking +- `instruct` (optional): Instruction text for the reranker +- `top_n` (optional): Maximum number of documents to return. Defaults to returning all documents. If specified value is greater than the total number of documents, all documents will be returned. +- `return_documents` (optional): Whether to return documents in the response. Defaults to `True`. + +### Response Format + +`/v1/rerank` returns a list of objects (sorted by descending score): + +- `score`: float, higher means more relevant +- `document`: the original document string (only included when `return_documents` is `true`) +- `index`: the original index in the input `documents` +- `meta_info`: optional debug/usage info (may be present for some models) + +The number of returned results is controlled by the `top_n` parameter. If `top_n` is not specified or is greater than the total number of documents, all documents are returned. + +Example (with `return_documents: true`): + +```json +[ + {"score": 0.99, "document": "法国的首都是巴黎。", "index": 0}, + {"score": 0.01, "document": "德国的首都是柏林。", "index": 1}, + {"score": 0.00, "document": "香蕉是黄色的水果。", "index": 2} +] +``` + +Example (with `return_documents: false`): + +```json +[ + {"score": 0.99, "index": 0}, + {"score": 0.01, "index": 1}, + {"score": 0.00, "index": 2} +] +``` + +Example (with `top_n: 2`): + +```json +[ + {"score": 0.99, "document": "法国的首都是巴黎。", "index": 0}, + {"score": 0.01, "document": "德国的首都是柏林。", "index": 1} +] +``` + +### Common Pitfalls + +- If you launch Qwen3-Reranker with `--is-embedding`, `/v1/rerank` cannot compute yes/no logprob scores. Relaunch **without** `--is-embedding`. +- If you see a validation error like "score should be a valid number" and the backend returned a list, upgrade to a version that coerces `embedding[0]` into `score` for rerank responses. + +## Qwen3-VL-Reranker (multimodal decoder-only rerank) + +Qwen3-VL-Reranker extends the Qwen3-Reranker to support multimodal content, allowing reranking of documents containing text, images, and videos. + +### Launch Command + +```shell +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen3-VL-Reranker-2B \ + --trust-remote-code \ + --disable-radix-cache \ + --host 0.0.0.0 \ + --port 30000 \ + --chat-template examples/chat_template/qwen3_vl_reranker.jinja +``` + +Qwen3-VL-Reranker uses decoder-only logprob scoring (yes/no) like Qwen3-Reranker. Do NOT launch it with `--is-embedding`. + + +### Text-Only Reranking (backward compatible) + +```python +import requests + +url = "http://127.0.0.1:30000/v1/rerank" + +payload = { + "model": "Qwen3-VL-Reranker-2B", + "query": "What is machine learning?", + "documents": [ + "Machine learning is a branch of artificial intelligence that enables computers to learn from data.", + "The weather in Paris is usually mild with occasional rain.", + "Deep learning is a subset of machine learning using neural networks with many layers.", + ], + "instruct": "Retrieve passages that answer the question.", + "return_documents": True +} + +response = requests.post(url, json=payload) +results = response.json() + +for item in results: + print(f"Score: {item['score']:.4f} - {item['document'][:60]}...") +``` + +### Image Reranking (text query, image/mixed documents) + +```python +import requests + +url = "http://127.0.0.1:30000/v1/rerank" + +payload = { + "query": "A woman playing with her dog on a beach at sunset.", + "documents": [ + # Document 1: Text description + "A woman shares a joyful moment with her golden retriever on a sun-drenched beach at sunset.", + # Document 2: Image URL + [ + { + "type": "image_url", + "image_url": { + "url": "https://example.com/beach_dog.jpeg" + } + } + ], + # Document 3: Text + Image (mixed) + [ + {"type": "text", "text": "A joyful scene at the beach:"}, + { + "type": "image_url", + "image_url": { + "url": "https://example.com/beach_dog.jpeg" + } + } + ] + ], + "instruct": "Retrieve images or text relevant to the user's query.", + "return_documents": False +} + +response = requests.post(url, json=payload) +results = response.json() + +for item in results: + print(f"Index: {item['index']}, Score: {item['score']:.4f}") +``` + +### Multimodal Query Reranking (query with image) + +```python +import requests + +url = "http://127.0.0.1:30000/v1/rerank" + +payload = { + # Query with text and image + "query": [ + {"type": "text", "text": "Find similar images to this:"}, + { + "type": "image_url", + "image_url": { + "url": "https://example.com/reference_image.jpeg" + } + } + ], + "documents": [ + "A cat sleeping on a couch.", + "A woman and her dog enjoying the sunset at the beach.", + "A busy city street with cars and pedestrians.", + [ + { + "type": "image_url", + "image_url": { + "url": "https://example.com/similar_image.jpeg" + } + } + ] + ], + "instruct": "Find images or descriptions similar to the query image." +} + +response = requests.post(url, json=payload) +results = response.json() + +for item in results: + print(f"Index: {item['index']}, Score: {item['score']:.4f}") +``` + +### Request Parameters (Multimodal) + +- `query` (required): Can be a string (text-only) or a list of content parts: + - `{"type": "text", "text": "..."}` for text + - `{"type": "image_url", "image_url": {"url": "..."}}` for images + - `{"type": "video_url", "video_url": {"url": "..."}}` for videos +- `documents` (required): List where each document can be a string or list of content parts (same format as query) +- `instruct` (optional): Instruction text for the reranker +- `top_n` (optional): Maximum number of documents to return +- `return_documents` (optional): Whether to return documents in the response (default: `false`) + +### Common Pitfalls + +- Always use `--chat-template examples/chat_template/qwen3_vl_reranker.jinja` for Qwen3-VL-Reranker. +- Do NOT launch with `--is-embedding`. +- For best results, use `--disable-radix-cache` to avoid caching issues with multimodal content. +- **Note**: Currently only `Qwen3-VL-Reranker-2B` is tested and supported. The 8B model may have different behavior and is not guaranteed to work with this template. diff --git a/docs_new/docs/supported-models/reward-models.mdx b/docs_new/docs/supported-models/reward-models.mdx new file mode 100644 index 000000000..0ba8ccf51 --- /dev/null +++ b/docs_new/docs/supported-models/reward-models.mdx @@ -0,0 +1,30 @@ +--- +title: Reward models +--- + +These models output a scalar reward score or classification result, often used in reinforcement learning or content moderation tasks. + +They are executed with `--is-embedding` and some may require `--trust-remote-code`. + +## Example launch Command + + +```shell Command +python3 -m sglang.launch_server \ + --model-path Qwen/Qwen2.5-Math-RM-72B \ # example HF/local path + --is-embedding \ + --host 0.0.0.0 \ + --tp-size=4 \ # set for tensor parallelism + --port 30000 \ +``` + + +## Supported models + +| Model Family (Reward) | Example HuggingFace Identifier | Description | +|---------------------------------------------------------------------------|-----------------------------------------------------|---------------------------------------------------------------------------------| +| **Llama (3.1 Reward / `LlamaForSequenceClassification`)** | `Skywork/Skywork-Reward-Llama-3.1-8B-v0.2` | Reward model (preference classifier) based on Llama 3.1 (8B) for scoring and ranking responses for RLHF. | +| **Gemma 2 (27B Reward / `Gemma2ForSequenceClassification`)** | `Skywork/Skywork-Reward-Gemma-2-27B-v0.2` | Derived from Gemma‑2 (27B), this model provides human preference scoring for RLHF and multilingual tasks. | +| **InternLM 2 (Reward / `InternLM2ForRewardMode`)** | `internlm/internlm2-7b-reward` | InternLM 2 (7B)–based reward model used in alignment pipelines to guide outputs toward preferred behavior. | +| **Qwen2.5 (Reward - Math / `Qwen2ForRewardModel`)** | `Qwen/Qwen2.5-Math-RM-72B` | A 72B math-specialized RLHF reward model from the Qwen2.5 series, tuned for evaluating and refining responses. | +| **Qwen2.5 (Reward - Sequence / `Qwen2ForSequenceClassification`)** | `jason9693/Qwen2.5-1.5B-apeach` | A smaller Qwen2.5 variant used for sequence classification, offering an alternative RLHF scoring mechanism. | diff --git a/docs_new/docs/supported-models/transformers-fallback.mdx b/docs_new/docs/supported-models/transformers-fallback.mdx new file mode 100644 index 000000000..f43708ea3 --- /dev/null +++ b/docs_new/docs/supported-models/transformers-fallback.mdx @@ -0,0 +1,70 @@ +--- +title: "Transformers Fallback in SGLang" +--- + +`sglang` can fall back to using models that are available in `transformers`. This works for most decoder-style language models and support for vision-language models is coming soon! + +## Example Launch Command + +By default, we will use sglang implementation if it is available. Otherwise, we will fall back to transformers one. However, you can switch the implementation by setting `--model-impl` to `transformers`. + + +```shell Launch Server +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.2-1B-Instruct \ + --host 0.0.0.0 \ + --port 30000 \ + --model-impl transformers +``` + + +## Supported Features + +### Quantization + +Transformers fallback has supported most of available quantization in SGLang (except GGUF). See the [Quantization page](../advanced_features/quantization) for more information about supported quantization in SGLang. + +### Remote Code + +This fallback also means that any model on the hub that can be used in `transformers` with `trust_remote_code=True` that correctly implements attention can be used in production! + +A model just needs the following two things: + + +```python Required Implementation +from transformers import PreTrainedModel +from torch import nn + +class MyAttention(nn.Module): + def forward(self, hidden_states, **kwargs): # <- kwargs are required + ... + attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] + attn_output, attn_weights = attention_interface( + self, + query_states, + key_states, + value_states, + **kwargs, + ) + ... + +class MyModel(PreTrainedModel): + _supports_attention_backend = True +``` + + +Here is what happens in the background: + +1. **Load the config** + +The config is loaded. + +2. **Load the model class** + +`MyModel` python class is loaded from the `auto_map`, and we check that the model `_supports_attention_backend`. + +3. **Use the TransformersModel backend** + +The `TransformersModel` backend is used. See `/srt/models/transformers`, which leverages `self.config._attn_implementation = "sglang"`, thus the need to use `ALL_ATTENTION_FUNCTIONS`. + +That's it! diff --git a/docs_new/docs/supported-models/vision-language-models.mdx b/docs_new/docs/supported-models/vision-language-models.mdx new file mode 100644 index 000000000..12265f80c --- /dev/null +++ b/docs_new/docs/supported-models/vision-language-models.mdx @@ -0,0 +1,316 @@ +These models accept multi-modal inputs (e.g., images and text) and generate text output. They augment language models with multimodal encoders. + +## Example launch Command + + +```bash Launch Server +python3 -m sglang.launch_server \ + --model-path meta-llama/Llama-3.2-11B-Vision-Instruct \ # example HF/local path + --host 0.0.0.0 \ + --port 30000 \ +``` + + +> See the [OpenAI APIs section](../basic_usage/openai_api_vision) for how to send multimodal requests. + +## Supported models + +Below the supported models are summarized in a table. + +If you are unsure if a specific architecture is implemented, you can search for it via GitHub. For example, to search for `Qwen2_5_VLForConditionalGeneration`, use the expression: + + +```text GitHub Search +repo:sgl-project/sglang path:/^python\/sglang\/srt\/models\// Qwen2_5_VLForConditionalGeneration +``` + + +in the GitHub search bar. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model Family (Variants)Example HuggingFace IdentifierDescriptionNotes
Qwen-VLQwen/Qwen3-VL-235B-A22B-InstructAlibaba's vision-language extension of Qwen; for example, Qwen2.5-VL (7B and larger variants) can analyze and converse about image content.
DeepSeek-VL2deepseek-ai/deepseek-vl2Vision-language variant of DeepSeek (with a dedicated image processor), enabling advanced multimodal reasoning on image and text inputs.
DeepSeek-OCR / OCR-2deepseek-ai/DeepSeek-OCR-2OCR-focused DeepSeek models for document understanding and text extraction.Use --trust-remote-code.
Janus-Pro (1B, 7B)deepseek-ai/Janus-Pro-7BDeepSeek's open-source multimodal model capable of both image understanding and generation. Janus-Pro employs a decoupled architecture for separate visual encoding paths, enhancing performance in both tasks.
MiniCPM-V / MiniCPM-oopenbmb/MiniCPM-V-2_6MiniCPM-V (2.6, ~8B) supports image inputs, and MiniCPM-o adds audio/video; these multimodal LLMs are optimized for end-side deployment on mobile/edge devices.
Llama 3.2 Vision (11B)meta-llama/Llama-3.2-11B-Vision-InstructVision-enabled variant of Llama 3 (11B) that accepts image inputs for visual question answering and other multimodal tasks.
LLaVA (v1.5 & v1.6)e.g. liuhaotian/llava-v1.5-13bOpen vision-chat models that add an image encoder to LLaMA/Vicuna (e.g. LLaMA2 13B) for following multimodal instruction prompts.
LLaVA-NeXT (8B, 72B)lmms-lab/llava-next-72bImproved LLaVA models (with an 8B Llama3 version and a 72B version) offering enhanced visual instruction-following and accuracy on multimodal benchmarks.
LLaVA-OneVisionlmms-lab/llava-onevision-qwen2-7b-ovEnhanced LLaVA variant integrating Qwen as the backbone; supports multiple images (and even video frames) as inputs via an OpenAI Vision API-compatible format.
Gemma 3 (Multimodal)google/gemma-3-4b-itGemma 3's larger models (4B, 12B, 27B) accept images (each image encoded as 256 tokens) alongside text in a combined 128K-token context.
Kimi-VL (A3B)moonshotai/Kimi-VL-A3B-InstructKimi-VL is a multimodal model that can understand and generate text from images.
Mistral-Small-3.1-24Bmistralai/Mistral-Small-3.1-24B-Instruct-2503Mistral 3.1 is a multimodal model that can generate text from text or images input. It also supports tool calling and structured output.
Phi-4-multimodal-instructmicrosoft/Phi-4-multimodal-instructPhi-4-multimodal-instruct is the multimodal variant of the Phi-4-mini model, enhanced with LoRA for improved multimodal capabilities. It supports text, vision and audio modalities in SGLang.
MiMo-VL (7B)XiaomiMiMo/MiMo-VL-7B-RLXiaomi's compact yet powerful vision-language model featuring a native resolution ViT encoder for fine-grained visual details, an MLP projector for cross-modal alignment, and the MiMo-7B language model optimized for complex reasoning tasks.
GLM-4.5V (106B) / GLM-4.1V(9B)zai-org/GLM-4.5VGLM-4.5V and GLM-4.1V-Thinking: Towards Versatile Multimodal Reasoning with Scalable Reinforcement LearningUse --chat-template glm-4v
GLM-OCRzai-org/GLM-OCRGLM-OCR: A fast and accurate general OCR model
DotsVLM (General/OCR)rednote-hilab/dots.vlm1.instRedNote's vision-language model built on a 1.2B vision encoder and DeepSeek V3 LLM, featuring NaViT vision encoder trained from scratch with dynamic resolution support and enhanced OCR capabilities through structured image data training.
DotsVLM-OCRrednote-hilab/dots.ocrSpecialized OCR variant of DotsVLM optimized for optical character recognition tasks with enhanced text extraction and document understanding capabilities.Don't use --trust-remote-code
NVILA (8B, 15B, Lite-2B, Lite-8B, Lite-15B)Efficient-Large-Model/NVILA-8BchatmlNVILA explores the full stack efficiency of multi-modal design, achieving cheaper training, faster deployment and better performance.
NVIDIA Nemotron Nano 2.0 VLnvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-BF16NVIDIA Nemotron Nano v2 VL enables multi-image reasoning and video understanding, along with strong document intelligence, visual Q&A and summarization capabilities. It builds on Nemotron Nano V2, a hybrid Mamba-Transformer LLM, in order to achieve higher inference throughput in long document and video scenarios.Use --trust-remote-code. You may need to adjust --max-mamba-cache-size [default is 512] to fit memory constraints.
Ernie4.5-VLbaidu/ERNIE-4.5-VL-28B-A3B-PTBaidu's vision-language models(28B,424B). Support image and video comprehension, and also support thinking.
JetVLMJetVLM is an vision-language model designed for high-performance multimodal understanding and generation tasks built upon Jet-Nemotron.Coming soon
Step3-VL (10B)stepfun-ai/Step3-VL-10BStepFun's lightweight open-source 10B parameter VLM for multimodal intelligence, excelling in visual perception, complex reasoning, and human alignment.
Qwen3-OmniQwen/Qwen3-Omni-30B-A3B-InstructAlibaba's omni-modal MoE model. Currently supports the Thinker component (multimodal understanding for text, images, audio, and video), while the Talker component (audio generation) is not yet supported.
+ +## Video Input Support + +SGLang supports video input for Vision-Language Models (VLMs), enabling temporal reasoning tasks such as video question answering, captioning, and holistic scene understanding. Video clips are decoded, key frames are sampled, and the resulting tensors are batched together with the text prompt, allowing multimodal inference to integrate visual and linguistic context. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Model FamilyExample IdentifierVideo notes
Qwen-VL (Qwen2-VL, Qwen2.5-VL, Qwen3-VL, Qwen3-Omni)Qwen/Qwen3-VL-235B-A22B-InstructThe processor gathers video_data, runs Qwen's frame sampler, and merges the resulting features with text tokens before inference.
GLM-4v (4.5V, 4.1V, MOE)zai-org/GLM-4.5VVideo clips are read with Decord, converted to tensors, and passed to the model alongside metadata for rotary-position handling.
NVILA (Full & Lite)Efficient-Large-Model/NVILA-8BThe runtime samples eight frames per clip and attaches them to the multimodal request when video_data is present.
LLaVA video variants (LLaVA-NeXT-Video, LLaVA-OneVision)lmms-lab/LLaVA-NeXT-Video-7BThe processor routes video prompts to the LlavaVid video-enabled architecture, and the provided example shows how to query it with sgl.video(...) clips.
NVIDIA Nemotron Nano 2.0 VLnvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-BF16The processor samples at 2 FPS, at a max of 128 frames, as per model training. The model uses EVS, a pruning method that removes redundant tokens from video embeddings. By default video_pruning_rate=0.7. Change this by providing: --json-model-override-args '{"video_pruning_rate": 0.0}' to disable EVS, for example.
JetVLMThe runtime samples eight frames per clip and attaches them to the multimodal request when video_data is present.
+ +Use `sgl.video(path, num_frames)` when building prompts to attach clips from your SGLang programs. + +Example OpenAI-compatible request that sends a video clip: + + +```python Complete Example +import requests + +url = "http://localhost:30000/v1/chat/completions" + +data = { + "model": "Qwen/Qwen3-VL-30B-A3B-Instruct", + "messages": [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What’s happening in this video?"}, + { + "type": "video_url", + "video_url": { + "url": "https://github.com/sgl-project/sgl-test-files/raw/refs/heads/main/videos/jobs_presenting_ipod.mp4" + }, + }, + ], + } + ], + "max_tokens": 300, +} + +response = requests.post(url, json=data) +print(response.text) +``` + + +## Usage Notes + +### Performance Optimization + +For multimodal models, you can use the `--keep-mm-feature-on-device` flag to optimize for latency at the cost of increased GPU memory usage: + +- **Default behavior**: Multimodal feature tensors are moved to CPU after processing to save GPU memory +- **With `--keep-mm-feature-on-device`**: Feature tensors remain on GPU, reducing device-to-host copy overhead and improving latency, but consuming more GPU memory + +Use this flag when you have sufficient GPU memory and want to minimize latency for multimodal inference. + +### Multimodal Inputs Limitation + +- **Use `--mm-process-config '{"image":{"max_pixels":1048576},"video":{"fps":3,"max_pixels":602112,"max_frames":60}}'`**: To set `image`, `video`, and `audio` input limits. + +This can reduce GPU memory usage, improve inference speed, and help to avoid OOM, but may impact model performance, thus set a proper value based on your specific use case. Currently, only `qwen_vl` supports this config. Please refer to [qwen_vl processor](https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/multimodal/processors/qwen_vl.py) for understanding the meaning of each parameter. + +### Bidirectional Attention in Multimodal Model Serving +**Note for serving the Gemma-3 multimodal model**: + +As mentioned in [Welcome Gemma 3: Google's all new multimodal, multilingual, long context open LLM +](https://huggingface.co/blog/gemma3#multimodality), Gemma-3 employs bidirectional attention between image tokens during the prefill phase. Currently, SGLang only supports bidirectional attention when using the Triton Attention Backend. Note, however, that SGLang's current bidirectional attention implementation is incompatible with both CUDA Graph and Chunked Prefill. + +To enable bidirectional attention, you can use the `TritonAttnBackend` while disabling CUDA Graph and Chunked Prefill. Example launch command: + +```bash Bidirectional Attention +python -m sglang.launch_server \ + --model-path google/gemma-3-4b-it \ + --host 0.0.0.0 --port 30000 \ + --enable-multimodal \ + --dtype bfloat16 --triton-attention-reduce-in-fp32 \ + --attention-backend triton \ # Use Triton attention backend + --disable-cuda-graph \ # Disable Cuda Graph + --chunked-prefill-size -1 # Disable Chunked Prefill +``` + + +If higher serving performance is required and a certain degree of accuracy loss is acceptable, you may choose to use other attention backends, and you can also enable features like CUDA Graph and Chunked Prefill for better performance, but note that the model will fall back to using causal attention instead of bidirectional attention. diff --git a/docs_new/docs_migration_plan.md b/docs_new/docs_migration_plan.md new file mode 100644 index 000000000..6391c6f9b --- /dev/null +++ b/docs_new/docs_migration_plan.md @@ -0,0 +1,133 @@ +# SGLang Documentation Migration Plan + +## Background + +Migrate the new Mintlify-based documentation (currently in the standalone `sgl-docs` repo) into the sglang main repo under `docs_new/`, and point `staging.docs.sglang.io` to it. + +### Current State + +| Item | Location | Stack | Domain | +|------|----------|-------|--------| +| Old docs | `sglang/docs/` | Sphinx + GitHub Pages | `docs.sglang.io` | +| New docs + cookbook | `sgl-project/sgl-docs` repo | Mintlify | `lmsysorg.mintlify.app` (temp preview) | + +- Cookbook is already inside `sgl-docs/cookbook/`, no separate repo needed. +- Old docs CI (`execute-notebook.yml`, `lint.yml`) only watches `docs/**`, will not be triggered by `docs_new/**`. + +--- + +## Phase 1: Git Subtree Merge (Local Experiment) + +> Goal: Merge `sgl-docs` into `sglang` repo's `docs_new/` directory, preserving full commit history and authorship. + +```bash +# 1. Create a new branch (sglang remote is NOT affected) +cd /path/to/sglang +git checkout -b docs-new-migration + +# 2. Add sgl-docs as a remote (sgl-docs repo is NOT affected, read-only fetch) +git remote add sgl-docs git@github.com:sgl-project/sgl-docs.git +git fetch sgl-docs + +# 3. Subtree merge — all sgl-docs content goes into docs_new/, full history preserved +git subtree add --prefix=docs_new sgl-docs main + +# 4. Keep the remote for ongoing sync during migration period +# (remove only after sgl-docs is officially archived) +``` + +### Safety Guarantees + +- `sgl-docs` original repo: **unaffected** (fetch only, no push) +- `sglang` remote: **unaffected** (local branch, no push until ready) +- Rollback: `git checkout main && git branch -D docs-new-migration` + +### Side Effect: Contributors + +`git subtree add` (without `--squash`) imports all original commits. Authors from `sgl-docs` will appear in `sglang`'s git history and GitHub Contributors list. This is intentional — it gives proper credit. + +--- + +## Phase 2: Configure Mintlify for `docs_new/` (on branch) + +> Goal: Make Mintlify read from `sglang` repo's `docs_new/` subdirectory instead of the standalone `sgl-docs` repo. **No need to merge to main first** — Mintlify can point to a specific branch for validation. + +1. Log in to [Mintlify Dashboard](https://dashboard.mintlify.com) +2. Change the project's **GitHub repository** from `sgl-project/sgl-docs` to `sgl-project/sglang` +3. Set **Branch** to `docs-new-migration` (temporarily, for validation) +4. Set **Documentation directory** to `docs_new` (Mintlify supports monorepo subdirectory) +5. `docs.json` (Mintlify config) will be at `docs_new/docs.json` after the subtree merge — paths inside it (e.g., `cookbook/llm/Qwen/Qwen3`) are relative to `docs_new/`, so no changes needed +6. Verify the preview build succeeds on Mintlify + +--- + +## Phase 3: DNS & Custom Domain for `staging.docs.sglang.io` + +> Goal: Make `staging.docs.sglang.io` serve the new Mintlify docs. + +1. **DNS**: Add a CNAME record for `staging.docs.sglang.io` pointing to Mintlify's endpoint (typically `cname.mintlify.dev`) +2. **Mintlify Dashboard**: Settings > Custom Domain > add `staging.docs.sglang.io` +3. Mintlify handles SSL certificate automatically +4. Verify `staging.docs.sglang.io` loads correctly + +--- + +## Phase 4: Ongoing Sync During Migration Period + +> During the transition, `sgl-docs` may still receive updates. Sync them into `docs_new/` as needed. + +```bash +# Pull latest changes from sgl-docs into docs_new/ +git subtree pull --prefix=docs_new sgl-docs main +``` + +Once `sgl-docs` is frozen, this step is no longer needed. + +--- + +## Phase 5: CI/CD (Optional, Post-Migration) + +Current `docs/**` CI workflows will **NOT** trigger for `docs_new/**` changes. This is fine initially since Mintlify has its own GitHub integration for auto-deployment on push to main. + +Optional additions later: +- Link checking (lychee) for `docs_new/**/*.mdx` +- Mintlify broken-link or build validation on PR + +--- + +## Phase 6: Final Cutover + +> Goal: Promote staging to production. + +| Stage | `docs.sglang.io` | `staging.docs.sglang.io` | +|-------|-------------------|--------------------------| +| After Phase 3 | Sphinx (old docs) | Mintlify (new docs) | +| After cutover | Mintlify (new docs) | Keep or remove | + +Cutover steps: +1. Confirm `staging.docs.sglang.io` is stable and content-complete +2. Update DNS: point `docs.sglang.io` CNAME from GitHub Pages to Mintlify (`cname.mintlify.dev`) +3. Update Mintlify Dashboard custom domain to `docs.sglang.io` +4. Remove or archive old resources: + - Delete `sglang/docs/` (old Sphinx docs) + - Delete `.github/workflows/release-docs.yml` and `.github/workflows/execute-notebook.yml` + - Archive `sgl-project/sgl-docs` repo on GitHub + - Remove the `sgl-docs` git remote: `git remote remove sgl-docs` + - Optionally archive `sgl-project/sgl-project.github.io` repo + +--- + +## Execution Order + +> Mintlify supports pointing to a specific branch, so we can validate on `docs-new-migration` **before** merging to main. + +| Step | Action | Who | Dependency | +|------|--------|-----|------------| +| 1 | Phase 1: subtree merge on local branch | Dev | — | +| 2 | Push branch to `sgl-project/sglang` | Dev | Step 1 | +| 3 | Phase 2: configure Mintlify Dashboard to read from `sgl-project/sglang` branch `docs-new-migration` `docs_new/` | Admin (Mintlify access) | Step 2 | +| 4 | Phase 3: DNS CNAME + Mintlify custom domain for `staging.docs.sglang.io` | Admin (DNS access) | Step 3 | +| 5 | Verify staging site | Team | Step 4 | +| 6 | Merge PR to main, switch Mintlify branch back to `main` | Dev + Admin | Step 5 confirmed OK | +| 7 | Phase 4: sync any remaining sgl-docs updates | Dev | As needed | +| 8 | Phase 6: final cutover when ready | Admin | Step 6 done | diff --git a/docs_new/favicon.png b/docs_new/favicon.png new file mode 100644 index 000000000..3e0fe3eda Binary files /dev/null and b/docs_new/favicon.png differ diff --git a/docs_new/fonts/Approach-Medium.woff2 b/docs_new/fonts/Approach-Medium.woff2 new file mode 100644 index 000000000..8fc25399e Binary files /dev/null and b/docs_new/fonts/Approach-Medium.woff2 differ diff --git a/docs_new/fonts/Approach-Regular.woff2 b/docs_new/fonts/Approach-Regular.woff2 new file mode 100644 index 000000000..2d57a149f Binary files /dev/null and b/docs_new/fonts/Approach-Regular.woff2 differ diff --git a/docs_new/images/dpa.png b/docs_new/images/dpa.png new file mode 100644 index 000000000..672e02218 Binary files /dev/null and b/docs_new/images/dpa.png differ diff --git a/docs_new/index.mdx b/docs_new/index.mdx new file mode 100644 index 000000000..be0eb1f3c --- /dev/null +++ b/docs_new/index.mdx @@ -0,0 +1,497 @@ +--- +title: Welcome to SGLang +description: High-performance serving framework for large language and multimodal models. +keywords: + - sglang + - llm serving + - multimodal + - inference runtime +mode: wide +--- + + + Star + + + Fork + + +

+ + + + Designed for low-latency, high-throughput inference with RadixAttention, prefix caching, and multi-GPU parallelism. + + + + Broad support for Llama, Qwen, DeepSeek, and more. Compatible with Hugging + Face and OpenAI APIs. + + + + Native support across Hardware Platforms + including NVIDIA, AMD, Intel Xeon, Google TPU, and Ascend NPU accelerators. + + + + Open-source with widespread adoption, powering 400k+ GPUs and integrated with major RL frameworks. + + + +SGLang powers large-scale production deployments, generating trillions of tokens each day across more than 400,000 GPUs worldwide. It is hosted under the non-profit open-source organization [LMSYS](https://lmsys.org/about/). + +--- + +## Get Started + +SGLang is an inference framework meant for production level serving. +It is designed to deliver low-latency and high-throughput inference across a wide range of setups, from a single GPU to large distributed clusters. + + + + Install SGLang with pip, from source, or via Docker on your preferred hardware platform. + + + + Launch your first model server and send requests in minutes with OpenAI-compatible APIs. + + + +## News and latest blogs + +{/* BEGIN_LMSYS_SGLANG_BLOG_CARDS */} + +{/* END_LMSYS_SGLANG_BLOG_CARDS */} + +--- + +## Learn more and join the community + +
+
+

+ Stay connected +

+
+
+ + + {" "} + Development roadmap + to follow current priorities and upcoming work. +
+
+ + + {" "} + Weekly public development meeting + to hear updates and join open discussions. +
+
+ + + {" "} + Slack + for questions, feedback, and community support. +
+
+ X Twitter + and + + + {" "} + LinkedIn + for project updates. +
+
+ + + {" "} + LMSYS blog + for release notes, benchmarks, and technical deep dives. +
+
+ + + {" "} + Learning materials + for blogs, slides, and videos. +
+
+
+
diff --git a/docs_new/logo/logo.png b/docs_new/logo/logo.png new file mode 100644 index 000000000..2a8bc258f Binary files /dev/null and b/docs_new/logo/logo.png differ diff --git a/docs_new/scripts/update_lmsys_sglang_blogs.py b/docs_new/scripts/update_lmsys_sglang_blogs.py new file mode 100755 index 000000000..d4623dc00 --- /dev/null +++ b/docs_new/scripts/update_lmsys_sglang_blogs.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Sync SGLang-related LMSYS blog cards into index.mdx.""" + +from __future__ import annotations + +import json +import os +import re +import urllib.request +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +INDEX_PATH = ROOT / "index.mdx" +OUTPUT_JSON_PATH = ROOT / "src" / "generated" / "lmsys_sglang_blogs.json" + +START_MARKER = "{/* BEGIN_LMSYS_SGLANG_BLOG_CARDS */}" +END_MARKER = "{/* END_LMSYS_SGLANG_BLOG_CARDS */}" + +LMSYS_BLOG_API_URL = ( + "https://api.github.com/repos/lm-sys/lm-sys.github.io/contents/blog" +) +LMSYS_BLOG_BASE_URL = "https://lmsys.org/blog" +LMSYS_BASE_URL = "https://lmsys.org" +DEFAULT_IMAGE_URL = "https://lmsys.org/social.png" + +MAX_CARDS = int(os.getenv("LMSYS_SGLANG_MAX_CARDS", "6")) +KEYWORDS = [ + "sglang", + "sgl-project/sglang", + "sgl-kernel", + "sglang-jax", + "sgl diffusion", + "sglang diffusion", +] + +FRONTMATTER_RE = re.compile(r"\A---\s*\n(.*?)\n---\s*\n?", flags=re.DOTALL) +HTML_IMG_RE = re.compile(r"]*\ssrc=[\"']([^\"']+)[\"']", flags=re.IGNORECASE) +MD_IMG_RE = re.compile(r"!\[[^\]]*]\(([^)]+)\)") + + +@dataclass +class BlogPost: + slug: str + title: str + url: str + image: str + date: str + + +def build_headers() -> dict[str, str]: + headers = { + "Accept": "application/vnd.github+json", + "User-Agent": "sgl-docs-lmsys-blog-sync", + } + token = os.getenv("GITHUB_TOKEN") + if token: + headers["Authorization"] = f"Bearer {token}" + return headers + + +def download_blog_sources() -> list[tuple[str, str]]: + # Fetch the directory listing for /blog only — no need to download the whole repo. + request = urllib.request.Request(LMSYS_BLOG_API_URL, headers=build_headers()) + with urllib.request.urlopen(request, timeout=60) as response: + items: list[dict] = json.loads(response.read()) + + sources: list[tuple[str, str]] = [] + for item in items: + if item.get("type") != "file" or not item.get("name", "").endswith(".md"): + continue + download_url = item.get("download_url") + if not download_url: + continue + raw_request = urllib.request.Request(download_url, headers=build_headers()) + with urllib.request.urlopen(raw_request, timeout=30) as raw_response: + content = raw_response.read().decode("utf-8", errors="replace") + sources.append((item["name"], content)) + + return sources + + +def split_frontmatter(content: str) -> tuple[dict[str, str], str]: + match = FRONTMATTER_RE.match(content) + if not match: + return {}, content + + frontmatter: dict[str, str] = {} + for raw_line in match.group(1).splitlines(): + line = raw_line.strip() + if not line or ":" not in line: + continue + + key, value = line.split(":", 1) + cleaned = value.strip() + if ( + (cleaned.startswith('"') and cleaned.endswith('"')) + or (cleaned.startswith("'") and cleaned.endswith("'")) + ) and len(cleaned) >= 2: + cleaned = cleaned[1:-1] + frontmatter[key.strip()] = cleaned + + return frontmatter, content[match.end() :] + + +def first_image_from_body(body: str) -> str | None: + markdown_match = MD_IMG_RE.search(body) + if markdown_match: + candidate = markdown_match.group(1).strip() + if candidate.startswith("<") and candidate.endswith(">"): + candidate = candidate[1:-1] + if " " in candidate: + candidate = candidate.split(" ", 1)[0] + return candidate + + html_match = HTML_IMG_RE.search(body) + if html_match: + return html_match.group(1).strip() + + return None + + +def to_absolute_url(url_or_path: str | None) -> str: + if not url_or_path: + return DEFAULT_IMAGE_URL + + value = url_or_path.strip() + if value.startswith(("http://", "https://")): + return value + if value.startswith("//"): + return f"https:{value}" + return f"{LMSYS_BASE_URL}/{value.lstrip('/')}" + + +def is_relevant(slug: str, title: str, body: str) -> bool: + searchable = f"{slug}\n{title}\n{body}".lower() + return any(keyword in searchable for keyword in KEYWORDS) + + +def parse_blog_post(filename: str, content: str) -> BlogPost | None: + if not filename.endswith(".md"): + return None + + slug = filename[:-3] + frontmatter, body = split_frontmatter(content) + + title = frontmatter.get("title", "").strip() or slug.replace("-", " ").title() + preview_img = frontmatter.get("previewImg") or first_image_from_body(body) + image = to_absolute_url(preview_img) + url = f"{LMSYS_BLOG_BASE_URL}/{slug}/" + date = frontmatter.get("date", "").strip() or slug[:10] + + if not is_relevant(slug=slug, title=title, body=body): + return None + + return BlogPost(slug=slug, title=title, url=url, image=image, date=date) + + +def render_cards(posts: list[BlogPost]) -> str: + if not posts: + return "No relevant LMSYS blog posts matched the current sync keywords." + + lines = [ + '
', + " ", + ] + for post in posts: + safe_title = json.dumps(post.title) + safe_url = json.dumps(post.url) + safe_image = json.dumps(post.image) + lines.extend( + [ + " ", + " ", + " ", + "
", + '
', + " ", + f" {{{safe_title}}}", + "

", + " ", + f" {{{json.dumps(post.date)}}}", + "

", + "
", + " ", + ] + ) + lines.extend([" ", ""]) + return "\n".join(lines) + + +def replace_generated_block(index_text: str, generated_cards: str) -> str: + pattern = re.compile( + rf"{re.escape(START_MARKER)}.*?{re.escape(END_MARKER)}", + flags=re.DOTALL, + ) + replacement = f"{START_MARKER}\n{generated_cards}\n{END_MARKER}" + updated_text, replacements = pattern.subn( + lambda _match: replacement, index_text, count=1 + ) + if replacements != 1: + raise RuntimeError( + f"Could not find exactly one marker block in {INDEX_PATH.name}. " + f"Expected markers: {START_MARKER} ... {END_MARKER}" + ) + return updated_text + + +def write_metadata(posts: list[BlogPost], total_blog_files: int) -> None: + OUTPUT_JSON_PATH.parent.mkdir(parents=True, exist_ok=True) + payload = { + "generatedAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), + "sourceRepo": "https://github.com/lm-sys/lm-sys.github.io/tree/main/blog", + "keywords": KEYWORDS, + "maxCards": MAX_CARDS, + "totalBlogFilesScanned": total_blog_files, + "cardsPublished": len(posts), + "posts": [asdict(post) for post in posts], + } + OUTPUT_JSON_PATH.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8") + + +def main() -> None: + sources = download_blog_sources() + relevant_posts: list[BlogPost] = [] + + for filename, content in sources: + post = parse_blog_post(filename=filename, content=content) + if post is not None: + relevant_posts.append(post) + + relevant_posts.sort(key=lambda post: post.slug, reverse=True) + selected_posts = relevant_posts[:MAX_CARDS] + + generated_cards = render_cards(selected_posts) + current_index = INDEX_PATH.read_text(encoding="utf-8") + updated_index = replace_generated_block( + index_text=current_index, generated_cards=generated_cards + ) + + if updated_index != current_index: + INDEX_PATH.write_text(updated_index, encoding="utf-8") + + write_metadata(posts=selected_posts, total_blog_files=len(sources)) + print( + "Scanned " + f"{len(sources)} blog files, matched {len(relevant_posts)} posts, " + f"published {len(selected_posts)} cards." + ) + + +if __name__ == "__main__": + main() diff --git a/docs_new/sglang-diffusion/intro.mdx b/docs_new/sglang-diffusion/intro.mdx new file mode 100644 index 000000000..c38b7650d --- /dev/null +++ b/docs_new/sglang-diffusion/intro.mdx @@ -0,0 +1,65 @@ +--- +title: SGLang Diffusion +description: Accelerated image and video generation with diffusion models. +--- + +SGLang Diffusion is an inference framework for accelerated image and video generation using diffusion models. It provides an end-to-end unified pipeline with optimized kernels and an efficient scheduler loop. + +## Key features + +* **Broad model support:** Wan series, FastWan series, Hunyuan, Qwen-Image, Qwen-Image-Edit, Flux, Z-Image, GLM-Image, and more +* **Fast inference:** optimized kernels, efficient scheduler loop, and Cache-DiT acceleration +* **Ease of use:** OpenAI-compatible API, CLI, and Python SDK +* **Multi-platform:** NVIDIA GPUs (H100, H200, A100, B200, 4090), AMD GPUs (MI300X, MI325X), and Ascend NPU (A2, A3) + +## Quick start + +1. **Install SGLang Diffusion** + +```bash +uv pip install "sglang[diffusion]" --prerelease=allow +``` + +See the [installation guide](../docs/sglang-diffusion/installation) for more installation methods and ROCm-specific instructions. + +2. **Run a one-off generation** + +```bash +sglang generate --model-path Qwen/Qwen-Image \ + --prompt "A beautiful sunset over the mountains" \ + --save-output +``` + +3. **Serve with the OpenAI-compatible API** + +```bash +sglang serve --model-path Qwen/Qwen-Image --port 30010 +``` + +## CLI quick reference + +### Generate (one-off generation) + +```bash +sglang generate --model-path --prompt "" --save-output +``` + +### Serve (HTTP server) + +```bash +sglang serve --model-path --port 30010 +``` + +### Enable Cache-DiT acceleration + +```bash +SGLANG_CACHE_DIT_ENABLED=true sglang generate --model-path --prompt "" +``` + +## References + +* [SGLang GitHub](https://github.com/sgl-project/sglang) +* [Cache-DiT](https://github.com/vipshop/cache-dit) +* [FastVideo](https://github.com/hao-ai-lab/FastVideo) +* [xDiT](https://github.com/xdit-project/xDiT) +* [Diffusers](https://github.com/huggingface/diffusers) diff --git a/docs_new/src/generated/lmsys_sglang_blogs.json b/docs_new/src/generated/lmsys_sglang_blogs.json new file mode 100644 index 000000000..138a3a287 --- /dev/null +++ b/docs_new/src/generated/lmsys_sglang_blogs.json @@ -0,0 +1,59 @@ +{ + "generatedAt": "2026-04-07T00:14:40.777335Z", + "sourceRepo": "https://github.com/lm-sys/lm-sys.github.io/tree/main/blog", + "keywords": [ + "sglang", + "sgl-project/sglang", + "sgl-kernel", + "sglang-jax", + "sgl diffusion", + "sglang diffusion" + ], + "maxCards": 6, + "totalBlogFilesScanned": 80, + "cardsPublished": 6, + "posts": [ + { + "slug": "2026-03-25-gtc2026", + "title": "Highlights of SGLang at NVIDIA GTC 2026", + "url": "https://lmsys.org/blog/2026-03-25-gtc2026/", + "image": "https://lmsys.org/images/blog/gtc2026/happyhour-crowd.jpg", + "date": "March 31, 2026" + }, + { + "slug": "2026-03-25-eep-partial-failure-tolerance", + "title": "Elastic EP in SGLang: Achieving Partial Failure Tolerance for DeepSeek MoE Deployments", + "url": "https://lmsys.org/blog/2026-03-25-eep-partial-failure-tolerance/", + "image": "https://lmsys.org/images/blog/eep-partial-failure-tolerance/figure.png", + "date": "March 25, 2026" + }, + { + "slug": "2026-03-17-rocm-miles-rl-amd", + "title": "ROCm Support for Miles: Large-Scale RL Post-Training on AMD Instinct\u2122 GPUs", + "url": "https://lmsys.org/blog/2026-03-17-rocm-miles-rl-amd/", + "image": "https://lmsys.org/images/blog/rocm_miles_rl/fig_1.png", + "date": "March 17, 2026" + }, + { + "slug": "2026-03-11-run-nvidia-nemotron-3-super", + "title": "SGLang Adds Day-0 Support for NVIDIA Nemotron 3 Super for building High-Efficiency Multi-Agent Systems", + "url": "https://lmsys.org/blog/2026-03-11-run-nvidia-nemotron-3-super/", + "image": "https://lmsys.org/images/blog/nemotron-3-super/figure_1.svg", + "date": "March 11, 2026" + }, + { + "slug": "2026-02-20-gb300-inferencex", + "title": "Unlocking 25x Inference Performance with SGLang on NVIDIA GB300 NVL72", + "url": "https://lmsys.org/blog/2026-02-20-gb300-inferencex/", + "image": "https://lmsys.org/images/blog/gb300_inferencex/img-1.png", + "date": "February 20, 2026" + }, + { + "slug": "2026-02-19-gb300-longctx", + "title": "Deploying DeepSeek on GB300 NVL72: Big Wins in Long-Context Inference", + "url": "https://lmsys.org/blog/2026-02-19-gb300-longctx/", + "image": "https://lmsys.org/images/blog/gb300_longctx/cover.png", + "date": "February 19, 2026" + } + ] +} diff --git a/docs_new/src/snippets/autoregressive/deepseek-math-v2-deployment.jsx b/docs_new/src/snippets/autoregressive/deepseek-math-v2-deployment.jsx new file mode 100644 index 000000000..5906d7877 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/deepseek-math-v2-deployment.jsx @@ -0,0 +1,359 @@ +export const DeepSeekMathV2Deployment = () => { + const modelFamily = 'deepseek-ai'; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', subtitle: '183GB', default: true }, + { id: 'b300', label: 'B300', subtitle: '275GB', default: false } + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser deepseek-r1' : null + }, + dpattention: { + name: 'dpattention', + title: 'DP Attention', + items: [ + { id: 'disabled', label: 'Disabled', subtitle: 'Low Latency', default: true }, + { id: 'enabled', label: 'Enabled', subtitle: 'High Throughput', default: false } + ], + commandRule: null + } + }; + + // BF16 only, B200/B300 tp=8 + const modelConfigs = { + b200: { bf16: { tp: 8, mem: null } }, + b300: { bf16: { tp: 8, mem: null } } + }; + + const generateCommand = (values) => { + const { hardware } = values; + + const modelName = `${modelFamily}/DeepSeek-Math-V2`; + + const hwConfig = modelConfigs[hardware].bf16; + const tpValue = hwConfig.tp; + const memFraction = hwConfig.mem; + + let cmd = 'sglang serve --model-path'; + cmd += ` ${modelName}`; + + // TP setting + cmd += ` \\\n --tp ${tpValue}`; + + // DP Attention: --dp matches --tp + if (values.dpattention === 'enabled') { + cmd += ` \\\n --dp ${tpValue} \\\n --enable-dp-attention`; + } + + // EP setting (commonly matches tp for MoE models) + cmd += ` \\\n --ep ${tpValue}`; + + // Apply commandRule from all options + Object.entries(options).forEach(([key, option]) => { + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) { + cmd += ` \\\n ${rule}`; + } + } + }); + + // Memory fraction based on hardware and quantization (skip for 8-card configs) + if (memFraction) { + cmd += ` \\\n --mem-fraction-static ${memFraction}`; + } + + cmd += ' \\\n --host 0.0.0.0 \\\n --port 30000'; + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/deepseek-ocr-deployment.jsx b/docs_new/src/snippets/autoregressive/deepseek-ocr-deployment.jsx new file mode 100644 index 000000000..ce2b70b64 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/deepseek-ocr-deployment.jsx @@ -0,0 +1,168 @@ +export const DeepSeekOCRDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'fp16', label: 'FP16', default: true } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false }, + { id: 'ep', label: 'EP', subtitle: 'Expert Parallel', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode - prioritize page theme over system preference + useEffect(() => { + const checkDarkMode = () => { + // Check Mintlify's theme class on html element + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization, strategy } = values; + const strategyArray = Array.isArray(strategy) ? strategy : []; + + // Validation checks + // Check MI300X compatibility - MI300X + DeepSeek-OCR only supports FP16 quantization + if ((hardware === 'mi300x') && quantization !== 'fp16') { + return '# Error: MI300X + DeepSeek-OCR only supports FP16 quantization\n# Please select FP16 quantization'; + } + + // Model path + let modelPath = 'deepseek-ai/DeepSeek-OCR'; + + let cmd = 'python3 -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelPath}`; + cmd += ` \\\n --dtype float16`; + + // TP strategy + if (strategyArray.includes('tp')) { + cmd += ` \\\n --tp 1`; + } + + // DP strategy + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp 1 \\\n --enable-dp-attention`; + } + + // EP strategy + if (strategyArray.includes('ep')) { + cmd += ` \\\n --ep 1`; + } + + cmd += ` \\\n --enable-symm-mem # Optional: improves performance, but may be unstable`; + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/deepseek-ocr-v2-deployment.jsx b/docs_new/src/snippets/autoregressive/deepseek-ocr-v2-deployment.jsx new file mode 100644 index 000000000..caf66e233 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/deepseek-ocr-v2-deployment.jsx @@ -0,0 +1,342 @@ +export const DeepSeekOCR2Deployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false }, + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'fp16', label: 'FP16', default: true }, + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false }, + { id: 'ep', label: 'EP', subtitle: 'Expert Parallel', default: false } + ] + }, + }; + + const generateCommand = (values) => { + const { hardware, strategy } = values; + + const strategyArray = Array.isArray(strategy) ? strategy : []; + + let modelPath = 'deepseek-ai/DeepSeek-OCR-2'; + + let cmd = 'sglang serve \\\n'; + cmd += ` --model-path ${modelPath}`; + cmd += ` \\\n --enable-multimodal`; + + if (strategyArray.includes('tp')) { + cmd += ` \\\n --tp 1`; + } + + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp 1 \\\n --enable-dp-attention`; + } + + if (strategyArray.includes('ep')) { + cmd += ` \\\n --ep 1`; + } + + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd += ` \\\n --attention-backend triton` + ` \\\n --trust-remote-code`; + } + + cmd += ` \\\n --host 0.0.0.0 \\\n --port 30000`; + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/deepseek-r1-advanced-deployment.jsx b/docs_new/src/snippets/autoregressive/deepseek-r1-advanced-deployment.jsx new file mode 100644 index 000000000..b342d6b84 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/deepseek-r1-advanced-deployment.jsx @@ -0,0 +1,856 @@ +export const DeepSeekR1AdvancedDeployment = () => { +const lookupData = { + "model": "deepseek-r1", + "version": "v0.5.6", + "ui_options": { + "hardware": [ + { + "id": "b200", + "label": "B200", + "default": true + }, + { + "id": "h200", + "label": "H200", + "default": false + }, + { + "id": "mi300x", + "label": "MI300X", + "default": false + }, + { + "id": "mi325x", + "label": "MI325X", + "default": false + }, + { + "id": "mi355x", + "label": "MI355X", + "default": false + } + ], + "quantization": [ + { + "id": "fp8", + "label": "FP8", + "default": true + }, + { + "id": "fp4", + "label": "FP4", + "default": false + } + ], + "scenario": [ + { + "id": "low-latency", + "label": "Low Latency", + "subtitle": "Concurrency 4-8", + "default": true + }, + { + "id": "high-throughput", + "label": "High Throughput", + "subtitle": "Concurrency 16-128", + "default": false + } + ], + "gpu_count": [ + { + "id": 4, + "label": "4 GPUs", + "default": false + }, + { + "id": 8, + "label": "8 GPUs", + "default": true + } + ] + }, + "configs": [ + { + "hardware": "b200", + "quantization": "fp4", + "gpu_count": 4, + "scenario": "low-latency", + "parameters": { + "model_path": "nvidia/DeepSeek-R1-0528-FP4-v2", + "tensor_parallel_size": 4, + "cuda_graph_max_bs": 256, + "max_running_requests": 256, + "mem_fraction_static": 0.85, + "ep_size": 4, + "scheduler_recv_interval": 10, + "enable_symm_mem": true, + "stream_interval": 10 + } + }, + { + "hardware": "b200", + "quantization": "fp4", + "gpu_count": 4, + "scenario": "high-throughput", + "parameters": { + "model_path": "nvidia/DeepSeek-R1-0528-FP4-v2", + "tensor_parallel_size": 4, + "cuda_graph_max_bs": 256, + "max_running_requests": 256, + "mem_fraction_static": 0.85, + "ep_size": 4, + "scheduler_recv_interval": 30, + "enable_symm_mem": true, + "stream_interval": 10 + } + }, + { + "hardware": "b200", + "quantization": "fp4", + "gpu_count": 8, + "scenario": "low-latency", + "parameters": { + "model_path": "nvidia/DeepSeek-R1-0528-FP4-v2", + "tensor_parallel_size": 8, + "cuda_graph_max_bs": 256, + "max_running_requests": 256, + "mem_fraction_static": 0.85, + "kv_cache_dtype": "fp8_e4m3", + "chunked_prefill_size": 16384, + "ep_size": 8, + "scheduler_recv_interval": 10, + "enable_symm_mem": true, + "stream_interval": 10 + } + }, + { + "hardware": "b200", + "quantization": "fp4", + "gpu_count": 8, + "scenario": "high-throughput", + "parameters": { + "model_path": "nvidia/DeepSeek-R1-0528-FP4-v2", + "tensor_parallel_size": 8, + "cuda_graph_max_bs": 256, + "max_running_requests": 256, + "mem_fraction_static": 0.85, + "kv_cache_dtype": "fp8_e4m3", + "chunked_prefill_size": 16384, + "ep_size": 8, + "scheduler_recv_interval": 30, + "enable_symm_mem": true, + "stream_interval": 10 + } + }, + { + "hardware": "b200", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "low-latency", + "parameters": { + "env_vars": "SGLANG_ENABLE_JIT_DEEPGEMM=false", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "tensor_parallel_size": 8, + "cuda_graph_max_bs": 128, + "max_running_requests": 128, + "mem_fraction_static": 0.82, + "kv_cache_dtype": "fp8_e4m3", + "chunked_prefill_size": 32768, + "max_prefill_tokens": 32768, + "scheduler_recv_interval": 10, + "stream_interval": 30, + "fp8_gemm_backend": "flashinfer_trtllm" + } + }, + { + "hardware": "b200", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "high-throughput", + "parameters": { + "env_vars": "SGLANG_ENABLE_JIT_DEEPGEMM=false", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "tensor_parallel_size": 8, + "cuda_graph_max_bs": 128, + "max_running_requests": 128, + "mem_fraction_static": 0.82, + "kv_cache_dtype": "fp8_e4m3", + "chunked_prefill_size": 32768, + "max_prefill_tokens": 32768, + "scheduler_recv_interval": 30, + "stream_interval": 30, + "fp8_gemm_backend": "flashinfer_trtllm" + } + }, + { + "hardware": "h200", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "low-latency", + "parameters": { + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "disable_radix_cache": true, + "max_running_requests": 256, + "cuda_graph_max_bs": 256, + "chunked_prefill_size": 32768, + "max_prefill_tokens": 32768, + "mem_fraction_static": 0.82, + "attention_backend": "flashinfer", + "stream_interval": 10, + "decode_log_interval": 1 + } + }, + { + "hardware": "h200", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "high-throughput", + "parameters": { + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "disable_radix_cache": true, + "max_running_requests": 512, + "cuda_graph_max_bs": 512, + "chunked_prefill_size": 32768, + "max_prefill_tokens": 32768, + "mem_fraction_static": 0.82, + "attention_backend": "flashinfer", + "stream_interval": 10, + "decode_log_interval": 1 + } + }, + { + "hardware": "mi300x", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "low-latency", + "parameters": { + "env_vars": "SGLANG_USE_AITER=1 SGLANG_AITER_MLA_PERSIST=1", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "mem_fraction_static": 0.8, + "cuda_graph_max_bs": 128, + "chunked_prefill_size": 131072, + "num_continuous_decode_steps": 4, + "max_prefill_tokens": 131072, + "kv_cache_dtype": "fp8_e4m3", + "attention_backend": "aiter", + "disable_radix_cache": true + } + }, + { + "hardware": "mi300x", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "high-throughput", + "parameters": { + "env_vars": "SGLANG_USE_AITER=1 SGLANG_AITER_MLA_PERSIST=1", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "mem_fraction_static": 0.8, + "cuda_graph_max_bs": 512, + "chunked_prefill_size": 131072, + "num_continuous_decode_steps": 4, + "max_prefill_tokens": 131072, + "kv_cache_dtype": "fp8_e4m3", + "attention_backend": "aiter", + "disable_radix_cache": true + } + }, + { + "hardware": "mi325x", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "low-latency", + "parameters": { + "env_vars": "SGLANG_USE_AITER=1 SGLANG_AITER_MLA_PERSIST=1", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "mem_fraction_static": 0.8, + "cuda_graph_max_bs": 128, + "chunked_prefill_size": 131072, + "num_continuous_decode_steps": 4, + "max_prefill_tokens": 131072, + "kv_cache_dtype": "fp8_e4m3", + "attention_backend": "aiter", + "disable_radix_cache": true + } + }, + { + "hardware": "mi325x", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "high-throughput", + "parameters": { + "env_vars": "SGLANG_USE_AITER=1 SGLANG_AITER_MLA_PERSIST=1", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "mem_fraction_static": 0.8, + "cuda_graph_max_bs": 512, + "chunked_prefill_size": 131072, + "num_continuous_decode_steps": 4, + "max_prefill_tokens": 131072, + "kv_cache_dtype": "fp8_e4m3", + "attention_backend": "aiter", + "disable_radix_cache": true + } + }, + { + "hardware": "mi355x", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "low-latency", + "parameters": { + "env_vars": "SGLANG_USE_AITER=1 RCCL_MSCCL_ENABLE=0 ROCM_QUICK_REDUCE_QUANTIZATION=INT4", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "mem_fraction_static": 0.8, + "disable_radix_cache": true, + "chunked_prefill_size": 196608, + "num_continuous_decode_steps": 4, + "max_prefill_tokens": 196608, + "cuda_graph_max_bs": 128, + "attention_backend": "aiter", + "kv_cache_dtype": "fp8_e4m3" + } + }, + { + "hardware": "mi355x", + "quantization": "fp8", + "gpu_count": 8, + "scenario": "high-throughput", + "parameters": { + "env_vars": "SGLANG_USE_AITER=1 RCCL_MSCCL_ENABLE=0 ROCM_QUICK_REDUCE_QUANTIZATION=INT4", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "mem_fraction_static": 0.8, + "disable_radix_cache": true, + "chunked_prefill_size": 196608, + "num_continuous_decode_steps": 4, + "max_prefill_tokens": 196608, + "cuda_graph_max_bs": 512, + "attention_backend": "aiter", + "kv_cache_dtype": "fp8_e4m3" + } + }, + { + "hardware": "mi355x", + "quantization": "fp4", + "gpu_count": 8, + "scenario": "low-latency", + "parameters": { + "env_vars": "SGLANG_USE_AITER=1 ROCM_QUICK_REDUCE_QUANTIZATION=INT4", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "mem_fraction_static": 0.8, + "disable_radix_cache": true, + "chunked_prefill_size": 196608, + "num_continuous_decode_steps": 4, + "max_prefill_tokens": 196608, + "cuda_graph_max_bs": 128, + "attention_backend": "aiter", + "kv_cache_dtype": "fp8_e4m3" + } + }, + { + "hardware": "mi355x", + "quantization": "fp4", + "gpu_count": 8, + "scenario": "high-throughput", + "parameters": { + "env_vars": "SGLANG_USE_AITER=1 ROCM_QUICK_REDUCE_QUANTIZATION=INT4", + "model_path": "deepseek-ai/DeepSeek-R1-0528", + "trust_remote_code": true, + "tensor_parallel_size": 8, + "mem_fraction_static": 0.8, + "disable_radix_cache": true, + "chunked_prefill_size": 196608, + "num_continuous_decode_steps": 4, + "max_prefill_tokens": 196608, + "cuda_graph_max_bs": 512, + "attention_backend": "aiter", + "kv_cache_dtype": "fp8_e4m3" + } + } + ], + "validation": [ + { + "hardware": "h200", + "quantization": "fp4", + "error": "FP4 is only available for B200 hardware. Please select FP8 quantization." + } + ] +}; + +const fieldToFlag = { + model_path: 'model-path', + trust_remote_code: 'trust-remote-code', + tensor_parallel_size: 'tp', + data_parallel_size: 'dp', + ep_size: 'ep-size', + cuda_graph_max_bs: 'cuda-graph-max-bs', + max_running_requests: 'max-running-requests', + mem_fraction_static: 'mem-fraction-static', + kv_cache_dtype: 'kv-cache-dtype', + chunked_prefill_size: 'chunked-prefill-size', + max_prefill_tokens: 'max-prefill-tokens', + enable_flashinfer_allreduce_fusion: 'enable-flashinfer-allreduce-fusion', + scheduler_recv_interval: 'scheduler-recv-interval', + enable_symm_mem: 'enable-symm-mem', + disable_radix_cache: 'disable-radix-cache', + attention_backend: 'attention-backend', + moe_runner_backend: 'moe-runner-backend', + stream_interval: 'stream-interval', + quantization: 'quantization', + decode_log_interval: 'decode-log-interval', + fp8_gemm_backend: 'fp8-gemm-backend', + num_continuous_decode_steps: 'num-continuous-decode-steps', +}; + +const findConfig = (hardware, quantization, gpuCount, scenario) => { + const match = lookupData.configs.find((entry) => { + const hardwareMatch = entry.hardware === hardware; + const quantizationMatch = entry.quantization === quantization; + const gpuCountMatch = !entry.gpu_count || entry.gpu_count === Number.parseInt(gpuCount, 10); + const scenarioMatch = entry.scenario === scenario; + return hardwareMatch && quantizationMatch && gpuCountMatch && scenarioMatch; + }); + return match ? match.parameters : null; +}; + +const getAvailableGpuCounts = (hardware, quantization) => { + const entries = lookupData.configs.filter( + (entry) => entry.hardware === hardware && entry.quantization === quantization + ); + const gpuCounts = [...new Set(entries.map((entry) => entry.gpu_count))].filter(Boolean); + return gpuCounts.length > 0 ? gpuCounts.sort((a, b) => a - b) : [8]; +}; + +const generateCommandFromConfig = (config) => { + if (!config) { + return '# Error: Configuration not found'; + } + + let command = ''; + if (config.env_vars) { + command = `${config.env_vars} `; + } + + command += 'python3 -m sglang.launch_server \\\n'; + command += ` --model-path ${config.model_path}`; + + for (const [key, value] of Object.entries(config)) { + if (key === 'model_path' || key === 'env_vars') { + continue; + } + + const flagName = fieldToFlag[key]; + if (!flagName) { + continue; + } + + if (typeof value === 'boolean') { + if (value) { + command += ` \\\n --${flagName}`; + } + continue; + } + + command += ` \\\n --${flagName} ${value}`; + } + + return command; +}; + +const validateSelection = (hardware, quantization) => { + for (const rule of lookupData.validation || []) { + const hardwareMatch = Array.isArray(rule.hardware) + ? rule.hardware.includes(hardware) + : rule.hardware === hardware; + const quantizationMatch = Array.isArray(rule.quantization) + ? rule.quantization.includes(quantization) + : rule.quantization === quantization; + if (hardwareMatch && quantizationMatch) { + return rule.error; + } + } + return null; +}; + +const resolveItems = (option, values) => + typeof option.getDynamicItems === 'function' ? option.getDynamicItems(values) : option.items; + + const uiOptions = lookupData.ui_options; + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: uiOptions.hardware + .filter((option) => + ['b200', 'h200', 'mi300x', 'mi325x', 'mi355x'].includes(option.id) + ) + .map((option) => ({ + id: option.id, + label: option.label, + default: option.id === 'b200', + })), + }, + quantization: { + name: 'quantization', + title: 'Quantization', + getDynamicItems: (values) => + uiOptions.quantization.map((option) => { + const fp4Disabled = ['h200', 'mi300x', 'mi325x'].includes(values.hardware) && option.id === 'fp4'; + return { + id: option.id, + label: option.label, + default: + ['h200', 'mi300x', 'mi325x'].includes(values.hardware) + ? option.id === 'fp8' + : option.default, + disabled: fp4Disabled, + disabledReason: fp4Disabled ? 'FP4 not supported on H200, MI300X, MI325X' : '', + }; + }), + }, + gpuCount: { + name: 'gpuCount', + title: 'GPU Count', + getDynamicItems: (values) => { + const availableGpuCounts = getAvailableGpuCounts(values.hardware, values.quantization); + const allGpuCounts = uiOptions.gpu_count.map((option) => + typeof option.id === 'number' ? option.id : Number.parseInt(option.id, 10) + ); + const defaultGpuCount = Math.max(...availableGpuCounts); + + return allGpuCounts.map((count) => ({ + id: String(count), + label: `${count} GPUs`, + default: count === defaultGpuCount, + disabled: !availableGpuCounts.includes(count), + disabledReason: availableGpuCounts.includes(count) + ? '' + : `${count} GPUs not available for ${values.hardware.toUpperCase()} ${values.quantization.toUpperCase()}`, + })); + }, + }, + scenario: { + name: 'scenario', + title: 'Scenario', + items: uiOptions.scenario.map((option) => ({ + id: option.id, + label: option.label, + subtitle: option.subtitle, + default: option.default, + })), + }, + }; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + const items = resolveItems(option, initialState) || []; + const fallback = + items.find((item) => item.default && !item.disabled) || + items.find((item) => !item.disabled) || + items[0]; + initialState[key] = fallback ? fallback.id : ''; + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => { + const next = { ...prev, [optionName]: value }; + for (const [key, option] of Object.entries(options)) { + if (typeof option.getDynamicItems !== 'function') { + continue; + } + const items = option.getDynamicItems(next); + const current = items.find((item) => item.id === next[key]); + if (!current || current.disabled) { + const fallback = + items.find((item) => item.default && !item.disabled) || + items.find((item) => !item.disabled); + if (fallback) { + next[key] = fallback.id; + } + } + } + return next; + }); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const generateCommand = (vals) => { + const validationError = validateSelection(vals.hardware, vals.quantization); + if (validationError) { + return `# Error: ${validationError}`; + } + + const config = findConfig( + vals.hardware, + vals.quantization, + vals.gpuCount || '8', + vals.scenario + ); + if (!config) { + return `# Error: No configuration found for: +# Hardware: ${vals.hardware} +# Quantization: ${vals.quantization} +# GPU Count: ${vals.gpuCount} +# Scenario: ${vals.scenario} +# This combination is not yet supported.`; + } + + return generateCommandFromConfig(config); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} + +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/deepseek-r1-basic-deployment.jsx b/docs_new/src/snippets/autoregressive/deepseek-r1-basic-deployment.jsx new file mode 100644 index 000000000..d95ca5a2d --- /dev/null +++ b/docs_new/src/snippets/autoregressive/deepseek-r1-basic-deployment.jsx @@ -0,0 +1,394 @@ +export const DeepSeekR1BasicDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h100', label: 'H100', default: false }, + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: true }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false }, + ], + }, + quantization: { + name: 'quantization', + title: 'Quantization', + getDynamicItems: (values) => { + const fp4Disabled = values.hardware === 'h100' || values.hardware === 'mi300x'; + return [ + { id: 'fp8', label: 'FP8', default: true }, + { + id: 'fp4', + label: 'FP4', + default: false, + disabled: fp4Disabled, + disabledReason: 'H100 and MI300X only support FP8 quantization', + }, + ]; + }, + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false }, + { id: 'ep', label: 'EP', subtitle: 'Expert Parallel', default: false }, + { id: 'mtp', label: 'MTP', subtitle: 'Multi-token Prediction', default: false }, + ], + }, + thinking: { + name: 'thinking', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false }, + ], + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false }, + ], + }, + }; + + const resolveItems = (option, values) => + typeof option.getDynamicItems === 'function' ? option.getDynamicItems(values) : option.items; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + continue; + } + + const items = resolveItems(option, initialState) || []; + const fallback = + items.find((item) => item.default && !item.disabled) || + items.find((item) => !item.disabled) || + items[0]; + initialState[key] = fallback ? fallback.id : ''; + } + return initialState; + }; + + const generateCommand = (values) => { + const { hardware, quantization, strategy, thinking, toolcall } = values; + const strategyValues = Array.isArray(strategy) ? strategy : []; + + if ((hardware === 'h100' || hardware === 'mi300x') && quantization === 'fp4') { + return '# Error: H100 and MI300X only support FP8 quantization'; + } + + const modelPath = + quantization === 'fp4' + ? 'nvidia/DeepSeek-R1-0528-FP4-v2' + : 'deepseek-ai/DeepSeek-R1-0528'; + + let command = 'python3 -m sglang.launch_server \\\n'; + command += ` --model-path ${modelPath}`; + + if (strategyValues.includes('tp')) { + command += ' \\\n --tp 8'; + } + if (strategyValues.includes('dp')) { + command += ' \\\n --dp 8 \\\n --enable-dp-attention'; + } + if (strategyValues.includes('ep')) { + command += ' \\\n --ep 8'; + } + if (strategyValues.includes('mtp')) { + command = 'SGLANG_ENABLE_SPEC_V2=1 ' + command; + command += + ' \\\n --speculative-algorithm EAGLE' + + ' \\\n --speculative-num-steps 3' + + ' \\\n --speculative-eagle-topk 1' + + ' \\\n --speculative-num-draft-tokens 4'; + } + + command += ' \\\n --enable-symm-mem # Optional: improves performance, but may be unstable'; + + if (hardware === 'b200' || (hardware === 'mi355x' && quantization === 'fp8')) { + command += + ' \\\n --kv-cache-dtype fp8_e4m3 # Optional: enables fp8 kv cache and fp8 attention kernels to improve performance'; + } + + if (thinking === 'enabled') { + command += ' \\\n --reasoning-parser deepseek-r1'; + } + if (toolcall === 'enabled') { + command += + ' \\\n --tool-call-parser deepseekv3' + + ' \\\n --chat-template examples/chat_template/tool_chat_template_deepseekr1.jinja'; + } + + return command; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => { + const next = { ...prev, [optionName]: value }; + if (optionName === 'hardware') { + const quantizationItems = resolveItems(options.quantization, next); + const current = quantizationItems.find((item) => item.id === next.quantization); + if (!current || current.disabled) { + const fallback = + quantizationItems.find((item) => item.default && !item.disabled) || + quantizationItems.find((item) => !item.disabled); + if (fallback) { + next.quantization = fallback.id; + } + } + } + return next; + }); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} + +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/deepseek-v3-deployment.jsx b/docs_new/src/snippets/autoregressive/deepseek-v3-deployment.jsx new file mode 100644 index 000000000..8615b01be --- /dev/null +++ b/docs_new/src/snippets/autoregressive/deepseek-v3-deployment.jsx @@ -0,0 +1,186 @@ +export const DeepSeekV3Deployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h100', label: 'H100', default: false }, + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: true }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'fp8', label: 'FP8', default: true }, + { id: 'fp4', label: 'FP4', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false }, + { id: 'ep', label: 'EP', subtitle: 'Expert Parallel', default: false }, + { id: 'mtp', label: 'MTP', subtitle: 'Multi-token Prediction', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode - prioritize page theme over system preference + useEffect(() => { + const checkDarkMode = () => { + // Check Mintlify's theme class on html element + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization, strategy, thinking, toolcall } = values; + const strategyArray = Array.isArray(strategy) ? strategy : []; + + // Validation - H100/H200/MI300X/MI325X only supports FP8 + if (['h100', 'h200', 'mi300x', 'mi325x'].includes(hardware) && quantization === 'fp4') { + return '# Error: This hardware only supports FP8 quantization\n# Please select FP8 quantization or use B200/MI355X hardware'; + } + + const modelPath = quantization === 'fp4' ? 'nvidia/DeepSeek-V3-0324-NVFP4' : 'deepseek-ai/DeepSeek-V3'; + + let cmd = 'python3 -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelPath}`; + + if (strategyArray.includes('tp')) cmd += ' \\\n --tp 8'; + if (strategyArray.includes('dp')) cmd += ' \\\n --dp 8 \\\n --enable-dp-attention'; + if (strategyArray.includes('ep')) cmd += ' \\\n --ep 8'; + if (strategyArray.includes('mtp')) { + cmd = 'SGLANG_ENABLE_SPEC_V2=1 ' + cmd; + cmd += ' \\\n --speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4'; + } + + cmd += ' \\\n --enable-symm-mem # Optional: improves performance, but may be unstable'; + + if (hardware === 'b200') { + cmd += ' \\\n --kv-cache-dtype fp8_e4m3 # Optional: enables fp8 kv cache and fp8 attention kernels'; + } + + if (thinking === 'enabled') cmd += ' \\\n --reasoning-parser deepseek-v3'; + if (toolcall === 'enabled') cmd += ' \\\n --tool-call-parser deepseekv3 \\\n --chat-template examples/chat_template/tool_chat_template_deepseekv3.jinja'; + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/deepseek-v31-deployment.jsx b/docs_new/src/snippets/autoregressive/deepseek-v31-deployment.jsx new file mode 100644 index 000000000..b09fa61f8 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/deepseek-v31-deployment.jsx @@ -0,0 +1,197 @@ +export const DeepSeekV31Deployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelname: { + name: 'modelname', + title: 'Model Name', + items: [ + { id: 'v31', label: 'DeepSeek-V3.1', default: true }, + { id: 'v31terminus', label: 'DeepSeek-V3.1-Terminus', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', default: true, required: true }, + { id: 'dp', label: 'DP attention', default: false }, + { id: 'ep', label: 'EP', default: false }, + { id: 'mtp', label: 'Multi-token Prediction', default: false } + ] + }, + reasoningParser: { + name: 'reasoningParser', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode - prioritize page theme over system preference + useEffect(() => { + const checkDarkMode = () => { + // Check Mintlify's theme class on html element + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, modelname, strategy, reasoningParser, toolcall } = values; + const strategyArray = Array.isArray(strategy) ? strategy : []; + + // Model name mapping + const modelMap = { + 'v31': 'DeepSeek-V3.1', + 'v31terminus': 'DeepSeek-V3.1-Terminus' + }; + + const modelName = `deepseek-ai/${modelMap[modelname]}`; + + let cmd = 'python3 -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelName}`; + + // TP is mandatory + cmd += ` \\\n --tp 8`; + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp 8 \\\n --enable-dp-attention`; + } + if (strategyArray.includes('ep')) { + cmd += ` \\\n --ep 8`; + } + // Multi-token prediction (MTP) configuration + if (strategyArray.includes('mtp')) { + cmd += ` \\\n --speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4`; + } + + // Add tool-call-parser if enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser deepseekv31`; + } + + // Add reasoning-parser when enabled + if (reasoningParser === 'enabled') { + cmd += ` \\\n --reasoning-parser deepseek-v3`; + } + + // Add chat-template if tool calling is enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --chat-template ./examples/chat_template/tool_chat_template_deepseekv31.jinja`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/deepseek-v32-deployment.jsx b/docs_new/src/snippets/autoregressive/deepseek-v32-deployment.jsx new file mode 100644 index 000000000..870e5d1df --- /dev/null +++ b/docs_new/src/snippets/autoregressive/deepseek-v32-deployment.jsx @@ -0,0 +1,318 @@ +export const DeepSeekV32Deployment = () => { + // Config mirrors sgl-cookbook src/components/autoregressive/DeepSeekConfigGenerator/index.js. + // + // Model variants: + // DeepSeek-V3.2, V3.2-Exp, V3.2-Speciale → deepseek-ai/ family, TP=8 + // DeepSeek-V3.2-NVFP4 → nvidia/ family, B200 only, TP=4 + // DeepSeek-V3.2-MXFP4 → amd/ family, MI300X/MI355X only, TP=8 + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelname: { + name: 'modelname', + title: 'Model Name', + getDynamicItems: (values) => { + const hw = values.hardware; + const isB200 = hw === 'b200'; + const isAMD = hw === 'mi300x' || hw === 'mi355x'; + return [ + { id: 'v32', label: 'DeepSeek-V3.2', default: !isB200 && !isAMD }, + { id: 'v32speciale', label: 'DeepSeek-V3.2-Speciale', default: false }, + { id: 'v32exp', label: 'DeepSeek-V3.2-Exp', default: false }, + { id: 'v32nvfp4', label: 'DeepSeek-V3.2-NVFP4', default: isB200, disabled: !isB200, disabledReason: 'NVFP4 requires B200 (Blackwell)' }, + { id: 'v32mxfp4', label: 'DeepSeek-V3.2-MXFP4', default: isAMD, disabled: !isAMD, disabledReason: 'MXFP4 requires AMD MI300X/MI355X' } + ]; + } + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + condition: (values) => values.modelname !== 'v32nvfp4' && values.modelname !== 'v32mxfp4', + items: [ + { id: 'tp', label: 'TP', default: true, required: true }, + { id: 'dp', label: 'DP attention', default: false }, + { id: 'ep', label: 'EP', default: false }, + { id: 'mtp', label: 'Multi-token Prediction', default: false } + ] + }, + reasoningParser: { + name: 'reasoningParser', + title: 'Reasoning Parser', + condition: (values) => values.modelname !== 'v32nvfp4' && values.modelname !== 'v32mxfp4', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + condition: (values) => values.modelname !== 'v32nvfp4' && values.modelname !== 'v32mxfp4' && values.modelname !== 'v32speciale', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + const resolveItems = (option, vals) => { + if (typeof option.getDynamicItems === 'function') return option.getDynamicItems(vals); + return option.items; + }; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + if (option.type === 'checkbox') { + const items = resolveItems(option, initialState); + initialState[key] = items.filter(i => i.default).map(i => i.id); + } else { + const items = resolveItems(option, initialState); + const def = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled) || items[0]; + initialState[key] = def.id; + } + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + // When hardware changes, re-resolve model name defaults (NVFP4→B200, MXFP4→AMD). + useEffect(() => { + setValues(prev => { + const next = { ...prev }; + for (const [key, option] of Object.entries(options)) { + if (typeof option.getDynamicItems !== 'function') continue; + const items = option.getDynamicItems(next); + const current = items.find(i => i.id === next[key]); + if (!current || current.disabled) { + const fallback = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled); + if (fallback) next[key] = fallback.id; + } + } + return next; + }); + }, [values.hardware]); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + const generateCommand = () => { + const { hardware, modelname, strategy, reasoningParser, toolcall } = values; + + const isNvfp4 = modelname === 'v32nvfp4'; + const isMxfp4 = modelname === 'v32mxfp4'; + const isAMD = hardware === 'mi300x' || hardware === 'mi355x'; + + // Validation: NVFP4 requires B200 + if (isNvfp4 && hardware !== 'b200') { + return `# Error: DeepSeek-V3.2-NVFP4 requires NVIDIA B200 (Blackwell) hardware\n# Please select "B200" for Hardware Platform or choose a different model`; + } + + // Validation: MXFP4 requires AMD MI300X/MI355X + if (isMxfp4 && !isAMD) { + return `# Error: DeepSeek-V3.2-MXFP4 requires AMD MI300X/MI355X hardware\n# Please select "MI300X" or "MI355X" for Hardware Platform or choose a different model`; + } + + // Validation: Speciale doesn't support tool calling + if (modelname === 'v32speciale' && toolcall === 'enabled') { + return `# Error: DeepSeek-V3.2-Speciale doesn't support tool calling\n# Please select "Disabled" for Tool Call Parser or choose a different model`; + } + + // Model name mapping + const modelMap = { + 'v32': 'DeepSeek-V3.2', + 'v32exp': 'DeepSeek-V3.2-Exp', + 'v32speciale': 'DeepSeek-V3.2-Speciale', + 'v32nvfp4': 'DeepSeek-V3.2-NVFP4', + 'v32mxfp4': 'DeepSeek-V3.2-mxfp4' + }; + + let modelFamily; + if (isNvfp4) modelFamily = 'nvidia'; + else if (isMxfp4) modelFamily = 'amd'; + else modelFamily = 'deepseek-ai'; + + const modelName = `${modelFamily}/${modelMap[modelname]}`; + + // NVFP4: fixed config + if (isNvfp4) { + let cmd = 'sglang serve \\\n'; + cmd += ` --model ${modelName}`; + cmd += ' \\\n --tp 4'; + cmd += ' \\\n --quantization modelopt_fp4'; + cmd += ' \\\n --moe-runner-backend flashinfer_trtllm'; + return cmd; + } + + // MXFP4: fixed config for AMD + if (isMxfp4) { + let cmd = 'sglang serve \\\n'; + cmd += ` --model ${modelName}`; + cmd += ' \\\n --tp 8'; + cmd += ' \\\n --trust-remote-code'; + return cmd; + } + + let cmd = 'sglang serve \\\n'; + cmd += ` --model ${modelName}`; + + // Hardware platform specific parameters + if (isAMD) { + cmd += ' \\\n --trust-remote-code'; + cmd += ' \\\n --nsa-prefill-backend tilelang'; + cmd += ' \\\n --nsa-decode-backend tilelang'; + cmd += ' \\\n --cuda-graph-max-bs 64'; + } + + // Strategy configurations + const strategyArray = Array.isArray(strategy) ? strategy : []; + const tpSize = 8; + const dpSize = 8; + const epSize = 8; + cmd += ` \\\n --tp ${tpSize}`; + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp ${dpSize} \\\n --enable-dp-attention`; + } + if (strategyArray.includes('ep')) { + cmd += ` \\\n --ep ${epSize}`; + } + + // Multi-token prediction (MTP) configuration + if (strategyArray.includes('mtp')) { + cmd += ' \\\n --speculative-algorithm EAGLE'; + cmd += ' \\\n --speculative-num-steps 3'; + cmd += ' \\\n --speculative-eagle-topk 1'; + cmd += ' \\\n --speculative-num-draft-tokens 4'; + } + + // Add tool-call-parser if enabled (not supported for Speciale) + if (toolcall === 'enabled' && modelname !== 'v32speciale') { + if (modelname === 'v32exp') { + cmd += ' \\\n --tool-call-parser deepseekv31'; + } else if (modelname === 'v32') { + cmd += ' \\\n --tool-call-parser deepseekv32'; + } + } + + // Add reasoning-parser when enabled + if (reasoningParser === 'enabled') { + cmd += ' \\\n --reasoning-parser deepseek-v3'; + } + + // Add chat-template if tool calling is enabled (only for v32exp) + if (toolcall === 'enabled' && modelname === 'v32exp') { + cmd += ' \\\n --chat-template ./examples/chat_template/tool_chat_template_deepseekv32.jinja'; + } + + return cmd; + }; + + // Styles + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.4 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (typeof option.condition === 'function' && !option.condition(values)) return null; + const items = resolveItems(option, values); + return ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required || !!item.disabled; + return ( + + ); + }) + ) : ( + items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = !!item.disabled; + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/devstral-2-deployment.jsx b/docs_new/src/snippets/autoregressive/devstral-2-deployment.jsx new file mode 100644 index 000000000..a3a66a415 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/devstral-2-deployment.jsx @@ -0,0 +1,182 @@ +export const Devstral2Deployment = () => { + // Config options based on Devstral2ConfigGenerator + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + model: { + name: 'model', + title: 'Model', + items: [ + { id: 'small', label: 'Devstral Small 2 (24B)', default: true }, + { id: 'large', label: 'Devstral 2 (123B)', default: false } + ] + }, + weights: { + name: 'weights', + title: 'Weights / Precision', + items: [ + { id: 'fp8', label: 'FP8', default: true } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Model configurations + const modelConfigs = { + small: { + modelId: 'mistralai/Devstral-Small-2-24B-Instruct-2512', + tpByHardware: { h100: 1, h200: 1, b200: 1, mi300x: 1, mi325x: 1, mi355x: 1 }, + allowedWeights: ['fp8'] + }, + large: { + modelId: 'mistralai/Devstral-2-123B-Instruct-2512', + tpByHardware: { h100: 4, h200: 2, b200: 2, mi300x: 2, mi325x: 2, mi355x: 2 }, + allowedWeights: ['fp8'] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, model, weights, toolcall } = values; + + const modelCfg = modelConfigs[model]; + if (!modelCfg) return `# Error: Unknown model selection: ${model}`; + + if (!modelCfg.allowedWeights.includes(weights)) { + const allowed = modelCfg.allowedWeights.map(w => w.toUpperCase()).join(', '); + return `# Error: ${modelCfg.modelId} only supports: ${allowed}\n# Please change "Weights / Precision" to a supported value.`; + } + + const tp = modelCfg.tpByHardware[hardware]; + if (!tp) return `# Error: Unknown hardware platform: ${hardware}`; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelCfg.modelId}`; + + if (tp > 1) { + cmd += ` \\\n --tp ${tp}`; + } + + // Add tool-call-parser if enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser mistral`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/ernie-45-deployment.jsx b/docs_new/src/snippets/autoregressive/ernie-45-deployment.jsx new file mode 100644 index 000000000..9adf1adf4 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/ernie-45-deployment.jsx @@ -0,0 +1,345 @@ +export const Ernie45Deployment = () => { + const options = { + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '21b', label: '21B', subtitle: 'A3B', default: true }, + { id: '300b', label: '300B', subtitle: 'A47B', default: false } + ] + }, + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false, disabledWhen: (values) => values.modelsize === '21b' }, + { id: 'ep', label: 'EP', subtitle: 'Expert Parallel', default: false, disabledWhen: (values) => values.modelsize === '21b' } + ] + } + }; + + const generateCommand = (values) => { + const { modelsize, hardware, strategy } = values; + + const strategyArray = Array.isArray(strategy) ? strategy : []; + + let modelPath; + if (modelsize === '21b') { + modelPath = 'baidu/ERNIE-4.5-21B-A3B-PT'; + } else if (modelsize === '300b') { + modelPath = 'baidu/ERNIE-4.5-300B-A47B-PT'; + } else { + modelPath = 'baidu/ERNIE-4.5-21B-A3B-PT'; + } + + let cmd = 'python3 -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelPath}`; + + const tpValue = modelsize === '300b' ? 8 : 1; + const dpValue = modelsize === '300b' ? 8 : null; + const epValue = modelsize === '300b' ? 8 : null; + + if (strategyArray.includes('tp')) { + cmd += ` \\\n --tp ${tpValue}`; + } + + if (strategyArray.includes('dp') && modelsize === '300b') { + cmd += ` \\\n --dp ${dpValue} \\\n --enable-dp-attention`; + } + + if (strategyArray.includes('ep') && modelsize === '300b') { + cmd += ` \\\n --ep ${epValue}`; + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/gemma4-deployment.jsx b/docs_new/src/snippets/autoregressive/gemma4-deployment.jsx new file mode 100644 index 000000000..c78d4c6ad --- /dev/null +++ b/docs_new/src/snippets/autoregressive/gemma4-deployment.jsx @@ -0,0 +1,376 @@ +export const Gemma4Deployment = () => { + const options = { + modelSize: { + name: 'modelSize', + title: 'Model Variant', + items: [ + { id: 'e2b', label: 'E2B (~2B)', default: false }, + { id: 'e4b', label: 'E4B (~4B)', default: true }, + { id: '31b', label: '31B (Dense)', default: false }, + { id: '26b-a4b', label: '26B-A4B (MoE)', default: false }, + ] + }, + hardware: { + name: 'hardware', + title: 'Hardware Platform', + getDynamicItems: (values) => { + const size = values.modelSize; + const showMI300X = size === '31b' || size === '26b-a4b'; + return [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false, disabled: !showMI300X }, + ]; + } + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser gemma4' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser gemma4' : null + }, + }; + + const modelConfigs = { + h200: { + e2b: { tp: 1, mem: 0.85 }, + e4b: { tp: 1, mem: 0.85 }, + '31b': { tp: 2, mem: 0.85 }, + '26b-a4b': { tp: 1, mem: 0.85 }, + }, + b200: { + e2b: { tp: 1, mem: 0.9 }, + e4b: { tp: 1, mem: 0.9 }, + '31b': { tp: 1, mem: 0.9 }, + '26b-a4b': { tp: 1, mem: 0.9 }, + }, + mi300x: { + '31b': { tp: 1, mem: 0.80 }, + '26b-a4b': { tp: 1, mem: 0.80 }, + }, + }; + + const generateCommand = (values) => { + const { hardware, modelSize } = values; + + const hwConfig = modelConfigs[hardware]?.[modelSize]; + if (!hwConfig) return `# Error: Unknown hardware/model combination`; + + const { tp, mem } = hwConfig; + + const modelNames = { + 'e2b': 'google/gemma-4-E2B-it', + 'e4b': 'google/gemma-4-E4B-it', + '31b': 'google/gemma-4-31B-it', + '26b-a4b': 'google/gemma-4-26B-A4B-it', + }; + + let cmd = `sglang serve --model-path ${modelNames[modelSize]}`; + if (tp > 1) { + cmd += ` \\\n --tp ${tp}`; + } + + Object.entries(options).forEach(([key, option]) => { + if (key === 'modelSize' || key === 'hardware') return; + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) cmd += ` \\\n ${rule}`; + } + }); + + cmd += ` \\\n --mem-fraction-static ${mem}`; + cmd += ` \\\n --host 0.0.0.0 --port 30000`; + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-45-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-45-deployment.jsx new file mode 100644 index 000000000..90ee08ffe --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-45-deployment.jsx @@ -0,0 +1,197 @@ +export const GLM45Deployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false }, + { id: 'ep', label: 'EP', subtitle: 'Expert Parallel', default: false }, + { id: 'mtp', label: 'MTP', subtitle: 'Multi-token Prediction', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Thinking Capabilities', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization, strategy, thinking, toolcall } = values; + const strategyArray = Array.isArray(strategy) ? strategy : []; + + const modelSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `zai-org/GLM-4.5${modelSuffix}`; + + // Determine TP value based on hardware and quantization + let tpValue = 4; // Default for MI300X/MI325X + if (hardware === 'mi355x') { + tpValue = quantization === 'fp8' ? 2 : 4; // MI355X: TP=2 for FP8, TP=4 for BF16 + } + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + // TP is mandatory + cmd += ` \\\n --tp ${tpValue}`; + + // MI300X/MI325X BF16 requires extra flags + if ((hardware === 'mi300x' || hardware === 'mi325x') && quantization === 'bf16') { + cmd += ` \\\n --max-context-length 8192 \\\n --mem-fraction-static 0.9`; + } + + // Strategy-specific parameters + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp 8 \\\n --enable-dp-attention`; + } + if (strategyArray.includes('ep')) { + cmd += ` \\\n --ep 8`; + } + if (strategyArray.includes('mtp')) { + cmd = 'SGLANG_ENABLE_SPEC_V2=1 ' + cmd; + cmd += ` \\\n --speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4`; + } + + // Add tool call parser if enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser glm45`; + } + + // Add thinking parser if enabled + if (thinking === 'enabled') { + cmd += ` \\\n --reasoning-parser glm45`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-45v-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-45v-deployment.jsx new file mode 100644 index 000000000..8fb67ad25 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-45v-deployment.jsx @@ -0,0 +1,175 @@ +export const GLM45VDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h100', label: 'H100', default: false }, + { id: 'h200', label: 'H200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization, reasoning, toolcall } = values; + + // Model configuration + const config = { + baseName: 'GLM-4.5V', + b200: { tp: 4 }, + h100: { tp: 4 }, + h200: { tp: 4 }, + mi300x: { tp: 4 }, + mi355x: { tp: 4 } + }; + + const hwConfig = config[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `zai-org/${config.baseName}${quantSuffix}`; + + // Check if AMD hardware + const isAMD = ['mi300x', 'mi325x', 'mi355x'].includes(hardware); + + let cmd = ''; + if (isAMD) { + cmd = 'SGLANG_USE_AITER=0 python3 -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelName}`; + cmd += ` \\\n --tp-size ${hwConfig.tp}`; + } else { + cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + } + + // Add reasoning parser + if (reasoning === 'enabled') { + cmd += ' \\\n --reasoning-parser glm45'; + } + + // Add tool call parser + if (toolcall === 'enabled') { + cmd += ' \\\n --tool-call-parser glm45'; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-46-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-46-deployment.jsx new file mode 100644 index 000000000..2c55fdbba --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-46-deployment.jsx @@ -0,0 +1,207 @@ +export const GLM46Deployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h100', label: 'H100', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false }, + { id: 'ep', label: 'EP', subtitle: 'Expert Parallel', default: false }, + { id: 'mtp', label: 'MTP', subtitle: 'Multi-token Prediction', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Thinking Capabilities', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization, strategy, thinking, toolcall } = values; + const strategyArray = Array.isArray(strategy) ? strategy : []; + + // Check for H100 + BF16 error + if (hardware === 'h100' && quantization === 'bf16') { + return '# Error: GLM-4.6 in BF16 precision requires more VRAM than 8*H100\n# Please use H200/B200 or select FP8 quantization'; + } + + const modelSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `zai-org/GLM-4.6${modelSuffix}`; + + // Determine TP value based on hardware and quantization + let tpValue = 8; // Default for NVIDIA GPUs + if (hardware === 'mi300x' || hardware === 'mi325x') { + tpValue = 4; // MI300X/MI325X: TP=4 for both BF16 and FP8 + } else if (hardware === 'mi355x') { + tpValue = quantization === 'fp8' ? 2 : 4; // MI355X: TP=2 for FP8, TP=4 for BF16 + } + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + // TP is mandatory + cmd += ` \\\n --tp ${tpValue}`; + + // MI300X/MI325X BF16 requires extra flags + if ((hardware === 'mi300x' || hardware === 'mi325x') && quantization === 'bf16') { + cmd += ` \\\n --max-context-length 8192 \\\n --mem-fraction-static 0.9`; + } + + // Strategy-specific parameters + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp 8 \\\n --enable-dp-attention`; + } + if (strategyArray.includes('ep')) { + cmd += ` \\\n --ep 8`; + } + if (strategyArray.includes('mtp')) { + cmd = 'SGLANG_ENABLE_SPEC_V2=1 ' + cmd; + cmd += ` \\\n --speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4`; + } + + // Add tool call parser if enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser glm45`; + } + + // Add thinking parser if enabled + if (thinking === 'enabled') { + cmd += ` \\\n --reasoning-parser glm45`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-46v-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-46v-deployment.jsx new file mode 100644 index 000000000..237fc307e --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-46v-deployment.jsx @@ -0,0 +1,196 @@ +export const GLM46VDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h100', label: 'H100', default: false }, + { id: 'h200', label: 'H200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '106b', label: '106B', subtitle: 'GLM-4.6V', default: true }, + { id: '9b', label: '9B', subtitle: 'GLM-4.6V-Flash', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command + const generateCommand = () => { + const { hardware, modelsize, quantization, reasoning, toolcall } = values; + + // Model configurations + const modelConfigs = { + '106b': { + baseName: 'GLM-4.6V', + h100: { tp: 8 }, + h200: { tp: 8 }, + b200: { tp: 8 }, + mi300x: { tp: 8 }, + mi355x: { tp: 8 } + }, + '9b': { + baseName: 'GLM-4.6V-Flash', + h100: { tp: 1 }, + h200: { tp: 1 }, + b200: { tp: 1 }, + mi300x: { tp: 1 }, + mi355x: { tp: 1 } + } + }; + + const config = modelConfigs[modelsize]; + if (!config) { + return `# Error: Unknown model size: ${modelsize}`; + } + + const hwConfig = config[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `zai-org/${config.baseName}${quantSuffix}`; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + if (hwConfig.tp === 8) { + cmd += ` \\\n --mm-enable-dp-encoder`; + } + } + + // Add reasoning parser if enabled + if (reasoning === 'enabled') { + cmd += ` \\\n --reasoning-parser glm45`; + } + + // Add tool call parser if enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser glm45`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-47-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-47-deployment.jsx new file mode 100644 index 000000000..f90b33c40 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-47-deployment.jsx @@ -0,0 +1,197 @@ +export const GLM47Deployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false }, + { id: 'ep', label: 'EP', subtitle: 'Expert Parallel', default: false }, + { id: 'mtp', label: 'MTP', subtitle: 'Multi-token Prediction', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Thinking Capabilities', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization, strategy, thinking, toolcall } = values; + const strategyArray = Array.isArray(strategy) ? strategy : []; + + const modelSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `zai-org/GLM-4.7${modelSuffix}`; + + // Determine TP value based on hardware and quantization + let tpValue = 4; // Default for MI300X and MI325X + if (hardware === 'mi355x') { + tpValue = quantization === 'fp8' ? 2 : 4; // MI355X: TP=2 for FP8, TP=4 for BF16 + } + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + // TP is mandatory + cmd += ` \\\n --tp ${tpValue}`; + + // MI300X/MI325X BF16 requires extra flags + if ((hardware === 'mi300x' || hardware === 'mi325x') && quantization === 'bf16') { + cmd += ` \\\n --max-context-length 8192 \\\n --mem-fraction-static 0.9`; + } + + // Strategy-specific parameters + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp 8 \\\n --enable-dp-attention`; + } + if (strategyArray.includes('ep')) { + cmd += ` \\\n --ep 8`; + } + if (strategyArray.includes('mtp')) { + cmd = 'SGLANG_ENABLE_SPEC_V2=1 ' + cmd; + cmd += ` \\\n --speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4`; + } + + // Add tool call parser if enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser glm47`; + } + + // Add thinking parser if enabled + if (thinking === 'enabled') { + cmd += ` \\\n --reasoning-parser glm47`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-47-flash-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-47-flash-deployment.jsx new file mode 100644 index 000000000..afdcdf46c --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-47-flash-deployment.jsx @@ -0,0 +1,191 @@ +export const GLM47FlashDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h100', label: 'H100', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', subtitle: 'Tensor Parallel', default: true, required: true }, + { id: 'dp', label: 'DP', subtitle: 'Data Parallel', default: false }, + { id: 'mtp', label: 'MTP', subtitle: 'Multi-token Prediction', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Thinking Capabilities', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization, strategy, thinking, toolcall } = values; + const strategyArray = Array.isArray(strategy) ? strategy : []; + + const modelName = `zai-org/GLM-4.7-Flash`; + + // GLM-4.7-Flash is a 30B-A3B MoE model, lighter than GLM-4.7 + const tpValue = 1; // Default for single GPU + + let cmd = 'python -m sglang.launch_server \\\n '; + cmd += ` --model ${modelName}`; + + // TP is mandatory + cmd += ` \\\n --tp ${tpValue}`; + + if (hardware === 'b200') { + cmd += ` \\\n --attention-backend triton`; + } + + // Strategy-specific parameters + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp 1 \\\n --enable-dp-attention`; + } + if (strategyArray.includes('mtp')) { + cmd = 'SGLANG_ENABLE_SPEC_V2=1 ' + cmd; + + if (hardware === 'b200') { + cmd += ` \\\n --speculative-draft-attention-backend triton`; + } + cmd += ` \\\n --speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4`; + } + + // Add tool call parser if enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser glm47`; + } + + // Add thinking parser if enabled + if (thinking === 'enabled') { + cmd += ` \\\n --reasoning-parser glm45`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-5-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-5-deployment.jsx new file mode 100644 index 000000000..1a7c8f274 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-5-deployment.jsx @@ -0,0 +1,266 @@ +export const GLM5Deployment = () => { + // Config mirrors sgl-cookbook src/components/autoregressive/GLM5ConfigGenerator/index.js. + // + // Supported quantization per hardware: + // H100 / H200 / MI300X / MI325X / MI355X → BF16 (AMD only) + FP8 (NV only) + // B200 → NVFP4 (default), FP8, BF16 + // + // BF16 always needs 2x GPUs compared to FP8. AMD only supports BF16. + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi300x', label: 'MI300X/MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + getDynamicItems: (values) => { + const hw = values.hardware; + const isAMD = hw === 'mi300x' || hw === 'mi355x'; + const isB200 = hw === 'b200'; + return [ + { id: 'bf16', label: 'BF16', subtitle: 'Full Weights', default: isAMD }, + { id: 'fp8', label: 'FP8', subtitle: 'High Throughput', default: !isAMD && !isB200, disabled: isAMD, disabledReason: 'FP8 not verified on AMD' }, + { id: 'nvfp4', label: 'NVFP4', subtitle: 'Highest Throughput', default: isB200, disabled: !isB200, disabledReason: 'NVFP4 only on B200' } + ]; + } + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + condition: (values) => values.quantization !== 'nvfp4', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + condition: (values) => values.quantization !== 'nvfp4', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + dpattention: { + name: 'dpattention', + title: 'DP Attention', + condition: (values) => values.quantization !== 'nvfp4', + items: [ + { id: 'disabled', label: 'Disabled', subtitle: 'Low Latency', default: true }, + { id: 'enabled', label: 'Enabled', subtitle: 'High Throughput', default: false } + ] + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding', + condition: (values) => values.hardware !== 'mi300x' && values.hardware !== 'mi355x' && values.quantization !== 'nvfp4', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + } + }; + + // BF16 always 2× the GPUs of FP8. + const modelConfigs = { + h100: { fp8: { tp: 16, mem: 0.85 }, bf16: { tp: 32, mem: 0.85 } }, + h200: { fp8: { tp: 8, mem: 0.85 }, bf16: { tp: 16, mem: 0.85 } }, + b200: { nvfp4: { tp: 4, mem: 0.9 }, fp8: { tp: 8, mem: 0.9 }, bf16: { tp: 16, mem: 0.9 } }, + mi300x: { bf16: { tp: 8, mem: 0.80 } }, + mi355x: { bf16: { tp: 8, mem: 0.80 } } + }; + + const resolveItems = (option, values) => { + if (typeof option.getDynamicItems === 'function') return option.getDynamicItems(values); + return option.items; + }; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + const items = resolveItems(option, initialState); + const def = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled) || items[0]; + initialState[key] = def.id; + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + // When hardware changes, re-resolve quantization (and downstream) defaults to + // stay consistent (AMD→BF16, B200→NVFP4, etc.). + useEffect(() => { + setValues(prev => { + const next = { ...prev }; + for (const [key, option] of Object.entries(options)) { + if (typeof option.getDynamicItems !== 'function') continue; + const items = option.getDynamicItems(next); + const current = items.find(i => i.id === next[key]); + if (!current || current.disabled) { + const fallback = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled); + if (fallback) next[key] = fallback.id; + } + } + return next; + }); + }, [values.hardware]); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const generateCommand = () => { + const { hardware, quantization } = values; + const isAMD = hardware === 'mi300x' || hardware === 'mi355x'; + const isNVFP4 = quantization === 'nvfp4'; + const effectiveQuant = isAMD ? 'bf16' : quantization; + + let modelName; + if (isNVFP4) { + modelName = 'nvidia/GLM-5-NVFP4'; + } else { + const suffix = effectiveQuant === 'fp8' ? '-FP8' : ''; + modelName = `zai-org/GLM-5${suffix}`; + } + + const hwConfig = modelConfigs[hardware][effectiveQuant]; + const tpValue = hwConfig.tp; + const memFraction = hwConfig.mem; + + let cmd = 'sglang serve \\\n'; + cmd += ` --model ${modelName}`; + cmd += ` \\\n --tp ${tpValue}`; + + // NVFP4 B200: trtllm NSA backends, flashinfer fusion, FP8 KV cache. + if (isNVFP4) { + cmd += ' \\\n --trust-remote-code'; + cmd += ' \\\n --quantization modelopt_fp4'; + cmd += ' \\\n --kv-cache-dtype fp8_e4m3'; + cmd += ' \\\n --nsa-decode-backend trtllm'; + cmd += ' \\\n --nsa-prefill-backend trtllm'; + cmd += ' \\\n --moe-runner-backend flashinfer_trtllm'; + cmd += ' \\\n --enable-flashinfer-allreduce-fusion'; + cmd += ' \\\n --enable-dp-lm-head'; + cmd += ' \\\n --disable-radix-cache'; + cmd += ' \\\n --max-prefill-tokens 32768'; + cmd += ' \\\n --chunked-prefill-size 32768'; + cmd += ` \\\n --mem-fraction-static ${memFraction}`; + cmd += ' \\\n --scheduler-recv-interval 10'; + cmd += ' \\\n --tokenizer-worker-num 6'; + return cmd; + } + + // AMD-specific: NSA tilelang backend. + if (isAMD) { + cmd += ' \\\n --trust-remote-code'; + cmd += ' \\\n --nsa-prefill-backend tilelang'; + cmd += ' \\\n --nsa-decode-backend tilelang'; + cmd += ' \\\n --chunked-prefill-size 131072'; + cmd += ' \\\n --watchdog-timeout 1200'; + } + + if (values.dpattention === 'enabled') { + cmd += ` \\\n --dp ${tpValue} \\\n --enable-dp-attention`; + } + if (values.reasoning === 'enabled') cmd += ' \\\n --reasoning-parser glm45'; + if (values.toolcall === 'enabled') cmd += ' \\\n --tool-call-parser glm47'; + if (values.speculative === 'enabled') { + cmd += ' \\\n --speculative-algorithm EAGLE'; + cmd += ' \\\n --speculative-num-steps 3'; + cmd += ' \\\n --speculative-eagle-topk 1'; + cmd += ' \\\n --speculative-num-draft-tokens 4'; + } + + // B200 FP8: consolidated optimized flags. + if (hardware === 'b200' && effectiveQuant === 'fp8') { + cmd += ' \\\n --ep 1'; + cmd += ' \\\n --quantization fp8'; + cmd += ' \\\n --attention-backend nsa'; + cmd += ' \\\n --nsa-decode-backend trtllm'; + cmd += ' \\\n --nsa-prefill-backend trtllm'; + cmd += ' \\\n --moe-runner-backend flashinfer_trtllm'; + cmd += ' \\\n --enable-flashinfer-allreduce-fusion'; + } + + cmd += ` \\\n --mem-fraction-static ${memFraction}`; + return cmd; + }; + + // Styles + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.4 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (typeof option.condition === 'function' && !option.condition(values)) return null; + const items = resolveItems(option, values); + return ( +
+
{option.title}
+
+ {items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = !!item.disabled; + return ( + + ); + })} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-51-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-51-deployment.jsx new file mode 100644 index 000000000..7b9489bd7 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-51-deployment.jsx @@ -0,0 +1,228 @@ +export const GLM51Deployment = () => { + // Config mirrors sgl-cookbook src/components/autoregressive/GLM51ConfigGenerator/index.js. + // + // Supported quantization per hardware: + // H100 / H200 / B200 → BF16 + FP8 + // GB300 → FP8 only + // MI300X/MI325X/MI355X → BF16 (FP8 not verified on AMD) + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'gb300', label: 'GB300', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi300x', label: 'MI300X/MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + getDynamicItems: (values) => { + const hw = values.hardware; + const isAMD = hw === 'mi300x' || hw === 'mi355x'; + const isGB300 = hw === 'gb300'; + return [ + { id: 'bf16', label: 'BF16', subtitle: 'Full Weights', default: isAMD, disabled: isGB300, disabledReason: isGB300 ? 'BF16 is not recommended on GB300 for GLM-5.1' : '' }, + { id: 'fp8', label: 'FP8', subtitle: 'High Throughput', default: !isAMD, disabled: isAMD, disabledReason: isAMD ? 'FP8 not verified on AMD' : '' } + ]; + } + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + dpattention: { + name: 'dpattention', + title: 'DP Attention', + items: [ + { id: 'disabled', label: 'Disabled', subtitle: 'Low Latency', default: true }, + { id: 'enabled', label: 'Enabled', subtitle: 'High Throughput', default: false } + ] + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding', + condition: (values) => values.hardware !== 'mi300x' && values.hardware !== 'mi355x', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + } + }; + + const modelConfigs = { + h100: { fp8: { tp: 16, mem: 0.85 }, bf16: { tp: 32, mem: 0.85 } }, + h200: { fp8: { tp: 8, mem: 0.85 }, bf16: { tp: 16, mem: 0.85 } }, + b200: { fp8: { tp: 8, mem: 0.9 }, bf16: { tp: 16, mem: 0.9 } }, + gb300: { fp8: { tp: 4, mem: 0.9 } }, + mi300x: { bf16: { tp: 8, mem: 0.80 } }, + mi355x: { bf16: { tp: 8, mem: 0.80 } } + }; + + const resolveItems = (option, values) => { + if (typeof option.getDynamicItems === 'function') return option.getDynamicItems(values); + return option.items; + }; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + const items = resolveItems(option, initialState); + const def = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled) || items[0]; + initialState[key] = def.id; + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + useEffect(() => { + setValues(prev => { + const next = { ...prev }; + for (const [key, option] of Object.entries(options)) { + if (typeof option.getDynamicItems !== 'function') continue; + const items = option.getDynamicItems(next); + const current = items.find(i => i.id === next[key]); + if (!current || current.disabled) { + const fallback = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled); + if (fallback) next[key] = fallback.id; + } + } + return next; + }); + }, [values.hardware]); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const generateCommand = () => { + const { hardware, quantization } = values; + const isAMD = hardware === 'mi300x' || hardware === 'mi355x'; + const isGB300 = hardware === 'gb300'; + const effectiveQuant = isAMD ? 'bf16' : (isGB300 && quantization === 'bf16' ? 'fp8' : quantization); + const suffix = effectiveQuant === 'fp8' ? '-FP8' : ''; + const modelName = `zai-org/GLM-5.1${suffix}`; + + const hwConfig = modelConfigs[hardware][effectiveQuant]; + if (!hwConfig) return '# Configuration not available for the selected hardware and quantization.'; + + const tpValue = hwConfig.tp; + const memFraction = hwConfig.mem; + const enableSpec = values.speculative === 'enabled'; + + let cmd = ''; + if (enableSpec) cmd += 'SGLANG_ENABLE_SPEC_V2=1 '; + cmd += 'sglang serve \\\n'; + cmd += ` --model-path ${modelName}`; + cmd += ` \\\n --tp ${tpValue}`; + + if (isAMD) { + cmd += ' \\\n --trust-remote-code'; + cmd += ' \\\n --nsa-prefill-backend tilelang'; + cmd += ' \\\n --nsa-decode-backend tilelang'; + cmd += ' \\\n --chunked-prefill-size 131072'; + cmd += ' \\\n --watchdog-timeout 1200'; + } + + if (values.dpattention === 'enabled') { + cmd += ` \\\n --dp ${tpValue} \\\n --enable-dp-attention`; + } + if (values.reasoning === 'enabled') cmd += ' \\\n --reasoning-parser glm45'; + if (values.toolcall === 'enabled') cmd += ' \\\n --tool-call-parser glm47'; + if (enableSpec) { + cmd += ' \\\n --speculative-algorithm EAGLE'; + cmd += ' \\\n --speculative-num-steps 3'; + cmd += ' \\\n --speculative-eagle-topk 1'; + cmd += ' \\\n --speculative-num-draft-tokens 4'; + } + + cmd += ` \\\n --mem-fraction-static ${memFraction}`; + return cmd; + }; + + // Styles + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.4 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (typeof option.condition === 'function' && !option.condition(values)) return null; + const items = resolveItems(option, values); + return ( +
+
{option.title}
+
+ {items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = !!item.disabled; + return ( + + ); + })} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-glyph-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-glyph-deployment.jsx new file mode 100644 index 000000000..62162a944 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-glyph-deployment.jsx @@ -0,0 +1,372 @@ +export const GLMGlyphDeployment = () => { + const modelFamily = 'zai-org'; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h100', label: 'H100', default: false }, + { id: 'h200', label: 'H200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser glm45' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser glm45' : null + } + }; + + const modelConfig = { + baseName: 'Glyph', + b200: { tp: 4, bf16: true, fp8: true }, + h100: { tp: 4, bf16: true, fp8: true }, + h200: { tp: 4, bf16: true, fp8: true }, + mi300x: { tp: 4, bf16: true, fp8: true }, + mi325x: { tp: 4, bf16: true, fp8: true }, + mi355x: { tp: 2, bf16: true, fp8: true } + }; + + const generateCommand = (values) => { + const { hardware, quantization } = values; + + const hwConfig = modelConfig[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `${modelFamily}/${modelConfig.baseName}${quantSuffix}`; + + const isAMD = ['mi300x', 'mi325x', 'mi355x'].includes(hardware); + + let cmd = ''; + if (isAMD) { + cmd = 'python3 -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelName}`; + cmd += ` \\\n --tp ${hwConfig.tp}`; + } else { + cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + } + + for (const [key, option] of Object.entries(options)) { + if (key === 'hardware' || key === 'quantization') continue; + + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) { + cmd += ` \\\n ${rule}`; + } + } + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/glm-ocr-deployment.jsx b/docs_new/src/snippets/autoregressive/glm-ocr-deployment.jsx new file mode 100644 index 000000000..773a922a0 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/glm-ocr-deployment.jsx @@ -0,0 +1,140 @@ +export const GLMOCRDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h100', label: 'H100', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'mtp', label: 'MTP', subtitle: 'Multi-token Prediction', default: true } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode - prioritize page theme over system preference + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { strategy } = values; + const strategyArray = Array.isArray(strategy) ? strategy : []; + + const modelName = 'zai-org/GLM-OCR'; + + let cmd = 'SGLANG_USE_CUDA_IPC_TRANSPORT=1 python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + if (strategyArray.includes('mtp')) { + cmd += ` \\\n --speculative-algorithm EAGLE`; + cmd += ` \\\n --speculative-num-steps 3`; + cmd += ` \\\n --speculative-eagle-topk 1`; + cmd += ` \\\n --speculative-num-draft-tokens 4`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/gpt-oss-deployment.jsx b/docs_new/src/snippets/autoregressive/gpt-oss-deployment.jsx new file mode 100644 index 000000000..6740554b9 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/gpt-oss-deployment.jsx @@ -0,0 +1,237 @@ +export const GPTOSSDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '120b', label: '120B', subtitle: 'MOE', default: true }, + { id: '20b', label: '20B', subtitle: 'MOE', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'mxfp4', label: 'MXFP4', default: true }, + { id: 'bf16', label: 'BF16', default: false } + ] + }, + reasoningParser: { + name: 'reasoningParser', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command + const generateCommand = () => { + const { hardware, modelsize, quantization, reasoningParser, toolcall, speculative } = values; + + // Model configurations + const modelConfigs = { + '120b': { + baseName: '120b', + h100: { tp: 8 }, + h200: { tp: 8 }, + b200: { tp: 8 }, + mi300x: { tp: 8 }, + mi325x: { tp: 8 }, + mi355x: { tp: 8 } + }, + '20b': { + baseName: '20b', + h100: { tp: 1 }, + h200: { tp: 1 }, + b200: { tp: 1 }, + mi300x: { tp: 1 }, + mi325x: { tp: 1 }, + mi355x: { tp: 1 } + } + }; + + const config = modelConfigs[modelsize]; + if (!config) { + return `# Error: Unknown model size: ${modelsize}`; + } + + const hwConfig = config[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantSuffix = quantization === 'bf16' ? '-bf16' : ''; + const orgPrefix = quantization === 'bf16' ? 'lmsys' : 'openai'; + const modelName = `${orgPrefix}/gpt-oss-${config.baseName}${quantSuffix}`; + + let cmd = ''; + + // MI30x GPUs with speculative decoding: Work In Progress + if ((hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') && speculative === 'enabled') { + return '# MI30x GPUs Speculative Decoding: Work In Progress'; + } + + // MI300X/MI325X MXFP4: Work In Progress (only MI355X with gfx950 supports MXFP4) + if ((hardware === 'mi300x' || hardware === 'mi325x') && quantization === 'mxfp4') { + return '# MI300X/MI325X GPUs with MXFP4 quantization: Work In Progress'; + } + + // AMD MI30x requires SGLANG_USE_AITER=0 due to YaRN RoPE precision issues + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd += 'SGLANG_USE_AITER=0 '; + } + + if (speculative === 'enabled') { + cmd += 'SGLANG_ENABLE_SPEC_V2=1 SGLANG_ALLOW_OVERWRITE_LONGER_CONTEXT_LEN=1 '; + } + + cmd += 'python -m sglang.launch_server \\\n'; + + cmd += ` --model ${modelName}`; + + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + + // Add reasoning parser if enabled + if (reasoningParser === 'enabled') { + cmd += ` \\\n --reasoning-parser gpt-oss`; + } + + // Add tool call parser if enabled + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser gpt-oss`; + } + + // Add speculative decoding if enabled (MI30x handled above) + if (speculative === 'enabled') { + cmd += ` \\\n --speculative-algorithm EAGLE3 \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4`; + + if (modelsize === '120b') { + cmd += ` \\\n --speculative-draft-model-path nvidia/gpt-oss-120b-Eagle3`; + } else if (modelsize === '20b') { + cmd += ` \\\n --speculative-draft-model-path zhuyksir/EAGLE3-gpt-oss-20b-bf16`; + } + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/kimi-k2-deployment.jsx b/docs_new/src/snippets/autoregressive/kimi-k2-deployment.jsx new file mode 100644 index 000000000..425ae3a97 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/kimi-k2-deployment.jsx @@ -0,0 +1,373 @@ +export const KimiK2Deployment = () => { + const modelFamily = 'moonshotai'; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelname: { + name: 'modelname', + title: 'Model Name', + items: [ + { id: 'instruct', label: 'Kimi-K2-Instruct', default: true }, + { id: 'thinking', label: 'Kimi-K2-Thinking', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', default: true, required: true }, + { id: 'dp', label: 'DP attention', default: false }, + { id: 'ep', label: 'EP', default: false } + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + const generateCommand = (values) => { + const { hardware, modelname, strategy, reasoning, toolcall } = values; + + if (modelname === 'instruct' && reasoning === 'enabled') { + return `# Error: Kimi-K2-Instruct doesn't support reasoning parser\n# Please select "Disabled" for Reasoning Parser or choose Kimi-K2-Thinking model`; + } + + const modelMap = { + 'instruct': 'Kimi-K2-Instruct', + 'thinking': 'Kimi-K2-Thinking' + }; + + const modelName = `${modelFamily}/${modelMap[modelname]}`; + + let cmd = 'python3 -m sglang.launch_server \\\n'; + + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd = 'SGLANG_ROCM_FUSED_DECODE_MLA=0 ' + cmd; + } + + cmd += ` --model-path ${modelName}`; + + const strategyArray = Array.isArray(strategy) ? strategy : []; + cmd += ` \\\n --tp 8`; + if (strategyArray.includes('dp')) { + cmd += ` \\\n --dp 4 \\\n --enable-dp-attention`; + } + if (strategyArray.includes('ep')) { + cmd += ` \\\n --ep 4`; + } + + cmd += ` \\\n --trust-remote-code`; + + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser kimi_k2`; + } + + if (reasoning === 'enabled') { + cmd += ` \\\n --reasoning-parser kimi_k2`; + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/kimi-k25-deployment.jsx b/docs_new/src/snippets/autoregressive/kimi-k25-deployment.jsx new file mode 100644 index 000000000..7376cb955 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/kimi-k25-deployment.jsx @@ -0,0 +1,264 @@ +export const KimiK25Deployment = () => { + // Config mirrors sgl-cookbook src/components/autoregressive/KimiK25ConfigGenerator/index.js. + // + // GPU requirements: + // H200: tp=8 + // B300: tp=8 + // MI300X: tp=4 (64 heads / 4 = 16 heads per GPU, AITER MLA requires heads_per_gpu % 16 == 0) + // MI325X: tp=4 (same constraint as MI300X) + // MI350X: tp=4 (same constraint as MI300X) + // MI355X: tp=4 (same constraint as MI300X) + // + // NVFP4 quantization is only supported on NVIDIA Blackwell (B300). + // Speculative decoding is only supported on H200 and B300. + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b300', label: 'B300', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi350x', label: 'MI350X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + getDynamicItems: (values) => { + const hw = values.hardware; + const isB300 = hw === 'b300'; + return [ + { id: 'int4', label: 'INT4', subtitle: 'initial model', default: true }, + { id: 'nvfp4', label: 'NVFP4', subtitle: 'Blackwell only', default: false, disabled: !isB300, disabledReason: 'NVFP4 only on B300' } + ]; + } + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + dpattention: { + name: 'dpattention', + title: 'DP Attention', + items: [ + { id: 'disabled', label: 'Disabled', subtitle: 'Low Latency', default: true }, + { id: 'enabled', label: 'Enabled', subtitle: 'High Throughput', default: false } + ] + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding', + condition: (values) => values.hardware === 'h200' || values.hardware === 'b300', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + const modelConfigs = { + h200: { tp: 8 }, + b300: { tp: 8 }, + mi300x: { tp: 4 }, + mi325x: { tp: 4 }, + mi350x: { tp: 4 }, + mi355x: { tp: 4 } + }; + + const resolveItems = (option, values) => { + if (typeof option.getDynamicItems === 'function') return option.getDynamicItems(values); + return option.items; + }; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + const items = resolveItems(option, initialState); + const def = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled) || items[0]; + initialState[key] = def.id; + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + // When hardware changes, re-resolve quantization defaults (NVFP4 only on B300). + useEffect(() => { + setValues(prev => { + const next = { ...prev }; + for (const [key, option] of Object.entries(options)) { + if (typeof option.getDynamicItems !== 'function') continue; + const items = option.getDynamicItems(next); + const current = items.find(i => i.id === next[key]); + if (!current || current.disabled) { + const fallback = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled); + if (fallback) next[key] = fallback.id; + } + } + return next; + }); + }, [values.hardware]); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command - mirrors sgl-cookbook's config.generateCommand(values) exactly. + const generateCommand = () => { + const { hardware, quantization, speculative } = values; + const isAMD = hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi350x' || hardware === 'mi355x'; + + // NVFP4 is only supported on NVIDIA Blackwell (B300) + if (quantization === 'nvfp4' && hardware !== 'b300') { + return '# NVFP4 quantization is only supported on NVIDIA Blackwell GPUs (B300)'; + } + + // Speculative decoding only supported on H200 and B300 + if (speculative === 'enabled' && hardware !== 'h200' && hardware !== 'b300') { + return '# Speculative Decoding for Kimi-K2.5 is only supported on H200 and B300'; + } + + // Model path depends on quantization + const modelName = quantization === 'nvfp4' + ? 'nvidia/Kimi-K2.5-NVFP4' + : 'moonshotai/Kimi-K2.5'; + + const hwConfig = modelConfigs[hardware]; + const tpValue = hwConfig.tp; + + let cmd = ''; + + // AMD ROCm environment variables + if (isAMD) { + cmd += 'SGLANG_USE_AITER=1 SGLANG_ROCM_FUSED_DECODE_MLA=0 '; + } + + // Speculative decoding env var + if (speculative === 'enabled') { + cmd += 'SGLANG_ENABLE_SPEC_V2=1 '; + } + + // If we added any env vars above, break to a new line for readability + if (isAMD || speculative === 'enabled') { + cmd += '\\\n'; + } + + cmd += 'sglang serve \\\n'; + cmd += ` --model-path ${modelName}`; + cmd += ` \\\n --tp ${tpValue}`; + cmd += ' \\\n --trust-remote-code'; + + // DP Attention: --dp matches --tp + if (values.dpattention === 'enabled') { + cmd += ` \\\n --dp ${tpValue} \\\n --enable-dp-attention`; + } + + // Reasoning parser + if (values.reasoning === 'enabled') { + cmd += ' \\\n --reasoning-parser kimi_k2'; + } + + // Tool call parser + if (values.toolcall === 'enabled') { + cmd += ' \\\n --tool-call-parser kimi_k2'; + } + + // Speculative decoding (EAGLE3) + if (speculative === 'enabled') { + cmd += ' \\\n --speculative-algorithm EAGLE3 \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4 \\\n --speculative-draft-model-path lightseekorg/kimi-k2.5-eagle3'; + } + + // AMD: FP8 KV cache for memory efficiency + if (isAMD) { + cmd += ' \\\n --kv-cache-dtype fp8_e4m3'; + } + + cmd += ' \\\n --host 0.0.0.0 \\\n --port 30000'; + + return cmd; + }; + + // Styles + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.4 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (typeof option.condition === 'function' && !option.condition(values)) return null; + const items = resolveItems(option, values); + return ( +
+
{option.title}
+
+ {items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = !!item.disabled; + return ( + + ); + })} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/kimi-k26-deployment.jsx b/docs_new/src/snippets/autoregressive/kimi-k26-deployment.jsx new file mode 100644 index 000000000..be2ccb6b4 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/kimi-k26-deployment.jsx @@ -0,0 +1,181 @@ +export const KimiK26Deployment = () => { + // Config mirrors sgl-cookbook src/components/autoregressive/KimiK26ConfigGenerator/index.js. + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b300', label: 'B300', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi350x', label: 'MI350X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false }, + ], + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true }, + ], + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true }, + ], + }, + dpattention: { + name: 'dpattention', + title: 'DP Attention', + items: [ + { id: 'disabled', label: 'Disabled', subtitle: 'Low Latency', default: true }, + { id: 'enabled', label: 'Enabled', subtitle: 'High Throughput', default: false }, + ], + }, + }; + + const modelConfigs = { + h200: { tp: 8 }, + b300: { tp: 8 }, + mi300x: { tp: 4 }, + mi325x: { tp: 4 }, + mi350x: { tp: 4 }, + mi355x: { tp: 4 }, + }; + + const resolveItems = (option, values) => + typeof option.getDynamicItems === 'function' ? option.getDynamicItems(values) : option.items || []; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + const items = resolveItems(option, initialState); + const def = items.find((item) => item.default && !item.disabled) || items.find((item) => !item.disabled) || items[0]; + initialState[key] = def.id; + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const generateCommand = () => { + const { hardware, reasoning, toolcall, dpattention } = values; + const isAMD = hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi350x' || hardware === 'mi355x'; + const hwConfig = modelConfigs[hardware]; + const tpValue = hwConfig.tp; + + let cmd = ''; + + if (isAMD) { + cmd += 'SGLANG_USE_AITER=1 SGLANG_ROCM_FUSED_DECODE_MLA=0 \\\n'; + } + + cmd += 'sglang serve \\\n'; + cmd += ' --model-path moonshotai/Kimi-K2.6'; + cmd += ` \\\n --tp ${tpValue}`; + if (isAMD) { + cmd += ' \\\n --mem-fraction-static 0.8'; + } + cmd += ' \\\n --trust-remote-code'; + + if (dpattention === 'enabled') { + cmd += ` \\\n --dp ${tpValue} \\\n --enable-dp-attention`; + } + + if (reasoning === 'enabled') { + cmd += ' \\\n --reasoning-parser kimi_k2'; + } + + if (toolcall === 'enabled') { + cmd += ' \\\n --tool-call-parser kimi_k2'; + } + + if (isAMD) { + cmd += ' \\\n --kv-cache-dtype fp8_e4m3'; + } + + cmd += ' \\\n --host 0.0.0.0 \\\n --port 30000'; + return cmd; + }; + + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.4 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + const items = resolveItems(option, values); + return ( +
+
{option.title}
+
+ {items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = !!item.disabled; + return ( + + ); + })} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/kimi-linear-deployment.jsx b/docs_new/src/snippets/autoregressive/kimi-linear-deployment.jsx new file mode 100644 index 000000000..74e4d11ef --- /dev/null +++ b/docs_new/src/snippets/autoregressive/kimi-linear-deployment.jsx @@ -0,0 +1,358 @@ +export const KimiLinearDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300x', default: false }, + { id: 'mi325x', label: 'MI325x', default: false }, + { id: 'mi355x', label: 'MI355x', default: false } + ] + }, + modelname: { + name: 'modelname', + title: 'Model Name', + items: [ + { id: 'instruct', label: 'Kimi-Linear-48B-A3B-Instruct', default: true }, + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', default: true, required: true }, + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + const generateCommand = (values) => { + const { hardware, modelname, strategy, reasoning, toolcall } = values; + + if (modelname === 'instruct' && reasoning === 'enabled') { + return `# Error: Kimi-Linear doesn't support reasoning parser\n# Please select "Disabled" for Reasoning Parser or choose Kimi-Linear-Thinking model`; + } + + const modelMap = { + 'instruct': 'moonshotai/Kimi-Linear-48B-A3B-Instruct', + }; + + const modelName = modelMap[modelname]; + + let cmd = 'python3 -m sglang.launch_server \\\n'; + + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd = 'SGLANG_ROCM_FUSED_DECODE_MLA=0 ' + cmd; + } + + cmd += ` --model-path ${modelName}`; + + cmd += ` \\\n --tp 4`; + + cmd += ` \\\n --trust-remote-code`; + + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser kimi_k2`; + } + + if (reasoning === 'enabled') { + cmd += ` \\\n --reasoning-parser kimi_k2`; + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/ling-25-1t-deployment.jsx b/docs_new/src/snippets/autoregressive/ling-25-1t-deployment.jsx new file mode 100644 index 000000000..f69c81e67 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/ling-25-1t-deployment.jsx @@ -0,0 +1,189 @@ +export const Ling251TDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'gb200', label: 'GB200', default: false }, + { id: 'gb300', label: 'GB300', default: false } + ] + }, + parallelism: { + name: 'parallelism', + title: 'Parallelism Strategy', + items: [ + { id: 'tp4pp2', label: 'TP4 + PP2', default: true }, + { id: 'tp8', label: 'TP8', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, parallelism, toolcall } = values; + + const isGB = hardware === 'gb200' || hardware === 'gb300'; + const envPrefix = isGB ? 'NCCL_IB_DISABLE=1 ' : ''; + + let tp, pp; + if (isGB && parallelism === 'tp8') { + tp = 8; + pp = null; + } else if (isGB) { + tp = 4; + pp = 2; + } else { + tp = 8; + pp = 2; + } + + const needMemFrac = hardware === 'h200' || (isGB && parallelism !== 'tp8'); + + const generateNodeCmd = (rank) => { + let cmd = `${envPrefix}python3 -m sglang.launch_server \\\n`; + cmd += ` --model-path inclusionAI/Ling-2.5-1T \\\n`; + cmd += ` --trust-remote-code \\\n`; + cmd += ` --tp-size ${tp} \\\n`; + if (pp) { + cmd += ` --pp-size ${pp} \\\n`; + } + cmd += ` --nnodes 2 \\\n`; + cmd += ` --node-rank ${rank} \\\n`; + if (rank === 0) { + cmd += ` --host 0.0.0.0 \\\n`; + cmd += ` --port \${PORT} \\\n`; + } + cmd += ` --dist-init-addr \${MASTER_IP}:\${DIST_PORT}`; + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser qwen`; + } + if (needMemFrac) { + cmd += ` \\\n --mem-frac 0.95`; + } + return cmd; + }; + + let output = `# MASTER_IP is Node 0 IP. PORT and DIST_PORT can be assigned by yourself.\n\n`; + output += `# Node 0:\n`; + output += generateNodeCmd(0); + output += `\n\n\n# Node 1:\n`; + output += generateNodeCmd(1); + + return output; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + const isGB = values.hardware === 'gb200' || values.hardware === 'gb300'; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + // Only show parallelism for GB200/GB300 + if (key === 'parallelism' && !isGB) return null; + return ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isItemDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/llada-21-deployment.jsx b/docs_new/src/snippets/autoregressive/llada-21-deployment.jsx new file mode 100644 index 000000000..025bf8247 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/llada-21-deployment.jsx @@ -0,0 +1,338 @@ +export const LLaDA21Deployment = () => { + const modelFamily = 'inclusionAI'; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h100', label: 'H100', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: 'mini', label: 'Mini (16B)', subtitle: 'MoE', default: true }, + { id: 'flash', label: 'Flash (100B)', subtitle: 'MoE', default: false } + ] + } + }; + + const generateCommand = (values) => { + const { hardware, modelsize } = values; + + const modelName = modelsize === 'mini' ? 'LLaDA2.1-mini' : 'LLaDA2.1-flash'; + const modelPath = `${modelFamily}/${modelName}`; + + let tpSize; + if (modelsize === 'mini') { + tpSize = 1; + } else { + if (hardware === 'b200') { + tpSize = 2; + } else { + tpSize = 4; + } + } + + const args = []; + args.push(`--model-path ${modelPath}`); + args.push(`--dllm-algorithm JointThreshold`); + args.push(`--tp ${tpSize}`); + args.push(`--trust-remote-code`); + args.push(`--mem-fraction-static 0.8`); + args.push(`--max-running-requests 1`); + if (hardware === 'h100' || hardware === 'h200' || hardware === 'b200') { + args.push(`--attention-backend flashinfer`); + } + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` ${args.join(' \\\n ')}`; + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/llama31-deployment.jsx b/docs_new/src/snippets/autoregressive/llama31-deployment.jsx new file mode 100644 index 000000000..d319b9cc9 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/llama31-deployment.jsx @@ -0,0 +1,252 @@ +export const Llama31Deployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h100', label: 'H100', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '8b', label: '8B', default: false }, + { id: '70b', label: '70B', default: true }, + { id: '405b', label: '405B', default: false } + ] + }, + category: { + name: 'category', + title: 'Category', + items: [ + { id: 'base', label: 'Base', default: false }, + { id: 'instruct', label: 'Instruct', default: true } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + optimization: { + name: 'optimization', + title: 'Optimization Mode', + items: [ + { id: 'basic', label: 'Basic', default: true }, + { id: 'throughput', label: 'Throughput Optimized', default: false }, + { id: 'latency', label: 'Latency Optimized', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command + const generateCommand = () => { + const { hardware, optimization, modelsize, category, toolcall, quantization } = values; + + const isAMD = hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x'; + + // Model size mapping + const sizeMap = { + '8b': '8B', + '70b': '70B', + '405b': '405B' + }; + const sizeToken = sizeMap[modelsize] || '70B'; + const categorySuffix = category === 'instruct' ? '-Instruct' : ''; + + // Determine model path + let modelPath; + if (quantization === 'fp8' && category === 'instruct') { + if (modelsize === '405b') { + // Meta official FP8 for 405B + modelPath = `meta-llama/Llama-3.1-${sizeToken}${categorySuffix}-FP8`; + } else if (isAMD) { + // AMD FP8-KV variants for 70B/8B on AMD GPUs + modelPath = `amd/Llama-3.1-${sizeToken}${categorySuffix}-FP8-KV`; + } else { + modelPath = `meta-llama/Llama-3.1-${sizeToken}${categorySuffix}`; + } + } else { + modelPath = `meta-llama/Llama-3.1-${sizeToken}${categorySuffix}`; + } + + // Determine TP size + let tpSize; + if (isAMD) { + // AMD GPU TP configuration + const amdTpConfig = { + 'mi300x': { + '405b': { bf16: 8, fp8: 4 }, + '70b': { bf16: 1, fp8: 1 }, + '8b': { bf16: 1, fp8: 1 } + }, + 'mi325x': { + '405b': { bf16: 8, fp8: 4 }, + '70b': { bf16: 1, fp8: 1 }, + '8b': { bf16: 1, fp8: 1 } + }, + 'mi355x': { + '405b': { bf16: 4, fp8: 2 }, + '70b': { bf16: 1, fp8: 1 }, + '8b': { bf16: 1, fp8: 1 } + } + }; + tpSize = quantization === 'fp8' + ? amdTpConfig[hardware][modelsize].fp8 + : amdTpConfig[hardware][modelsize].bf16; + } else { + // NVIDIA GPU TP configuration + if (modelsize === '405b') { + tpSize = 8; + } else if (modelsize === '70b' && (hardware === 'h100' || hardware === 'h200')) { + tpSize = 2; + } + } + + // Build command args + const args = []; + args.push(`--model-path ${modelPath}`); + + if (tpSize) { + args.push(`--tp ${tpSize}`); + } + + // Add quantization flag only if not using FP8 variant model + if (quantization === 'fp8' && category !== 'instruct') { + args.push(`--quantization fp8`); + } + + // NVIDIA-specific optimizations + if (!isAMD) { + if (optimization === 'throughput') { + args.push(`--enable-dp-attention`); + args.push(`--mem-fraction-static 0.85`); + } else if (optimization === 'latency') { + args.push(`--speculative-algorithm EAGLE3`); + args.push(`--speculative-num-steps 3`); + args.push(`--speculative-eagle-topk 1`); + args.push(`--speculative-num-draft-tokens 4`); + if (modelsize === '8b' && category === 'instruct') { + args.push(`--speculative-draft-model-path yuhuili/EAGLE3-LLaMA3.1-Instruct-8B`); + } else { + args.push(`--speculative-draft-model-path \${EAGLE3_MODEL_PATH}`); + } + args.push(`--disable-shared-experts-fusion`); + args.push(`--max-running-requests 64`); + args.push(`--mem-fraction-static 0.85`); + args.push(`--kv-cache-dtype fp8_e4m3`); + args.push(`--context-length 32768`); + } + } + + if (toolcall === 'enabled') { + args.push(`--tool-call-parser llama3`); + } + + let cmd = 'sglang serve \\\n'; + cmd += ` ${args.join(' \\\n ')}`; + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/llama33-70b-deployment.jsx b/docs_new/src/snippets/autoregressive/llama33-70b-deployment.jsx new file mode 100644 index 000000000..ca53bb394 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/llama33-70b-deployment.jsx @@ -0,0 +1,138 @@ +export const Llama33Deployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Calling', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization, toolcall } = values; + + // Select model based on quantization + const modelPath = quantization === 'fp8' + ? 'amd/Llama-3.3-70B-Instruct-FP8-KV' + : 'meta-llama/Llama-3.3-70B-Instruct'; + + // Build command + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelPath} \\\n`; + cmd += ` --tp 1`; + + // Add tool calling parser + if (toolcall === 'enabled') { + cmd += ' \\\n --tool-call-parser llama3'; + } + + cmd += ' \\\n --host 0.0.0.0 \\\n'; + cmd += ' --port 30000'; + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/llama4-maverick-deployment.jsx b/docs_new/src/snippets/autoregressive/llama4-maverick-deployment.jsx new file mode 100644 index 000000000..b93fb6ed9 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/llama4-maverick-deployment.jsx @@ -0,0 +1,347 @@ +export const Llama4MaverickDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300x', default: true }, + { id: 'mi325x', label: 'MI325x', default: false }, + { id: 'mi355x', label: 'MI355x', default: false } + ] + }, + host: { + name: 'host', + title: 'Host', + type: 'text', + default: '0.0.0.0', + placeholder: '0.0.0.0' + }, + port: { + name: 'port', + title: 'Port', + type: 'text', + default: '8000', + placeholder: '8000' + } + }; + + const generateCommand = (values) => { + const { hardware, quantization, toolcall, speculative, host, port } = values; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model-path meta-llama/Llama-4-Scout-17B-16E-Instruct`; + + if (hardware === 'h100' || hardware === 'h200') { + cmd += ` \\\n --tp 8`; + } else if (hardware === 'b200') { + cmd += ` \\\n --tp 8`; + } else if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd += ` \\\n --tp 8`; + } + + if (quantization === 'fp8') { + cmd += ` \\\n --quantization fp8`; + } + + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser pythonic`; + } + + if (speculative === 'enabled') { + cmd += ` \\\n --speculative-algorithm EAGLE3 \\\n`; + cmd += ` --speculative-draft-model-path lmsys/sglang-EAGLE3-Llama-4-Scout-17B-16E-Instruct-v1 \\\n`; + cmd += ` --speculative-num-steps 3 \\\n`; + cmd += ` --speculative-eagle-topk 1 \\\n`; + cmd += ` --speculative-num-draft-tokens 4 \\\n`; + cmd += ` --mem-fraction-static 0.75 \\\n`; + cmd += ` --cuda-graph-max-bs 2`; + } + + cmd += ` \\\n --enable-multimodal`; + cmd += ` \\\n --context-length 65536`; + cmd += ` \\\n --dtype bfloat16`; + cmd += ` \\\n --trust-remote-code`; + cmd += ` \\\n --host ${host || '0.0.0.0'}`; + cmd += ` \\\n --port ${port || '8000'}`; + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/llama4-scout-deployment.jsx b/docs_new/src/snippets/autoregressive/llama4-scout-deployment.jsx new file mode 100644 index 000000000..14d4029f1 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/llama4-scout-deployment.jsx @@ -0,0 +1,374 @@ +export const Llama4ScoutDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: false }, + { id: 'h100', label: 'H100', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'mi300x', label: 'MI300x', default: false }, + { id: 'mi325x', label: 'MI325x', default: false }, + { id: 'mi355x', label: 'MI355x', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding (EAGLE3)', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enable EAGLE3', default: false } + ] + }, + host: { + name: 'host', + title: 'Host', + type: 'text', + default: '0.0.0.0', + placeholder: '0.0.0.0' + }, + port: { + name: 'port', + title: 'Port', + type: 'text', + default: '8000', + placeholder: '8000' + } + }; + + const generateCommand = (values) => { + const { hardware, quantization, toolcall, speculative, host, port } = values; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model-path meta-llama/Llama-4-Scout-17B-16E-Instruct`; + + if (hardware === 'h100' || hardware === 'h200') { + cmd += ` \\\n --tp 8`; + } else if (hardware === 'b200') { + cmd += ` \\\n --tp 8`; + } else if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd += ` \\\n --tp 8`; + } + + if (quantization === 'fp8') { + cmd += ` \\\n --quantization fp8`; + } + + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser pythonic`; + } + + if (speculative === 'enabled') { + cmd += ` \\\n --speculative-algorithm EAGLE3 \\\n`; + cmd += ` --speculative-draft-model-path lmsys/sglang-EAGLE3-Llama-4-Scout-17B-16E-Instruct-v1 \\\n`; + cmd += ` --speculative-num-steps 3 \\\n`; + cmd += ` --speculative-eagle-topk 1 \\\n`; + cmd += ` --speculative-num-draft-tokens 4 \\\n`; + cmd += ` --mem-fraction-static 0.75 \\\n`; + cmd += ` --cuda-graph-max-bs 2`; + } + + cmd += ` \\\n --enable-multimodal`; + cmd += ` \\\n --context-length 65536`; + cmd += ` \\\n --dtype bfloat16`; + cmd += ` \\\n --trust-remote-code`; + cmd += ` \\\n --host ${host || '0.0.0.0'}`; + cmd += ` \\\n --port ${port || '8000'}`; + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/mimo-v2-flash-deployment.jsx b/docs_new/src/snippets/autoregressive/mimo-v2-flash-deployment.jsx new file mode 100644 index 000000000..985d1a285 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/mimo-v2-flash-deployment.jsx @@ -0,0 +1,194 @@ +export const MiMoV2FlashDeployment = () => { + // Config mirrors sgl-cookbook src/components/autoregressive/MiMoConfigGenerator/index.js. + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelname: { + name: 'modelname', + title: 'Model Name', + items: [ + { id: 'mimo-v2-flash', label: 'MiMo-V2-Flash', default: true } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP 8 (Required)', default: true, disabled: true }, + { id: 'dp', label: 'DP Attention (DP 2)', default: true }, + { id: 'mtp', label: 'Multi-token Prediction (MTP)', default: true }, + { id: 'optimization', label: 'Performance Optimizations', default: true } + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning & Tools', + type: 'checkbox', + items: [ + { id: 'reasoning', label: 'Reasoning Parser (Qwen3)', default: true }, + { id: 'toolcall', label: 'Tool Call Parser', default: true } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command — mirrors sgl-cookbook's config.generateCommand(values) exactly + const generateCommand = () => { + const { hardware, strategy, reasoning } = values; + const isMI355X = hardware === 'mi355x'; + + const modelPath = 'XiaomiMiMo/MiMo-V2-Flash'; + const strategyArray = Array.isArray(strategy) ? strategy : []; + const reasoningArray = Array.isArray(reasoning) ? reasoning : []; + + if (isMI355X && strategyArray.includes('mtp')) { + return '# MI355X Speculative Decoding (EAGLE): Work In Progress\n' + + '# Uncheck "Multi-token Prediction (MTP)" to view the validated non-speculative MI355X command.'; + } + + const commandPrefix = isMI355X + ? 'PYTHONPATH=/sgl-workspace/aiter SGLANG_USE_AITER=0 USE_ROCM_AITER_ROPE_BACKEND=0' + : 'SGLANG_ENABLE_SPEC_V2=1'; + const tpSize = isMI355X ? 4 : 8; + + let cmd = `${commandPrefix} sglang serve \\\n`; + cmd += ` --model-path ${modelPath} \\\n`; + cmd += ` --trust-remote-code \\\n`; + cmd += ` --tp-size ${tpSize}`; + + // DP settings + if (!isMI355X && strategyArray.includes('dp')) { + cmd += ` \\\n --dp-size 2 \\\n --enable-dp-attention`; + } + + // Performance Optimizations + if (strategyArray.includes('optimization')) { + cmd += ` \\\n --mem-fraction-static 0.75 \\\n --max-running-requests 128 \\\n --chunked-prefill-size 16384 \\\n --model-loader-extra-config '{"enable_multithread_load": "true","num_threads": 64}'`; + cmd += isMI355X + ? ` \\\n --attention-backend triton \\\n --prefill-attention-backend triton \\\n --decode-attention-backend triton \\\n --disable-custom-all-reduce` + : ` \\\n --attention-backend fa3`; + } + + // MTP/Speculative settings + if (!isMI355X && strategyArray.includes('mtp')) { + cmd += ` \\\n --speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4 \\\n --enable-multi-layer-eagle`; + } + + // Reasoning Parser + if (reasoningArray.includes('reasoning')) { + cmd += ` \\\n --reasoning-parser qwen3`; + } + + // Tool Call Parser + if (reasoningArray.includes('toolcall')) { + cmd += ` \\\n --tool-call-parser mimo`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = item.disabled; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/minimax-m2-deployment.jsx b/docs_new/src/snippets/autoregressive/minimax-m2-deployment.jsx new file mode 100644 index 000000000..420199f52 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/minimax-m2-deployment.jsx @@ -0,0 +1,353 @@ +export const MiniMaxM2Deployment = () => { + const modelFamily = 'MiniMaxAI'; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelname: { + name: 'modelname', + title: 'Model Name', + items: [ + { id: 'M2.1', label: 'MiniMax-M2.1', default: true }, + { id: 'M2', label: 'MiniMax-M2', default: false } + ] + }, + strategy: { + name: 'strategy', + title: 'Deployment Strategy', + type: 'checkbox', + items: [ + { id: 'tp', label: 'TP', default: true, required: true }, + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + const generateCommand = (values) => { + const { hardware, modelname, strategy, reasoning, toolcall } = values; + + const modelMap = { + 'M2.1': 'MiniMax-M2.1', + 'M2': 'MiniMax-M2' + }; + + const modelName = `${modelFamily}/${modelMap[modelname]}`; + + let cmd = 'sglang serve \\\n'; + cmd += ` --model-path ${modelName}`; + + cmd += ` \\\n --tp 4`; + + cmd += ` \\\n --trust-remote-code`; + + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser minimax-m2`; + } + + if (reasoning === 'enabled') { + cmd += ` \\\n --reasoning-parser minimax-append-think`; + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/minimax-m25-deployment.jsx b/docs_new/src/snippets/autoregressive/minimax-m25-deployment.jsx new file mode 100644 index 000000000..a0aa95740 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/minimax-m25-deployment.jsx @@ -0,0 +1,390 @@ +export const MiniMaxM25Deployment = () => { + const modelFamily = 'MiniMaxAI'; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'a100', label: 'A100', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + gpuCount: { + name: 'gpuCount', + title: 'GPU Count', + getDynamicItems: (values) => { + const isAMD = values.hardware === 'mi300x' || values.hardware === 'mi325x' || values.hardware === 'mi355x'; + return [ + { + id: '2gpu', + label: '2', + default: isAMD, + disabled: !isAMD + }, + { + id: '4gpu', + label: '4', + default: !isAMD, + disabled: false + }, + { + id: '8gpu', + label: '8', + default: false, + disabled: false + } + ]; + } + }, + thinking: { + name: 'thinking', + title: 'Thinking Capabilities', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser minimax-append-think' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser minimax-m2' : null + } + }; + + const generateCommand = (values) => { + const { hardware, gpuCount, thinking, toolcall } = values; + + const isAMD = hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x'; + if (gpuCount === '2gpu' && !isAMD) { + return '# Please select compatible hardware\n# 2-GPU requires AMD MI300X/MI325X/MI355X'; + } + + const modelName = `${modelFamily}/MiniMax-M2.5`; + + let cmd = ''; + cmd += 'python -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelName}`; + + if (gpuCount === '8gpu') { + cmd += ` \\\n --tp 8`; + cmd += ` \\\n --ep 8`; + } else if (gpuCount === '4gpu') { + cmd += ` \\\n --tp 4`; + if (isAMD) { + cmd += ` \\\n --ep 4`; + } + } else if (gpuCount === '2gpu') { + cmd += ` \\\n --tp 2`; + if (isAMD) { + cmd += ` \\\n --ep 2`; + } + } + + if (toolcall === 'enabled') { + cmd += ` \\\n --tool-call-parser minimax-m2`; + } + + if (thinking === 'enabled') { + cmd += ` \\\n --reasoning-parser minimax-append-think`; + } + + cmd += ` \\\n --trust-remote-code`; + cmd += ` \\\n --mem-fraction-static 0.85`; + + if (isAMD) { + cmd += ` \\\n --kv-cache-dtype fp8_e4m3`; + cmd += ` \\\n --attention-backend triton`; + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/minimax-m27-deployment.jsx b/docs_new/src/snippets/autoregressive/minimax-m27-deployment.jsx new file mode 100644 index 000000000..198f4ca5b --- /dev/null +++ b/docs_new/src/snippets/autoregressive/minimax-m27-deployment.jsx @@ -0,0 +1,203 @@ +export const MiniMaxM27Deployment = () => { + // Config options. `getDynamicItems(values)` is evaluated at render time so that + // e.g. the 2-GPU option is only enabled on AMD or GB300 hardware. + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'gb300', label: 'GB300', default: false }, + { id: 'a100', label: 'A100', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + gpuCount: { + name: 'gpuCount', + title: 'GPU Count', + getDynamicItems: (values) => { + const hw = values.hardware; + const isAMD = hw === 'mi300x' || hw === 'mi325x' || hw === 'mi355x'; + const isGB300 = hw === 'gb300'; + const canUse2GPU = isAMD || isGB300; + return [ + { id: '2gpu', label: '2', default: canUse2GPU, disabled: !canUse2GPU }, + { id: '4gpu', label: '4', default: !canUse2GPU, disabled: false }, + { id: '8gpu', label: '8', default: false, disabled: isGB300 } + ]; + } + }, + thinking: { + name: 'thinking', + title: 'Thinking Capabilities', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + } + }; + + // Helper: resolve an option's items (static or dynamic) given current values + const resolveItems = (option, values) => { + if (typeof option.getDynamicItems === 'function') { + return option.getDynamicItems(values); + } + return option.items; + }; + + const getInitialState = () => { + const initialState = {}; + // Resolve hardware first so gpuCount's dynamic items can see it + for (const [key, option] of Object.entries(options)) { + const items = resolveItems(option, initialState); + const defaultItem = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled) || items[0]; + initialState[key] = defaultItem.id; + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + // When hardware changes, re-evaluate gpuCount so disabled/default shifts apply + useEffect(() => { + setValues(prev => { + const next = { ...prev }; + for (const [key, option] of Object.entries(options)) { + if (typeof option.getDynamicItems !== 'function') continue; + const items = option.getDynamicItems(next); + const current = items.find(i => i.id === next[key]); + if (!current || current.disabled) { + const fallback = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled); + if (fallback) next[key] = fallback.id; + } + } + return next; + }); + }, [values.hardware]); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command mirrors sgl-cookbook src/components/autoregressive/MiniMaxM27ConfigGenerator/index.js + const generateCommand = () => { + const { hardware, gpuCount, thinking, toolcall } = values; + + const isAMD = hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x'; + const isGB300 = hardware === 'gb300'; + const canUse2GPU = isAMD || isGB300; + + if (gpuCount === '2gpu' && !canUse2GPU) { + return '# Please select compatible hardware\n# 2-GPU requires AMD MI300X/MI325X/MI355X or GB300'; + } + + const modelName = 'MiniMaxAI/MiniMax-M2.7'; + + let cmd = 'sglang serve \\\n'; + cmd += ` --model-path ${modelName}`; + + if (gpuCount === '8gpu') { + cmd += ' \\\n --tp 8'; + cmd += ' \\\n --ep 8'; + } else if (gpuCount === '4gpu') { + cmd += ' \\\n --tp 4'; + if (isAMD) cmd += ' \\\n --ep 4'; + } else if (gpuCount === '2gpu') { + cmd += ' \\\n --tp 2'; + if (isAMD) cmd += ' \\\n --ep 2'; + } + + if (toolcall === 'enabled') cmd += ' \\\n --tool-call-parser minimax-m2'; + if (thinking === 'enabled') cmd += ' \\\n --reasoning-parser minimax-append-think'; + + cmd += ' \\\n --trust-remote-code'; + cmd += ' \\\n --mem-fraction-static 0.85'; + + if (isAMD) { + cmd += ' \\\n --kv-cache-dtype fp8_e4m3'; + cmd += ' \\\n --attention-backend triton'; + } + + return cmd; + }; + + // Styles + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.4 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + const items = resolveItems(option, values); + return ( +
+
{option.title}
+
+ {items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = !!item.disabled; + return ( + + ); + })} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/ministral-3-deployment.jsx b/docs_new/src/snippets/autoregressive/ministral-3-deployment.jsx new file mode 100644 index 000000000..94f007ab5 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/ministral-3-deployment.jsx @@ -0,0 +1,348 @@ +export const Ministral3Deployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300x', default: true }, + { id: 'mi325x', label: 'MI325x', default: false }, + { id: 'mi355x', label: 'MI355x', default: false } + ] + }, + model: { + name: 'model', + title: 'Model', + items: [ + { id: 'small', label: 'Ministral-3-8B-Instruct-2512', default: true }, + { id: 'large', label: 'Ministral-3-14B-Instruct-2512', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'enabled', label: 'enabled', default: true }, + { id: 'disabled', label: 'disabled', default: false } + ], + commandRule: (value) => (value === 'enabled' ? '--tool-call-parser mistral' : null) + } + }; + + const modelConfigs = { + small: { + modelId: 'mistralai/Ministral-3-8B-Instruct-2512', + tpByHardware: { mi300x: 1, mi325x: 1, mi355x: 1 } + }, + large: { + modelId: 'mistralai/Ministral-3-14B-Instruct-2512', + tpByHardware: { mi300x: 1, mi325x: 1, mi355x: 1 } + } + }; + + const generateCommand = (values) => { + const { hardware, model } = values; + + const modelCfg = modelConfigs[model]; + if (!modelCfg) return `# Error: Unknown model selection: ${model}`; + + const tp = modelCfg.tpByHardware[hardware]; + if (!tp) return `# Error: Unknown hardware platform: ${hardware}`; + + let cmd = 'sglang serve \\\n'; + + cmd += ` --model ${modelCfg.modelId}`; + + if (tp > 1) { + cmd += ` \\\n --tp ${tp}`; + } + + cmd += ` \\\n --trust-remote-code`; + + for (const [key, option] of Object.entries(options)) { + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) cmd += ` \\\n ${rule}`; + } + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/mistral-small-4-deployment.jsx b/docs_new/src/snippets/autoregressive/mistral-small-4-deployment.jsx new file mode 100644 index 000000000..d70f47b58 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/mistral-small-4-deployment.jsx @@ -0,0 +1,365 @@ +export const MistralSmall4Deployment = () => { + const modelId = 'mistralai/Mistral-Small-4-119B-2603'; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + getDynamicItems: (values) => { + const isNvfp4 = values.quantization === 'fp4'; + return [ + { id: 'h100', label: 'H100', default: !isNvfp4, disabled: isNvfp4 }, + { id: 'h200', label: 'H200', default: false, disabled: isNvfp4 }, + { id: 'b200', label: 'B200', default: isNvfp4, disabled: false }, + { id: 'b300', label: 'B300', default: false, disabled: false }, + ]; + } + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'fp8', label: 'FP8', default: true }, + { id: 'fp4', label: 'NVFP4', subtitle: 'Blackwell only', default: false }, + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser mistral' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser mistral' : null + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding (EAGLE)', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--speculative-algorithm EAGLE \\\n --speculative-draft-model-path mistralai/Mistral-Small-4-119B-2603-eagle \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4' : null + }, + }; + + const modelConfigs = { + h100: { fp8: { tp: 2 } }, + h200: { fp8: { tp: 2 } }, + b200: { fp8: { tp: 1 }, fp4: { tp: 1 } }, + b300: { fp8: { tp: 1 }, fp4: { tp: 1 } }, + }; + + const generateCommand = (values) => { + const { hardware, quantization } = values; + + const hwConfig = modelConfigs[hardware]?.[quantization]; + if (!hwConfig) return `# Error: Unknown hardware/quantization combination`; + + const { tp } = hwConfig; + + const modelName = quantization === 'fp4' + ? 'mistralai/Mistral-Small-4-119B-2603-NVFP4' + : modelId; + + let cmd = `sglang serve --model-path ${modelName}`; + cmd += ` \\\n --tp ${tp}`; + + Object.entries(options).forEach(([key, option]) => { + if (key === 'quantization' || key === 'hardware') return; + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) cmd += ` \\\n ${rule}`; + } + }); + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/nemotron3-nano-deployment.jsx b/docs_new/src/snippets/autoregressive/nemotron3-nano-deployment.jsx new file mode 100644 index 000000000..421bcb46e --- /dev/null +++ b/docs_new/src/snippets/autoregressive/nemotron3-nano-deployment.jsx @@ -0,0 +1,371 @@ +export const Nemotron3NanoDeployment = () => { + const modelFamily = 'nvidia'; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: true } + ] + }, + modelVariant: { + name: 'modelVariant', + title: 'Model Variant', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false }, + { id: 'nvfp4', label: 'NVFP4', default: false } + ] + }, + tp: { + name: 'tp', + title: 'Tensor Parallel (TP)', + items: [ + { id: '1', label: 'TP=1', default: true }, + { id: '2', label: 'TP=2', default: false }, + { id: '4', label: 'TP=4', default: false }, + { id: '8', label: 'TP=8', default: false } + ] + }, + kvcache: { + name: 'kvcache', + title: 'KV Cache DType', + items: [ + { id: 'fp8_e4m3', label: 'fp8_e4m3', default: true }, + { id: 'bf16', label: 'bf16', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser nemotron_3' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser qwen3_coder' : null + } + }; + + const generateCommand = (values) => { + const { hardware, modelVariant, tp, kvcache, thinking, toolcall } = values; + + // Default to FP8 if not selected + const variant = modelVariant || 'fp8'; + const baseName = 'NVIDIA-Nemotron-3-Nano-30B-A3B'; + + const modelName = `${modelFamily}/${baseName}-${variant.toUpperCase()}`; + + let cmd = 'python3 -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelName} \\\n`; + cmd += ` --trust-remote-code \\\n`; + cmd += ` --tp ${tp} \\\n`; + cmd += ` --kv-cache-dtype ${kvcache} \\\n`; + + // Add thinking parser and tool call parser if enabled + for (const [key, option] of Object.entries(options)) { + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) { + cmd += ` ${rule} \\\n`; + } + } + } + + // Remove trailing backslash from last option + cmd = cmd.trimEnd(); + if (cmd.endsWith('\\')) { + cmd = cmd.slice(0, -1).trimEnd(); + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/nemotron3-super-deployment.jsx b/docs_new/src/snippets/autoregressive/nemotron3-super-deployment.jsx new file mode 100644 index 000000000..c9c623695 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/nemotron3-super-deployment.jsx @@ -0,0 +1,381 @@ +export const Nemotron3SuperDeployment = () => { + const MODEL_PATHS = { + bf16: 'nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-BF16', + fp8: 'nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-FP8', + nvfp4: 'nvidia/NVIDIA-Nemotron-3-Super-120B-A12B-NVFP4', + }; + + const options = { + model: { + name: 'model', + title: 'Model', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false }, + { id: 'nvfp4', label: 'NVFP4', default: false }, + ] + }, + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: true } + ] + }, + tp: { + name: 'tp', + title: 'Tensor Parallel (TP)', + items: [ + { id: '2', label: 'TP=2', default: false }, + { id: '4', label: 'TP=4', default: true }, + { id: '8', label: 'TP=8', default: false } + ] + }, + mtp: { + name: 'mtp', + title: 'Multi-token Prediction (MTP)', + items: [ + { id: 'enabled', label: 'Enabled', default: false }, + { id: 'disabled', label: 'Disabled', default: true } + ], + commandRule: (value) => value === 'enabled' ? '--speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4 \\\n --disable-radix-cache' : null + }, + kvcache: { + name: 'kvcache', + title: 'KV Cache DType', + items: [ + { id: 'none', label: 'None', default: true }, + { id: 'fp8_e4m3', label: 'fp8_e4m3', default: false }, + { id: 'bf16', label: 'bf16', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Reasoning Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser nemotron_3' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser qwen3_coder' : null + } + }; + + const generateCommand = (values) => { + const { tp, kvcache, model } = values; + + const modelPath = MODEL_PATHS[model] || MODEL_PATHS['bf16']; + + let cmd = 'python3 -m sglang.launch_server \\\n'; + cmd += ` --model-path ${modelPath} \\\n`; + cmd += ` --trust-remote-code \\\n`; + cmd += ` --tp ${tp} \\\n`; + + if (kvcache && kvcache !== 'none') { + cmd += ` --kv-cache-dtype ${kvcache} \\\n`; + } + + for (const [key, option] of Object.entries(options)) { + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) { + cmd += ` ${rule} \\\n`; + } + } + } + + cmd = cmd.trimEnd(); + if (cmd.endsWith('\\')) { + cmd = cmd.slice(0, -1).trimEnd(); + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen25-vl-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen25-vl-deployment.jsx new file mode 100644 index 000000000..4c686cb42 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen25-vl-deployment.jsx @@ -0,0 +1,364 @@ +export const Qwen25VLDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '72b', label: '72B', subtitle: 'Dense', default: true }, + { id: '32b', label: '32B', subtitle: 'Dense', default: false }, + { id: '7b', label: '7B', subtitle: 'Dense', default: false }, + { id: '3b', label: '3B', subtitle: 'Dense', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true } + ] + } + }; + + const modelConfigs = { + '72b': { + baseName: '72B', + mi300x: { tp: 8, ep: 0 }, + mi325x: { tp: 8, ep: 0 }, + mi355x: { tp: 8, ep: 0 } + }, + '32b': { + baseName: '32B', + mi300x: { tp: 2, ep: 0 }, + mi325x: { tp: 2, ep: 0 }, + mi355x: { tp: 2, ep: 0 } + }, + '7b': { + baseName: '7B', + mi300x: { tp: 1, ep: 0 }, + mi325x: { tp: 1, ep: 0 }, + mi355x: { tp: 1, ep: 0 } + }, + '3b': { + baseName: '3B', + mi300x: { tp: 1, ep: 0 }, + mi325x: { tp: 1, ep: 0 }, + mi355x: { tp: 1, ep: 0 } + } + }; + + const generateCommand = (values) => { + const { hardware, modelsize: modelSize } = values; + + const modelSizeConfig = modelConfigs[modelSize]; + if (!modelSizeConfig) { + return `# Error: Unknown model size: ${modelSize}`; + } + + const hwConfig = modelSizeConfig[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const modelName = `Qwen/Qwen2.5-VL-${modelSizeConfig.baseName}-Instruct`; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + + if ((hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') && modelSize === '72b') { + cmd += ` \\\n --context-length 128000`; + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen3-coder-480b-a35b-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen3-coder-480b-a35b-deployment.jsx new file mode 100644 index 000000000..a24985464 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen3-coder-480b-a35b-deployment.jsx @@ -0,0 +1,139 @@ +export const Qwen3CoderDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + } + }; + + // Model configurations + const modelConfigs = { + '480b': { + baseName: '480B-A35B', + mi300x: { tp: 8, ep: 0 } + } + }; + + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command + const generateCommand = () => { + const { hardware, quantization } = values; + + const config = modelConfigs['480b']; + const hwConfig = config[hardware]; + + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + // Build model name + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `Qwen/Qwen3-Coder-${config.baseName}-Instruct${quantSuffix}`; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + // TP is always 8 for this model + cmd += ` \\\n --tp ${hwConfig.tp}`; + + // FP8 requires EP=2 for MoE dimension alignment + if (quantization === 'fp8') { + cmd += ` \\\n --ep 2`; + } + + // Context length verified on MI300X + cmd += ` \\\n --context-length 8192`; + + // Page size for MoE models + cmd += ` \\\n --page-size 32`; + + // FP8 requires trust-remote-code + if (quantization === 'fp8') { + cmd += ` \\\n --trust-remote-code`; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = item.disabled; + return ( + + ); + })} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen3-coder-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen3-coder-deployment.jsx new file mode 100644 index 000000000..1ceccbf42 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen3-coder-deployment.jsx @@ -0,0 +1,426 @@ +export const Qwen3CoderDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false }, + { id: 'b200', label: 'B200', default: false }, + { id: 'gb200', label: 'GB200', default: false } + ] + }, + modelSize: { + name: 'modelSize', + title: 'Model Size', + items: [ + { id: '480b', label: '480B', subtitle: 'MOE', default: true }, + { id: '30b', label: '30B', subtitle: 'MOE', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false }, + { id: 'nvfp4', label: 'NVFP4', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser qwen3_coder' : null + } + }; + + const modelConfigs = { + '480b': { + baseName: '480B-A35B', + mi300x: { tp: 8 }, + mi325x: { tp: 8 }, + mi355x: { tp: 8 }, + b200: { tp: 8 }, + gb200: { tp: 8 } + }, + '30b': { + baseName: '30B-A3B', + mi300x: { tp: 1 }, + mi325x: { tp: 1 }, + mi355x: { tp: 1 } + } + }; + + const generateCommand = (values) => { + const { hardware, modelSize, quantization } = values; + + const isNvidia = hardware === 'b200' || hardware === 'gb200'; + + const modelConfig = modelConfigs[modelSize]; + const hwConfig = modelConfig[hardware]; + + if (!hwConfig) { + return `# Configuration not available: ${modelSize.toUpperCase()} model has not been verified on ${hardware.toUpperCase()}.`; + } + + // NVFP4 is only available on NVIDIA hardware + if (quantization === 'nvfp4' && !isNvidia) { + return `# NVFP4 quantization is only available on NVIDIA B200/GB200 hardware.`; + } + + // BF16 not verified on NVIDIA + if (quantization === 'bf16' && isNvidia) { + return `# BF16 deployment on ${hardware.toUpperCase()} has not been verified yet. Please use FP8 or NVFP4.`; + } + + // Build model name + let modelName; + if (quantization === 'nvfp4') { + modelName = `nvidia/Qwen3-Coder-${modelConfig.baseName}-Instruct-NVFP`; + } else { + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + modelName = `Qwen/Qwen3-Coder-${modelConfig.baseName}-Instruct${quantSuffix}`; + } + + let cmd = ''; + if (!isNvidia) { + cmd += 'SGLANG_USE_AITER=0 '; + } + cmd += 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + // TP setting + cmd += ` \\\n --tp ${hwConfig.tp}`; + + // EP and DP attention settings + if (quantization === 'nvfp4') { + cmd += ` \\\n --ep 1`; + cmd += ` \\\n --enable-dp-attention`; + } else if (modelSize === '480b' && quantization === 'fp8') { + // FP8 requires EP=2 for 480B model due to MoE dimension alignment + // moe_intermediate_size=2560, with tp=8 ep=1: 2560/8=320, 320%128!=0 + // with tp=8 ep=2: 2560/4=640, 640%128=0 ✓ + cmd += ` \\\n --ep 2`; + } + + // MOE runner backend for NVIDIA + if (isNvidia) { + if (quantization === 'nvfp4') { + cmd += ` \\\n --moe-runner-backend flashinfer_cutlass`; + cmd += ` \\\n --quantization modelopt_fp4`; + } else if (quantization === 'fp8') { + cmd += ` \\\n --moe-runner-backend triton`; + } + } + + // Apply commandRule from all options + Object.entries(options).forEach(([key, option]) => { + if (option.commandRule && values[key]) { + // Pass the full values object so commandRule can access other option values + const additionalCmd = option.commandRule(values[key], values); + if (additionalCmd) { + cmd += ` \\\n ${additionalCmd}`; + } + } + }); + + // AMD-specific flags + if (!isNvidia) { + // Context length verified on MI300X/MI325X/MI355X + cmd += ` \\\n --context-length 8192`; + + // Page size for MoE models + cmd += ` \\\n --page-size 32`; + + // FP8 requires trust-remote-code + if (quantization === 'fp8') { + cmd += ` \\\n --trust-remote-code`; + } + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen3-coder-next-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen3-coder-next-deployment.jsx new file mode 100644 index 000000000..700768c9a --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen3-coder-next-deployment.jsx @@ -0,0 +1,370 @@ +export const Qwen3CoderNextDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'h100', label: 'H100', default: false }, + { id: 'b200', label: 'B200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'enabled', label: 'Enabled', default: true }, + { id: 'disabled', label: 'Disabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser qwen3_coder' : null + }, + mambaCache: { + name: 'mambaCache', + title: 'Mamba Radix Cache', + items: [ + { id: 'v1', label: 'V1', default: true }, + { id: 'v2', label: 'V2', default: false } + ], + commandRule: (value) => value === 'v2' ? '--mamba-scheduler-strategy extra_buffer \\\n --page-size 64' : null + } + }; + + const modelConfigs = { + default: { + baseName: 'Qwen3-Coder-Next', + h100: { bf16: { tp: 4 }, fp8: { tp: 2 } }, + h200: { bf16: { tp: 2 }, fp8: { tp: 1 } }, + b200: { bf16: { tp: 2 }, fp8: { tp: 1 } }, + mi300x: { bf16: { tp: 2 }, fp8: { tp: 1 } }, + mi325x: { bf16: { tp: 2 }, fp8: { tp: 1 } }, + mi355x: { bf16: { tp: 2 }, fp8: { tp: 1 } } + } + }; + + const generateCommand = (values) => { + const { hardware, quantization } = values; + + const hwConfig = modelConfigs.default[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantConfig = hwConfig[quantization]; + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `Qwen/${modelConfigs.default.baseName}${quantSuffix}`; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + // TP setting + if (quantConfig.tp > 1) { + cmd += ` \\\n --tp ${quantConfig.tp}`; + } + + // Apply commandRule from all options + Object.entries(options).forEach(([key, option]) => { + if (option.commandRule && values[key]) { + const additionalCmd = option.commandRule(values[key], values); + if (additionalCmd) { + cmd += ` \\\n ${additionalCmd}`; + } + } + }); + + // AMD GPUs require triton attention backend + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd += ` \\\n --attention-backend triton`; + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen3-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen3-deployment.jsx new file mode 100644 index 000000000..ee99a5793 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen3-deployment.jsx @@ -0,0 +1,330 @@ +export const Qwen3Deployment = () => { + // Model configurations + const modelConfigs = { + '235b': { + baseName: '235B-A22B', + hasThinkingVariants: true, + h100: { tp: 8, ep: 0, bf16: true, fp8: true }, + h200: { tp: 8, ep: 0, bf16: true, fp8: true }, + b200: { tp: 8, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 4, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 4, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 4, ep: 0, bf16: true, fp8: true } + }, + '30b': { + baseName: '30B-A3B', + hasThinkingVariants: true, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '32b': { + baseName: '32B', + hasThinkingVariants: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '14b': { + baseName: '14B', + hasThinkingVariants: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '8b': { + baseName: '8B', + hasThinkingVariants: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '4b': { + baseName: '4B', + hasThinkingVariants: true, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '1.7b': { + baseName: '1.7B', + hasThinkingVariants: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '0.6b': { + baseName: '0.6B', + hasThinkingVariants: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + } + }; + + // Base options + const baseOptions = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h100', label: 'H100', default: false }, + { id: 'h200', label: 'H200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '235b', label: '235B', subtitle: 'MOE', default: true }, + { id: '30b', label: '30B', subtitle: 'MOE', default: false }, + { id: '32b', label: '32B', subtitle: 'Dense', default: false }, + { id: '14b', label: '14B', subtitle: 'Dense', default: false }, + { id: '8b', label: '8B', subtitle: 'Dense', default: false }, + { id: '4b', label: '4B', subtitle: 'Dense', default: false }, + { id: '1.7b', label: '1.7B', subtitle: 'Dense', default: false }, + { id: '0.6b', label: '0.6B', subtitle: 'Dense', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + category: { + name: 'category', + title: 'Categories', + items: [ + { id: 'base', label: 'Base', default: true }, + { id: 'instruct', label: 'Instruct', default: false }, + { id: 'thinking', label: 'Thinking', default: false } + ] + }, + reasoningParser: { + name: 'reasoningParser', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Get dynamic options based on current values + const getDisplayOptions = (values) => { + const options = { ...baseOptions }; + const currentModelConfig = modelConfigs[values.modelsize]; + + // If model doesn't have thinking variants, disable non-base category options + if (currentModelConfig && !currentModelConfig.hasThinkingVariants) { + options.category = { + ...baseOptions.category, + items: baseOptions.category.items.map(item => ({ + ...item, + disabled: item.id !== 'base' + })) + }; + } + + // Only show reasoningParser when category is not 'instruct' + if (values.category === 'instruct') { + delete options.reasoningParser; + } + + return options; + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(baseOptions).forEach(([key, option]) => { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => { + const newValues = { ...prev, [optionName]: value }; + + // Auto-switch to 'base' category for models without thinking variants + if (optionName === 'modelsize') { + const modelConfig = modelConfigs[value]; + if (modelConfig && !modelConfig.hasThinkingVariants) { + if (newValues.category !== 'base') { + newValues.category = 'base'; + } + } + } + + // Reset reasoningParser when switching to 'instruct' category + if (optionName === 'category' && value === 'instruct') { + newValues.reasoningParser = 'disabled'; + } + + return newValues; + }); + }; + + // Generate command + const generateCommand = () => { + const { hardware, modelsize, quantization, category, reasoningParser, toolcall } = values; + const displayOptions = getDisplayOptions(values); + + // Special error handling + const commandKey = `${hardware}-${modelsize}-${quantization}-${category}`; + if (commandKey === 'h100-235b-bf16-instruct' || commandKey === 'h100-235b-bf16-thinking') { + return '# Error: Model is too large, cannot fit into 8*H100\n# Please use H200 (141GB) or select FP8 quantization'; + } + + const config = modelConfigs[modelsize]; + if (!config) { + return `# Error: Unknown model size: ${modelsize}`; + } + + const hwConfig = config[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + + // Build model name based on model category + let modelName; + if (config.hasThinkingVariants) { + if (category === 'base') { + modelName = `Qwen/Qwen3-${config.baseName}${quantSuffix}`; + } else { + const thinkingSuffix = category === 'thinking' ? '-Thinking' : '-Instruct'; + const dateSuffix = '-2507'; + modelName = `Qwen/Qwen3-${config.baseName}${thinkingSuffix}${dateSuffix}${quantSuffix}`; + } + } else { + modelName = `Qwen/Qwen3-${config.baseName}${quantSuffix}`; + } + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + + let ep = hwConfig.ep; + if (quantization === 'fp8' && hwConfig.tp === 8) { + ep = 2; + } + + if (ep > 0) { + cmd += ` \\\n --ep ${ep}`; + } + + // Add reasoning parser + if (reasoningParser === 'enabled' && category !== 'instruct') { + cmd += ' \\\n --reasoning-parser qwen3'; + } + + // Add tool call parser + if (toolcall === 'enabled') { + cmd += ' \\\n --tool-call-parser qwen25'; + } + + return cmd; + }; + + // Get current display options + const displayOptions = getDisplayOptions(values); + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(displayOptions).map(([key, option]) => ( +
+
{option.title}
+
+ {option.items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = item.disabled; + return ( + + ); + })} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen3-next-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen3-next-deployment.jsx new file mode 100644 index 000000000..87dee3ee2 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen3-next-deployment.jsx @@ -0,0 +1,409 @@ +export const Qwen3NextDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '80b', label: '80B', subtitle: 'MOE', default: true }, + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', subtitle: 'Full Weights', default: true }, + { id: 'fp8', label: 'FP8', subtitle: 'High Throughput', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Thinking Capabilities', + items: [ + { id: 'instruct', label: 'Instruct', subtitle: 'General Purpose', default: true }, + { id: 'thinking', label: 'Thinking', subtitle: 'Reasoning / CoT', default: false } + ], + commandRule: (value) => value === 'thinking' ? '--reasoning-parser qwen3' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser qwen' : null + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4' : null + }, + mambaCache: { + name: 'mambaCache', + title: 'Mamba Radix Cache', + items: [ + { id: 'v1', label: 'V1', default: true }, + { id: 'v2', label: 'V2', default: false } + ], + commandRule: (value) => value === 'v2' ? '--mamba-scheduler-strategy extra_buffer \\\n --page-size 64' : null + } + }; + + const modelConfigs = { + '80b': { + baseName: '80B-A3B', + isMOE: true, + h100: { tp: 4, ep: 0, bf16: true, fp8: true }, + h200: { tp: 2, ep: 0, bf16: true, fp8: true }, + b200: { tp: 2, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 2, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 2, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 2, ep: 0, bf16: true, fp8: true } + } + }; + + const generateCommand = (values) => { + const { hardware, modelsize: modelSize, quantization, thinking } = values; + const commandKey = `${hardware}-${modelSize}-${quantization}-${thinking}`; + + const modelSizeConfig = modelConfigs[modelSize]; + if (!modelSizeConfig) { + return `# Error: Unknown model size: ${modelSize}`; + } + + const hwConfig = modelSizeConfig[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const thinkingSuffix = thinking === 'thinking' ? '-Thinking' : '-Instruct'; + const modelName = `Qwen/Qwen3-Next-${modelSizeConfig.baseName}${thinkingSuffix}${quantSuffix}`; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + + let ep = hwConfig.ep; + if (quantization === 'fp8' && hwConfig.tp === 8) { + ep = 2; + } + + if (ep > 0) { + cmd += ` \\\n --ep ${ep}`; + } + + for (const [key, option] of Object.entries(options)) { + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) { + cmd += ` \\\n ${rule}`; + } + } + } + + // AMD GPUs require triton attention backend + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd += ` \\\n --attention-backend triton`; + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen3-vl-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen3-vl-deployment.jsx new file mode 100644 index 000000000..06137bd0c --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen3-vl-deployment.jsx @@ -0,0 +1,245 @@ +export const Qwen3VLDeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h100', label: 'H100', default: false }, + { id: 'h200', label: 'H200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '235b', label: '235B', subtitle: 'MOE', default: true }, + { id: '30b', label: '30B', subtitle: 'MOE', default: false }, + { id: '32b', label: '32B', subtitle: 'Dense', default: false }, + { id: '8b', label: '8B', subtitle: 'Dense', default: false }, + { id: '4b', label: '4B', subtitle: 'Dense', default: false }, + { id: '2b', label: '2B', subtitle: 'Dense', default: false } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + thinking: { + name: 'thinking', + title: 'Thinking Capabilities', + items: [ + { id: 'instruct', label: 'Instruct', default: true }, + { id: 'thinking', label: 'Thinking', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + // Model configurations + const modelConfigs = { + '235b': { + baseName: '235B-A22B', + isMOE: true, + h100: { tp: 8, ep: 0, bf16: true, fp8: true }, + h200: { tp: 8, ep: 0, bf16: true, fp8: true }, + b200: { tp: 8, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 8, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 8, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 8, ep: 0, bf16: true, fp8: true } + }, + '30b': { + baseName: '30B-A3B', + isMOE: true, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '32b': { + baseName: '32B', + isMOE: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '8b': { + baseName: '8B', + isMOE: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '4b': { + baseName: '4B', + isMOE: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + }, + '2b': { + baseName: '2B', + isMOE: false, + h100: { tp: 1, ep: 0, bf16: true, fp8: true }, + h200: { tp: 1, ep: 0, bf16: true, fp8: true }, + b200: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi300x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi325x: { tp: 1, ep: 0, bf16: true, fp8: true }, + mi355x: { tp: 1, ep: 0, bf16: true, fp8: true } + } + }; + + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command + const generateCommand = () => { + const { hardware, modelsize, quantization, thinking, toolcall } = values; + const commandKey = `${hardware}-${modelsize}-${quantization}-${thinking}`; + + // Special error handling + if (commandKey === 'h100-235b-bf16-instruct' || commandKey === 'h100-235b-bf16-thinking') { + return '# Error: Model is too large, cannot fit into 8*H100\n# Please use H200 (141GB) or select FP8 quantization'; + } + + const config = modelConfigs[modelsize]; + if (!config) { + return `# Error: Unknown model size: ${modelsize}`; + } + + const hwConfig = config[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const thinkingSuffix = thinking === 'thinking' ? '-Thinking' : '-Instruct'; + const modelName = `Qwen/Qwen3-VL-${config.baseName}${thinkingSuffix}${quantSuffix}`; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + + let ep = hwConfig.ep; + if (quantization === 'fp8' && hwConfig.tp === 8) { + ep = 2; + } + + if (ep > 0) { + cmd += ` \\\n --ep ${ep}`; + } + + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + if (modelsize === '32b' && quantization === 'bf16') { + cmd += ` \\\n --context-length 65536`; + } + } + + if (thinking === 'thinking') { + cmd += ' \\\n --reasoning-parser qwen3'; + } + + if (toolcall === 'enabled') { + cmd += ' \\\n --tool-call-parser qwen'; + } + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = item.disabled; + return ( + + ); + })} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen35-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen35-deployment.jsx new file mode 100644 index 000000000..68b074ce2 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen35-deployment.jsx @@ -0,0 +1,442 @@ +export const Qwen35Deployment = () => { + // Qwen3.5 Configuration Generator + // + // MoE models (Gated Delta Networks + sparse MoE, hybrid architecture): + // 397B-A17B, 122B-A10B, 35B-A3B + // + // Dense models (standard transformer): + // 27B, 9B, 4B, 2B, 0.8B + // + // GPU requirements (BF16): + // 397B-A17B: H100 tp=16, H200 tp=8, B200 tp=8, B300 tp=4, MI300X tp=8, MI325X tp=4, MI355X tp=4 + // 122B-A10B: H100 tp=4, H200 tp=2, B200 tp=2, B300 tp=1, MI300X tp=2, MI325X tp=1, MI355X tp=1 + // 35B-A3B: H100 tp=1, H200 tp=1, B200 tp=1, B300 tp=1, MI300X tp=1, MI325X tp=1, MI355X tp=1 + // 27B/9B/4B/2B/0.8B: tp=1 on all hardware (including MI300X, MI325X, MI355X) + // + // GPU requirements (FP8, where available): + // 397B-A17B: H100 tp=8, H200 tp=8 ep=8, B200 tp=4, B300 tp=2, MI300X tp=4, MI325X tp=2, MI355X tp=2 + // 122B-A10B: H100 tp=2, H200 tp=1, B200 tp=1, B300 tp=1, MI300X tp=1, MI325X tp=1, MI355X tp=1 + // 35B-A3B: H100 tp=1, H200 tp=1, B200 tp=1, B300 tp=1, MI300X tp=1, MI325X tp=1, MI355X tp=1 + // 27B: tp=1 on all hardware (including MI300X, MI325X, MI355X) + // + // FP4 (397B only, Blackwell required): B200 tp=4, B300 tp=2 + + const MOE_MODELS = new Set(['397b', '122b', '35b']); + const FP8_MODELS = new Set(['397b', '122b', '35b', '27b']); + + // Maps model id -> HuggingFace model name suffix + const MODEL_SUFFIX = { + '397b': '397B-A17B', + '122b': '122B-A10B', + '35b': '35B-A3B', + '27b': '27B', + '9b': '9B', + '4b': '4B', + '2b': '2B', + '0.8b': '0.8B', + }; + + const options = { + model: { + name: 'model', + title: 'Model Variant', + items: [ + { id: '397b', label: '397B', subtitle: 'MoE', default: true }, + { id: '122b', label: '122B', subtitle: 'MoE', default: false }, + { id: '35b', label: '35B', subtitle: 'MoE', default: false }, + { id: '27b', label: '27B', subtitle: 'Dense', default: false }, + { id: '9b', label: '9B', subtitle: 'Dense', default: false }, + { id: '4b', label: '4B', subtitle: 'Dense', default: false }, + { id: '2b', label: '2B', subtitle: 'Dense', default: false }, + { id: '0.8b', label: '0.8B', subtitle: 'Dense', default: false }, + ] + }, + hardware: { + name: 'hardware', + title: 'Hardware Platform', + getDynamicItems: (values) => { + const isNvfp4 = values.quantization === 'fp4'; + return [ + { id: 'h100', label: 'H100', default: !isNvfp4, disabled: isNvfp4 }, + { id: 'h200', label: 'H200', default: false, disabled: isNvfp4 }, + { id: 'b200', label: 'B200', default: false, disabled: false }, + { id: 'b300', label: 'B300', default: isNvfp4, disabled: false }, + { id: 'mi300x', label: 'MI300X', default: false, disabled: isNvfp4 }, + { id: 'mi325x', label: 'MI325X', default: false, disabled: isNvfp4 }, + { id: 'mi355x', label: 'MI355X', default: false, disabled: isNvfp4 } + ]; + } + }, + quantization: { + name: 'quantization', + title: 'Quantization', + getDynamicItems: (values) => { + const hasFp8 = FP8_MODELS.has(values.model); + const hasFp4 = values.model === '397b'; + return [ + { id: 'bf16', label: 'BF16', default: !hasFp8 }, + { id: 'fp8', label: 'FP8', default: hasFp8, disabled: !hasFp8, + disabledReason: 'No FP8 variant available for this model' }, + { id: 'fp4', label: 'FP4', default: false, disabled: !hasFp4, + disabledReason: 'FP4 is only available for Qwen3.5-397B-A17B' } + ]; + } + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding (MTP)', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true } + ] + }, + mambaCache: { + name: 'mambaCache', + title: 'Mamba Radix Cache', + condition: (values) => MOE_MODELS.has(values.model), + getDynamicItems: (currentValues) => { + const amdGpus = ['mi300x', 'mi325x', 'mi355x']; + const isAmdGpu = amdGpus.includes(currentValues.hardware); + const mtpEnabled = currentValues.speculative === 'enabled'; + + // MTP requires V2 mamba radix cache + if (mtpEnabled && !isAmdGpu) { + return [ + { id: 'v1', label: 'V1', default: false, disabled: true }, + { id: 'v2', label: 'V2', default: true } + ]; + } + + // Show V2 as disabled for AMD GPUs (V2 requires FLA backend, NVIDIA only) + if (isAmdGpu) { + return [ + { id: 'v1', label: 'V1', default: true }, + { id: 'v2', label: 'V2', default: false, disabled: true } + ]; + } + + // Show both V1 and V2 enabled for NVIDIA GPUs + return [ + { id: 'v1', label: 'V1', default: true }, + { id: 'v2', label: 'V2', default: false } + ]; + } + } + }; + + const modelConfigs = { + '397b': { + h100: { bf16: { tp: 16, mem: 0.8 }, fp8: { tp: 8, mem: 0.8 } }, + h200: { bf16: { tp: 8, mem: 0.8 }, fp8: { tp: 8, ep: 8, mem: 0.8 } }, + b200: { bf16: { tp: 8, mem: 0.8 }, fp8: { tp: 4, mem: 0.8 }, fp4: { tp: 4, mem: 0.85 } }, + b300: { bf16: { tp: 4, mem: 0.8 }, fp8: { tp: 2, mem: 0.8 }, fp4: { tp: 2, mem: 0.8 } }, + mi300x: { bf16: { tp: 8, mem: 0.8 }, fp8: { tp: 4, mem: 0.8 } }, + mi325x: { bf16: { tp: 4, mem: 0.8 }, fp8: { tp: 2, mem: 0.8 } }, + mi355x: { bf16: { tp: 4, mem: 0.8 }, fp8: { tp: 2, mem: 0.8 } } + }, + '122b': { + h100: { bf16: { tp: 4, mem: 0.8 }, fp8: { tp: 2, mem: 0.8 } }, + h200: { bf16: { tp: 2, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + b200: { bf16: { tp: 2, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + b300: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi300x: { bf16: { tp: 2, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi325x: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi355x: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } } + }, + '35b': { + h100: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + h200: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + b200: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + b300: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi300x: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi325x: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi355x: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } } + }, + '27b': { + h100: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + h200: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + b200: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + b300: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi300x: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi325x: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + mi355x: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } } + }, + '9b': { + h100: { bf16: { tp: 1, mem: 0.8 } }, + h200: { bf16: { tp: 1, mem: 0.8 } }, + b200: { bf16: { tp: 1, mem: 0.8 } }, + b300: { bf16: { tp: 1, mem: 0.8 } }, + mi300x: { bf16: { tp: 1, mem: 0.8 } }, + mi325x: { bf16: { tp: 1, mem: 0.8 } }, + mi355x: { bf16: { tp: 1, mem: 0.8 } } + }, + '4b': { + h100: { bf16: { tp: 1, mem: 0.8 } }, + h200: { bf16: { tp: 1, mem: 0.8 } }, + b200: { bf16: { tp: 1, mem: 0.8 } }, + b300: { bf16: { tp: 1, mem: 0.8 } }, + mi300x: { bf16: { tp: 1, mem: 0.8 } }, + mi325x: { bf16: { tp: 1, mem: 0.8 } }, + mi355x: { bf16: { tp: 1, mem: 0.8 } } + }, + '2b': { + h100: { bf16: { tp: 1, mem: 0.8 } }, + h200: { bf16: { tp: 1, mem: 0.8 } }, + b200: { bf16: { tp: 1, mem: 0.8 } }, + b300: { bf16: { tp: 1, mem: 0.8 } }, + mi300x: { bf16: { tp: 1, mem: 0.8 } }, + mi325x: { bf16: { tp: 1, mem: 0.8 } }, + mi355x: { bf16: { tp: 1, mem: 0.8 } } + }, + '0.8b': { + h100: { bf16: { tp: 1, mem: 0.8 } }, + h200: { bf16: { tp: 1, mem: 0.8 } }, + b200: { bf16: { tp: 1, mem: 0.8 } }, + b300: { bf16: { tp: 1, mem: 0.8 } }, + mi300x: { bf16: { tp: 1, mem: 0.8 } }, + mi325x: { bf16: { tp: 1, mem: 0.8 } }, + mi355x: { bf16: { tp: 1, mem: 0.8 } } + } + }; + + const resolveItems = (option, vals) => + typeof option.getDynamicItems === 'function' ? option.getDynamicItems(vals) : option.items; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + const items = resolveItems(option, initialState); + const def = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled) || items[0]; + initialState[key] = def.id; + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + // When hardware or model changes, re-resolve dynamic selections to stay consistent. + useEffect(() => { + setValues(prev => { + const next = { ...prev }; + for (const [key, option] of Object.entries(options)) { + if (typeof option.getDynamicItems !== 'function') continue; + const items = option.getDynamicItems(next); + const current = items.find(i => i.id === next[key]); + if (!current || current.disabled) { + const fallback = items.find(i => i.default && !i.disabled) || items.find(i => !i.disabled); + if (fallback) next[key] = fallback.id; + } + } + return next; + }); + }, [values.hardware, values.model]); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command — must produce byte-identical output to sgl-cookbook's + // config.generateCommand(values) for every valid combination. + const generateCommand = () => { + const { model, hardware, quantization, speculative, mambaCache } = values; + + const hwConfig = modelConfigs[model]?.[hardware]?.[quantization]; + if (!hwConfig) { + if (quantization === 'fp4') { + return '# FP4 requires B200/B300 (Blackwell) and is only available for Qwen3.5-397B-A17B'; + } + return '# Please select a valid hardware and quantization combination'; + } + + let modelName; + if (quantization === 'fp4') { + modelName = 'nvidia/Qwen3.5-397B-A17B-NVFP4'; + } else { + const suffix = MODEL_SUFFIX[model]; + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + modelName = `Qwen/Qwen3.5-${suffix}${quantSuffix}`; + } + + const tpValue = hwConfig.tp; + const epValue = hwConfig.ep; + const memFraction = hwConfig.mem; + + // Initialize the base command + let cmd = `sglang serve --model-path ${modelName}`; + if (tpValue > 1) { + cmd += ` \\\n --tp ${tpValue}`; + } + if (epValue) { + cmd += ` \\\n --expert-parallel-size ${epValue}`; + } + + // Force Mamba V1 for AMD GPUs (V2 requires FLA backend) + // Force Mamba V2 when MTP is enabled + const amdGpus = ['mi300x', 'mi325x', 'mi355x']; + const actualMambaCache = amdGpus.includes(hardware) ? 'v1' : (speculative === 'enabled' ? 'v2' : mambaCache); + + // Apply commandRules from options (reasoning, toolcall, speculative, mambaCache) + // Skip quantization and model (handled via model name) + const commandRules = { + reasoning: (value) => value === 'enabled' ? '--reasoning-parser qwen3' : null, + toolcall: (value) => value === 'enabled' ? '--tool-call-parser qwen3_coder' : null, + speculative: (value) => value === 'enabled' ? '--speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4' : null, + mambaCache: (value) => value === 'v2' ? '--mamba-scheduler-strategy extra_buffer' : null, + }; + + // Iterate options in order, applying commandRules + for (const [key, option] of Object.entries(options)) { + if (key === 'quantization' || key === 'model') continue; + // Skip options that don't pass their condition + if (option.condition && !option.condition(values)) continue; + const rule = commandRules[key]; + if (rule) { + const adjustedValue = key === 'mambaCache' ? actualMambaCache : values[key]; + const result = rule(adjustedValue); + if (result) { + cmd += ` \\\n ${result}`; + } + } + } + + // Chunked prefill tuning for H200 FP8 + MTP (validated on H200 only) + if (hardware === 'h200' && quantization === 'fp8' && speculative === 'enabled') { + cmd += ` \\\n --max-running-requests 128`; + cmd += ` \\\n --chunked-prefill-size 16384`; + cmd += ` \\\n --tokenizer-worker-num 6`; + } + + // Enable allreduce fusion for all Qwen3.5 configs (skip for FP4: benchmark only enables this for TP>=8). + if (quantization !== 'fp4') { + cmd += ` \\\n --enable-flashinfer-allreduce-fusion`; + } + + // H200 FP8-specific optimizations + if (hardware === 'h200' && quantization === 'fp8') { + cmd += ` \\\n --attention-backend flashinfer`; + if (MOE_MODELS.has(model)) { + cmd += ` \\\n --mamba-ssm-dtype bfloat16`; + } + } + + // Append backend configurations + if (hardware === 'b200' || hardware === 'b300') { + cmd += ` \\\n --attention-backend trtllm_mha`; + } + + // Append AMD GPU-specific backend configurations + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd += ` \\\n --attention-backend triton`; + } + + // Tokenizer workers for H200 and B200/B300 + if (hardware === 'h200' || hardware === 'b200' || hardware === 'b300') { + if (speculative === 'disabled') { + cmd += ` \\\n --tokenizer-worker-num 6`; + } + } + + // FP4-specific backend settings + if (quantization === 'fp4') { + cmd += ' \\\n --quantization modelopt_fp4'; + cmd += ' \\\n --fp4-gemm-backend flashinfer_cutlass'; + cmd += ' \\\n --kv-cache-dtype fp8_e4m3'; + cmd += ' \\\n --moe-runner-backend flashinfer_trtllm'; + cmd += ' \\\n --chunked-prefill-size 32768'; + cmd += ' \\\n --max-prefill-tokens 32768'; + cmd += ' \\\n --max-running-requests 128'; + cmd += ' \\\n --stream-interval 30'; + cmd += ' \\\n --disable-radix-cache'; + } + + // Add memory fraction last + cmd += ` \\\n --mem-fraction-static ${memFraction}`; + + return cmd; + }; + + // Styles + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.4 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (typeof option.condition === 'function' && !option.condition(values)) return null; + const items = resolveItems(option, values); + return ( +
+
{option.title}
+
+ {items.map(item => { + const isChecked = values[option.name] === item.id; + const isDisabled = !!item.disabled; + return ( + + ); + })} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/qwen36-deployment.jsx b/docs_new/src/snippets/autoregressive/qwen36-deployment.jsx new file mode 100644 index 000000000..af23db105 --- /dev/null +++ b/docs_new/src/snippets/autoregressive/qwen36-deployment.jsx @@ -0,0 +1,219 @@ +export const Qwen36Deployment = () => { + // Config mirrors sgl-cookbook src/components/autoregressive/Qwen36ConfigGenerator/index.js. + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h100', label: 'H100', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'b200', label: 'B200', default: false }, + ], + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'fp8', label: 'FP8', default: true }, + { id: 'bf16', label: 'BF16', default: false }, + ], + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true }, + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser qwen3' : null, + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true }, + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser qwen3_coder' : null, + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding (MTP)', + items: [ + { id: 'disabled', label: 'Disabled', default: false }, + { id: 'enabled', label: 'Enabled', default: true }, + ], + commandRule: (value) => value === 'enabled' ? '--speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4' : null, + }, + mambaCache: { + name: 'mambaCache', + title: 'Mamba Radix Cache', + getDynamicItems: (values) => { + const mtpEnabled = values.speculative === 'enabled'; + if (mtpEnabled) { + return [ + { id: 'v1', label: 'V1', default: false, disabled: true }, + { id: 'v2', label: 'V2', default: true }, + ]; + } + return [ + { id: 'v1', label: 'V1', default: true }, + { id: 'v2', label: 'V2', default: false }, + ]; + }, + commandRule: (value) => value === 'v2' ? '--mamba-scheduler-strategy extra_buffer' : null, + }, + }; + + const modelConfigs = { + h100: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + h200: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + b200: { bf16: { tp: 1, mem: 0.8 }, fp8: { tp: 1, mem: 0.8 } }, + }; + + const resolveItems = (option, vals) => + typeof option.getDynamicItems === 'function' ? option.getDynamicItems(vals) : option.items; + + const getInitialState = () => { + const initialState = {}; + for (const [key, option] of Object.entries(options)) { + const items = resolveItems(option, initialState); + const def = items.find((item) => item.default && !item.disabled) || items.find((item) => !item.disabled) || items[0]; + initialState[key] = def.id; + } + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + useEffect(() => { + setValues((prev) => { + const next = { ...prev }; + for (const [key, option] of Object.entries(options)) { + if (typeof option.getDynamicItems !== 'function') continue; + const items = option.getDynamicItems(next); + const current = items.find((item) => item.id === next[key]); + if (!current || current.disabled) { + const fallback = items.find((item) => item.default && !item.disabled) || items.find((item) => !item.disabled); + if (fallback) next[key] = fallback.id; + } + } + return next; + }); + }, [values.speculative]); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const generateCommand = () => { + const { hardware, quantization, speculative } = values; + const hwConfig = modelConfigs[hardware]?.[quantization]; + if (!hwConfig) { + return '# Please select a valid hardware and quantization combination'; + } + + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `Qwen/Qwen3.6-35B-A3B${quantSuffix}`; + + let cmd = ''; + if (speculative === 'enabled') { + cmd += 'SGLANG_ENABLE_SPEC_V2=1 '; + } + + cmd += `sglang serve --model-path ${modelName}`; + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + + const adjustedValues = { + ...values, + mambaCache: speculative === 'enabled' ? 'v2' : values.mambaCache, + }; + + for (const [key, option] of Object.entries(options)) { + if (key === 'quantization' || key === 'hardware') continue; + if (!option.commandRule) continue; + const rule = option.commandRule(adjustedValues[key]); + if (rule) { + cmd += ` \\\n ${rule}`; + } + } + + if (hardware === 'b200') { + cmd += ` \\\n --attention-backend trtllm_mha`; + } + + cmd += ` \\\n --mem-fraction-static ${hwConfig.mem}`; + return cmd; + }; + + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.4 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + const items = resolveItems(option, values); + return ( +
+
{option.title}
+
+ {items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = !!item.disabled; + return ( + + ); + })} +
+
+ ); + })} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/ring-25-1t-deployment.jsx b/docs_new/src/snippets/autoregressive/ring-25-1t-deployment.jsx new file mode 100644 index 000000000..6ffa5169e --- /dev/null +++ b/docs_new/src/snippets/autoregressive/ring-25-1t-deployment.jsx @@ -0,0 +1,217 @@ +export const Ring251TDeployment = () => { + // Config mirrors sgl-cookbook src/components/autoregressive/Ring25ConfigGenerator/index.js. + // + // GPU requirements: + // H200 / B200 / GB200 / GB300 / MI355X: single-node (tp per platform) + // MI300X / MI325X: two nodes, tp-size 8, pp-size 2 (multi-node scripts) + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'b200', label: 'B200', default: false }, + { id: 'gb200', label: 'GB200', default: false }, + { id: 'gb300', label: 'GB300', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ] + } + }; + + const modelConfigs = { + h200: { fp8: { tp: 8 } }, + b200: { fp8: { tp: 8 } }, + gb200: { fp8: { tp: 4 } }, + gb300: { fp8: { tp: 4 } }, + mi300x: { fp8: { tp: 8, pp: 2, nnodes: 2 } }, + mi325x: { fp8: { tp: 8, pp: 2, nnodes: 2 } }, + mi355x: { fp8: { tp: 8 } } + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = option.items.filter(item => item.default).map(item => item.id); + } else { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues(prev => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } else { + return { ...prev, [optionName]: currentValues.filter(id => id !== itemId) }; + } + }); + }; + + // Generate command — byte-identical to sgl-cookbook Ring25ConfigGenerator + const generateCommand = () => { + const { hardware, reasoning, toolcall } = values; + const modelName = 'inclusionAI/Ring-2.5-1T'; + const amdMultiNode = hardware === 'mi300x' || hardware === 'mi325x'; + + // Extra flags from reasoning / toolcall + const extraFlags = []; + if (reasoning === 'enabled') extraFlags.push('--reasoning-parser deepseek-r1'); + if (toolcall === 'enabled') extraFlags.push('--tool-call-parser qwen'); + + if (amdMultiNode) { + const hwConfig = modelConfigs[hardware].fp8; + const tpSize = hwConfig.tp; + const ppSize = hwConfig.pp; + + const buildAmdNodeCmd = (nodeRank) => { + let cmd = 'sglang serve \\\n'; + cmd += `--model-path ${modelName} \\\n`; + cmd += '--trust-remote-code \\\n'; + cmd += `--tp-size ${tpSize} \\\n`; + cmd += `--pp-size ${ppSize} \\\n`; + cmd += `--nnodes ${hwConfig.nnodes} \\\n`; + cmd += `--node-rank ${nodeRank} \\\n`; + if (nodeRank === 0) { + cmd += '--host 0.0.0.0 \\\n'; + cmd += '--port 30000 \\\n'; + } + cmd += '--dist-init-addr ${MASTER_IP}:${DIST_PORT} \\\n'; + cmd += '--attention-backend triton \\\n'; + cmd += '--model-loader-extra-config \'{"enable_multithread_load": "true","num_threads": 64}\' \\\n'; + cmd += '--mem-frac 0.95'; + extraFlags.forEach((flag) => { + cmd += ` \\\n${flag}`; + }); + return cmd; + }; + + const envBlock = + 'export MASTER_IP= # Replace with the IP of Node 0\n' + + 'export PORT=30000\n' + + 'export DIST_PORT=20000\n' + + '# Replace with your actual NIC interface name\n' + + 'export GLOO_SOCKET_IFNAME=\n' + + 'export TP_SOCKET_IFNAME=\n'; + + let out = envBlock + '\n'; + + out += '\n# Node 0:\n'; + out += buildAmdNodeCmd(0); + + out += '\n\n\n# Node 1:\n'; + out += buildAmdNodeCmd(1); + + return out; + } + + // Single-node path (H200, B200, GB200, GB300, MI355X) + const hwConfig = modelConfigs[hardware].fp8; + const tpValue = hwConfig.tp; + + let cmd = 'sglang serve \\\n'; + cmd += ` --model-path ${modelName}`; + cmd += ` \\\n --tp ${tpValue}`; + cmd += ' \\\n --trust-remote-code'; + + extraFlags.forEach((flag) => { + cmd += ` \\\n ${flag}`; + }); + + return cmd; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const disabledStyle = { cursor: 'not-allowed', opacity: 0.5 }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.type === 'checkbox' ? ( + option.items.map(item => { + const isChecked = (values[option.name] || []).includes(item.id); + const isItemDisabled = item.required; + return ( + + ); + }) + ) : ( + option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + }) + )} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/step-35-deployment.jsx b/docs_new/src/snippets/autoregressive/step-35-deployment.jsx new file mode 100644 index 000000000..9e633b64c --- /dev/null +++ b/docs_new/src/snippets/autoregressive/step-35-deployment.jsx @@ -0,0 +1,393 @@ +export const Step35Deployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'h200', label: 'H200', default: true }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi350x', label: 'MI350X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '196b', label: '196B', subtitle: 'MOE', default: true }, + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + reasoningParser: { + name: 'reasoningParser', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser step3p5' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser step3p5' : null + }, + speculative: { + name: 'speculative', + title: 'Speculative Decoding', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => { + if (value !== 'enabled') return null; + + let cmd = '--speculative-algorithm EAGLE \\\n --speculative-num-steps 3 \\\n --speculative-eagle-topk 1 \\\n --speculative-num-draft-tokens 4 \\\n --enable-multi-layer-eagle '; + + return cmd; + } + } + }; + + const modelConfigs = { + '196b': { + baseName: '196b', + isMOE: true, + h200: { tp: 4, bf16: true }, + mi300x: { tp: 4, bf16: true }, + mi325x: { tp: 4, bf16: true }, + mi350x: { tp: 4, bf16: true }, + mi355x: { tp: 4, bf16: true }, + }, + }; + + const generateCommand = (values) => { + const { hardware, modelsize: modelSize, quantization, reasoningParser } = values; + const isAMD = hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi350x' || hardware === 'mi355x'; + + const modelSizeConfig = modelConfigs[modelSize]; + const hwConfig = modelSizeConfig[hardware]; + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `stepfun-ai/Step-3.5-Flash${quantSuffix}`; + + let tpValue = hwConfig.tp; + + let cmd = ''; + + cmd += 'sglang serve \\\n'; + cmd += ` --model-path ${modelName}`; + + if (tpValue > 1) { + cmd += ` \\\n --tp ${tpValue}`; + } + // EP required for FP8, and for AMD BF16 (AITER CK GEMM N=320 crash without EP) + if (quantSuffix === '-FP8' || isAMD) { + cmd += ` \\\n --ep ${tpValue}`; + } + + // Trust remote code for custom architecture + cmd += ' \\\n --trust-remote-code'; + + for (const [key, option] of Object.entries(options)) { + if (option.commandRule) { + const rule = option.commandRule(values[key], values); + + if (rule) { + cmd += ` \\\n ${rule}`; + } + } + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/autoregressive/step-3vl-10b-deployment.jsx b/docs_new/src/snippets/autoregressive/step-3vl-10b-deployment.jsx new file mode 100644 index 000000000..d6e80970a --- /dev/null +++ b/docs_new/src/snippets/autoregressive/step-3vl-10b-deployment.jsx @@ -0,0 +1,383 @@ +export const Step3VL10BDeployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h100', label: 'H100', default: false }, + { id: 'h200', label: 'H200', default: false }, + { id: 'a100', label: 'A100', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '10b', label: '10B', subtitle: 'Dense', default: true } + ] + }, + quantization: { + name: 'quantization', + title: 'Quantization', + items: [ + { id: 'bf16', label: 'BF16', default: true }, + { id: 'fp8', label: 'FP8', default: false } + ] + }, + reasoning: { + name: 'reasoning', + title: 'Reasoning Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--reasoning-parser deepseek-r1' : null + }, + toolcall: { + name: 'toolcall', + title: 'Tool Call Parser', + items: [ + { id: 'disabled', label: 'Disabled', default: true }, + { id: 'enabled', label: 'Enabled', default: false } + ], + commandRule: (value) => value === 'enabled' ? '--tool-call-parser hermes' : null + } + }; + + const modelConfigs = { + '10b': { + baseName: '10B', + isMOE: false, + b200: { tp: 1, bf16: true, fp8: true }, + h100: { tp: 1, bf16: true, fp8: true }, + h200: { tp: 1, bf16: true, fp8: true }, + a100: { tp: 1, bf16: true, fp8: true }, + mi300x: { tp: 1, bf16: true, fp8: true }, + mi325x: { tp: 1, bf16: true, fp8: true }, + mi355x: { tp: 1, bf16: true, fp8: true } + } + }; + + const generateCommand = (values) => { + const { hardware, modelsize: modelSize, quantization } = values; + + const modelSizeConfig = modelConfigs[modelSize]; + if (!modelSizeConfig) { + return `# Error: Unknown model size: ${modelSize}`; + } + + const hwConfig = modelSizeConfig[hardware]; + if (!hwConfig) { + return `# Error: Unknown hardware platform: ${hardware}`; + } + + const quantSuffix = quantization === 'fp8' ? '-FP8' : ''; + const modelName = `stepfun-ai/Step3-VL-10B${quantSuffix}`; + + let cmd = 'python -m sglang.launch_server \\\n'; + cmd += ` --model ${modelName}`; + + if (hwConfig.tp > 1) { + cmd += ` \\\n --tp ${hwConfig.tp}`; + } + + cmd += ' \\\n --host 0.0.0.0 \\\n --port 30000'; + if (hardware === 'mi300x' || hardware === 'mi325x' || hardware === 'mi355x') { + cmd += ' \\\n --attention-backend triton'; + } + cmd += ' \\\n --trust-remote-code'; + + for (const [key, option] of Object.entries(options)) { + if (option.commandRule) { + const rule = option.commandRule(values[key]); + if (rule) { + cmd += ` \\\n ${rule}`; + } + } + } + + return cmd; + }; + + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = generateCommand(values); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + return ( + + ); + }) + )} +
+
+ ); + })} +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/diffusion/flux-deployment.jsx b/docs_new/src/snippets/diffusion/flux-deployment.jsx new file mode 100644 index 000000000..2a004865c --- /dev/null +++ b/docs_new/src/snippets/diffusion/flux-deployment.jsx @@ -0,0 +1,335 @@ +export const FluxDeployment = () => { + const config = { + modelFamily: 'FLUX', + + options: { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi355x', label: 'MI355X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + ] + }, + version: { + name: 'version', + title: 'Model Version', + items: [ + { id: 'flux1-dev', label: 'FLUX.1-dev', subtitle: '12B', default: true }, + { id: 'flux2-dev', label: 'FLUX.2-dev', subtitle: '32B', default: false } + ] + } + }, + + modelConfigs: { + 'flux1-dev': { repoId: 'black-forest-labs/FLUX.1-dev' }, + 'flux2-dev': { repoId: 'black-forest-labs/FLUX.2-dev' } + }, + + generateCommand: function(values) { + const { version } = values; + const config = this.modelConfigs[version]; + + return `sglang serve \\ + --model-path ${config.repoId} \\ + --ulysses-degree=1 \\ + --ring-degree=1`; + } + }; + + if (!config || !config.options) { + return
Error: Invalid configuration provided
; + } + + const getInitialState = () => { + const initialState = {}; + Object.entries(config.options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(config.options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = config.generateCommand ? config.generateCommand.call(config, values) : ''; + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(config.options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + + return ( + + ); + }) + )} +
+
+ ); + })} + +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/diffusion/mova-deployment.jsx b/docs_new/src/snippets/diffusion/mova-deployment.jsx new file mode 100644 index 000000000..aabd6284e --- /dev/null +++ b/docs_new/src/snippets/diffusion/mova-deployment.jsx @@ -0,0 +1,115 @@ +export const MOVADeployment = () => { + // Config options + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'a100', label: 'A100', default: false } + ] + }, + resolution: { + name: 'resolution', + title: 'Resolution', + items: [ + { id: '360p', label: '360p', subtitle: 'Fast inference, lower VRAM', default: true }, + { id: '720p', label: '720p', subtitle: 'Higher resolution', default: false } + ] + } + }; + + // Initialize state + const getInitialState = () => { + const initialState = {}; + Object.entries(options).forEach(([key, option]) => { + const defaultItem = option.items.find(item => item.default); + initialState[key] = defaultItem ? defaultItem.id : option.items[0].id; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues(prev => ({ ...prev, [optionName]: value })); + }; + + // Generate command + const generateCommand = () => { + const { resolution } = values; + const modelPath = resolution === '720p' + ? 'OpenMOSS-Team/MOVA-720p' + : 'OpenMOSS-Team/MOVA-360p'; + + return `export SG_OUTPUT_DIR=/root/output_mova +mkdir -p "$SG_OUTPUT_DIR" + +sglang serve \\ + --model-path ${modelPath} \\ + --host 0.0.0.0 \\ + --port 30002 \\ + --adjust-frames false \\ + --num-gpus 8 \\ + --ring-degree 2 \\ + --ulysses-degree 4 \\ + --tp 1 \\ + --enable-torch-compile \\ + --save-output \\ + --output-dir "$SG_OUTPUT_DIR"`; + }; + + // Styles - with dark mode support + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; + const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + })} +
+
+ ))} +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/diffusion/qwen-image-deployment.jsx b/docs_new/src/snippets/diffusion/qwen-image-deployment.jsx new file mode 100644 index 000000000..1328c819d --- /dev/null +++ b/docs_new/src/snippets/diffusion/qwen-image-deployment.jsx @@ -0,0 +1,316 @@ +export const QwenImageDeployment = () => { + const config = { + modelFamily: 'Qwen-Image', + + options: { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + } + }, + + generateCommand: function(values) { + return `sglang serve \\ + --model-path Qwen/Qwen-Image \\ + --ulysses-degree=1 \\ + --ring-degree=1`; + } + }; + + if (!config || !config.options) { + return
Error: Invalid configuration provided
; + } + + const getInitialState = () => { + const initialState = {}; + Object.entries(config.options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(config.options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = config.generateCommand ? config.generateCommand.call(config, values) : ''; + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(config.options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + + return ( + + ); + }) + )} +
+
+ ); + })} + +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/diffusion/qwen-image-edit-deployment.jsx b/docs_new/src/snippets/diffusion/qwen-image-edit-deployment.jsx new file mode 100644 index 000000000..866cbd70e --- /dev/null +++ b/docs_new/src/snippets/diffusion/qwen-image-edit-deployment.jsx @@ -0,0 +1,319 @@ +export const QwenImageEditDeployment = () => { + const config = { + modelFamily: 'Qwen-Image-Edit', + + options: { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'h100', label: 'H100', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false } + ] + } + }, + + generateCommand: function(values) { + return `sglang serve \\ + --model-path Qwen/Qwen-Image-Edit-2511 \\ + --ulysses-degree=1 \\ + --ring-degree=1`; + } + }; + + if (!config || !config.options) { + return
Error: Invalid configuration provided
; + } + + const getInitialState = () => { + const initialState = {}; + Object.entries(config.options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(config.options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = config.generateCommand ? config.generateCommand.call(config, values) : ''; + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(config.options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + + return ( + + ); + }) + )} +
+
+ ); + })} + +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/diffusion/wan21-deployment.jsx b/docs_new/src/snippets/diffusion/wan21-deployment.jsx new file mode 100644 index 000000000..e1f44a60e --- /dev/null +++ b/docs_new/src/snippets/diffusion/wan21-deployment.jsx @@ -0,0 +1,337 @@ +export const Wan21Deployment = () => { + const MODELSIZE_DEFS = [ + { + id: '14b', + label: '14B', + subtitle: 'High-quality, 480P/720P', + default: true, + validTasks: ['t2v', 'i2v'], + }, + { + id: '1_3b', + label: '1.3B', + subtitle: 'Lightweight, 480P', + default: false, + validTasks: ['t2v'], + }, + ]; + + const modelConfigs = { + 't2v-14b': { + repoId: 'Wan-AI/Wan2.1-T2V-14B-Diffusers', + supportedLoras: [ + { id: 'general', label: 'General Wan2.1 LoRA', path: 'NIVEDAN/wan2.1-lora' }, + ], + }, + 't2v-1_3b': { + repoId: 'Wan-AI/Wan2.1-T2V-1.3B-Diffusers', + supportedLoras: [], + }, + 'i2v-14b': { + repoId: 'Wan-AI/Wan2.1-I2V-14B-720P-Diffusers', + supportedLoras: [ + { id: 'fight', label: 'Fight Style LoRA', path: 'valiantcat/Wan2.1-Fight-LoRA' }, + ], + }, + }; + + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [{ id: 'mi300x', label: 'MI300X/MI325X/MI355X', default: true }], + }, + task: { + name: 'task', + title: 'Task Type', + items: [ + { id: 't2v', label: 'Text-to-Video (T2V)', default: true }, + { id: 'i2v', label: 'Image-to-Video (I2V)', default: false }, + ], + }, + modelsize: { + name: 'modelsize', + title: 'Model Variant', + items: MODELSIZE_DEFS.map(({ validTasks, ...rest }) => rest), + }, + bestPractice: { + name: 'bestPractice', + title: 'Sequence Parallelism', + items: [ + { id: 'off', label: 'Standard', default: true }, + { id: 'on', label: 'Best Practice (4 GPUs)', default: false }, + ], + }, + }; + + function modelSizeItemsForTask(task) { + return MODELSIZE_DEFS.filter((item) => item.validTasks.includes(task)).map( + ({ validTasks, ...rest }) => rest + ); + } + + const getInitialState = () => { + const task = 't2v'; + const sizes = modelSizeItemsForTask(task); + const modelsize = sizes.find((size) => size.default)?.id || sizes[0].id; + const configKey = `${task}-${modelsize}`; + const supported = modelConfigs[configKey]?.supportedLoras || []; + return { + hardware: 'mi300x', + task, + modelsize, + bestPractice: 'off', + selectedLoraPath: supported[0]?.path ?? '', + }; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, itemId) => { + setValues((prev) => { + let next = { ...prev, [optionName]: itemId }; + + if (optionName === 'task') { + const sizes = modelSizeItemsForTask(itemId); + if (!sizes.some((size) => size.id === next.modelsize)) { + next.modelsize = sizes.find((size) => size.default)?.id || sizes[0].id; + } + } + + if (optionName === 'task' || optionName === 'modelsize') { + const configKey = `${next.task}-${next.modelsize}`; + const supported = modelConfigs[configKey]?.supportedLoras || []; + if (supported.length === 0) { + next.selectedLoraPath = ''; + } else if ( + next.selectedLoraPath && + !supported.some((lora) => lora.path === next.selectedLoraPath) + ) { + next.selectedLoraPath = supported[0].path; + } + } + + return next; + }); + }; + + const handleLoraToggle = (path) => { + setValues((prev) => ({ + ...prev, + selectedLoraPath: prev.selectedLoraPath === path ? '' : path, + })); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const generateCommand = () => { + const { task, modelsize, selectedLoraPath, bestPractice } = values; + const configKey = `${task}-${modelsize}`; + const config = modelConfigs[configKey]; + + if (!config) { + return '# Error: Invalid configuration'; + } + + let command = `sglang serve \\\n --model-path ${config.repoId} \\\n --dit-layerwise-offload true`; + + if (bestPractice === 'on') { + command += ` \\\n --num-gpus 4 \\\n --ulysses-degree 2 \\\n --enable-cfg-parallel`; + } + + if (selectedLoraPath) { + command += ` \\\n --lora-path ${selectedLoraPath}`; + } + + return command; + }; + + const modelSizeItems = modelSizeItemsForTask(values.task); + const loraConfigKey = `${values.task}-${values.modelsize}`; + const availableLoras = modelConfigs[loraConfigKey]?.supportedLoras || []; + const command = generateCommand(); + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(options).map(([key, option]) => ( +
+
{option.title}
+
+ {(key === 'modelsize' ? modelSizeItems : option.items).map((item) => { + const isChecked = values[option.name] === item.id; + return ( + + ); + })} +
+
+ ))} + + {availableLoras.length > 0 && ( +
+
Select LoRA Model (Only some of the supported LoRAs are listed here)
+
+ {availableLoras.map((lora) => { + const isChecked = values.selectedLoraPath === lora.path; + return ( + + ); + })} +
+
+ )} + +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/diffusion/wan22-deployment.jsx b/docs_new/src/snippets/diffusion/wan22-deployment.jsx new file mode 100644 index 000000000..fe749d531 --- /dev/null +++ b/docs_new/src/snippets/diffusion/wan22-deployment.jsx @@ -0,0 +1,216 @@ + + export const Wan22Deployment = () => { + const options = { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'b200', label: 'B200', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'mi300x', label: 'MI300X', default: false }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false }, + ], + }, + task: { + name: 'task', + title: 'Task Type', + items: [ + { id: 'i2v', label: 'Image-to-Video (I2V)', default: false }, + { id: 't2v', label: 'Text-to-Video (T2V)', default: true }, + { id: 'ti2v', label: 'Text/Image-to-Video (TI2V)', default: false }, + ], + }, + modelsize: { + name: 'modelsize', + title: 'Model Size', + items: [ + { id: '14b', label: 'A14B', subtitle: 'Diffusers (A14B)', default: true, validTasks: ['i2v', 't2v'] }, + { id: '5b', label: '5B', subtitle: 'Diffusers', default: false, validTasks: ['ti2v'] }, + ], + }, + bestPractice: { + name: 'bestPractice', + title: 'Sequence Parallelism', + items: [ + { id: 'off', label: 'Standard', default: true }, + { id: 'on', label: 'Best Practice (4 GPUs)', default: false }, + ], + }, + }; + + const modelConfigs = { + 'i2v-14b': { + repoId: 'Wan-AI/Wan2.2-I2V-A14B-Diffusers', + supportedLoras: [{ id: 'distill', path: 'lightx2v/Wan2.2-Distill-Loras' }], + }, + 't2v-14b': { + repoId: 'Wan-AI/Wan2.2-T2V-A14B-Diffusers', + supportedLoras: [{ id: 'arcane', path: 'Cseti/wan2.2-14B-Arcane_Jinx-lora-v1' }], + }, + 'ti2v-5b': { + repoId: 'Wan-AI/Wan2.2-TI2V-5B-Diffusers', + supportedLoras: [], + }, + }; + + const getInitialState = () => ({ + hardware: 'b200', + task: 't2v', + modelsize: '14b', + bestPractice: 'off', + selectedLoraPath: 'none', + }); + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + const availableLoras = (() => { + const configKey = `${values.task}-${values.modelsize}`; + return modelConfigs[configKey]?.supportedLoras || []; + })(); + + const handleRadioChange = (optionName, itemId) => { + setValues((prev) => { + const next = { ...prev, [optionName]: itemId }; + if (optionName === 'task') { + next.modelsize = itemId === 'ti2v' ? '5b' : '14b'; + } + + const configKey = `${next.task}-${next.modelsize}`; + const nextSupported = modelConfigs[configKey]?.supportedLoras || []; + const isValid = nextSupported.some((lora) => lora.path === prev.selectedLoraPath); + if (!isValid) { + next.selectedLoraPath = 'none'; + } + return next; + }); + }; + + const handleLoraToggle = (path) => { + setValues((prev) => ({ + ...prev, + selectedLoraPath: prev.selectedLoraPath === path ? 'none' : path, + })); + }; + + const generateCommand = () => { + const { task, modelsize, selectedLoraPath, bestPractice } = values; + const configKey = `${task}-${modelsize}`; + const config = modelConfigs[configKey]; + if (!config) { + return '# Error: Invalid configuration'; + } + + let command = `sglang serve \\\n --model-path ${config.repoId} \\\n --dit-layerwise-offload true`; + if (bestPractice === 'on') { + command += ` \\\n --num-gpus 4 \\\n --ulysses-degree 2 \\\n --enable-cfg-parallel`; + } + if (selectedLoraPath && selectedLoraPath !== 'none') { + command += ` \\\n --lora-path ${selectedLoraPath}`; + } + return command; + }; + +const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; +const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'center', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; +const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '140px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit' }; +const itemsStyle = { display: 'flex', rowGap: '2px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center', flex: 1 }; +const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', flex: 1, background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; +const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; +const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; +const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + return ( +
+ {Object.entries(options).map(([key, option]) => { + const itemsToDisplay = key === 'modelsize' + ? option.items.filter((item) => item.validTasks.includes(values.task)) + : option.items; + + return ( +
+
{option.title}
+
+ {itemsToDisplay.map((item) => { + const isChecked = values[option.name] === item.id; + return ( + + ); + })} +
+
+ ); + })} + +
+
Select LoRA Model (Only some of the supported LoRAs are listed here)
+
+ {availableLoras.length === 0 && ( +
+ No LoRA models available for this model. +
+ )} + {availableLoras.map((lora) => { + const isSelected = values.selectedLoraPath === lora.path; + return ( + + ); + })} +
+
+ +
+
Run this Command:
+
{generateCommand()}
+
+
+ ); + }; diff --git a/docs_new/src/snippets/diffusion/zimage-turbo-deployment.jsx b/docs_new/src/snippets/diffusion/zimage-turbo-deployment.jsx new file mode 100644 index 000000000..71d9d80f8 --- /dev/null +++ b/docs_new/src/snippets/diffusion/zimage-turbo-deployment.jsx @@ -0,0 +1,319 @@ +export const ZImageTurboDeployment = () => { + const config = { + modelFamily: 'Z-Image-Turbo', + + options: { + hardware: { + name: 'hardware', + title: 'Hardware Platform', + items: [ + { id: 'mi300x', label: 'MI300X', default: true }, + { id: 'mi325x', label: 'MI325X', default: false }, + { id: 'mi355x', label: 'MI355X', default: false }, + { id: 'b200', label: 'B200', default: true }, + { id: 'h200', label: 'H200', default: false }, + { id: 'h100', label: 'H100', default: false } + ] + } + }, + + generateCommand: function(values) { + return `sglang serve \\ + --model-path Tongyi-MAI/Z-Image-Turbo \\ + --ulysses-degree=1 \\ + --ring-degree=1`; + } + }; + + if (!config || !config.options) { + return
Error: Invalid configuration provided
; + } + + const getInitialState = () => { + const initialState = {}; + Object.entries(config.options).forEach(([key, option]) => { + if (option.type === 'checkbox') { + initialState[key] = (option.items || []) + .filter((item) => item.default) + .map((item) => item.id); + return; + } + + if (option.type === 'text') { + initialState[key] = option.default || ''; + return; + } + + let items = option.items || []; + if (option.getDynamicItems) { + const defaultValues = {}; + Object.entries(config.options).forEach(([innerKey, innerOption]) => { + if (innerOption.type === 'checkbox') { + defaultValues[innerKey] = (innerOption.items || []) + .filter((item) => item.default) + .map((item) => item.id); + } else if (innerOption.type === 'text') { + defaultValues[innerKey] = innerOption.default || ''; + } else if (innerOption.items && innerOption.items.length > 0) { + const defaultItem = innerOption.items.find((item) => item.default); + defaultValues[innerKey] = defaultItem ? defaultItem.id : innerOption.items[0].id; + } + }); + items = option.getDynamicItems(defaultValues); + } + + const defaultItem = items && items.find((item) => item.default); + initialState[key] = defaultItem ? defaultItem.id : items && items[0] ? items[0].id : ''; + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = + html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { + attributes: true, + attributeFilter: ['class', 'data-theme', 'style'], + }); + + return () => observer.disconnect(); + }, []); + + const handleRadioChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const handleCheckboxChange = (optionName, itemId, isChecked) => { + setValues((prev) => { + const currentValues = prev[optionName] || []; + if (isChecked) { + return { ...prev, [optionName]: [...currentValues, itemId] }; + } + return { + ...prev, + [optionName]: currentValues.filter((id) => id !== itemId), + }; + }); + }; + + const handleTextChange = (optionName, value) => { + setValues((prev) => ({ ...prev, [optionName]: value })); + }; + + const command = config.generateCommand ? config.generateCommand.call(config, values) : ''; + + const containerStyle = { + maxWidth: '900px', + margin: '0 auto', + display: 'flex', + flexDirection: 'column', + gap: '4px', + }; + const cardStyle = { + padding: '8px 12px', + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, + borderRadius: '4px', + display: 'flex', + alignItems: 'center', + gap: '12px', + background: isDark ? '#1f2937' : '#fff', + }; + const titleStyle = { + fontSize: '13px', + fontWeight: '600', + minWidth: '140px', + flexShrink: 0, + color: isDark ? '#e5e7eb' : 'inherit', + }; + const itemsStyle = { + display: 'flex', + rowGap: '2px', + columnGap: '6px', + flexWrap: 'wrap', + alignItems: 'center', + flex: 1, + }; + const labelBaseStyle = { + padding: '4px 10px', + border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, + borderRadius: '3px', + cursor: 'pointer', + display: 'inline-flex', + flexDirection: 'column', + alignItems: 'center', + justifyContent: 'center', + fontWeight: '500', + fontSize: '13px', + transition: 'all 0.2s', + userSelect: 'none', + minWidth: '45px', + textAlign: 'center', + flex: 1, + background: isDark ? '#374151' : '#fff', + color: isDark ? '#e5e7eb' : 'inherit', + }; + const checkedStyle = { + background: '#D45D44', + color: 'white', + borderColor: '#D45D44', + }; + const disabledStyle = { + cursor: 'not-allowed', + opacity: 0.5, + }; + const subtitleStyle = { + display: 'block', + fontSize: '9px', + marginTop: '1px', + lineHeight: '1.1', + opacity: 0.7, + }; + const textInputStyle = { + flex: 1, + padding: '8px 10px', + borderRadius: '4px', + border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, + background: isDark ? '#111827' : '#fff', + color: isDark ? '#e5e7eb' : '#111827', + fontSize: '13px', + }; + const commandDisplayStyle = { + flex: 1, + padding: '12px 16px', + background: isDark ? '#111827' : '#f5f5f5', + borderRadius: '6px', + fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", + fontSize: '12px', + lineHeight: '1.5', + color: isDark ? '#e5e7eb' : '#374151', + whiteSpace: 'pre-wrap', + overflowX: 'auto', + margin: 0, + border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, + }; + + return ( +
+ {Object.entries(config.options).map(([key, option]) => { + if (option.condition && !option.condition(values)) { + return null; + } + + const items = option.getDynamicItems ? option.getDynamicItems(values) : option.items || []; + + return ( +
+
{option.title}
+
+ {option.type === 'text' ? ( + handleTextChange(option.name, event.target.value)} + style={textInputStyle} + /> + ) : option.type === 'checkbox' ? ( + (option.items || []).map((item) => { + const isChecked = (values[option.name] || []).includes(item.id); + const isDisabled = + item.required || + (typeof item.disabledWhen === 'function' && item.disabledWhen(values)); + + return ( + + ); + }) + ) : ( + items.map((item) => { + const isChecked = values[option.name] === item.id; + const isDisabled = Boolean(item.disabled); + + return ( + + ); + }) + )} +
+
+ ); + })} + +
+
Run this Command:
+
{command}
+
+
+ ); +}; diff --git a/docs_new/src/snippets/specbundle/specbundle-deployment.jsx b/docs_new/src/snippets/specbundle/specbundle-deployment.jsx new file mode 100644 index 000000000..aa40caa43 --- /dev/null +++ b/docs_new/src/snippets/specbundle/specbundle-deployment.jsx @@ -0,0 +1,214 @@ +export const SpecBundleDeployment = () => { + // Config options based on SpecBundleConfigGenerator - matching original structure exactly + const baseConfig = { + options: { + mode: { + name: 'mode', + title: 'Launch Mode', + renderType: 'radio', + items: [ + { id: 'with-server', label: 'With Server', subtitle: 'Launch SGLang server & Benchmark concurrently', default: true }, + { id: 'without-server', label: 'Without Server', subtitle: 'Connect to an existing server (--skip-launch-server)', default: false } + ] + }, + common: { + name: 'common', + title: 'Common Configuration', + renderType: 'inputs', + items: [ + { id: 'modelPath', label: 'Model Path', type: 'text', placeholder: 'e.g., meta-llama/Llama-3.1-8B-Instruct', default: 'meta-llama/Llama-3.1-8B-Instruct', description: 'Path to the target model.' }, + { id: 'port', label: 'Port', type: 'number', default: 30000, description: 'Port to launch/connect the SGLang server.' }, + { id: 'configList', label: 'Config List', type: 'text', default: '1,3,1,4', description: 'Format: ,,,' }, + { id: 'benchmarkList', label: 'Benchmark List', type: 'textarea', default: 'mtbench:5 ceval:5:accountant', description: 'Format: ::. Supported: aime, ceval, financeqa, gpqa, gsm8k, humaneval, livecodebench, math500, mmlu, mmstar, mtbench, simpleqa' } + ] + }, + server: { + name: 'server', + title: 'Server Configuration', + renderType: 'inputs', + requiredMode: 'with-server', + items: [ + { id: 'draftModelPath', label: 'Draft Model Path', type: 'text', placeholder: 'Path to draft model', default: '', description: 'Path to the speculative draft model.' }, + { id: 'tpSize', label: 'TP Size', type: 'number', default: 1, description: 'Number of GPUs for Tensor Parallelism.' }, + { id: 'memFraction', label: 'Memory Fraction Static', type: 'number', step: '0.1', default: 0.9, description: 'The memory fraction for the static memory.' }, + { id: 'attentionBackend', label: 'Attention Backend', type: 'text', default: '', description: 'The attention backend used in sglang' }, + { id: 'trustRemoteCode', label: 'Trust Remote Code', type: 'checkbox', default: true, description: 'Whether to trust remote code.' } + ] + } + } + }; + + // Initialize state - matching original logic + const getInitialState = () => { + const initialState = {}; + Object.values(baseConfig.options).forEach(option => { + if (option.renderType === 'radio') { + const defaultItem = option.items.find(item => item.default); + initialState[option.name] = defaultItem ? defaultItem.id : option.items[0].id; + } else if (option.renderType === 'inputs') { + option.items.forEach(item => { + initialState[item.id] = item.default; + }); + } + }); + return initialState; + }; + + const [values, setValues] = useState(getInitialState); + const [isDark, setIsDark] = useState(false); + + // Detect dark mode + useEffect(() => { + const checkDarkMode = () => { + const html = document.documentElement; + const isDarkMode = html.classList.contains('dark') || + html.getAttribute('data-theme') === 'dark' || + html.style.colorScheme === 'dark'; + setIsDark(isDarkMode); + }; + checkDarkMode(); + const observer = new MutationObserver(checkDarkMode); + observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }); + return () => observer.disconnect(); + }, []); + + // Get display options based on current mode + const getDisplayOptions = () => { + const options = {}; + const currentMode = values.mode; + Object.entries(baseConfig.options).forEach(([key, option]) => { + if (option.requiredMode && option.requiredMode !== currentMode) { + return; + } + options[key] = option; + }); + return options; + }; + + const handleRadioChange = (optionName, itemId) => { + setValues(prev => ({ ...prev, [optionName]: itemId })); + }; + + const handleInputChange = (itemId, value) => { + setValues(prev => ({ ...prev, [itemId]: value })); + }; + + const handleCheckboxChange = (itemId, checked) => { + setValues(prev => ({ ...prev, [itemId]: checked })); + }; + + // Generate command - matching original logic + const generateCommand = () => { + const { mode, modelPath, port, configList, benchmarkList, draftModelPath, tpSize, memFraction, attentionBackend, trustRemoteCode } = values; + + let cmd = 'python bench_eagle3.py'; + if (modelPath) cmd += ` \\\n --model-path ${modelPath}`; + if (port) cmd += ` \\\n --port ${port}`; + if (configList) cmd += ` \\\n --config-list ${configList}`; + if (benchmarkList) cmd += ` \\\n --benchmark-list ${benchmarkList.replace(/\n/g, ' ')}`; + + if (mode === 'without-server') { + cmd += ' \\\n --skip-launch-server'; + } else { + if (draftModelPath) cmd += ` \\\n --speculative-draft-model-path ${draftModelPath}`; + if (tpSize) cmd += ` \\\n --tp-size ${tpSize}`; + if (memFraction) cmd += ` \\\n --mem-fraction-static ${memFraction}`; + if (attentionBackend) cmd += ` \\\n --attention-backend ${attentionBackend}`; + if (trustRemoteCode) cmd += ` \\\n --trust-remote-code`; + } + + return cmd; + }; + + // Styles + const containerStyle = { maxWidth: '900px', margin: '0 auto', display: 'flex', flexDirection: 'column', gap: '4px' }; + const cardStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}`, borderLeft: `3px solid ${isDark ? '#E85D4D' : '#D45D44'}`, borderRadius: '4px', display: 'flex', alignItems: 'flex-start', gap: '12px', background: isDark ? '#1f2937' : '#fff' }; + const titleStyle = { fontSize: '13px', fontWeight: '600', minWidth: '180px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit', paddingTop: '4px' }; + const contentStyle = { flex: 1 }; + const itemsStyle = { display: 'flex', rowGap: '4px', columnGap: '6px', flexWrap: 'wrap', alignItems: 'center' }; + const labelBaseStyle = { padding: '4px 10px', border: `1px solid ${isDark ? '#9ca3af' : '#d1d5db'}`, borderRadius: '3px', cursor: 'pointer', display: 'inline-flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', fontWeight: '500', fontSize: '13px', transition: 'all 0.2s', userSelect: 'none', minWidth: '45px', textAlign: 'center', background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit' }; + const checkedStyle = { background: '#D45D44', color: 'white', borderColor: '#D45D44' }; + const subtitleStyle = { display: 'block', fontSize: '9px', marginTop: '1px', lineHeight: '1.1', opacity: 0.7 }; + const inputGroupStyle = { display: 'flex', flexDirection: 'column', gap: '8px' }; + const inputRowStyle = { display: 'flex', alignItems: 'flex-start', gap: '12px' }; + const inputLabelStyle = { fontSize: '13px', fontWeight: '500', minWidth: '180px', flexShrink: 0, color: isDark ? '#e5e7eb' : 'inherit', paddingTop: '8px' }; + const inputContentStyle = { flex: 1, display: 'flex', flexDirection: 'column' }; + const inputStyle = { padding: '8px 12px', border: `1px solid ${isDark ? '#4b5563' : '#d1d5db'}`, borderRadius: '4px', fontSize: '13px', background: isDark ? '#374151' : '#fff', color: isDark ? '#e5e7eb' : 'inherit', width: '100%', boxSizing: 'border-box' }; + const textareaStyle = { ...inputStyle, minHeight: '60px', resize: 'vertical' }; + const descStyle = { color: isDark ? '#9ca3af' : '#666', marginTop: '4px', fontSize: '11px' }; + const commandDisplayStyle = { flex: 1, padding: '12px 16px', background: isDark ? '#111827' : '#f5f5f5', borderRadius: '6px', fontFamily: "'Menlo', 'Monaco', 'Courier New', monospace", fontSize: '12px', lineHeight: '1.5', color: isDark ? '#e5e7eb' : '#374151', whiteSpace: 'pre-wrap', overflowX: 'auto', margin: 0, border: `1px solid ${isDark ? '#374151' : '#e5e7eb'}` }; + + const displayOptions = getDisplayOptions(); + + return ( +
+ {Object.entries(displayOptions).map(([key, option]) => ( +
+ {/* Render Radio Group - title on left */} + {option.renderType === 'radio' && ( +
+
{option.title}
+
+ {option.items.map(item => { + const isChecked = values[option.name] === item.id; + return ( + + ); + })} +
+
+ )} + + {/* Render Input Group - each input has label on left */} + {option.renderType === 'inputs' && ( +
+ {option.items.map(item => ( +
+
{item.label}
+
+ {item.type === 'textarea' ? ( +