Skip to content

[Feature] support beam search. - #15645

Closed
cswuyg wants to merge 72 commits into
sgl-project:mainfrom
cswuyg:feature/beam_search
Closed

cswuyg wants to merge 72 commits into
sgl-project:mainfrom
cswuyg:feature/beam_search

Conversation

@cswuyg

@cswuyg cswuyg commented Dec 22, 2025 •

Copy link
Copy Markdown
Contributor

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 HuggingFace transformers with the same model and num_beams, asserting that the returned sequence sets have a sufficiently high overlap ratio.

Key Features

  • Dynamic Beam Width: The beam width is specified on a per-request basis via the standard n parameter. 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.
  • Comprehensive API Support:
    • SGLang native: Engine.generate() API.
    • OpenAI-compatible: v1/chat/completions and v1/completions endpoints.
  • Per-sequence Score: Each returned candidate carries its beam score, exposed as sequence_score under the SGLang response extension field sglext.

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-search

2. Send a Request with Beam Search

The request body follows the standard OpenAI schema. Simply set n to 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 choices array. Each choice's beam score is returned under sglext.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 Engine API:

import sglang as sgl

if __name__ == "__main__":
    engine = sgl.Engine(
        model_path="/data/model/Qwen3-1.7B",
        enable_beam_search=True,
    )

    outputs = engine.generate(
        prompt="Hello SGLang",
        sampling_params={"max_new_tokens": 10, "n": 4},
    )

    for beam in outputs["meta_info"]["beam_results"]:
        print(beam["meta_info"]["sequence_score"], beam["text"])

    engine.shutdown()

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:

  • Model: Qwen3-1.7B
  • Hardware: Single NVIDIA L20 GPU
  • Dataset: ShareGPT (100 samples, filtered for prompt length < 100)
  • Parameters: max_tokens=10
  • Software Versions:
    • SGLang: This PR
    • TensorRT-LLM: v1.2.0rc4
    • vLLM: v0.13.0
    • Transformers: 4.57.1
Engine \ Beam Width 10 50 100 200 400
SGLang (Ours) 11.53 10.23 8.73 6.83 4.27
TensorRT-LLM 12.23 10.70 8.79 6.21 3.50
transformers 4.41 3.77 2.94 1.96 1.08
vLLM 5.54 2.01 0.80 0.23 0.06
image

Note: SGLang exhibits even greater performance advantages when using smaller models or a lower max_tokens setting.

Detailed benchmark reproduction steps can be found in this Google Doc.

Further Reading (in Chinese):

Technical Implementation Details

image

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/ and test/registered/unit/managers/) as well as an end-to-end accuracy test against transformers, to ensure stability.

Other Notes

  • Design Trade-off: In order to minimize changes to the existing codebase, some conditional branches slightly deviate from the principle of "ensuring the common path comes first."
  • Feature Compatibility: When --enable-beam-search is set, PD separation, pipeline parallelism, overlap schedule, chunked prefill, and page_size != 1 are automatically disabled. This keeps beam search self-contained and avoids surprising interactions with these optimizations in the initial version.
  • Acknowledgment: I would like to express my gratitude for the implementation reference provided by PR #3066, which offered valuable insights during the development of this feature.

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
Latest PR Test (Extra): ⚠️ Not enabled -- add run-ci-extra label to opt in.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @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

  • Beam Search Implementation: Introduced comprehensive support for the Beam Search decoding strategy, enabling enhanced generation quality and diverse sampling options within the system.
  • Modular Integration via Mixin Pattern: Implemented beam search functionality using a Mixin pattern, ensuring clean separation of concerns and seamless integration into existing model executors and OpenAI-compatible serving endpoints without bloating core classes.
  • Performance Optimization: Benchmarking demonstrates SGLang's superior scalability and Query Per Second (QPS) performance, especially at higher beam widths (e.g., BW >= 200), outperforming TensorRT-LLM and vLLM.
  • OpenAI API Compatibility: Extended the OpenAI protocol to include a use_beam_search parameter and sequence_score in response choices, allowing clients to leverage beam search through the standard API.
  • Optimized KV Cache Management: Developed specialized KV cache handling for beam search, including efficient allocation, copying for surviving beams, and freeing for pruned beams, using vectorized operations for performance.
  • Enhanced Sampling and Scheduling Logic: Modified the sampler to store full log probabilities for beam search and updated the scheduler to manage beam search specific batch preparation, filtering, and result processing.

🧠 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 Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@ispobock

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Dec 23, 2025
cswuyg and others added 6 commits December 23, 2025 08:49
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
@cswuyg
cswuyg force-pushed the feature/beam_search branch from f325e46 to df5684b Compare April 27, 2026 06:47
- diff test: read beams from meta_info["beam_results"]
- processor mixin test: assert free_by_indices instead of free
@cswuyg

cswuyg commented Apr 27, 2026

Copy link
Copy Markdown
Contributor Author

@sleepwalker2017 Currently, multi-modal support is not yet available.

@sleepwalker2017

Copy link
Copy Markdown

@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.

@cswuyg

cswuyg commented Apr 27, 2026

Copy link
Copy Markdown
Contributor Author

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.

vedantjh2 pushed a commit to vedantjh2/sglang that referenced this pull request Apr 28, 2026
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).
@sleepwalker2017

Copy link
Copy Markdown

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.

Is this PR likely to be merged? It has lasted for such a long time.

@cswuyg

cswuyg commented May 10, 2026

Copy link
Copy Markdown
Contributor Author

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.

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.

@Marco692

Copy link
Copy Markdown

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.🤝

vedantjh2 added a commit to vedantjh2/sglang that referenced this pull request Jun 9, 2026
…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.
severus51950 pushed a commit to severus51950/sglang that referenced this pull request Jul 1, 2026
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.
@cswuyg

cswuyg commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi all,

I have recently introduced several enhancements to the Beam Search feature. Because the previous branch had diverged significantly from main and contained many merge commits, I decided to re-implement and clean up the code directly on top of the latest main with AI assistance.

Key Features Supported:

  1. Dual-Mode Support: Removed the rigid server-level mode restriction—the server now natively supports both Beam Search and non-Beam Search modes simultaneously. Beam Search can be dynamically enabled per request by passing use_beam_search: true in the OpenAI-compatible API payload.
  2. Qwen 3.5 Support: Full support for Qwen 3.5 models, including Mamba/SSM state handling.
  3. Decode-First Scheduling: Optimized request scheduling tailored for Generative Retrieval scenarios with short output lengths, achieving lower latency and higher throughput.
  4. Cascade Attention: Accelerated decoding for long contexts and large beam widths via FlashInfer.
  5. Constrained Decoding: Support for constrained decoding, particularly useful for Generative Retrieval tasks.
  6. Repetition Penalty: Added penalty support to mitigate repetitive generation during beam search.

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 main, I will follow up by adding these features on top of it. In the meantime, I will continue experimenting with new features and performance optimizations in my personal branch. Feel free to discuss, share ideas, or report any bugs!

@cswuyg
cswuyg requested a review from alphabetc1 as a code owner July 31, 2026 16:09
@blacker521

Copy link
Copy Markdown
Contributor

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!

@cswuyg

cswuyg commented Aug 1, 2026

Copy link
Copy Markdown
Contributor Author

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.

@chenxb002

Copy link
Copy Markdown
Collaborator

Hi all,

I have recently introduced several enhancements to the Beam Search feature. Because the previous branch had diverged significantly from main and contained many merge commits, I decided to re-implement and clean up the code directly on top of the latest main with AI assistance.

Key Features Supported:

  1. Dual-Mode Support: Removed the rigid server-level mode restriction—the server now natively supports both Beam Search and non-Beam Search modes simultaneously. Beam Search can be dynamically enabled per request by passing use_beam_search: true in the OpenAI-compatible API payload.
  2. Qwen 3.5 Support: Full support for Qwen 3.5 models, including Mamba/SSM state handling.
  3. Decode-First Scheduling: Optimized request scheduling tailored for Generative Retrieval scenarios with short output lengths, achieving lower latency and higher throughput.
  4. Cascade Attention: Accelerated decoding for long contexts and large beam widths via FlashInfer.
  5. Constrained Decoding: Support for constrained decoding, particularly useful for Generative Retrieval tasks.
  6. Repetition Penalty: Added penalty support to mitigate repetitive generation during beam search.

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 main, I will follow up by adding these features on top of it. In the meantime, I will continue experimenting with new features and performance optimizations in my personal branch. Feel free to discuss, share ideas, or report any bugs!

Great work! I recently came across a paper that also discusses attention and scheduling optimizations for Beam Search in generative recommendation:

Sun et al., "xGR: Efficient Generative Recommendation Serving at Scale", arXiv:2512.11529v3 – https://arxiv.org/html/2512.11529v3

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!

@cswuyg cswuyg closed this Aug 27, 2026
@cswuyg

cswuyg commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

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.
#31626

@chenxb002

Copy link
Copy Markdown
Collaborator

@cswuyg
Thank you for your great work. Do you plan to open a separate PR for other features like Qwen 3.5 support? We're looking forward to better support for Qwen3.5 and would appreciate knowing your roadmap. Thanks!

@blacker521

Copy link
Copy Markdown
Contributor

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.

https://github.com/sohu-mptc/FlashRec

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:

  • CUDA-graph capture of the decode path, including beam expansion, at widths 50–512+
  • A fused SID trie (dense or CSR) so illegal IDs are never candidates
  • Scheduling by beam-row slot budget, so rows from different requests share a step
  • FP8 by default (W8A8 weights, fp8 KV), OpenAI-compatible /v1/chat/completions

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:

flashrec --serve --model-path ./OneRec-1.7B --port 8000 \
  --beam-width 32 --max-tokens 5 \
  --sid-vocab-file data/catalogs/sid2pid_beamrec_l4.json

We welcome the community to try it, file issues, and contribute. Please feel free to forward.

Thanks,
Chongyang Wang
[email protected]
sohu-mptc / FlashRec

@cswuyg

cswuyg commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

@cswuyg Thank you for your great work. Do you plan to open a separate PR for other features like Qwen 3.5 support? We're looking forward to better support for Qwen3.5 and would appreciate knowing your roadmap. 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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.