Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions bindings/python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,11 @@ struct Router {
mesh_advertise_host: Option<String>,
mesh_port: u16,
mesh_peer_urls: Vec<String>,
pre_prefill_urls: Option<Vec<(String, Option<u16>)>>,
pre_prefill_decode_urls: Option<Vec<String>>,
pre_prefill_match_threshold: f32,
pre_prefill_unmatched_chars_threshold: usize,
pre_prefill_min_chars: usize,
}

impl Router {
Expand Down Expand Up @@ -564,6 +569,13 @@ impl Router {
.as_ref()
.map(convert_policy)
.transpose()?,
pre_prefill_urls: self.pre_prefill_urls.clone().unwrap_or_default(),
pre_prefill_decode_urls: self.pre_prefill_decode_urls.clone().unwrap_or_default(),
pre_prefill_config: config::PrePrefillConfig {
match_threshold: self.pre_prefill_match_threshold,
unmatched_chars_threshold: self.pre_prefill_unmatched_chars_threshold,
min_chars: self.pre_prefill_min_chars,
},
}
} else {
RoutingMode::Regular {
Expand Down Expand Up @@ -846,6 +858,11 @@ impl Router {
mesh_port = 39527u16,
mesh_peer_urls = vec![],
mesh_advertise_host = None,
pre_prefill_urls = None,
pre_prefill_decode_urls = None,
pre_prefill_match_threshold = 0.1,
pre_prefill_unmatched_chars_threshold = 10000,
pre_prefill_min_chars = 10000,
))]
#[expect(clippy::too_many_arguments)]
#[expect(
Expand Down Expand Up @@ -952,6 +969,11 @@ impl Router {
mesh_port: u16,
mesh_peer_urls: Vec<String>,
mesh_advertise_host: Option<String>,
pre_prefill_urls: Option<Vec<(String, Option<u16>)>>,
pre_prefill_decode_urls: Option<Vec<String>>,
pre_prefill_match_threshold: f32,
pre_prefill_unmatched_chars_threshold: usize,
pre_prefill_min_chars: usize,
) -> PyResult<Self> {
let mut all_urls = worker_urls.clone();

Expand All @@ -965,6 +987,16 @@ impl Router {
all_urls.extend(decode_urls.clone());
}

if let Some(ref pre_prefill_urls) = pre_prefill_urls {
for (url, _) in pre_prefill_urls {
all_urls.push(url.clone());
}
}

if let Some(ref pre_prefill_decode_urls) = pre_prefill_decode_urls {
all_urls.extend(pre_prefill_decode_urls.clone());
}

let connection_mode = Self::determine_connection_mode(&all_urls);

Ok(Router {
Expand Down Expand Up @@ -1068,6 +1100,11 @@ impl Router {
mesh_advertise_host,
mesh_port,
mesh_peer_urls,
pre_prefill_urls,
pre_prefill_decode_urls,
pre_prefill_match_threshold,
pre_prefill_unmatched_chars_threshold,
pre_prefill_min_chars,
})
}

Expand Down
48 changes: 48 additions & 0 deletions bindings/python/src/smg/router_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ class RouterArgs:
default_factory=list
) # List of (url, bootstrap_port)
decode_urls: list[str] = dataclasses.field(default_factory=list)
# Pre-prefill routing configuration
pre_prefill_urls: list[tuple] = dataclasses.field(
default_factory=list
) # List of (url, bootstrap_port) for pre-prefill workers
pre_prefill_decode_urls: list[str] = dataclasses.field(
default_factory=list
) # Decode URLs paired with pre-prefill workers
pre_prefill_match_threshold: float = 0.1 # Cache match threshold for cold detection
pre_prefill_unmatched_chars_threshold: int = 10000 # Min unmatched chars to trigger
pre_prefill_min_chars: int = 10000 # Min total characters for eligibility

# Routing policy
policy: str = "cache_aware"
Expand Down Expand Up @@ -424,6 +434,38 @@ def add_cli_args(
default=RouterArgs.worker_startup_check_interval,
help="Interval in seconds between checks for worker startup",
)
pd_group.add_argument(
f"--{prefix}pre-prefill",
nargs="+",
action="append",
help="Pre-prefill server URL and optional bootstrap port. Can be specified multiple times. "
"Format: --pre-prefill URL [BOOTSTRAP_PORT]. Same format as --prefill.",
)
pd_group.add_argument(
f"--{prefix}pre-prefill-decode",
nargs=1,
action="append",
metavar=("URL",),
help="Decode server URL paired with pre-prefill workers. Can be specified multiple times.",
)
pd_group.add_argument(
f"--{prefix}pre-prefill-match-threshold",
type=float,
default=RouterArgs.pre_prefill_match_threshold,
help="Cache match ratio threshold below which a request is considered 'cold' (default: 0.1)",
)
pd_group.add_argument(
f"--{prefix}pre-prefill-unmatched-chars-threshold",
type=int,
default=RouterArgs.pre_prefill_unmatched_chars_threshold,
help="Minimum unmatched characters to trigger pre-prefill routing (default: 10000)",
)
pd_group.add_argument(
f"--{prefix}pre-prefill-min-chars",
type=int,
default=RouterArgs.pre_prefill_min_chars,
help="Minimum total characters for pre-prefill eligibility (default: 10000)",
)

# Load monitoring
parser.add_argument(
Expand Down Expand Up @@ -1134,6 +1176,12 @@ def from_cli_args(cls, args: argparse.Namespace, use_router_prefix: bool = False
args_dict["decode_urls"] = cls._parse_decode_urls(
cli_args_dict.get(f"{prefix}decode", None)
)
args_dict["pre_prefill_urls"] = cls._parse_prefill_urls(
cli_args_dict.get(f"{prefix}pre_prefill", None)
)
args_dict["pre_prefill_decode_urls"] = cls._parse_decode_urls(
cli_args_dict.get(f"{prefix}pre_prefill_decode", None)
)
args_dict["selector"] = cls._parse_selector(cli_args_dict.get(f"{prefix}selector", None))
args_dict["prefill_selector"] = cls._parse_selector(
cli_args_dict.get(f"{prefix}prefill_selector", None)
Expand Down
12 changes: 11 additions & 1 deletion crates/protocols/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub const DEFAULT_WORKER_COST: f32 = 1.0;
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default, schemars::JsonSchema,
)]
#[serde(rename_all = "lowercase")]
#[serde(rename_all = "snake_case")]
pub enum WorkerType {
/// Regular worker for standard routing.
#[default]
Expand All @@ -39,6 +39,10 @@ pub enum WorkerType {
Prefill,
/// Decode worker for PD disaggregated mode.
Decode,
/// Pre-prefill worker: a subtype of Prefill used for cold-request warming.
PrePrefill,
/// Pre-prefill decode worker: a subtype of Decode paired with a pre-prefill worker.
PrePrefillDecode,
}

impl std::fmt::Display for WorkerType {
Expand All @@ -47,6 +51,8 @@ impl std::fmt::Display for WorkerType {
WorkerType::Regular => write!(f, "regular"),
WorkerType::Prefill => write!(f, "prefill"),
WorkerType::Decode => write!(f, "decode"),
WorkerType::PrePrefill => write!(f, "pre_prefill"),
WorkerType::PrePrefillDecode => write!(f, "pre_prefill_decode"),
}
}
}
Expand All @@ -61,6 +67,10 @@ impl std::str::FromStr for WorkerType {
Ok(WorkerType::Prefill)
} else if s.eq_ignore_ascii_case("decode") {
Ok(WorkerType::Decode)
} else if s.eq_ignore_ascii_case("pre_prefill") {
Ok(WorkerType::PrePrefill)
} else if s.eq_ignore_ascii_case("pre_prefill_decode") {
Ok(WorkerType::PrePrefillDecode)
} else {
Err(format!("Unknown worker type: {s}"))
}
Expand Down
6 changes: 6 additions & 0 deletions model_gateway/src/config/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ impl RouterConfigBuilder {
decode_urls,
prefill_policy: None,
decode_policy: None,
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: super::types::PrePrefillConfig::default(),
};
self
}
Expand All @@ -79,6 +82,9 @@ impl RouterConfigBuilder {
decode_urls,
prefill_policy,
decode_policy,
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: super::types::PrePrefillConfig::default(),
};
self
}
Expand Down
76 changes: 75 additions & 1 deletion model_gateway/src/config/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,15 @@ pub enum RoutingMode {
prefill_policy: Option<PolicyConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
decode_policy: Option<PolicyConfig>,
/// Pre-prefill worker URLs with optional bootstrap ports (cold request warming)
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pre_prefill_urls: Vec<(String, Option<u16>)>,
/// Decode URLs paired with pre-prefill workers
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pre_prefill_decode_urls: Vec<String>,
/// Pre-prefill routing thresholds
#[serde(default)]
pre_prefill_config: PrePrefillConfig,
},
#[serde(rename = "openai")]
OpenAI { worker_urls: Vec<String> },
Expand All @@ -199,8 +208,15 @@ impl RoutingMode {
RoutingMode::PrefillDecode {
prefill_urls,
decode_urls,
pre_prefill_urls,
pre_prefill_decode_urls,
..
} => prefill_urls.len() + decode_urls.len(),
} => {
prefill_urls.len()
+ decode_urls.len()
+ pre_prefill_urls.len()
+ pre_prefill_decode_urls.len()
}
RoutingMode::OpenAI { worker_urls } => worker_urls.len(),
RoutingMode::Anthropic { worker_urls } => worker_urls.len(),
RoutingMode::Gemini { worker_urls } => worker_urls.len(),
Expand Down Expand Up @@ -339,6 +355,43 @@ fn default_manual_max_idle_secs() -> u64 {
4 * 3600
}

pub(crate) fn default_pre_prefill_match_threshold() -> f32 {
0.1
}

pub(crate) fn default_pre_prefill_unmatched_chars_threshold() -> usize {
10000
}

pub(crate) fn default_pre_prefill_min_chars() -> usize {
10000
}

/// Pre-prefill routing configuration.
/// Controls when cold requests are routed to a dedicated pre-prefill worker.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrePrefillConfig {
/// Cache match ratio threshold below which a request is considered "cold"
#[serde(default = "default_pre_prefill_match_threshold")]
pub match_threshold: f32,
/// Minimum unmatched characters to trigger pre-prefill routing
#[serde(default = "default_pre_prefill_unmatched_chars_threshold")]
pub unmatched_chars_threshold: usize,
/// Minimum total characters for pre-prefill eligibility
#[serde(default = "default_pre_prefill_min_chars")]
pub min_chars: usize,
}

impl Default for PrePrefillConfig {
fn default() -> Self {
Self {
match_threshold: default_pre_prefill_match_threshold(),
unmatched_chars_threshold: default_pre_prefill_unmatched_chars_threshold(),
min_chars: default_pre_prefill_min_chars(),
}
}
}

impl PolicyConfig {
pub fn name(&self) -> &'static str {
match self {
Expand Down Expand Up @@ -731,6 +784,9 @@ mod tests {
decode_urls: vec!["http://decode1".to_string()],
prefill_policy: None,
decode_policy: None,
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: PrePrefillConfig::default(),
};
assert!(pd.is_pd_mode());
}
Expand Down Expand Up @@ -758,6 +814,9 @@ mod tests {
],
prefill_policy: None,
decode_policy: None,
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: PrePrefillConfig::default(),
};
assert_eq!(pd.worker_count(), 5);

Expand All @@ -781,6 +840,9 @@ mod tests {
decode_urls: vec!["http://decode1".to_string()],
prefill_policy: None,
decode_policy: None,
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: PrePrefillConfig::default(),
};
let json = serde_json::to_string(&pd).unwrap();
assert!(json.contains("\"type\":\"prefill_decode\""));
Expand Down Expand Up @@ -1255,6 +1317,9 @@ mod tests {
decode_policy: Some(PolicyConfig::PowerOfTwo {
load_check_interval_secs: 60,
}),
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: PrePrefillConfig::default(),
};

let main_policy = PolicyConfig::Random;
Expand Down Expand Up @@ -1284,6 +1349,9 @@ mod tests {
block_size: 16,
}),
decode_policy: None,
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: PrePrefillConfig::default(),
};

let main_policy = PolicyConfig::RoundRobin;
Expand All @@ -1308,6 +1376,9 @@ mod tests {
decode_policy: Some(PolicyConfig::PowerOfTwo {
load_check_interval_secs: 60,
}),
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: PrePrefillConfig::default(),
};

let main_policy = PolicyConfig::Random;
Expand All @@ -1330,6 +1401,9 @@ mod tests {
decode_urls: vec!["http://decode1".to_string()],
prefill_policy: None,
decode_policy: None,
pre_prefill_urls: vec![],
pre_prefill_decode_urls: vec![],
pre_prefill_config: PrePrefillConfig::default(),
};

let main_policy = PolicyConfig::CacheAware {
Expand Down
Loading
Loading