-
Notifications
You must be signed in to change notification settings - Fork 293
[Feat][Router] Add TTFT Routing #670
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @chickeyton, 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 a novel Time To First Token (TTFT) routing mechanism into the vLLM router. This enhancement aims to optimize request distribution across available backends by predicting the fastest path to the first generated token, thereby improving overall system responsiveness and efficiency. The changes also include necessary updates to the request monitoring and benchmarking tools to support and evaluate this new routing approach.
Highlights
- New TTFT Routing Logic: Introduced a new Time To First Token (TTFT) routing strategy that intelligently selects the optimal backend by estimating the time it will take to generate the first token, considering KV cache hits and current engine load.
- Enhanced Prompt Handling: Implemented a robust utility to extract prompts from various request formats (completion, chat, multimodal) for accurate tokenization, which is essential for effective KV cache lookups in the new routing logic.
- Improved Request Statistics: Extended the request statistics monitoring to track critical metrics such as 'engine_prefill_tps' (tokens per second during prefill) and 'uncomputed_prefix_tokens', providing the necessary data for the TTFT routing algorithm's estimations.
- Benchmarking Tool Updates: Modified the multi-round QA benchmark to include a 'max_unfinished_queries' parameter, allowing for better control over concurrent requests and more accurate simulation of load during performance testing of the new routing strategy.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command>
or @gemini-code-assist <command>
. Below is a summary of the supported commands.
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 issue 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
-
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. ↩
There was a problem hiding this comment.
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 a new TTFT (Time To First Token) routing strategy, which is a significant feature. The implementation spans routing logic, statistics collection, and request processing, and includes updates to the benchmarking tool. The overall approach is sound, but I've identified a critical bug in the new TtftRouter
where an exception is created but not raised. I've also left several comments to improve code clarity, maintainability, and robustness, such as renaming misleading variables, removing magic numbers, and improving an algorithm's efficiency. Addressing these points will strengthen the new routing logic.
Signed-off-by: chickeyton <[email protected]>
245f902
to
2361a17
Compare
Signed-off-by: chickeyton <[email protected]>
This PR depends on to be merged FullLookup feature of LMCache, so cannot be merged yet, but please take a look of the design if u have time, thanks! |
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
/gemini review |
/gemini summary |
There was a problem hiding this comment.
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 a new TTFT (Time-To-First-Token) based routing logic, which is a significant feature enhancement. The implementation includes the new TtftRouter
, supporting CLI arguments, and necessary updates to statistics collection. The code is well-structured, but I've found a few critical issues and areas for improvement. Specifically, there are critical bugs in the TtftRouter
's logic for finding the best-matched cache and in the initialization of a data class for request stats. There are also opportunities to improve the robustness of argument parsing and the correctness of an interval-merging utility class. Addressing these points will be crucial for the stability and correctness of this new feature.
Summary of ChangesThis pull request introduces a new routing logic, Highlights
Changelog
Activity
|
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
/gemini review |
/gemini summary |
There was a problem hiding this comment.
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 a new TtftRouter
routing logic that aims to reduce Time To First Token (TTFT) by selecting instances with the lowest estimated prefill workload. The changes are extensive, touching routing logic, request processing, and statistics monitoring. Overall, this is a valuable feature addition. However, I've identified a few critical issues, including a potential runtime error due to an incomplete refactoring, a missing return statement that could cause crashes, and a memory leak in the statistics monitor. Addressing these issues is crucial for the stability and correctness of the new functionality.
Summary of ChangesThis pull request introduces a significant enhancement to the Highlights
Changelog
Activity
|
/gemini review |
There was a problem hiding this comment.
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 a new TTFT (Time To First Token) based routing logic for the vLLM router. The goal is to improve request scheduling by estimating the prefill workload on each instance and routing to the one with the lowest expected TTFT. The changes are comprehensive, touching the routing logic, statistics monitoring, command-line argument parsing, and benchmarking tools. The overall design is sound and the implementation is mostly solid. However, I've identified a few critical bugs that could lead to runtime errors or incorrect behavior, along with several suggestions for improving code quality and robustness. Please address the critical issues before merging.
0 | ||
].split("//")[1] | ||
) | ||
endpoint_instance_id = await self.query_manager(query_message) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This line calls self.query_manager
, but this method was removed from KvawareRouter
in this same pull request. This will cause an AttributeError
at runtime. You should call self.kv_manager.handle_orchestration_message
directly, as you've done in other parts of the code.
endpoint_instance_id = await self.kv_manager.handle_orchestration_message(query_message)
if best_matched_info: | ||
cache_info.num_cached_tokens = num_cached_tokens | ||
else: | ||
return best_inst_url, cache_info |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This logic is flawed. If best_matched_info
is True
, the function will fall through the if
block and implicitly return None
because there is no return
statement. This is a critical bug. Additionally, if best_matched_info
is False
, num_cached_tokens
is discarded, leading to incorrect stats. The logic should be simplified to always set num_cached_tokens
on cache_info
and return the result.
cache_info.num_cached_tokens = num_cached_tokens
return best_inst_url, cache_info
workload = (stats.prefill_todo_workload + | ||
prefill_workload(num_prefix_tokens, num_cache_tokens)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The stats
object can be None
if request_stats.get(url, None)
returns None
(e.g., for a new or idle endpoint). Accessing stats.prefill_todo_workload
will raise an AttributeError
. You should handle the case where stats
is None
, for example by assuming a pending workload of 0.
workload = ((stats.prefill_todo_workload if stats else 0) +
prefill_workload(num_prefix_tokens, num_cache_tokens))
if instance_id_to_url is None: | ||
self.instance_id_to_url = {} | ||
else: | ||
self.instance_id_to_url = instance_id_to_url |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if instance_id_to_url is None: | ||
self.instance_id_to_url = {} | ||
else: | ||
self.instance_id_to_url = instance_id_to_url |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
self.tokenizer_name = tokenizer_name | ||
self.tokenizer = None | ||
self.enable_shared_cache = enable_shared_cache | ||
self.cached_prefix_tokens = None |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ip=endpoint.url.split(f":{endpoint.url.split(":")[-1]}")[ | ||
0 | ||
].split("//")[1] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This logic to extract the IP address from the URL is complex and can be fragile. Using urllib.parse.urlparse
would be a more robust and readable way to get the hostname. You'll need to add from urllib.parse import urlparse
at the top of the file. This same improvement can be applied to KvawareRouter
as well.
ip=urlparse(endpoint.url).hostname
class RequestStatsCacheInfo: | ||
""" | ||
Cache information. | ||
""" | ||
def __init__(self): | ||
self.num_prefix_tokens : int = 0 | ||
self.num_cached_tokens : int = 0 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This class can be simplified by using the @dataclass
decorator, which automatically generates methods like __init__
and __repr__
. It would make the code more concise and idiomatic. The dataclasses
module is already imported in this file.
class RequestStatsCacheInfo: | |
""" | |
Cache information. | |
""" | |
def __init__(self): | |
self.num_prefix_tokens : int = 0 | |
self.num_cached_tokens : int = 0 | |
@dataclass | |
class RequestStatsCacheInfo: | |
""" | |
Cache information. | |
""" | |
num_prefix_tokens: int = 0 | |
num_cached_tokens: int = 0 |
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
Signed-off-by: chickeyton <[email protected]>
/gemini review |
There was a problem hiding this comment.
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 a new TTFT-based routing logic, which is a significant feature enhancement. The goal is to improve request routing by estimating prefill workload and selecting the instance with the lowest load, which should lead to better TTFT. The implementation is comprehensive, with changes across routing, statistics monitoring, and application configuration. The code is well-structured, and the inclusion of benchmark results is very helpful. I've identified a couple of areas for minor improvements related to code clarity and performance optimization.
if best_matched_info is None: | ||
raise ValueError("no best matched instance was found") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
for endpoint in endpoints: | ||
msg = QueryInstMsg( | ||
event_id="", | ||
ip=urlparse(endpoint.url).hostname | ||
) | ||
ret_msg = await self.kv_manager.handle_orchestration_message(msg) | ||
self.instance_id_to_url[ret_msg.instance_id] = endpoint.url | ||
if ret_msg.instance_id == instance_id: | ||
url = endpoint.url |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The loop iterates through all endpoints to find the URL for a given instance_id
, even after a match is found. This can be inefficient, especially with a large number of endpoints. Consider adding a break
statement after finding the matching instance to avoid unnecessary queries.
for endpoint in endpoints: | |
msg = QueryInstMsg( | |
event_id="", | |
ip=urlparse(endpoint.url).hostname | |
) | |
ret_msg = await self.kv_manager.handle_orchestration_message(msg) | |
self.instance_id_to_url[ret_msg.instance_id] = endpoint.url | |
if ret_msg.instance_id == instance_id: | |
url = endpoint.url | |
for endpoint in endpoints: | |
msg = QueryInstMsg( | |
event_id="", | |
ip=urlparse(endpoint.url).hostname | |
) | |
ret_msg = await self.kv_manager.handle_orchestration_message(msg) | |
self.instance_id_to_url[ret_msg.instance_id] = endpoint.url | |
if ret_msg.instance_id == instance_id: | |
url = endpoint.url | |
break |
FIX #583
An answer to the feature request TTFT Routing
Dependancies
This PR depends on the to be merged feature FullLookUp in LMCache. Therefore, this PR can not be merged until FullLookUp be merged and be released in an offiical version of LMCache
Design
Motivation
The current PrefixAwareRouter and KvawareRouter (in production-stack) route user request purely base on the length the cached prefix. However, it may not be optimal due to the selected instance may have a long pending request queue. A more efficient way is estimating TTFT(or prefill workload) of the incoming request for each instance, select the one with the least estimated TTFT(or prefill workload).
TTFT & Prefill Workload Estimation
TTFT esitmation require 1) prefill computation workload estimation & 2) computation speed profiling, but since there are different parallelisms going on and there are lots of factors, it often give unreliable numbers about the speed, the solution is simply assume the computation speed of all instances are the same, then comparing workload is equivalent to comparing TTFT, the experiment result supports that point.
Prefill Workload Estimation:
It is not the actual no. of float operations required, since each model architecture introduce differences, it is not practical to have a tailor made formula for each architecture, so we use a comparable number to represent the size of computation amount (no. of Q•K dot products or alike operations).
For each instance, we forcast the pending workload with the addtion workload from the new request:
num_cache_tokens: No. of cached tokens in prefix, queried from the FullLookup service of LMCache, if share cache is enabled, the max no. of cached tokens among all vllm instance will be used.
Actual Code Changes:
Added
TtftRouter
, likeKvawareRouter
, it host a centralized LMCache registry service, the vllm instances using the LMCache connector and register/unregister prefix caches from that registry service. On request routing,TtftRouter
do a FullLookup (to be merged feature in LMCache) from the registry service to retrieveAdded optional commandline argument
--tokenizer <model>
for specifing the tokenizer path or HF model name,KvawareRouter
andTtftRouter
will load that tokenizer immediately after starting the LMCache registry service. If not specified they will load the tokenizer with the model specified in the first vllm endpoint on routing the first user request.Added optional commandline argument
--lmcache-instances <comman separated list of LMCache instance id>
used with--service-discovery static
only, if two or more vllm endpoints share a same IP then--lmcache-instances
must be specified, otherwise theQueryInstMsg
to LMCache queries inKvawareRouter
andTtftRouter
will give wrong resultsAdded optional commandline argument
--enable-share-cache
, specify that if p2p transfer is enabled in LMCache.Added
prefill_todo_workload
measures toRequestStats
referring toqueue_workload
Added
RequestStatsCacheInfo
that returns byTtftRouter.route_request()
and kept track byRequestStatsMonitor
Usage:
Assuming two vllm endpoints, vllm router, and Redis service are hosted on the same machine
1. prepare 2 LMCache yaml config files:
~/lmcache_config_0.yaml
and~/lmcache_config_1.yaml
:example lmcache_config_0.yaml
2. Start Redis server:
redis-server --port 8600
3. Start the first vllm endpoint:
4. Start the second vllm endpoint like the first one with proper namings, port and CUDA_VISIBLE_DEVICES, LMCACHE_CONFIG_FILE values
5. Start vllm-router with
TtftRouter
:--routing-logic
set tottft
--lmcache-controller-port
must be same as thecontroller_url
's port specified inlmcache_config_*.yaml
--lmcache-instances
must be listing thelmcache_instance_id
value specified inlmcache_config_*.yaml
as two vllm endpoints share the same IP6. Good to send request to the vllm-router now:
Experiment 1
Setup
Model: Qwen/Qwen2-7B x 2 vllm instances
GPU: NVIDIA GeForce RTX 3090 (24GB) X 2
Routers:
TTFT
Kvaware
QPS (fallback of Kvaware by setting '--kv-aware-threshold 0')
Benchmark Script (from production-stack/benchmarks/multi-round-qa):
Results
TTFT
Kvaware
QPS
Avg. TTFT:
TTFT: 0.3968s (Kvaware -17.1%)
Kvaware: 0.4788s
QPS: 0.5119s
Experiment 2
Setup
Same as experiment 1
Benchmark script is a talior made one simulates a scenario that the first same 256 tokens are always be cached then followed by 20k random tokens
Avg. TTFT:
TTFT: 2.4981s (QPS -18.5%)
Kvaware: 5.3141s
QPS: 3.0669s
In this experiement, Kvaware always route the requests to the same vllm instance, so it perform poorly
Conculsion
TTFT routing shows significant reduction in TTFT compare to Kvaware & QPS routing by estimating the prefill workload of the vllm instances. And it is more robust than Kvaware routing, consider that, A client keep sending requests with a fixed system prompt of a few hundreds tokens, the Kvaware routing will always route the request to the same vllm instance while TTFT routing provides a good load balancing in that use case.
-s
when doinggit commit
[Bugfix]
,[Feat]
, and[CI]
.Detailed Checklist (Click to Expand)
Thank you for your contribution to production-stack! Before submitting the pull request, please ensure the PR meets the following criteria. This helps us maintain the code quality and improve the efficiency of the review process.
PR Title and Classification
Please try to classify PRs for easy understanding of the type of changes. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:
[Bugfix]
for bug fixes.[CI/Build]
for build or continuous integration improvements.[Doc]
for documentation fixes and improvements.[Feat]
for new features in the cluster (e.g., autoscaling, disaggregated prefill, etc.).[Router]
for changes to thevllm_router
(e.g., routing algorithm, router observability, etc.).[Misc]
for PRs that do not fit the above categories. Please use this sparingly.Note: If the PR spans more than one category, please include all relevant prefixes.
Code Quality
The PR need to meet the following code quality standards:
pre-commit
to format your code. SeeREADME.md
for installation.DCO and Signed-off-by
When contributing changes to this project, you must agree to the DCO. Commits must include a
Signed-off-by:
header which certifies agreement with the terms of the DCO.Using
-s
withgit commit
will automatically add this header.What to Expect for the Reviews
We aim to address all PRs in a timely manner. If no one reviews your PR within 5 days, please @-mention one of YuhanLiu11
, Shaoting-Feng or ApostaC.