Skip to content

Conversation

PeaBrane
Copy link
Contributor

@PeaBrane PeaBrane commented May 28, 2025

Overview:

This PR introduces:

  1. Better replicate the vllm scheduling + block managing behaviors. Plus several bug fixes.
  2. Much better simulation of TTFL and ITL thanks to empirical results from @tedzhouhk. See this script
  3. Hook everything up to an AsyncEngine, integrating with dynamo-run
  4. A preliminary (toy) large-scale KV routing benchmarking with the mockers (done with dynamo-run)

Will close #995

prefix_ratio_mocker

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added active block ratio metric and detailed prefill cost with new blocks count.
    • Introduced asynchronous notifications for block state changes via channels.
    • Added a two-stage scheduling and execution model (prefill and decode) with enhanced budget enforcement.
    • Implemented a mock engine simulating streaming token generation with multi-worker support, metrics, and KV event publishing.
    • Added output token generation status signaling and expanded protocol capabilities.
    • Enabled loading mocker engine configuration from JSON files via command-line flags.
    • Integrated mocker engine as a selectable runtime option in the launch system.
  • Refactor

    • Replaced timestamp-based eviction with a counter-based, strictly ordered eviction mechanism.
    • Renamed and streamlined scheduler state queues and methods for clarity and efficiency.
    • Removed unused parameters and simplified sequence and scheduling interfaces.
    • Updated scheduling intervals and internal state management for improved simulation accuracy.
    • Refactored engine creation logic to support new mocker engine configuration.
  • Bug Fixes

    • Enhanced block eviction and scheduling logic for consistent behavior and accurate cache hit rate tracking.

Copy link

copy-pr-bot bot commented May 28, 2025

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@PeaBrane PeaBrane mentioned this pull request May 28, 2025
5 tasks
Copy link
Contributor

coderabbitai bot commented May 30, 2025

Caution

Review failed

The head commit changed during the review from c7c4be5 to 1845a8d.

Walkthrough

The codebase underwent a major refactor of the mock worker's scheduling, eviction, and sequence management logic. The LRU evictor now uses integer counters and a BTreeSet for precise eviction order. Scheduler and KV manager logic were updated to support a two-phase (prefill/decode) model, improved resource accounting, and simplified interfaces. Sequence and protocol structures were adjusted accordingly. A new asynchronous mock engine was introduced, integrating schedulers, streaming token generation, metrics, and KV event publishing.

Changes

File(s) Change Summary
lib/llm/src/mocker/evictor.rs Replaced timestamp-based LRU eviction with integer counter-based eviction using BTreeSet; added PriorityItem, new methods, and refactored API.
lib/llm/src/mocker/kv_manager.rs Added optional channel for block responses; refactored process to send block store/remove responses; replaced scheduling with cost computation; added active percent method; updated tests.
lib/llm/src/mocker/protocols.rs Modified MoveBlock variants; added MoveBlockResponse enum; added dp_rank field to DirectRequest; added new_blocks to PrefillCost; added OutputSignal and MockEngineArgs structs; added utility function for cache event conversion.
lib/llm/src/mocker/scheduler.rs Refactored to two-phase (prefill/decode) model; updated scheduling and simulation logic; changed constructor and metrics; added speedup ratio and cache hit rate tracking; updated background tasks and tests.
lib/llm/src/mocker/sequence.rs Removed unused chunk_size field and parameter from ActiveSequence and related methods.
lib/llm/src/mocker.rs Added new public module declaration engine.
lib/llm/src/mocker/engine.rs Added MockVllmEngine implementing AsyncEngine trait; manages multiple schedulers, streams tokens, publishes metrics and KV events; includes integration test with distributed runtime.
launch/dynamo-run/src/flags.rs Added optional extra_mocker_args JSON config file path; refactored engine args loading to support mocker args loading.
launch/dynamo-run/src/lib.rs Added engine creation arm for Mocker output; loads mocker args from JSON and builds MockEngineArgs; creates mocker engine asynchronously.
launch/dynamo-run/src/opt.rs Added Mocker variant to Output enum; updated conversions and available engines list.
docs/guides/dynamo_run.md Added documentation for the new mocker engine, its usage, configuration options, and examples.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MockVllmEngine
    participant Scheduler
    participant KvManager
    participant Evictor

    Client->>MockVllmEngine: generate(DirectRequest)
    MockVllmEngine->>Scheduler: submit request
    Scheduler->>KvManager: compute prefill cost
    Scheduler->>Scheduler: insert into prefill queue
    loop Prefill phase
        Scheduler->>Scheduler: process prefill queue
        Scheduler->>KvManager: update active blocks/tokens
    end
    Scheduler->>Scheduler: move to decode queue
    loop Decode phase
        Scheduler->>Scheduler: process decode queue
        Scheduler->>Evictor: evict if needed
        Scheduler->>KvManager: send block store/remove responses
    end
    Scheduler->>MockVllmEngine: output signals
    MockVllmEngine->>Client: stream generated tokens
Loading

Assessment against linked issues

Objective Addressed Explanation
Simulate/predict KvEvents based on eviction policy (#995, #1033)
Model memory + compute complexity based on cache/request sizes (#995, #1159)
Integrate modeling into mocker, simulate vllm scheduling, hook as AsyncEngine/component (#995, #1236) The new MockVllmEngine implements AsyncEngine trait and integrates scheduling and KV events.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
None found

Possibly related PRs

Poem

A scheduler hops with counters anew,
Prefill and decode—now a two-phase queue!
Evictors march in ordered sets,
Simulating work without GPU sweats.
The mocker’s world is neat and bright,
As rabbits code through day and night! 🐇✨


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
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented May 30, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
lib/llm/src/mocker/scheduler.rs (1)

294-346: 🛠️ Refactor suggestion

⚠️ Potential issue

Locks are held across an .await; this blocks every other task

state_guard and kv_manager_guard stay alive while the task sleeps:

let adjusted_time = Duration::from_secs_f64(total_time.as_secs_f64() / speedup_ratio);
if adjusted_time.as_millis() > 0 {
    tokio::time::sleep(adjusted_time).await;   // <-- await with locks held
}

While sleeping, all other async tasks that need the same Mutexes (e.g. receive, metrics queries, other scheduler ticks) will starve, drastically reducing concurrency and possibly causing dead-locks when used with additional locks elsewhere.

Fix by dropping the guards before the await:

-// Sleep once for the adjusted duration
-let adjusted_time = Duration::from_secs_f64(total_time.as_secs_f64() / speedup_ratio);
-if adjusted_time.as_millis() > 0 {
-    tokio::time::sleep(adjusted_time).await;
-}
+// Sleep once for the adjusted duration
+let adjusted_time = Duration::from_secs_f64(total_time.as_secs_f64() / speedup_ratio);
+
+// Explicitly drop locks to avoid holding them across await points
+drop(state_guard);
+drop(kv_manager_guard);
+
+if adjusted_time.as_millis() > 0 {
+    tokio::time::sleep(adjusted_time).await;
+}

Please scope the guard usages or call drop() as above to restore non-blocking behaviour.

🧹 Nitpick comments (7)
lib/llm/src/mocker/protocols.rs (1)

58-63: Consider documenting the new new_blocks field

PrefillCost now exposes new_blocks, but the struct-level doc comment still talks about “the cost of prefilling content” without explaining that both token and block deltas are returned. A short description will make downstream usage clearer and avoid confusion with the pre–refactor signature.

 /// Represents the cost of prefilling content in the cache
-#[derive(Debug, Clone, Serialize, Deserialize)]
+/// `new_blocks` – number of blocks not currently resident in **active** cache  
+/// `new_tokens` – number of tokens that need to be copied for those blocks  
+/// `prefill_compute` – empirical latency model (µs)
+#[derive(Debug, Clone, Serialize, Deserialize)]
 pub struct PrefillCost {
lib/llm/src/mocker/sequence.rs (3)

69-76: Parameter name still indicates an option, but the struct has a fixed block_size

The constructor now takes block_size: Option<usize>, which is fine, yet the earlier discussion in the PR implied the removal of a configurable size.
If external callers are no longer expected to pass None (i.e. we always default to 64) consider:

  1. Dropping the Option wrapper and accepting usize directly, or
  2. Renaming to block_size_override (or similar) to clarify semantics.

This will prevent accidental None propagation or double-wrapped options elsewhere.


107-110: new_with_signal leaks the same default-handling logic twice

new_with_signal forwards to Self::new which already expands the default for block_size.
If you accept the previous suggestion and drop the Option, you can simplify the call and the tests that pass Some(16).


229-234: Tests rely on magic numbers – make them constants

Some(16) is repeated in every test case. Replacing the literal with a const BLOCK: usize = 16; at the module level improves readability and prevents drift when the default changes.

lib/llm/src/mocker/kv_manager.rs (1)

203-206: Floating-point division on integers – cast once

A micro-nit: you convert both operands every call. Caching max_capacity as f64 in the struct saves a few casts in hot loops.

lib/llm/src/mocker/evictor.rs (1)

108-113: Risk of i64 counter under-/overflow & eventual wrap-around

negative_counter monotonically decreases and positive_counter increases forever.
With long-running services (billions of insertions) the counters may reach the limits of i64, wrapping to the opposite sign and breaking ordering guarantees.

Mitigations:

  • Use i128, or reset both counters when they approach the limits (e.g. every 2^60 ops) while re-normalising all stored counters.
  • Alternatively, store (Instant, u64) or (u64, GenerationId) and rely on wrapping add with safe tiebreakers.

Although unlikely in tests, overflow bugs manifest in persistent services.

lib/llm/src/mocker/scheduler.rs (1)

108-113: Decode LRU is not refreshed on every access

run() merely checks membership; it does not update recency, so eviction order is insertion order, not true LRU.
If the intent is genuine LRU pre-emption, consider calling decode.insert(uuid) inside run() (or providing a specialised touch method) to bump the counter each time the sequence is decoded.

This is a functional not a correctness bug – but it biases eviction unfairly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 07e4720 and 394c2bf.

📒 Files selected for processing (5)
  • lib/llm/src/mocker/evictor.rs (2 hunks)
  • lib/llm/src/mocker/kv_manager.rs (3 hunks)
  • lib/llm/src/mocker/protocols.rs (1 hunks)
  • lib/llm/src/mocker/scheduler.rs (12 hunks)
  • lib/llm/src/mocker/sequence.rs (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
lib/llm/src/mocker/scheduler.rs (3)
lib/llm/src/mocker/kv_manager.rs (4)
  • new (70-82)
  • num_active_blocks (199-201)
  • get_prefill_cost (224-239)
  • get_active_perc (204-206)
lib/llm/src/mocker/evictor.rs (2)
  • new (62-65)
  • default (50-57)
lib/llm/src/mocker/sequence.rs (3)
  • new (69-87)
  • generate (151-177)
  • pop (210-218)
🔇 Additional comments (1)
lib/llm/src/mocker/kv_manager.rs (1)

178-183: probe_new_blocks no longer checks the inactive pool – is that deliberate?

Switching the probe from all_blocks to only active_blocks means a block that resides in the inactive LRU will now be treated as new.
That will over-estimate new_blocks and new_tokens, skewing both budget checks and the latency model.

If the intent is precisely “blocks not currently active”, please update the docstring of PrefillCost::new_blocks to match.
Otherwise, consider reverting to !self.all_blocks.contains(block) (or additionally checking inactive_blocks) to preserve previous behaviour.

@PeaBrane
Copy link
Contributor Author

PeaBrane commented Jun 8, 2025

can be used for #1409 for pure predictive routing (via mocking the KV Events and load metrics)

@PeaBrane PeaBrane marked this pull request as ready for review June 16, 2025 19:54
Copy link
Contributor

@grahamking grahamking left a comment

Choose a reason for hiding this comment

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

You can't create DistributedRuntime there, see my comment.

@PeaBrane PeaBrane enabled auto-merge (squash) July 1, 2025 18:04
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.

[FEATURE]: a mock worker API
3 participants