Repository navigation
Conversation
Summary of ChangesHello @cswuyg, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request integrates the Beam Search decoding strategy into the SGLang framework. The primary goal is to improve the quality and diversity of generated outputs by exploring multiple candidate sequences. The implementation utilizes a modular Mixin pattern for easy integration across various components, including OpenAI-compatible endpoints, and includes significant optimizations for KV cache management. Extensive benchmarking confirms SGLang's competitive performance, particularly under high beam width conditions. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces beam search support, which is a significant feature. The implementation is well-structured, using mixins to separate concerns and integrate the new logic cleanly. The changes span across the serving layer, scheduler, and model execution components, and include necessary modifications to data structures and protocols. I've identified a potential bug in the stop condition checking for beam search and a minor inconsistency in JSON serialization. Overall, this is a solid contribution.
… to completions streaming interface.
|
/tag-and-rerun-ci |
1. handle_beam_search_output, beam search only support BatchTokenIDOutput and BatchStrOutput 2. _create_initial_beam_sequences, add beam score for complete beam 3. _tail_str unit test error
f325e46 to
df5684b
Compare
- diff test: read beams from meta_info["beam_results"] - processor mixin test: assert free_by_indices instead of free
|
@sleepwalker2017 Currently, multi-modal support is not yet available. |
You mean it's implemented but not fully validated? In fact, I fixed the support for Qwen3.5 2B, with only a few modifications. |
Multimodal and text-only models share the majority of the execution flow with only slight variations, so adding support should only require minimal changes. However, I’d prefer not to add more features to this PR; it’s already quite large, and further additions would make it difficult to merge into main. |
The previous commit's env-var-based dispatch was a benchmarking shortcut. This
replaces it with the proper, upstream-shippable design that uses SGLang's
existing CustomLogitProcessor infrastructure.
Per-request flow now matches the existing DisallowedTokensLogitsProcessor /
ThinkingBudgetLogitProcessor patterns:
from sglang.srt.managers.beam_constraint import PrefixIndexCustomLogitProcessor
out = engine.generate(
prompt,
sampling_params={
"n": 500, "max_new_tokens": 3,
"custom_params": {
"prefix_index_path": "/.../prefix_index-v2.npz",
"tokenizer_path": "/.../sft_checkpoint",
"vocab_size": 176245,
"codebook_size": 8192,
"num_codebook": 3,
},
},
custom_logit_processor=PrefixIndexCustomLogitProcessor.to_str(),
)
Changes:
- python/sglang/srt/managers/beam_constraint.py:
Replaced env-var-driven module-level singleton with
PrefixIndexCustomLogitProcessor(CustomLogitProcessor). Class is dill-
serialized via .to_str() and shipped to workers through the existing
io_struct.custom_logit_processor field. Per-worker cache keyed by index
path so the prefix index loads at most once per worker even if many
requests reference it.
- python/sglang/srt/managers/scheduler_beam_search_processor_mixin.py:
Hook now reads req.custom_logit_processor (already plumbed through to
workers by PR sgl-project#15645's wiring; no new fields), deserializes via
CustomLogitProcessor.from_str() (lru_cached), and reads custom_params
from req.sampling_params.custom_params. Per-request __req__ reference
passed in custom_param_list so the processor can read req.beam_list.
incomplete for per-beam state — same pattern as ThinkingBudgetLogitProcessor.
Verified at full PR sgl-project#36 scale (Qwen3-0.6B SFT, 16 prompts × beam=500 ×
return=200 = 3200 sequences):
- HF (PR sgl-project#36 ground truth): 3200/3200 valid
- SGLang via CustomLogitProcessor: 3200/3200 valid
- HF↔SGLang set overlap: 97.6% (3124/3200)
- Top-1 match: 15/16 prompts (94%)
- Top-50 set overlap (avg/prompt): 48.7/50 (97%)
- Steady-state per-prompt latency: 0.049s (matches env-var version)
custom-scripts/test_proper.py adds the framework-API smoke test;
custom-scripts/correctness_full_proper.py runs the full validation against
the saved HF reference outputs.
No new server args required (we don't go through the standard sampler path
that gates on enable_custom_logit_processor; works either way).
Is this PR likely to be merged? It has lasted for such a long time. |
It has indeed been a long time. I’ve followed up several times over the past few months, but it seems Beam Search isn't the current priority for the SGLang community. Let's wait a bit longer and see. |
|
Beam search is key to the industrial-scale implementation of GR(generative retrieval), and I believe many people are hoping that the official support for this feature will be available.🤝 |
…im down Brings PR sgl-project#15645 (beam search) up to date with current upstream/main and aligns it with the new architecture, on top of the original commits. Rebase / conflict resolution (upstream refactored the scheduler output pipeline: ModelWorkerBatch removed; output processing split into composed components): - Thread is_beam_search through ForwardBatch.init_new (ModelWorkerBatch gone) - Re-home beam output-building into _GenerationStreamAccumulator - Decode stats via metrics_reporter.report_decode_stats Architecture (match upstream's mixin -> composed-component direction): - Convert SchedulerBeamSearchProcessorMixin into a SchedulerBeamSearchProcessor component in scheduler_components/, the beam sibling of SchedulerBatchResultProcessor, dispatched as self.beam_search_processor.*. (The Req/ScheduleBatch/Detokenizer/Tokenizer/OpenAI extensions stay mixins, which is still the upstream convention for those classes.) Robustness (carried from the internal fork): - Beam-aware admission gate + typed BeamSearchAdmissionError + pre-flight check + scheduler skip-tick (linkedin-managed sgl-project#341) - report_decode_stats rename, fixing the log_decode_stats AttributeError crash under sustained beam traffic (linkedin-managed sgl-project#339) Code-review fixes: - Fix crash in _create_completed_beams_for_insufficient_candidates (req left unfinished with beam_list.last_tokens=None) - Per-request flags in the beam detokenizer batch_decode path - NaN-guard the beam sampler logprob path - Dedup the OpenAI chat/completion beam halves; succinct comments; remove dead code Validated on H200/CUDA13 against sglang-internal-serving 0.5.10.post1: full functional + token-exact parity across /generate, /v1/completions and /v1/chat/completions (max sequence_score delta 0); error handling matches; n=3200 @4 QPS and 10 QPS loads stable; 82 beam unit tests pass.
Connect the beam-search scheduler, output, detokenizer, and raw req-pool paths so the v0.5.14 PR sgl-project#15645 rebase can run beam-width decoding end to end.
|
Hi all, I have recently introduced several enhancements to the Beam Search feature. Because the previous branch had diverged significantly from
Key Features Supported:
Note / Next Steps: I've noticed that GPU utilization is not fully saturated under high-concurrency scenarios with the current implementation. I am considering exploring CUDA streams to improve parallel execution, while carefully evaluating the potential downside of reduced batching efficiency. Considering that the core SGLang maintainers are currently refactoring the Beam Search implementation (see #31626), I will hold off on opening a new PR for now. Once the official refactoring is merged into |
|
Hi cswuyg, Thanks for sharing your work on the Beam Search enhancements. The improvements around Qwen 3.5 support, decode-first scheduling, cascade attention, and constrained decoding are very interesting, especially for Generative Retrieval scenarios. Our team is also working on improving SGLang for Generative Retrieval workloads. We have been investigating similar challenges, particularly around scheduling optimization, GPU utilization under high concurrency, and improving inference efficiency for short-output generation scenarios. We have observed that current scheduling strategies can leave GPU resources underutilized in some cases, and we are exploring different approaches to improve execution efficiency while balancing batching performance. It would be great to collaborate with you on these efforts. We would like to share our experience, discuss potential solutions, and help validate or improve some of the ideas in your branch. We are also interested in contributing to the upstream PR once the Beam Search refactoring is merged into main. Please feel free to reach out if there are any areas where we can help, such as benchmarking, performance analysis, or feature implementation. We would love to have more discussions and work together to make SGLang better for Generative Retrieval workloads. Looking forward to collaborating with you! |
Sounds great! Looking forward to exchanging ideas with you. |
Great work! I recently came across a paper that also discusses attention and scheduling optimizations for Beam Search in generative recommendation:
The paper proposes splitting KV cache for shared prefixes and using two-phase attention to reduce memory traffic (xAttention), along with pipeline overlapping and graph-based kernel dispatch for host-side scheduling (xSchedule). The current implementation here seems to share some similar ideas, e.g., reusing common prefix computations and reducing per-step overhead. Just sharing as a useful reference! |
|
The official developers have conducted in-depth integration based on this PR and added support for the overlap scheduler. The code has been merged into main, so this PR is being closed. |
|
@cswuyg |
|
Introducing FlashRec: a wide-beam inference engine for generative recommendation Hi all, Today we’re excited to introduce FlashRec, an open-source inference engine for generative recommendation. General-purpose LLM engines (vLLM, SGLang, TensorRT-LLM) are optimized for long, single-path decoding. Generative recommendation is a different shape: a few decode steps, a very wide beam, and every continuation must land in a valid semantic-ID catalog. A wide-beam request occupies the engine; throughput barely scales with concurrency; open-vocabulary decoding leaves ~17–27% of beams illegal. FlashRec is built for that workload:
On public OneRec-1.7B (OpenOneRec RecIF-Bench, RTX 5090), FlashRec consistently delivers higher throughput than existing engines, achieving up to 2.0× vs SGLang, 2.2× vs TensorRT-LLM, and 7.2× vs vLLM. On production SoHuRec traffic, up to ~3× vs SGLang. The illegal-SID rate is 0. FlashRec is fully open-source (Apache-2.0), with a layout following mini-sglang. You can serve a public checkpoint with: We welcome the community to try it, file issues, and contribute. Please feel free to forward. Thanks, |
Thanks for the kind words! Currently, I'm fully occupied with some customized model architectures for my main work and have a few personal engagements lined up for my spare time. Because of this, I won't be able to open a dedicated PR for Qwen 3.5 in the immediate future. I definitely hope to circle back to this once my schedule clears up later on. In the meantime, please feel free to take over or build upon the idea if anyone in the community wants to pick it up sooner! Thanks again for the support! |
Motivation
Added support for the Beam Search decoding strategy to enhance generation quality and provide users with more diverse sampling options.
Beam Search is relatively uncommon in end-to-end Large Language Model (LLM) applications; however, it has gained traction in search and recommendation scenarios.
Prior to this Pull Request (PR), we conducted an in-depth analysis of the implementation in PR 3066. Building upon that foundation, we have introduced significant enhancements to optimize performance, refine the system architecture, and ensure full compatibility with the OpenAI API.
Modifications
Implemented Beam Search functionality using a Mixin pattern. This approach ensures a clean separation of concerns and allows the beam search logic to be easily integrated into existing components (tokenizer manager, scheduler, detokenizer manager, OpenAI serving endpoints, etc.) without bloating the core classes.
Beam search is enabled via a dedicated server argument
--enable-beam-search. When this flag is set, the server automatically disables features that are currently incompatible with beam search (PD separation, pipeline parallelism, overlap schedule, chunked prefill,page_size != 1) and emits a warning listing the disabled features, so users do not need to configure these manually.Accuracy Tests
The Beam Search logic is integrated using Mixins and conditional branching, ensuring that the existing inference pipeline remains untouched. We have verified that the main workflow is not affected, and standard (non-beam-search) inference outputs remain identical to the baseline.
We also added a dedicated test (
test/registered/core/test_beam_search_diff.py) that cross-checks SGLang's beam search outputs against HuggingFacetransformerswith the same model andnum_beams, asserting that the returned sequence sets have a sufficiently high overlap ratio.Key Features
nparameter. Unlike some other inference engines, SGLang allows users to switch between different beam widths dynamically without restarting the server, providing maximum flexibility for diverse generation tasks.Engine.generate()API.v1/chat/completionsandv1/completionsendpoints.sequence_scoreunder the SGLang response extension fieldsglext.Usage Example
1. Launch the Server
Start the SGLang server with
--enable-beam-search. Incompatible features will be auto-disabled internally; no extra flags are required:python3 -m sglang.launch_server \ --model-path /data/modelscope/Qwen3-1.7B \ --enable-beam-search2. Send a Request with Beam Search
The request body follows the standard OpenAI schema. Simply set
nto the desired beam width (must be > 1 when beam search is enabled):curl http://localhost:30000/v1/chat/completions \ -H "Content-Type: application/json" \ -d '{ "model": "default", "messages": [ { "role": "user", "content": "Hello SGLang" } ], "max_completion_tokens": 10, "n": 2 }'3. Example Response
The response contains multiple candidates in the
choicesarray. Each choice's beam score is returned undersglext.sequence_score:{ "id": "f86a5f337e544c3f8733e5ca4698fd2e", "object": "chat.completion", "created": 1766481788, "model": "default", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "<think>\nOkay, the user said \"Hello S", "reasoning_content": null, "tool_calls": null }, "logprobs": null, "finish_reason": "length", "matched_stop": null, "sglext": { "sequence_score": -0.05671458244323731 } }, { "index": 1, "message": { "role": "assistant", "content": "<think>\nOkay, the user just said \"Hello", "reasoning_content": null, "tool_calls": null }, "logprobs": null, "finish_reason": "length", "matched_stop": null, "sglext": { "sequence_score": -0.19482492208480834 } } ], "usage": { "prompt_tokens": 12, "total_tokens": 32, "completion_tokens": 20, "prompt_tokens_details": null, "reasoning_tokens": 0 }, "metadata": { "weight_version": "default" } }4. Native Engine Usage
Beam search is also available through the native
EngineAPI:Benchmarking and Profiling
The following table shows the QPS (Queries Per Second) comparison across different engines and beam widths. Our implementation in SGLang demonstrates superior scalability, especially at higher beam widths ($BW \ge 200$ ), outperforming TensorRT-LLM and significantly leading vLLM.
Benchmark Settings:
max_tokens=10v1.2.0rc4v0.13.04.57.1Note: SGLang exhibits even greater performance advantages when using smaller models or a lower
max_tokenssetting.Detailed benchmark reproduction steps can be found in this Google Doc.
Further Reading (in Chinese):
Technical Implementation Details
Core technical challenges:
Request Expansion and Pruning: Managing the expansion of a single path into multiple candidate paths and the subsequent pruning of unused branches.
KV Cache Management: Ensuring that expanded requests efficiently reuse the KV Cache of their common prefixes, while pruning operations recycle the KV Cache of discarded paths.
Other Considerations: These include criteria for beam search completion, handling scenarios where partial beams are finished while the overall request remains active, final request teardown, and ensuring compatibility with beam-search request/response protocols across both the native and OpenAI-compatible APIs.
High Test Coverage: Core logic—including beam expansion, pruning, KV cache recycling, and the output/IO paths—is covered by unit tests (see
test/registered/scheduler/andtest/registered/unit/managers/) as well as an end-to-end accuracy test againsttransformers, to ensure stability.Other Notes
--enable-beam-searchis set, PD separation, pipeline parallelism, overlap schedule, chunked prefill, andpage_size != 1are automatically disabled. This keeps beam search self-contained and avoids surprising interactions with these optimizations in the initial version.Future Work
Early Stopping: Support early stopping strategies to reduce redundant computation.
Throughput Optimization: Enhance performance via overlap schedule, Multi-Token Prediction (MTP), and decode-prioritized scheduling.
Feature Compatibility: Progressively re-enable the currently auto-disabled features (overlap schedule, chunked prefill, larger
page_size, PP, PD separation) for beam search.Checklist
CI States
Latest PR Test (Base): Not run yet⚠️ Not enabled -- add
Latest PR Test (Extra):
run-ci-extralabel to opt in.