Skip to content

Conversation

PeaBrane
Copy link
Contributor

@PeaBrane PeaBrane commented Jul 10, 2025

Overview:

Only update the active blocks when
(isl + current osl - 1) / block_size
changes, meaning that a generation block is committed and a new generation block is allocated

Benchmarks

not really sure what happened at hit rate 0.7, but generally looks good, particularly pure load balancer
load_balancer

Summary by CodeRabbit

  • New Features

    • Improved performance by allowing batch processing of multiple tokens at once, rather than handling tokens individually.
  • Bug Fixes

    • Enhanced accuracy in block management when processing sequences of tokens.
  • Tests

    • Updated tests to cover scenarios with multiple tokens pushed in a single operation.

@github-actions github-actions bot added the feat label Jul 10, 2025
@PeaBrane PeaBrane marked this pull request as ready for review July 10, 2025 01:31
@PeaBrane PeaBrane requested a review from tedzhouhk July 10, 2025 01:31
Copy link
Contributor

coderabbitai bot commented Jul 10, 2025

Walkthrough

The changes refactor the token handling pipeline to support batch token pushes instead of single-token pushes. Methods in the router, scheduler, and sequence management layers are updated to accept and process slices of tokens, with corresponding updates to block management logic and related enum variants. Tests and multi-worker infrastructure are also adapted.

Changes

File(s) Change Summary
lib/llm/src/kv_router.rs KvRouter::push now accepts a slice of tokens (&[u32]) instead of a single token; bulk token forwarding logic added in generate.
lib/llm/src/kv_router/scheduler.rs KvScheduler::push updated to accept a slice of tokens; documentation and internal calls adjusted accordingly.
lib/llm/src/kv_router/sequence.rs ActiveSequences::push and related enum variants updated for batch token support; block management logic revised; multi-worker and tests updated.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant KvRouter
    participant KvScheduler
    participant ActiveSequences

    Client->>KvRouter: push(request_id, &[tokens])
    KvRouter->>KvScheduler: push(request_id, &[tokens])
    KvScheduler->>ActiveSequences: push(request_id, &[tokens])
    ActiveSequences-->>KvScheduler: update blocks, manage sequences
    KvScheduler-->>KvRouter: ack
    KvRouter-->>Client: ack
Loading

Possibly related PRs

Poem

A bundle of tokens, not just one,
Now travel together—the batch push begun!
Sequences grow in leaps, not in hops,
Blocks update smoothly, no more single drops.
The scheduler smiles, the router is keen,
Batch by batch, the code runs clean!
🐇✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7bc70bc and 222844d.

📒 Files selected for processing (3)
  • lib/llm/src/kv_router.rs (3 hunks)
  • lib/llm/src/kv_router/scheduler.rs (1 hunks)
  • lib/llm/src/kv_router/sequence.rs (7 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: oandreeva-nv
PR: ai-dynamo/dynamo#1195
File: lib/llm/tests/block_manager.rs:150-152
Timestamp: 2025-06-02T19:37:27.666Z
Learning: In Rust/Tokio applications, when background tasks use channels for communication, dropping the sender automatically signals task termination when the receiver gets `None`. The `start_batching_publisher` function in `lib/llm/tests/block_manager.rs` demonstrates this pattern: when the `KVBMDynamoRuntimeComponent` is dropped, its `batch_tx` sender is dropped, causing `rx.recv()` to return `None`, which triggers cleanup and task termination.
Learnt from: PeaBrane
PR: ai-dynamo/dynamo#1285
File: lib/llm/src/kv_router/scheduler.rs:260-266
Timestamp: 2025-05-30T06:34:12.785Z
Learning: In the KV router scheduler code, PeaBrane prefers fail-fast behavior over silent failure handling. When accessing worker metrics data that could be out-of-bounds (like dp_rank indexing), explicit panics are preferred over graceful degradation with continue statements to ensure data integrity issues are caught early.
lib/llm/src/kv_router.rs (4)
Learnt from: alec-flowers
PR: ai-dynamo/dynamo#1181
File: lib/llm/src/kv_router/publisher.rs:379-425
Timestamp: 2025-05-29T00:02:35.018Z
Learning: In lib/llm/src/kv_router/publisher.rs, the functions `create_stored_blocks` and `create_stored_block_from_parts` are correctly implemented and not problematic duplications of existing functionality elsewhere in the codebase.
Learnt from: PeaBrane
PR: ai-dynamo/dynamo#1285
File: lib/llm/src/kv_router/scoring.rs:58-63
Timestamp: 2025-05-30T06:38:09.630Z
Learning: In lib/llm/src/kv_router/scoring.rs, the user prefers to keep the panic behavior when calculating load_avg and variance with empty endpoints rather than adding guards for division by zero. They want the code to fail fast on this error condition.
Learnt from: ishandhanani
PR: ai-dynamo/dynamo#1626
File: lib/llm/src/preprocessor.rs:238-239
Timestamp: 2025-06-24T20:59:35.725Z
Learning: In lib/llm/src/preprocessor.rs, the `sampling_options` call in the `preprocess_request` method is placed in the common section after the match statement on `request.prompt_input_type()`, meaning it applies to both `PromptInput::Tokens` and `PromptInput::Text` request types.
Learnt from: t-ob
PR: ai-dynamo/dynamo#1290
File: launch/dynamo-run/src/subprocess/sglang_inc.py:80-110
Timestamp: 2025-06-03T10:17:51.711Z
Learning: The sglang `async_encode` method does not support streaming options, so collecting all embeddings before yielding is the correct approach for embedding requests.
🧬 Code Graph Analysis (1)
lib/llm/src/kv_router.rs (3)
lib/llm/src/kv_router/scheduler.rs (2)
  • push (263-266)
  • new (353-357)
lib/llm/src/kv_router/sequence.rs (2)
  • push (189-234)
  • push (414-426)
lib/llm/src/kv_router/approx.rs (1)
  • block_size (276-278)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Mirror Repository to GitLab
  • GitHub Check: pre-merge-rust (.)
  • GitHub Check: pre-merge-rust (lib/runtime/examples)
  • GitHub Check: pre-merge-rust (lib/bindings/python)
  • GitHub Check: Build and Test - vllm
🔇 Additional comments (8)
lib/llm/src/kv_router/scheduler.rs (1)

262-266: LGTM: Clean batch token push implementation

The method signature change from single token to token slice is consistent with the PR objective. The implementation correctly forwards the slice to the underlying sequences layer.

lib/llm/src/kv_router.rs (2)

209-212: LGTM: Consistent API change for batch token push

The method signature change aligns with the batch token push implementation across the codebase.


276-320: Well-implemented batch token accumulation logic

The refactoring correctly implements batch token pushing by:

  • Tracking initial sequence length and block boundaries
  • Accumulating tokens from response chunks
  • Pushing accumulated tokens only when crossing block boundaries
  • Properly updating block indices after each push

The block boundary detection logic is sound - using (isl + total_output_length).saturating_sub(1) / block_size to calculate the current block index and comparing with the previous index.

Note: Any remaining accumulated tokens at stream end are handled by the free() call, which should properly clean up partial blocks.

lib/llm/src/kv_router/sequence.rs (5)

188-234: Excellent refactoring to handle batch token pushes with proper borrow management

The implementation correctly handles the transition from single-token to batch-token pushes:

  1. Proper borrow management: The deferred operations pattern elegantly solves borrow checker issues by collecting operations during iteration and executing them after releasing the token_seq borrow.

  2. Correct block boundary detection: Using token_seq.total_tokens() % self.block_size != 1 correctly identifies when a block boundary is crossed (first token in a new block).

  3. Efficient batch processing: The method processes all tokens in the slice while maintaining the same block management semantics as the original single-token version.

The logic flow is clear and maintains data integrity throughout the batch operation.


248-249: Consistent enum variant update for batch token support

The UpdateSequences::Push variant correctly changed from single token to Vec<u32> to support the batch token push functionality.


311-313: Proper worker thread handling for batch tokens

The worker thread correctly processes the updated enum variant by passing the tokens slice to the underlying push method.


414-426: Well-implemented multi-worker batch token push

The method correctly:

  • Accepts token slice parameter
  • Finds the appropriate worker for the request
  • Converts slice to Vec<u32> for sending across thread boundaries
  • Maintains proper error handling

The slice-to-vector conversion is necessary for thread communication.


519-519: Good test updates for batch token push API

The test cases correctly demonstrate the new batch push functionality by pushing multiple tokens at once instead of individual token pushes.

Also applies to: 573-573


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@PeaBrane PeaBrane merged commit 5e511e9 into main Jul 10, 2025
13 of 14 checks passed
@PeaBrane PeaBrane deleted the rupei/router-sse-fixes branch July 10, 2025 03:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants