diff --git a/atom/mesh/README.md b/atom/mesh/README.md index 6dfcf5a9eb4..d2bd3a8c3cf 100644 --- a/atom/mesh/README.md +++ b/atom/mesh/README.md @@ -286,7 +286,7 @@ Supported tool parsers: `json`, `python`, `xml`. |--------|-------------| | `random` | Uniform random selection | | `round_robin` | Sequential rotation with atomic counters | -| `cache_aware` | Prefix-tree matching for cache reuse, with configurable balance thresholds; with `--kv-events`, a request the router can tokenize goes by the blocks each worker's device cache holds, and with `--kv-storage-weight` by what its engine will load from the Mooncake Store it reads, at that weight per token, once one holds more of it than `cache_threshold`. Requests with media, imbalanced load and workers without indexed events stay on the tree | +| `cache_aware` | Prefix-tree matching for cache reuse, with configurable balance thresholds; with `--kv-events`, a request the router can tokenize goes by the blocks each worker's device cache holds, by what its engine will copy in from the device pools of its share group (ATOM's `umbp_pool`) at `--kv-share-weight` (0.9) per token, and with `--kv-storage-weight` by what its engine will load from the Mooncake Store it reads, at that weight per token, once one holds more of it than `cache_threshold`. Requests with media, imbalanced load and workers without indexed events stay on the tree | | `power_of_two` | Chooses the lighter of two randomly sampled workers | | `prefix_hash` | Consistent prefix hashing | diff --git a/atom/mesh/docs/metrics.md b/atom/mesh/docs/metrics.md index e6e4217b42a..1527e267ee7 100644 --- a/atom/mesh/docs/metrics.md +++ b/atom/mesh/docs/metrics.md @@ -107,6 +107,8 @@ Defaults are the CLI defaults. | | `relocate` | That ratio is at or below the threshold: the least-loaded worker, ties broken at random. Workers outside the candidates keep their matches in the tree. | ratio | | | `imbalanced` | The max minus min load exceeds `--balance-abs-threshold` (64) and the max exceeds `--balance-rel-threshold` (1.5) times the min: the least-loaded worker, without a tree lookup. | | | | `no_tree` | No tree for the model and pool: a random healthy worker. | | +| | `kv_affinity` | With `--kv-events`: the worker whose device cache holds the largest share of the prompt, above the threshold, then the least loaded. | ratio | +| | `kv_shared` | The same, where that worker's share counts what its engine will copy in from the device pools of its share group, at `--kv-share-weight` (0.9) per token. | ratio | | `prefix_hash` | `ring_hit` | The hash ring owner of the first `--prefix-token-count` (256) tokens, when its load is at most `--prefix-hash-load-factor` (1.25) times the average load including this request. | | | | `load_balance_walk` | The owner is over that bound: the least-loaded worker within it, or the owner if none is. | | | | `fallback_least_load` | No ring, or the owner is not healthy: the least-loaded worker. | | @@ -215,10 +217,11 @@ match ratio only when it picked the worker holding the best match, which covers every `affinity` decision and any `relocate` that happened to pick it. With `--kv-events`, its `kv_affinity` decisions estimate the selection from the KV event index, short of the block of the prompt's last token, which the engine -always computes. With `--kv-storage-weight`, they add what the engine will load -from the Mooncake Store the worker reads, by ATOM's load rule. When that store -does not answer, the match rate counts the device cache alone and the decision -has no estimate. The +always computes. `kv_shared` decisions add what the engine will copy in from +the device pools of its share group, which it reports cached as well. With +`--kv-storage-weight`, they add what the engine will load from the Mooncake +Store the worker reads, by ATOM's load rule. When that store does not answer, +the match rate leaves the store out and the decision has no estimate. The router drops the estimate when it sends the prompt to a different worker than the policy chose, because DP ranks keep separate KV caches; under `--atom-pd-rank-mapping-policy idx2idx` that takes a health or membership change @@ -231,7 +234,8 @@ while the engine counts tokens in blocks, and the tree does not see engine eviction, chat templates or KV offload. `kv_affinity` counts tokens: the blocks the index matches, short of the last token's block, and with `--kv-storage-weight` what the engine will load from the store, over the -prompt's tokens. It differs where the index is not the engine's cache at that +prompt's tokens; `kv_shared` also counts what the engine will copy in from its +share group. It differs where the index is not the engine's cache at that moment: batches not applied yet, blocks evicted since, and predictions for a worker without exact events. A positive error means the router overestimated; a negative one means the engine reused more than predicted. diff --git a/atom/mesh/mocker/app_helpers.rs b/atom/mesh/mocker/app_helpers.rs index fe08006b0e3..aa9521e857a 100644 --- a/atom/mesh/mocker/app_helpers.rs +++ b/atom/mesh/mocker/app_helpers.rs @@ -76,7 +76,7 @@ async fn create_mocker_context_inner( }; let worker_registry = Arc::new(WorkerRegistry::new()); - let policy_registry = Arc::new(PolicyRegistry::new(config.policy.clone())); + let policy_registry = Arc::new(PolicyRegistry::for_router(&config)); let response_storage = Arc::new(MemoryResponseStorage::new()); let conversation_storage = Arc::new(MemoryConversationStorage::new()); let conversation_item_storage = Arc::new(MemoryConversationItemStorage::new()); diff --git a/atom/mesh/src/app_context.rs b/atom/mesh/src/app_context.rs index 5479900a69e..1d4778f2bb9 100644 --- a/atom/mesh/src/app_context.rs +++ b/atom/mesh/src/app_context.rs @@ -21,7 +21,7 @@ use crate::{ kv_storage::StorageSources, middleware::TokenBucket, observability::inflight_tracker::InFlightRequestTracker, - policies::PolicyRegistry, + policies::{KvTiers, PolicyRegistry}, reasoning_parser::ParserFactory as ReasoningParserFactory, routers::{ atom_bridge::AtomBridgeRuntime, @@ -298,11 +298,11 @@ impl AppContextBuilder { let port = router_config.mooncake_admin_port; Arc::new(StorageSources::new(port, deadline, client.clone())) }); + // The policies read the index and ask the stores themselves, each at the tier + // weights in its own config. if let Some(monitor) = &kv_event_monitor { - if let Some(storage) = &kv_storage { - monitor.read_stores(storage.clone(), router_config.kv_storage_weight); - } - policy_registry.set_kv_events(monitor.clone()); + let tiers = KvTiers::new(monitor.clone(), kv_storage.clone()); + policy_registry.set_kv_tiers(tiers); } let tokenize_limits = TokenizeLimits::new(&router_config); Ok(AppContext { @@ -438,7 +438,7 @@ impl AppContextBuilder { /// Create policy registry fn with_policy_registry(mut self, config: &RouterConfig) -> Self { - self.policy_registry = Some(Arc::new(PolicyRegistry::new(config.policy.clone()))); + self.policy_registry = Some(Arc::new(PolicyRegistry::for_router(config))); self } diff --git a/atom/mesh/src/cliargs.rs b/atom/mesh/src/cliargs.rs index 06abf862fce..80e72f8ac9c 100644 --- a/atom/mesh/src/cliargs.rs +++ b/atom/mesh/src/cliargs.rs @@ -290,6 +290,12 @@ pub struct CliArgs { #[arg(long, default_value_t = 0.0, value_parser = parse_fraction, help_heading = "Routing Policy")] pub kv_storage_weight: f64, + /// With --kv-events, what a token a worker's engine will copy in from the device pool of + /// another rank of its share group (ATOM's umbp_pool) counts for in cache_aware's match + /// rate (0 to 1), against one its own device cache holds; 0 ignores share groups + #[arg(long, default_value_t = 0.9, value_parser = parse_fraction, help_heading = "Routing Policy")] + pub kv_share_weight: f64, + // ==================== PD Disaggregation ==================== /// Enable PD (Prefill-Decode) disaggregated mode #[arg(long, default_value_t = false, help_heading = "PD Disaggregation")] @@ -722,6 +728,7 @@ impl CliArgs { .mooncake_admin_port(self.mooncake_admin_port) .kv_storage_deadline_ms(self.kv_storage_deadline_ms) .kv_storage_weight(self.kv_storage_weight) + .kv_share_weight(self.kv_share_weight) .retries(!self.disable_retries) .circuit_breaker(!self.disable_circuit_breaker) .build() @@ -858,6 +865,62 @@ mod tests { } } + /// The two weights on the command line are the `TierWeights` in the config of each + /// cache-aware policy of the `AppContext` built from it: the default policy, one a + /// worker's `policy` label asks for by name, and one the PD routers create. Leaving + /// either out of the `RouterConfig`, or of what the registry creates policies with, + /// fails it at the defaults. + #[tokio::test] + async fn cli_kv_weights_fill_the_tier_weights_of_every_cache_aware_policy() { + use crate::{ + app_context::AppContext, + core::prepare_pool::PreparePoolRuntime, + policies::{CacheAwarePolicy, LoadBalancingPolicy, TierWeights}, + }; + + let flags = "atomesh --kv-events --kv-share-weight 0.5 --kv-storage-weight 0.25"; + let args = CliArgs::try_parse_from(flags.split_whitespace()).unwrap(); + let config = args.to_router_config(Vec::new()).unwrap(); + let runtime = PreparePoolRuntime::new(config.resolved_prepare_pool().unwrap()).unwrap(); + let context = AppContext::from_config(config.clone(), 5, runtime.handle()) + .await + .unwrap(); + let registry = &context.policy_registry; + let policies: [std::sync::Arc; 3] = [ + registry.get_default_policy(), + registry.on_worker_added("m", Some("cache_aware")), + registry.create_policy(&config.policy), + ]; + for policy in policies { + let cache_aware = policy.as_any().downcast_ref::().unwrap(); + let want = TierWeights { + shared: 0.5, + stored: 0.25, + }; + assert_eq!(cache_aware.tier_weights(), want); + } + } + + /// The weights no flag sets are `TierWeights::default()`, however the config is made. + #[test] + fn kv_tier_weights_default_alike_on_the_command_line_and_in_the_config() { + use crate::policies::TierWeights; + + let parsed = CliArgs::try_parse_from(["atomesh"]).unwrap(); + let mut saved = serde_json::to_value(RouterConfig::default()).unwrap(); + for weight in ["kv_share_weight", "kv_storage_weight"] { + assert!(saved.as_object_mut().unwrap().remove(weight).is_some()); + } + for config in [ + parsed.to_router_config(Vec::new()).unwrap(), + CliArgs::default().to_router_config(Vec::new()).unwrap(), + RouterConfig::default(), + serde_json::from_value(saved).unwrap(), + ] { + assert_eq!(config.kv_tier_weights(), TierWeights::default()); + } + } + #[test] fn cli_kv_storage_options_map_to_router_config() { let args = CliArgs::try_parse_from([ @@ -1007,6 +1070,7 @@ impl Default for CliArgs { mooncake_admin_port: 9003, kv_storage_deadline_ms: 3, kv_storage_weight: 0.0, + kv_share_weight: 0.9, pd_disaggregation: false, decode: Vec::new(), prefill_policy: None, diff --git a/atom/mesh/src/config/builder.rs b/atom/mesh/src/config/builder.rs index c0cd401f42d..a5d34832253 100644 --- a/atom/mesh/src/config/builder.rs +++ b/atom/mesh/src/config/builder.rs @@ -394,6 +394,11 @@ impl RouterConfigBuilder { self } + pub fn kv_share_weight(mut self, weight: f64) -> Self { + self.config.kv_share_weight = weight; + self + } + /// Inverse of disable_retries field pub fn retries(mut self, enable: bool) -> Self { self.config.disable_retries = !enable; diff --git a/atom/mesh/src/config/types.rs b/atom/mesh/src/config/types.rs index 5e581b76494..dba7169c718 100644 --- a/atom/mesh/src/config/types.rs +++ b/atom/mesh/src/config/types.rs @@ -3,7 +3,10 @@ use std::time::Duration; use serde::{Deserialize, Serialize}; use super::{ConfigError, ConfigResult}; -use crate::core::{prepare_pool::PoolConfig, runtime::default_prepare_workers, ConnectionMode}; +use crate::{ + core::{prepare_pool::PoolConfig, runtime::default_prepare_workers, ConnectionMode}, + kv_tiers::TierWeights, +}; /// Backend runtime type for inference workers. /// Determines PD-disaggregation protocol (SGLang dual-dispatch+bootstrap vs vLLM Mooncake kv_transfer_params). @@ -98,6 +101,10 @@ pub struct RouterConfig { /// device; 0 asks no store. #[serde(default)] pub kv_storage_weight: f64, + /// What a token a worker copies in from its share group counts for in routing, against + /// one on its device; 0 ignores share groups. + #[serde(default = "default_kv_share_weight")] + pub kv_share_weight: f64, pub api_key: Option, pub metrics: Option, pub log_dir: Option, @@ -515,6 +522,10 @@ fn default_kv_storage_deadline_ms() -> u64 { 3 } +fn default_kv_share_weight() -> f64 { + 0.9 +} + impl Default for RouterConfig { fn default() -> Self { Self { @@ -538,6 +549,7 @@ impl Default for RouterConfig { mooncake_admin_port: default_mooncake_admin_port(), kv_storage_deadline_ms: default_kv_storage_deadline_ms(), kv_storage_weight: 0.0, + kv_share_weight: default_kv_share_weight(), api_key: None, metrics: None, log_dir: None, @@ -643,6 +655,15 @@ impl RouterConfig { matches!(self.backend, BackendType::Atom) && self.atom_pd_concurrent } + /// What `kv_share_weight` and `kv_storage_weight` count the tiers below a worker's + /// device cache for, as each cache-aware policy takes them in its config. + pub fn kv_tier_weights(&self) -> TierWeights { + TierWeights { + shared: self.kv_share_weight, + stored: self.kv_storage_weight, + } + } + /// Create a new configuration with mode and policy pub fn new(mode: RoutingMode, policy: PolicyConfig) -> Self { Self { diff --git a/atom/mesh/src/config/validation.rs b/atom/mesh/src/config/validation.rs index 474ae26824f..874096da5d9 100644 --- a/atom/mesh/src/config/validation.rs +++ b/atom/mesh/src/config/validation.rs @@ -228,12 +228,17 @@ impl ConfigValidator { }); } - if !(0.0..=1.0).contains(&config.kv_storage_weight) { - return Err(ConfigError::InvalidValue { - field: "kv_storage_weight".to_string(), - value: config.kv_storage_weight.to_string(), - reason: "Must be between 0 and 1".to_string(), - }); + for (field, weight) in [ + ("kv_storage_weight", config.kv_storage_weight), + ("kv_share_weight", config.kv_share_weight), + ] { + if !(0.0..=1.0).contains(&weight) { + return Err(ConfigError::InvalidValue { + field: field.to_string(), + value: weight.to_string(), + reason: "Must be between 0 and 1".to_string(), + }); + } } Ok(()) @@ -474,6 +479,12 @@ mod tests { }; let error = config.validate().unwrap_err(); assert!(error.to_string().contains("kv_storage_weight"), "{error}"); + let config = RouterConfig { + kv_share_weight: weight, + ..Default::default() + }; + let error = config.validate().unwrap_err(); + assert!(error.to_string().contains("kv_share_weight"), "{error}"); } } diff --git a/atom/mesh/src/kv_events/monitor.rs b/atom/mesh/src/kv_events/monitor.rs index 91ff0309f47..97d335631f5 100644 --- a/atom/mesh/src/kv_events/monitor.rs +++ b/atom/mesh/src/kv_events/monitor.rs @@ -4,22 +4,21 @@ //! Batches the stream missed are replayed from the engine, if it serves a replay. //! Admitted batches go to the writer of the rank's index partition, which has a thread of //! its own. What each stream carried is what `/kv_events/sources` shows. A registered -//! worker without exact events is also predicted to hold the prompts routed to it. What a -//! worker's engine will report cached also counts what it loads from the store it reads, -//! if any. The ranks whose device pools are in one share group are followed as such: a -//! rank's engine will copy in what the pools of the other ranks of its group hold. +//! worker without exact events is also predicted to hold the prompts routed to it. Of each +//! worker the index tells the policies what its device cache holds and what its engine +//! will copy in from the pools of its share group. What either counts for, and the stores +//! the workers read, are the policies'. use std::{ collections::{BTreeMap, VecDeque}, fmt, sync::{ atomic::{AtomicUsize, Ordering}, - Arc, OnceLock, + Arc, }, time::{Duration, SystemTime, UNIX_EPOCH}, }; -use async_trait::async_trait; use bytes::Bytes; use dashmap::DashMap; use futures::StreamExt; @@ -41,11 +40,11 @@ use super::{ wire::{self, DecodedBatch}, }; use crate::{ - core::{Worker, WorkerType}, + core::Worker, kv_index::{ match_groups, match_lanes, Holder, Lane, Partition, Predictor, PrefixMatchProvider, }, - kv_storage::StorageSources, + kv_tiers::{TierWeights, TieredHit}, observability::metrics::schema::names, }; @@ -74,7 +73,6 @@ pub struct KvEventMonitor { /// while its partition has no lane left. predictors: DashMap>, partitions: DashMap<(String, &'static str, u32), Arc>, - stores: OnceLock<(Arc, f64)>, /// The subscriptions of ranks in a share group; below two, no rank copies from another. shared_ranks: AtomicUsize, threads: Handle, @@ -184,7 +182,6 @@ impl KvEventMonitor { subscriptions: DashMap::new(), predictors: DashMap::new(), partitions: DashMap::new(), - stores: OnceLock::new(), shared_ranks: AtomicUsize::new(0), threads: runtime.handle().clone(), runtime: Some(runtime), @@ -266,12 +263,6 @@ impl KvEventMonitor { } } - /// Counts, in what a worker's engine will report cached, what it loads from the store - /// it reads among `stores`, and in its match rate `weight` of each of those tokens. - pub fn read_stores(&self, stores: Arc, weight: f64) { - let _ = self.stores.set((stores, weight)); - } - fn partition(&self, model_id: &str, pool: &'static str, block_size: u32) -> Arc { self.partitions .entry((model_id.into(), pool, block_size)) @@ -288,10 +279,12 @@ impl KvEventMonitor { sources.sort_by(|a, b| a.worker.cmp(&b.worker)); sources } -} -#[async_trait] -impl PrefixMatchProvider for KvEventMonitor { + /// The leading tokens of `tokens` each worker's device cache holds, in the order of + /// `workers`: by its KV events when they are exact, raised to the prompts routed to it + /// when they are partial, and by those prompts alone when it has none indexed. + /// `Some(0)` for a worker that holds none of them, `None` for one the index knows + /// nothing of. The walk read-locks the shards of the partitions it reads. fn match_workers(&self, tokens: &[u32], workers: &[Arc]) -> Vec> { let (events, predicted): (Vec<_>, Vec<_>) = workers .iter() @@ -312,6 +305,33 @@ impl PrefixMatchProvider for KvEventMonitor { .unzip(); match_lanes(tokens, &events, &predicted) } +} + +impl PrefixMatchProvider for KvEventMonitor { + fn tiered_hits( + &self, + tokens: &[u32], + workers: &[Arc], + weights: &TierWeights, + ) -> Vec> { + let device = self.match_workers(tokens, workers); + // Share groups that count for nothing are left out of the walk. + let held = if weights.shared > 0.0 { + self.shared_tokens(tokens, workers, &device) + } else { + None + }; + let held = held.as_deref().unwrap_or(&device); + let hit = |(device, held): (&Option, &Option)| { + let (device, held) = ((*device)?, (*held)?); + Some(TieredHit { + device, + shared: held.saturating_sub(device), + stored: Some(0), + }) + }; + device.iter().zip(held).map(hit).collect() + } fn on_routed(&self, tokens: &[u32], worker: &dyn Worker) { let url = worker.url(); @@ -346,35 +366,6 @@ impl PrefixMatchProvider for KvEventMonitor { predict(predictor, tokens, worker); } } - - async fn cached_tokens( - &self, - tokens: &[u32], - workers: &[Arc], - device: &[Option], - ) -> Vec> { - let mut cached = device.to_vec(); - let Some((stores, _)) = self.stores.get() else { - return cached; - }; - // A decode worker takes the prompt's KV from its prefill worker. - let (readers, asked): (Vec, Vec<(&str, u32)>) = (workers.iter().zip(device)) - .enumerate() - .filter(|(_, (worker, _))| !matches!(worker.worker_type(), WorkerType::Decode)) - .filter_map(|(i, (worker, device))| Some((i, (worker.url(), (*device)?)))) - .unzip(); - for (i, found) in readers - .into_iter() - .zip(stores.cached_tokens(tokens, &asked).await) - { - cached[i] = found; - } - cached - } - - fn store_weight(&self) -> f64 { - self.stores.get().map_or(0.0, |(_, weight)| *weight) - } } impl KvEventMonitor { @@ -382,8 +373,6 @@ impl KvEventMonitor { /// `workers`, when it holds what `device` says: that, or more where its engine copies /// the prefix in from the pools of the other ranks of its share group. None where no /// worker's can, and `device` stands. - // No policy counts these tokens yet (ROCm/ATOM#3620 does), so only the tests ask. - #[allow(dead_code)] fn shared_tokens( &self, tokens: &[u32], @@ -1178,8 +1167,9 @@ mod tests { assert_eq!(monitor.match_workers(&prompt, &workers), removed); } - /// A rank's engine copies in what the other followed ranks of its share group hold, - /// block by block; not what ranks of another group, or of none, hold. + /// Where a share group's tokens count, a rank's engine copies in what the other + /// followed ranks of its group hold, block by block; not what ranks of another group, + /// or of none, hold. Where they count for nothing, the groups are left out. #[tokio::test] async fn a_rank_holds_what_its_share_group_holds() { let monitor = KvEventMonitor::start().unwrap(); @@ -1236,13 +1226,30 @@ mod tests { .collect(); let device = [Some(8), Some(0), Some(12), Some(12)]; matched(&monitor, &prompt, &workers, &device).await; + // Each rank's hit where a token copied in counts `shared`. + let hits = |shared: f64| { + let weights = TierWeights { + shared, + ..Default::default() + }; + monitor.tiered_hits(&prompt, &workers, &weights) + }; + let hit = |device, shared| { + Some(TieredHit { + device, + shared, + stored: Some(0), + }) + }; + let own = [hit(8, 0), hit(0, 0), hit(12, 0), hit(12, 0)]; + assert_eq!(hits(0.0), own); // Rank 1 copies in the 8 tokens rank 0 holds. - let held = monitor.shared_tokens(&prompt, &workers, &device); - assert_eq!(held, Some(vec![Some(8), Some(8), Some(12), Some(12)])); + let copied = [hit(8, 0), hit(0, 8), hit(12, 0), hit(12, 0)]; + assert_eq!(hits(0.9), copied); // Without another followed rank in its group, no rank copies anything in. monitor.detach(&urls[1]); assert_eq!(monitor.shared_ranks.load(Ordering::Relaxed), 2); - assert_eq!(monitor.shared_tokens(&prompt, &workers, &device), None); + assert_eq!(hits(0.9), [hit(8, 0), None, hit(12, 0), hit(12, 0)]); } /// A rank that keeps some of its blocks private shares with its group only those its @@ -1284,9 +1291,15 @@ mod tests { .into(); let (prompt, device): (Vec, _) = ((1..=10).collect(), [Some(8), Some(0)]); assert_eq!(monitor.match_workers(&prompt, &workers), device); - // Its peer copies in the 4 tokens of the block it shares. - let held = monitor.shared_tokens(&prompt, &workers, &device); - assert_eq!(held, Some(vec![Some(8), Some(4)])); + let hits = monitor.tiered_hits(&prompt, &workers, &TierWeights::default()); + let hit = |device, shared| { + Some(TieredHit { + device, + shared, + stored: Some(0), + }) + }; + assert_eq!(hits, [hit(8, 0), hit(0, 4)]); } /// A worker is predicted from its registration to its detach: in the partition of its @@ -1331,66 +1344,6 @@ mod tests { assert!(recorder.handle().render().contains(dropped)); } - /// A decode worker takes the prompt's KV from its prefill worker, and a worker whose - /// device cache the index knows nothing of is not asked for: of four readers of a - /// store, it answers for the last two, each by what its own device holds. - #[tokio::test] - async fn a_store_answers_for_its_readers_the_index_knows_but_decode_workers() { - use std::collections::HashMap; - - use axum::{extract::Query, routing::get, Json, Router}; - use serde_json::{json, Map, Value}; - - use crate::kv_storage::{keys, OffloadReport}; - - // A master's admin service that holds every key but the taint key. - let answer = |Query(query): Query>| async move { - let state = |key: &str| json!({"ok": key != keys::TAINT_KEY, "values": [{}]}); - let data: Map = (query["keys"].split(',')) - .map(|key| (key.to_string(), state(key))) - .collect(); - Json(json!({"success": true, "data": data})) - }; - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let service = Router::new().route("/batch_query_keys", get(answer)); - tokio::spawn(async move { axum::serve(listener, service).await }); - let stores = StorageSources::new(port, Duration::from_millis(500), reqwest::Client::new()); - let report = OffloadReport { - backend: "mooncake_store".into(), - masters: vec!["127.0.0.1:50051".into()], - namespace: "atomkv1-0123456789abcdef01234567".into(), - chunk_tokens: 2, - world: 1, - min_load_tokens: 4, - chain_check: keys::chain_check(2), - }; - let urls = [ - "http://d:8000", - "http://n:8000", - "http://r:8000", - "http://h:8000", - ]; - for url in urls { - stores.add(url, "model", &report); - } - let monitor = KvEventMonitor::start().unwrap(); - monitor.read_stores(Arc::new(stores), 1.0); - let decode = BasicWorkerBuilder::new(urls[0]).worker_type(WorkerType::Decode); - let workers: Vec> = vec![ - Arc::new(decode.build()), - Arc::new(BasicWorkerBuilder::new(urls[1]).build()), - Arc::new(BasicWorkerBuilder::new(urls[2]).build()), - Arc::new(BasicWorkerBuilder::new(urls[3]).build()), - ]; - // The store holds the 6 chunks of 12 tokens, of which the engine takes 10. With 8 on - // the device, the 2 more are under the 4 it loads at least. - let prompt: Vec = (0..12).collect(); - let device = [Some(0), None, Some(0), Some(8)]; - let cached = monitor.cached_tokens(&prompt, &workers, &device).await; - assert_eq!(cached, [Some(0), None, Some(10), Some(8)]); - } - #[test] fn a_message_is_a_batch_of_the_rank_or_dropped() { let payload = Bytes::from(encode(&format!("[1.0, {CLEAR}, 1]"))); diff --git a/atom/mesh/src/kv_index/mod.rs b/atom/mesh/src/kv_index/mod.rs index 287618673b5..3e2e333316a 100644 --- a/atom/mesh/src/kv_index/mod.rs +++ b/atom/mesh/src/kv_index/mod.rs @@ -15,10 +15,12 @@ mod tests; use std::{fmt::Debug, sync::Arc}; -use async_trait::async_trait; pub(crate) use partition::{match_groups, match_lanes, Holder, Lane, Partition, Predictor}; -use crate::core::Worker; +use crate::{ + core::Worker, + kv_tiers::{TierWeights, TieredHit}, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] struct PrefixHash(u64); @@ -28,35 +30,24 @@ struct PrefixHash(u64); pub(crate) struct HolderId(u8); /// What policies read of the index. -#[async_trait] pub(crate) trait PrefixMatchProvider: Send + Sync + Debug { - /// The leading tokens of `tokens` each worker's device cache holds, in the order of - /// `workers`: by its KV events when they are exact, raised to the prompts routed to it - /// when they are partial, and by those prompts alone when it has none indexed. - /// `Some(0)` for a worker that holds none of them, `None` for one the index knows - /// nothing of. The walk read-locks the shards of the partitions it reads. - fn match_workers(&self, tokens: &[u32], workers: &[Arc]) -> Vec>; + /// What the index knows of the leading tokens of `tokens` at each worker, in the order + /// of `workers`; `None` for a worker it knows nothing of. `device` is what the + /// worker's device cache holds, `Some(0)` when none of them: by its KV events when + /// they are exact, raised to the prompts routed to it when they are partial, and by + /// those prompts alone when it has none indexed. `shared` is what its engine will then + /// copy in from the pools of the other ranks of its share group: 0 where none can, + /// and where `weights` counts the tier for nothing, as the groups are then left out + /// of the walk. `stored` is not the index's to tell, and `Some(0)`. The walk + /// read-locks the shards of the partitions it reads. + fn tiered_hits( + &self, + tokens: &[u32], + workers: &[Arc], + weights: &TierWeights, + ) -> Vec>; /// Predicts that `worker` will hold `tokens`, routed to it, without waiting for the /// index's writer. fn on_routed(&self, _tokens: &[u32], _worker: &dyn Worker) {} - - /// The tokens of `tokens` each worker's engine will report cached, in the order of - /// `workers`, when its device cache holds what `device` says: that, with what it then - /// loads from a store `store_weight` counts; None where `device` is, or where that - /// store does not answer. - async fn cached_tokens( - &self, - _tokens: &[u32], - _workers: &[Arc], - device: &[Option], - ) -> Vec> { - device.to_vec() - } - - /// What a token an engine loads from a store counts for in a match rate, against one - /// its device cache holds: 0 while no store is asked. - fn store_weight(&self) -> f64 { - 0.0 - } } diff --git a/atom/mesh/src/kv_storage/mod.rs b/atom/mesh/src/kv_storage/mod.rs index d3c75b39e24..7dc93c408d8 100644 --- a/atom/mesh/src/kv_storage/mod.rs +++ b/atom/mesh/src/kv_storage/mod.rs @@ -5,8 +5,8 @@ //! those workers read (`sources`), its chunks keyed by ATOM's rule (`keys`) and asked of //! each pool master's admin service (`mooncake`). With `--kv-storage-weight`, what a //! worker's engine will load from the store it reads, looked up on the request path -//! (`lookup`), counts in `cache_aware`'s match rate and estimate. `GET /kv_storage/sources` -//! shows every source. +//! (`lookup`), counts in `cache_aware`'s match rate and estimate: the policy asks +//! `StorageSources::cached_tokens` for it. `GET /kv_storage/sources` shows every source. pub(crate) mod keys; mod lookup; diff --git a/atom/mesh/src/kv_tiers.rs b/atom/mesh/src/kv_tiers.rs new file mode 100644 index 00000000000..2eba4f70d4b --- /dev/null +++ b/atom/mesh/src/kv_tiers.rs @@ -0,0 +1,138 @@ +//! The tiers a worker's engine takes a prompt's KV from, with `--kv-events`, nearest +//! first: its device cache, the device pools of its share group, and the store it reads. +//! What the router knows of a prompt at one worker is one `TieredHit`, what a token of +//! each tier counts for is one `TierWeights`, in the policy's config, and +//! `effective_cached` is the one score of the two that the policies route by. Another +//! tier is a field of each, and its term in the score. + +/// What the router knows of a prompt's leading tokens at one worker, by the tier its +/// engine will take them from. Each tier holds the tokens past those of the tiers before +/// it, so together they are what the engine will report cached. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct TieredHit { + /// The tokens the worker's device cache holds. + pub device: u32, + /// The tokens its engine will copy in from the device pools of its share group. + pub shared: u32, + /// The tokens its engine will load from the store it reads; None when that store was + /// asked and did not answer. + pub stored: Option, +} + +impl TieredHit { + /// What the worker's device cache will hold once its engine has copied in what its + /// share group holds: what the store it reads adds to. + pub(crate) fn on_device(&self) -> u32 { + self.device + self.shared + } + + /// What the worker's engine will report cached, every tier's tokens; None when the + /// store it reads did not answer. + pub(crate) fn cached(&self) -> Option { + Some(self.on_device() + self.stored?) + } +} + +/// What a token of each tier below a worker's device cache counts for in a policy's score, +/// against one its device cache holds, which counts 1. A tier that counts 0 is not asked. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct TierWeights { + /// A token the engine will copy in from the device pools of its share group: + /// `--kv-share-weight`. + pub shared: f64, + /// A token the engine will load from the store it reads: `--kv-storage-weight`. + pub stored: f64, +} + +impl Default for TierWeights { + fn default() -> Self { + Self { + shared: 0.9, + stored: 0.0, + } + } +} + +/// What `hit` is worth in tokens on the device: each tier's tokens at what `weights` counts +/// one of them for, a store that did not answer adding none. Over the prompt's tokens, it +/// is the match rate `cache_aware` holds against `cache_threshold`. +pub(crate) fn effective_cached(hit: &TieredHit, weights: &TierWeights) -> f64 { + f64::from(hit.device) + + weights.shared * f64::from(hit.shared) + + weights.stored * f64::from(hit.stored.unwrap_or(0)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The score `cache_aware` wrote out by hand, a term a tier, before the tiers had one, + /// from what the index then answered a tier at a time: `device` tokens on the worker's + /// device, `held` there once its share group's are copied in, and `cached` once its + /// store's are loaded, None when the store does not answer. + fn hand_written( + (device, held, cached): (u32, u32, Option), + (share_weight, store_weight): (f64, f64), + ) -> f64 { + let copied = held.saturating_sub(device); + let loaded = cached.map_or(0, |cached| cached.saturating_sub(device + copied)); + f64::from(device) + share_weight * f64::from(copied) + store_weight * f64::from(loaded) + } + + #[test] + fn the_score_of_a_hit_is_the_one_cache_aware_wrote_out_by_hand() { + let hits = [ + // On the device alone, copied in, loaded, both, and nothing at all. + (60, 60, Some(60)), + (20, 80, Some(80)), + (0, 0, Some(90)), + (20, 80, Some(96)), + (0, 0, Some(0)), + // A store that does not answer. + (60, 60, None), + (20, 80, None), + // A long prompt, and a sum of weighed tokens that an f64 rounds. + (3000, 11_008, Some(16_384)), + (1, 4, Some(11)), + ]; + // The defaults of the two flags, then others, 0 and 1 included. + let weights = [ + (0.9, 0.0), + (0.9, 0.6), + (0.5, 1.0), + (0.0, 0.0), + (0.0, 0.3), + (1.0, 1.0), + (0.1, 0.7), + ]; + assert_eq!( + TierWeights::default(), + TierWeights { + shared: weights[0].0, + stored: weights[0].1 + } + ); + for (shared, stored) in weights { + let tier_weights = TierWeights { shared, stored }; + for (device, held, cached) in hits { + let hit = TieredHit { + device, + shared: held - device, + stored: cached.map(|cached| cached - held), + }; + assert_eq!((hit.on_device(), hit.cached()), (held, cached)); + // The same bits, not only the same within a rounding. + let want = hand_written((device, held, cached), (shared, stored)); + let got = effective_cached(&hit, &tier_weights); + assert_eq!(got.to_bits(), want.to_bits(), "{hit:?} at {tier_weights:?}"); + } + } + // 20 on the device, 60 copied in at 0.9 each, and 16 loaded at nothing. + let hit = TieredHit { + device: 20, + shared: 60, + stored: Some(16), + }; + assert_eq!(effective_cached(&hit, &TierWeights::default()), 74.0); + } +} diff --git a/atom/mesh/src/lib.rs b/atom/mesh/src/lib.rs index a490ec0cf68..ab5eb851680 100644 --- a/atom/mesh/src/lib.rs +++ b/atom/mesh/src/lib.rs @@ -9,6 +9,7 @@ pub mod ext_proc; pub mod kv_events; mod kv_index; pub mod kv_storage; +mod kv_tiers; pub mod middleware; pub mod observability; pub mod policies; diff --git a/atom/mesh/src/policies/cache_aware.rs b/atom/mesh/src/policies/cache_aware.rs index 2de82baf338..c93a40a5b16 100644 --- a/atom/mesh/src/policies/cache_aware.rs +++ b/atom/mesh/src/policies/cache_aware.rs @@ -58,11 +58,18 @@ Maximum characters each worker may hold in a tree. Above it, that worker's LRU leaves are evicted during the next eviction cycle. + 6. tier_weights: (two floats, 0.0 to 1.0) + With --kv-events, what a token a worker's engine takes from a tier below its + device cache counts for in the match rate held against cache_threshold: + --kv-share-weight and --kv-storage-weight. At 0 a tier is not asked. + With --kv-events, a request the router can tokenize goes to the worker whose device cache, as its KV events show, holds the largest share of its tokens, - if that share is above cache_threshold. With --kv-storage-weight above 0, a - worker's share also counts the tokens its engine will load from the Mooncake - Store it reads, at that weight each. The tree places all other requests: + if that share is above cache_threshold. A worker's share also counts the + tokens its engine will copy in from the device pools of its share group + (ATOM's umbp_pool), at --kv-share-weight each, and with --kv-storage-weight + above 0, those it will load from the Mooncake Store it reads, at that weight + each. The tree places all other requests: those at or below the threshold, those with media, those under imbalanced load, and those whose candidates have no indexed events. */ @@ -77,13 +84,14 @@ use tracing::debug; use super::{ get_healthy_worker_indices, normalize_model_key, + tiers::KvTiers, tree::{Candidates, Tree}, utils::PeriodicTask, CacheAwareConfig, LoadBalancingPolicy, RouteDecision, SelectWorkerInfo, NO_HEALTHY_WORKERS, }; use crate::{ core::{Worker, WorkerType}, - kv_index::PrefixMatchProvider, + kv_tiers::effective_cached, }; /// Prefill and decode workers hold entirely different cache state for the same @@ -121,7 +129,7 @@ pub struct CacheAwarePolicy { /// Tree keys already reported as missing, so the request-path warning /// fires once per key instead of once per request. missing_tree_warned: Arc>, - kv_events: OnceLock>, + kv_tiers: OnceLock, _eviction_task: Option, } @@ -195,14 +203,21 @@ impl CacheAwarePolicy { config, trees, missing_tree_warned: Arc::new(DashSet::new()), - kv_events: OnceLock::new(), + kv_tiers: OnceLock::new(), _eviction_task: eviction_task, } } - /// Places requests the router can tokenize by the KV event index from now on. - pub(crate) fn set_kv_events(&self, provider: Arc) { - let _ = self.kv_events.set(provider); + /// Places requests the router can tokenize by the KV tiers from now on: the KV event + /// index, and the stores the workers read. + pub(crate) fn set_kv_tiers(&self, tiers: KvTiers) { + let _ = self.kv_tiers.set(tiers); + } + + /// What the KV tiers below a worker's device cache count for in this policy's config. + #[cfg(test)] + pub(crate) fn tier_weights(&self) -> super::TierWeights { + self.config.tier_weights } /// Initialize the tree with worker URLs (used only during initial setup) @@ -337,11 +352,13 @@ impl CacheAwarePolicy { Some(min_load_idx) } - /// The tree's affinity branch, with the match rate of the KV event index: the share of - /// the request's tokens a worker's device cache holds, each token its engine will then - /// load from its store counted at `--kv-storage-weight`; the highest first, then the lower - /// load. None leaves the request to the tree: it has no tokens or has media, or no - /// candidate's match rate is above `cache_threshold`. + /// The tree's affinity branch, with the match rate of the KV tiers: the share of the + /// request's tokens a worker's device cache holds, each token its engine will then copy + /// in from its share group counted at `--kv-share-weight`, and each it will load from + /// its store at `--kv-storage-weight`, the config's `tier_weights`; the highest first, + /// then the lower load. `kv_shared` where the worker counts copies. None leaves the + /// request to the tree: it has no tokens or has media, or no candidate's match rate is + /// above `cache_threshold`. async fn select_by_kv_events( &self, workers: &[Arc], @@ -352,24 +369,17 @@ impl CacheAwarePolicy { let tokens = info .tokens .filter(|tokens| !tokens.is_empty() && !info.carries_media)?; - let provider = self.kv_events.get()?; - let hits = provider.match_workers(tokens, workers); - let weight = provider.store_weight(); - let stored = if weight > 0.0 { - Some(provider.cached_tokens(tokens, workers, &hits).await) - } else { - None - }; - let cached = |idx: usize| stored.as_ref().map_or(hits[idx], |stored| stored[idx]); + let tiers = self.kv_tiers.get()?; + let weights = &self.config.tier_weights; + let hits = tiers.tiered_hits(tokens, workers, weights).await; let score = |idx: usize| { - let device = hits[idx]?; - let loaded = cached(idx).map_or(0, |cached| cached.saturating_sub(device)); - Some(f64::from(device) + weight * f64::from(loaded)) + let hit = hits[idx]?; + Some((idx, hit, effective_cached(&hit, weights))) }; - let (idx, score) = healthy_indices + let (idx, hit, score) = healthy_indices .iter() - .filter_map(|&idx| Some((idx, score(idx)?))) - .max_by(|&(a, x), &(b, y)| { + .filter_map(|&idx| score(idx)) + .max_by(|&(a, _, x), &(b, _, y)| { let lower_load = || workers[b].load().cmp(&workers[a].load()); x.total_cmp(&y).then_with(lower_load) })?; @@ -385,11 +395,18 @@ impl CacheAwarePolicy { } self.routed(info, workers[idx].as_ref()); workers[idx].increment_processed(); - let estimate = cached(idx).map(|cached| f64::from(cached) / tokens.len() as f64); + let estimate = hit + .cached() + .map(|cached| f64::from(cached) / tokens.len() as f64); + let branch = if hit.shared > 0 { + "kv_shared" + } else { + "kv_affinity" + }; let decision = RouteDecision { match_ratio: Some(match_rate), estimated_hit_ratio: estimate, - ..RouteDecision::branch("kv_affinity") + ..RouteDecision::branch(branch) }; Some((Some(idx), decision)) } @@ -403,8 +420,8 @@ impl CacheAwarePolicy { let tokens = info .tokens .filter(|tokens| !tokens.is_empty() && !info.carries_media); - if let (Some(provider), Some(tokens)) = (self.kv_events.get(), tokens) { - provider.on_routed(tokens, worker); + if let (Some(tiers), Some(tokens)) = (self.kv_tiers.get(), tokens) { + tiers.on_routed(tokens, worker); } } } @@ -552,7 +569,7 @@ impl LoadBalancingPolicy for CacheAwarePolicy { } fn wants_tokens(&self) -> bool { - self.kv_events.get().is_some() + self.kv_tiers.get().is_some() } fn as_any(&self) -> &dyn std::any::Any { @@ -568,8 +585,17 @@ impl Default for CacheAwarePolicy { #[cfg(test)] mod tests { - use super::*; - use crate::core::{BasicWorkerBuilder, WorkerType}; + use std::sync::atomic::Ordering; + + use super::{ + super::tiers::testing::{stores, Pool}, + *, + }; + use crate::{ + core::{BasicWorkerBuilder, WorkerType}, + kv_index::PrefixMatchProvider, + kv_tiers::{TierWeights, TieredHit}, + }; #[tokio::test] async fn seeded_prefill_pool_routes_a_repeated_prefix_to_one_worker() { @@ -704,6 +730,7 @@ mod tests { balance_rel_threshold: 2.0, eviction_interval_secs: 0, // Disable eviction thread max_tree_size: 10000, + ..Default::default() }); let worker1 = BasicWorkerBuilder::new("http://w1:8000") @@ -741,6 +768,7 @@ mod tests { balance_rel_threshold: 2.0, eviction_interval_secs: 0, max_tree_size: 10000, + ..Default::default() }); let workers: Vec> = ["http://w1:8000", "http://w2:8000"] .into_iter() @@ -802,15 +830,34 @@ mod tests { ); } - /// Hits of the KV event index, by worker URL. + /// A hit of `device` tokens on the worker's device, and in no other tier. + fn device_hit(device: u32) -> TieredHit { + TieredHit { + device, + shared: 0, + stored: Some(0), + } + } + + /// The KV tiers of an index alone, as where no worker reads a store. + fn index(index: impl PrefixMatchProvider + 'static) -> KvTiers { + KvTiers::new(Arc::new(index), None) + } + + /// Device hits of the KV event index, by worker URL. #[derive(Debug)] struct Hits(Vec<(&'static str, u32)>); impl PrefixMatchProvider for Hits { - fn match_workers(&self, _tokens: &[u32], workers: &[Arc]) -> Vec> { + fn tiered_hits( + &self, + _tokens: &[u32], + workers: &[Arc], + _: &TierWeights, + ) -> Vec> { let hit = |worker: &Arc| { let found = self.0.iter().find(|(url, _)| *url == worker.url()); - found.map(|&(_, hit)| hit) + found.map(|&(_, hit)| device_hit(hit)) }; workers.iter().map(hit).collect() } @@ -830,10 +877,15 @@ mod tests { struct Routed(parking_lot::Mutex>); impl PrefixMatchProvider for Routed { - fn match_workers(&self, tokens: &[u32], workers: &[Arc]) -> Vec> { + fn tiered_hits( + &self, + tokens: &[u32], + workers: &[Arc], + _: &TierWeights, + ) -> Vec> { let routed = self.0.lock(); let held = |worker: &Arc| routed.iter().any(|url| url == worker.url()); - let held = |worker| held(worker).then_some(tokens.len() as u32); + let held = |worker| held(worker).then(|| device_hit(tokens.len() as u32)); workers.iter().map(held).collect() } @@ -856,7 +908,7 @@ mod tests { }); policy.init_workers(&workers); let routed = Arc::new(Routed::default()); - policy.set_kv_events(routed.clone()); + policy.set_kv_tiers(KvTiers::new(routed.clone(), None)); let tokens: Vec = (0..100).collect(); let info = SelectWorkerInfo { request_text: Some("hello world"), @@ -902,7 +954,7 @@ mod tests { }); policy.init_workers(&workers); if let Some(hits) = hits { - policy.set_kv_events(Arc::new(Hits(hits))); + policy.set_kv_tiers(index(Hits(hits))); } policy }; @@ -967,72 +1019,161 @@ mod tests { ); } - /// Each worker's device hit and what its engine reports cached once it loads from a - /// store (None when the store does not answer), and the weight of those loads. - #[derive(Debug)] - struct Stored(Vec<(u32, Option)>, f64); + const URLS: [&str; 2] = ["http://w1:8000", "http://w2:8000"]; - #[async_trait] - impl PrefixMatchProvider for Stored { - fn match_workers(&self, _tokens: &[u32], _: &[Arc]) -> Vec> { - self.0.iter().map(|&(device, _)| Some(device)).collect() - } - - async fn cached_tokens( - &self, - _: &[u32], - _: &[Arc], - device: &[Option], - ) -> Vec> { - assert!(self.1 > 0.0, "a store asked at weight 0"); - assert_eq!(device, self.match_workers(&[], &[])); - self.0.iter().map(|&(_, cached)| cached).collect() - } + fn two_workers() -> Vec> { + URLS.into_iter() + .map(|url| Arc::new(BasicWorkerBuilder::new(url).build()) as Arc) + .collect() + } - fn store_weight(&self) -> f64 { - self.1 - } + /// A policy that counts the tiers at `tier_weights`, over `workers`. + fn weighing(tier_weights: TierWeights, workers: &[Arc]) -> CacheAwarePolicy { + let policy = CacheAwarePolicy::with_config(CacheAwareConfig { + eviction_interval_secs: 0, + tier_weights, + ..Default::default() + }); + policy.init_workers(workers); + policy } #[tokio::test] async fn the_kv_match_rate_weighs_what_the_engine_loads_from_a_store() { - let workers: Vec> = ["http://w1:8000", "http://w2:8000"] - .into_iter() - .map(|url| Arc::new(BasicWorkerBuilder::new(url).build()) as Arc) - .collect(); + let workers = two_workers(); let tokens: Vec = (0..100).collect(); let info = SelectWorkerInfo { tokens: Some(&tokens), ..Default::default() }; - // w1's device cache holds 60 of the 100 tokens; w2's none, but its store 90. - let stored = |weight| Stored(vec![(60, Some(60)), (0, Some(90))], weight); - for (stored, want) in [ + // Both workers read a store of chunks of 10 tokens and load no fewer than 40. w1's + // device cache holds 60 of the 100 tokens and w2's none. Of the 90 the store holds, + // w2's engine will load all, and w1's none: 30 more are too few. + for (devices, held, answers, weight, want) in [ // At weight 0 the store is not asked: the device caches alone. - (stored(0.0), Some((0, 0.6, Some(0.6)))), + ([60, 0], 9, true, 0.0, Some((0, 0.6, Some(0.6)))), // A loaded token weighing 1 is worth one on the device, and 0.5 half of it. - (stored(1.0), Some((1, 0.9, Some(0.9)))), - (stored(0.5), Some((0, 0.6, Some(0.6)))), + ([60, 0], 9, true, 1.0, Some((1, 0.9, Some(0.9)))), + ([60, 0], 9, true, 0.5, Some((0, 0.6, Some(0.6)))), // A store that does not answer adds nothing, and leaves no estimate. - ( - Stored(vec![(60, None), (0, None)], 1.0), - Some((0, 0.6, None)), - ), + ([60, 0], 9, false, 1.0, Some((0, 0.6, None))), // At most cache_threshold of the prompt, the tree places it. - (Stored(vec![(30, Some(30)), (0, Some(50))], 1.0), None), + ([30, 0], 5, true, 1.0, None), ] { - let policy = CacheAwarePolicy::with_config(CacheAwareConfig { - eviction_interval_secs: 0, + let pool = Arc::new(Pool::default()); + pool.held.store(held, Ordering::Relaxed); + pool.fail.store(!answers, Ordering::Relaxed); + let stores = stores(pool.clone(), &URLS, 10, 40).await; + let weights = TierWeights { + stored: weight, ..Default::default() - }); - policy.init_workers(&workers); - policy.set_kv_events(Arc::new(stored)); + }; + let policy = weighing(weights, &workers); + let hits = Hits(URLS.into_iter().zip(devices).collect()); + policy.set_kv_tiers(KvTiers::new(Arc::new(hits), Some(stores))); let (selected, decision) = policy.select_with_decision(&workers, &info).await; let got = (decision.branch == "kv_affinity").then(|| { let match_rate = decision.match_ratio.unwrap(); (selected.unwrap(), match_rate, decision.estimated_hit_ratio) }); assert_eq!(got, want); + // The store is asked once a selection, and not at all where it counts for nothing. + let asked = pool.asked.load(Ordering::Relaxed); + assert_eq!(asked, usize::from(weight > 0.0), "at weight {weight}"); + } + } + + /// Each worker's device hit and what its device cache will hold once its engine copies + /// in from its share group. + #[derive(Debug)] + struct Shared(Vec<(u32, u32)>); + + impl PrefixMatchProvider for Shared { + fn tiered_hits( + &self, + _: &[u32], + _: &[Arc], + _: &TierWeights, + ) -> Vec> { + let hit = |&(device, held): &(u32, u32)| TieredHit { + shared: held - device, + ..device_hit(device) + }; + self.0.iter().map(hit).map(Some).collect() + } + } + + #[tokio::test] + async fn the_kv_match_rate_weighs_what_the_engine_copies_from_its_share_group() { + let workers = two_workers(); + let tokens: Vec = (0..100).collect(); + let info = SelectWorkerInfo { + tokens: Some(&tokens), + ..Default::default() + }; + // w1's device cache holds 60 of the 100 tokens; w2's 20, and its share group 80. + let shared = || Shared(vec![(60, 60), (20, 80)]); + for (shared, weight, want) in [ + // w2's 20 + 0.9 * 60 beats w1's 60, and its engine reports the copies cached. + (shared(), 0.9, Some((1, "kv_shared", 0.74, Some(0.8)))), + (shared(), 0.5, Some((0, "kv_affinity", 0.6, Some(0.6)))), + // At most cache_threshold of the prompt, the tree places it. + (Shared(vec![(10, 10), (0, 40)]), 0.9, None), + ] { + let weights = TierWeights { + shared: weight, + ..Default::default() + }; + let policy = weighing(weights, &workers); + policy.set_kv_tiers(index(shared)); + let (selected, decision) = policy.select_with_decision(&workers, &info).await; + let got = decision.branch.starts_with("kv_").then(|| { + let match_rate = decision.match_ratio.unwrap(); + let estimate = decision.estimated_hit_ratio; + (selected.unwrap(), decision.branch, match_rate, estimate) + }); + assert_eq!(got, want); + } + } + + /// A worker's tiers add up in one match rate, and its store adds to what its device + /// cache will hold once the copies are in: of the 90 tokens the store holds, w2's + /// engine, with 20 on its device and 40 to copy in, loads the 30 past those, unless + /// it loads no fewer than 40. + #[tokio::test] + async fn the_kv_match_rate_adds_up_the_tiers_a_worker_takes_the_prompt_from() { + let workers = two_workers(); + let tokens: Vec = (0..100).collect(); + let info = SelectWorkerInfo { + tokens: Some(&tokens), + ..Default::default() + }; + let weights = TierWeights { + shared: 0.9, + stored: 0.5, + }; + for (min_load_tokens, want) in [ + // 20 + 0.9 * 40 + 0.5 * 30 beats w1's 60, and the engine reports all 90 cached. + (20, (1, "kv_shared", 0.71, Some(0.9))), + // 20 + 0.9 * 40 does not. + (40, (0, "kv_affinity", 0.6, Some(0.6))), + ] { + let pool = Arc::new(Pool::default()); + pool.held.store(9, Ordering::Relaxed); + // w1 reads no store. + let stores = stores(pool, &URLS[1..], 10, min_load_tokens).await; + let policy = weighing(weights, &workers); + let shared = Shared(vec![(60, 60), (20, 60)]); + policy.set_kv_tiers(KvTiers::new(Arc::new(shared), Some(stores))); + let (selected, decision) = policy.select_with_decision(&workers, &info).await; + let (match_rate, estimate) = (decision.match_ratio, decision.estimated_hit_ratio); + let got = ( + selected.unwrap(), + decision.branch, + match_rate.unwrap(), + estimate, + ); + assert_eq!(got, want, "loading no fewer than {min_load_tokens}"); } } diff --git a/atom/mesh/src/policies/factory.rs b/atom/mesh/src/policies/factory.rs index e1f90766dba..701a7645ec4 100644 --- a/atom/mesh/src/policies/factory.rs +++ b/atom/mesh/src/policies/factory.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use super::{ CacheAwareConfig, CacheAwarePolicy, DpStickyPolicy, LoadBalancingPolicy, PowerOfTwoPolicy, - PrefixHashConfig, PrefixHashPolicy, RandomPolicy, RoundRobinPolicy, + PrefixHashConfig, PrefixHashPolicy, RandomPolicy, RoundRobinPolicy, TierWeights, }; use crate::config::PolicyConfig; @@ -14,6 +14,15 @@ pub struct PolicyFactory; impl PolicyFactory { /// Create a policy from configuration pub fn create_from_config(config: &PolicyConfig) -> Arc { + Self::create_from_config_with_tier_weights(config, TierWeights::default()) + } + + /// Create a policy from configuration for a router: a cache-aware one counts the KV + /// tiers below a worker's device cache at the router's `tier_weights` + pub fn create_from_config_with_tier_weights( + config: &PolicyConfig, + tier_weights: TierWeights, + ) -> Arc { match config { PolicyConfig::Random => Arc::new(RandomPolicy::new()), PolicyConfig::RoundRobin => Arc::new(RoundRobinPolicy::new()), @@ -28,6 +37,7 @@ impl PolicyFactory { } => { let config = CacheAwareConfig { cache_threshold: *cache_threshold, + tier_weights, balance_abs_threshold: *balance_abs_threshold, balance_rel_threshold: *balance_rel_threshold, eviction_interval_secs: *eviction_interval_secs, @@ -50,12 +60,26 @@ impl PolicyFactory { /// Create a policy by name (for dynamic loading) pub fn create_by_name(name: &str) -> Option> { + Self::create_by_name_with_tier_weights(name, TierWeights::default()) + } + + /// Create a policy by name for a router, a cache-aware one with its `tier_weights` + pub fn create_by_name_with_tier_weights( + name: &str, + tier_weights: TierWeights, + ) -> Option> { match name.to_lowercase().as_str() { "random" => Some(Arc::new(RandomPolicy::new())), "round_robin" | "roundrobin" => Some(Arc::new(RoundRobinPolicy::new())), "dp_sticky" | "dpsticky" => Some(Arc::new(DpStickyPolicy::new())), "power_of_two" | "poweroftwo" => Some(Arc::new(PowerOfTwoPolicy::new())), - "cache_aware" | "cacheaware" => Some(Arc::new(CacheAwarePolicy::new())), + "cache_aware" | "cacheaware" => { + let config = CacheAwareConfig { + tier_weights, + ..Default::default() + }; + Some(Arc::new(CacheAwarePolicy::with_config(config))) + } "prefix_hash" | "prefixhash" => Some(Arc::new(PrefixHashPolicy::with_defaults())), _ => None, } diff --git a/atom/mesh/src/policies/mod.rs b/atom/mesh/src/policies/mod.rs index 3c29ee4200d..602b0f9f360 100644 --- a/atom/mesh/src/policies/mod.rs +++ b/atom/mesh/src/policies/mod.rs @@ -17,6 +17,7 @@ mod prefix_hash; mod random; mod registry; mod round_robin; +mod tiers; pub mod tree; pub(crate) mod utils; pub use cache_aware::CacheAwarePolicy; @@ -27,8 +28,11 @@ pub use prefix_hash::{PrefixHashConfig, PrefixHashPolicy}; pub use random::RandomPolicy; pub use registry::PolicyRegistry; pub use round_robin::RoundRobinPolicy; +pub(crate) use tiers::KvTiers; pub use tree::PrefixMatchResult; +pub use crate::kv_tiers::TierWeights; + /// Branch for selections that found no healthy candidate. pub const NO_HEALTHY_WORKERS: &str = "no_healthy_workers"; @@ -146,6 +150,9 @@ pub trait LoadBalancingPolicy: Send + Sync + Debug { #[derive(Debug, Clone)] pub struct CacheAwareConfig { pub cache_threshold: f32, + /// With `--kv-events`, what a token of each tier below a worker's device cache counts + /// for in the match rate held against `cache_threshold`. + pub tier_weights: TierWeights, pub balance_abs_threshold: usize, pub balance_rel_threshold: f32, pub eviction_interval_secs: u64, @@ -156,6 +163,7 @@ impl Default for CacheAwareConfig { fn default() -> Self { Self { cache_threshold: 0.5, + tier_weights: TierWeights::default(), balance_abs_threshold: 32, balance_rel_threshold: 1.1, eviction_interval_secs: 30, diff --git a/atom/mesh/src/policies/registry.rs b/atom/mesh/src/policies/registry.rs index 164b309d0d1..0e59e201660 100644 --- a/atom/mesh/src/policies/registry.rs +++ b/atom/mesh/src/policies/registry.rs @@ -9,8 +9,11 @@ use tracing::{debug, info, warn}; /// When the first worker of a new model is added, it determines the policy for that model. /// All subsequent workers of the same model use the established policy. /// When the last worker of a model is removed, the policy mapping is cleaned up. -use super::{CacheAwarePolicy, LoadBalancingPolicy, PolicyFactory}; -use crate::{config::types::PolicyConfig, core::Worker, kv_index::PrefixMatchProvider}; +use super::{CacheAwarePolicy, KvTiers, LoadBalancingPolicy, PolicyFactory, TierWeights}; +use crate::{ + config::types::{PolicyConfig, RouterConfig}, + core::Worker, +}; /// Registry for managing model-to-policy mappings #[derive(Clone)] @@ -30,14 +33,33 @@ pub struct PolicyRegistry { /// Decode policy for PD mode (set once at startup, lock-free reads via OnceLock) decode_policy: Arc>>, - /// The KV event index, for cache-aware policies (set once at startup) - kv_events: Arc>>, + /// The KV event index and the stores the workers read, for cache-aware policies (set + /// once at startup) + kv_tiers: Arc>, + + /// What the KV tiers below a worker's device cache count for in the config of every + /// cache-aware policy the registry creates + tier_weights: TierWeights, } impl PolicyRegistry { - /// Create a new PolicyRegistry with a default policy + /// Create a new PolicyRegistry with a default policy, its cache-aware policies with + /// the default tier weights pub fn new(default_policy_config: PolicyConfig) -> Self { - let default_policy = Self::create_policy_from_config(&default_policy_config); + Self::with_tier_weights(default_policy_config, TierWeights::default()) + } + + /// The registry of a router: its default policy, and the tier weights of its + /// `kv_share_weight` and `kv_storage_weight` for every cache-aware policy it creates + pub fn for_router(config: &RouterConfig) -> Self { + Self::with_tier_weights(config.policy.clone(), config.kv_tier_weights()) + } + + fn with_tier_weights(default_policy_config: PolicyConfig, tier_weights: TierWeights) -> Self { + let default_policy = PolicyFactory::create_from_config_with_tier_weights( + &default_policy_config, + tier_weights, + ); Self { model_policies: Arc::new(DashMap::new()), @@ -45,28 +67,36 @@ impl PolicyRegistry { default_policy, prefill_policy: Arc::new(OnceLock::new()), decode_policy: Arc::new(OnceLock::new()), - kv_events: Arc::new(OnceLock::new()), + kv_tiers: Arc::new(OnceLock::new()), + tier_weights, } } + /// Create a policy from its config as the registry creates its own: a cache-aware one + /// with the registry's tier weights. The PD routers create their prefill and decode + /// policies here. + pub fn create_policy(&self, config: &PolicyConfig) -> Arc { + PolicyFactory::create_from_config_with_tier_weights(config, self.tier_weights) + } + /// Lets every cache-aware policy, the ones created later included, place requests by - /// the KV event index. - pub(crate) fn set_kv_events(&self, provider: Arc) { - let _ = self.kv_events.set(provider); + /// the KV tiers: the KV event index, and the stores the workers read. + pub(crate) fn set_kv_tiers(&self, tiers: KvTiers) { + let _ = self.kv_tiers.set(tiers); let policies = [self.prefill_policy.get(), self.decode_policy.get()]; for policy in policies.into_iter().flatten() { - self.hand_kv_events(policy); + self.hand_kv_tiers(policy); } - self.hand_kv_events(&self.default_policy); + self.hand_kv_tiers(&self.default_policy); for entry in self.model_policies.iter() { - self.hand_kv_events(entry.value()); + self.hand_kv_tiers(entry.value()); } } - fn hand_kv_events(&self, policy: &Arc) { + fn hand_kv_tiers(&self, policy: &Arc) { let cache_aware = policy.as_any().downcast_ref::(); - if let (Some(provider), Some(cache_aware)) = (self.kv_events.get(), cache_aware) { - cache_aware.set_kv_events(provider.clone()); + if let (Some(tiers), Some(cache_aware)) = (self.kv_tiers.get(), cache_aware) { + cache_aware.set_kv_tiers(tiers.clone()); } } @@ -98,7 +128,7 @@ impl PolicyRegistry { // New model - determine policy let policy = self.determine_policy_for_model(model_id, policy_hint); - self.hand_kv_events(&policy); + self.hand_kv_tiers(&policy); info!( "Assigning policy {} to new model {}", @@ -185,15 +215,11 @@ impl PolicyRegistry { /// Create a policy from a type string (delegates to PolicyFactory) fn create_policy_from_type(&self, policy_type: &str) -> Arc { - PolicyFactory::create_by_name(policy_type).unwrap_or_else(|| { - warn!("Unknown policy type '{}', using default", policy_type); - Arc::clone(&self.default_policy) - }) - } - - /// Create a policy from a PolicyConfig (delegates to PolicyFactory) - fn create_policy_from_config(config: &PolicyConfig) -> Arc { - PolicyFactory::create_from_config(config) + PolicyFactory::create_by_name_with_tier_weights(policy_type, self.tier_weights) + .unwrap_or_else(|| { + warn!("Unknown policy type '{}', using default", policy_type); + Arc::clone(&self.default_policy) + }) } /// Get current model->policy mappings (for debugging/monitoring) @@ -220,7 +246,7 @@ impl PolicyRegistry { /// Set the prefill policy for PD mode (lock-free, set once at startup) pub fn set_prefill_policy(&self, policy: Arc) { - self.hand_kv_events(&policy); + self.hand_kv_tiers(&policy); // OnceLock::set returns Err if already set, which we ignore since // the policy should only be set once at startup let _ = self.prefill_policy.set(policy); @@ -228,7 +254,7 @@ impl PolicyRegistry { /// Set the decode policy for PD mode (lock-free, set once at startup) pub fn set_decode_policy(&self, policy: Arc) { - self.hand_kv_events(&policy); + self.hand_kv_tiers(&policy); // OnceLock::set returns Err if already set, which we ignore since // the policy should only be set once at startup let _ = self.decode_policy.set(policy); @@ -600,19 +626,24 @@ mod tests { assert_eq!(policy.name(), "round_robin"); // Falls back to default } - use crate::policies::CacheAwareConfig; + use crate::{kv_index::PrefixMatchProvider, kv_tiers::TieredHit, policies::CacheAwareConfig}; #[derive(Debug)] struct NoHits; impl PrefixMatchProvider for NoHits { - fn match_workers(&self, _tokens: &[u32], workers: &[Arc]) -> Vec> { + fn tiered_hits( + &self, + _tokens: &[u32], + workers: &[Arc], + _: &TierWeights, + ) -> Vec> { vec![None; workers.len()] } } #[tokio::test] - async fn kv_events_reach_every_cache_aware_policy() { + async fn the_kv_tiers_reach_every_cache_aware_policy() { let cache_aware = || { let config = CacheAwareConfig { eviction_interval_secs: 0, @@ -628,7 +659,7 @@ mod tests { max_tree_size: 100, }); registry.set_prefill_policy(cache_aware()); - registry.set_kv_events(Arc::new(NoHits)); + registry.set_kv_tiers(KvTiers::new(Arc::new(NoHits), None)); registry.set_decode_policy(cache_aware()); let model = registry.on_worker_added("m", Some("cache_aware")); for policy in [ @@ -643,4 +674,44 @@ mod tests { .on_worker_added("n", Some("round_robin")) .wants_tokens()); } + + /// A router's tier weights are in the config of every cache-aware policy its registry + /// creates: its default policy, one a worker's `policy` label asks for by name, and + /// the ones the PD routers have it create. + #[tokio::test] + async fn a_routers_tier_weights_are_in_every_cache_aware_policy_its_registry_creates() { + let cache_aware = PolicyConfig::CacheAware { + cache_threshold: 0.5, + balance_abs_threshold: 32, + balance_rel_threshold: 1.1, + eviction_interval_secs: 0, + max_tree_size: 100, + }; + let config = RouterConfig { + policy: cache_aware.clone(), + kv_share_weight: 0.5, + kv_storage_weight: 0.25, + ..Default::default() + }; + let weights = |policy: Arc| { + let cache_aware = policy.as_any().downcast_ref::(); + cache_aware.unwrap().tier_weights() + }; + let registry = PolicyRegistry::for_router(&config); + let want = TierWeights { + shared: 0.5, + stored: 0.25, + }; + for policy in [ + registry.get_default_policy(), + registry.on_worker_added("m", Some("cache_aware")), + registry.create_policy(&cache_aware), + ] { + assert_eq!(weights(policy), want); + } + // Without a router's config, the defaults of its flags. + let registry = PolicyRegistry::new(cache_aware); + let default = registry.get_default_policy(); + assert_eq!(weights(default), TierWeights::default()); + } } diff --git a/atom/mesh/src/policies/tiers.rs b/atom/mesh/src/policies/tiers.rs new file mode 100644 index 00000000000..750bfc10645 --- /dev/null +++ b/atom/mesh/src/policies/tiers.rs @@ -0,0 +1,298 @@ +//! Where the policies read the tiers a worker's engine takes a prompt's KV from, with +//! `--kv-events`: the KV event index, for its device cache and its share group, and the +//! stores the workers read, which a policy asks itself for what its engine will load. + +use std::sync::Arc; + +use crate::{ + core::{Worker, WorkerType}, + kv_index::PrefixMatchProvider, + kv_storage::StorageSources, + kv_tiers::{TierWeights, TieredHit}, +}; + +/// The KV event index and the stores the workers read, if any. +#[derive(Debug, Clone)] +pub(crate) struct KvTiers { + index: Arc, + stores: Option>, +} + +impl KvTiers { + pub(crate) fn new( + index: Arc, + stores: Option>, + ) -> Self { + Self { index, stores } + } + + /// What each worker's engine will take the leading tokens of `tokens` from, in the + /// order of `workers`; None for a worker the index knows nothing of. A tier `weights` + /// counts for nothing is not asked, and holds no tokens: the index leaves it out of + /// its walk, and the stores are asked, once a call, only where what they hold counts. + pub(crate) async fn tiered_hits( + &self, + tokens: &[u32], + workers: &[Arc], + weights: &TierWeights, + ) -> Vec> { + let mut hits = self.index.tiered_hits(tokens, workers, weights); + if let (true, Some(stores)) = (weights.stored > 0.0, &self.stores) { + ask_stores(stores, tokens, workers, &mut hits).await; + } + hits + } + + /// Predicts that `worker` will hold `tokens`, routed to it. + pub(crate) fn on_routed(&self, tokens: &[u32], worker: &dyn Worker) { + self.index.on_routed(tokens, worker); + } +} + +/// Sets what each worker's engine will load of `tokens` from the store it reads, past what +/// its device cache will hold by `hits`: None where that store does not answer. +async fn ask_stores( + stores: &StorageSources, + tokens: &[u32], + workers: &[Arc], + hits: &mut [Option], +) { + // A decode worker takes the prompt's KV from its prefill worker. + let (readers, asked): (Vec, Vec<(&str, u32)>) = (workers.iter().zip(hits.iter())) + .enumerate() + .filter(|(_, (worker, _))| !matches!(worker.worker_type(), WorkerType::Decode)) + .filter_map(|(i, (worker, hit))| Some((i, (worker.url(), (*hit)?.on_device())))) + .unzip(); + let cached = stores.cached_tokens(tokens, &asked).await; + for ((i, (_, on_device)), cached) in readers.into_iter().zip(asked).zip(cached) { + if let Some(hit) = &mut hits[i] { + hit.stored = cached.map(|cached| cached.saturating_sub(on_device)); + } + } +} + +/// A Mooncake Store for the tests of what the policies read of it. +#[cfg(test)] +pub(crate) mod testing { + use std::{ + collections::HashMap, + sync::atomic::{AtomicBool, AtomicUsize, Ordering}, + time::Duration, + }; + + use axum::{ + extract::{Query, State}, + http::StatusCode, + response::{IntoResponse, Response}, + routing::get, + Json, Router, + }; + use serde_json::{json, Map, Value}; + + use super::*; + use crate::kv_storage::{keys, OffloadReport}; + + /// The one pool of a store: its master's admin service holds the first `held` chunks + /// of a prompt asked for in one batch, or fails, and counts the requests it gets. + #[derive(Debug, Default)] + pub(crate) struct Pool { + pub held: AtomicUsize, + pub fail: AtomicBool, + pub asked: AtomicUsize, + } + + async fn answer( + State(pool): State>, + Query(query): Query>, + ) -> Response { + pool.asked.fetch_add(1, Ordering::Relaxed); + if pool.fail.load(Ordering::Relaxed) { + return StatusCode::INTERNAL_SERVER_ERROR.into_response(); + } + let held = pool.held.load(Ordering::Relaxed); + let state = |(i, key): (usize, &str)| { + let replicas = match i < held && key != keys::TAINT_KEY { + true => json!({"ok": true, "values": [{}]}), + false => json!({"ok": false, "error": "OBJECT_NOT_FOUND"}), + }; + (key.to_string(), replicas) + }; + let data: Map = query["keys"].split(',').enumerate().map(state).collect(); + Json(json!({"success": true, "data": data})).into_response() + } + + /// The store of `pool`, read by `readers` in chunks of `chunk_tokens`, each loading no + /// fewer than `min_load_tokens`. + pub(crate) async fn stores( + pool: Arc, + readers: &[&str], + chunk_tokens: u32, + min_load_tokens: u32, + ) -> Arc { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let service = Router::new() + .route("/batch_query_keys", get(answer)) + .with_state(pool); + tokio::spawn(async move { axum::serve(listener, service).await }); + let stores = StorageSources::new(port, Duration::from_secs(10), reqwest::Client::new()); + let report = OffloadReport { + backend: "mooncake_store".into(), + masters: vec!["127.0.0.1:50051".into()], + namespace: "atomkv1-0123456789abcdef01234567".into(), + chunk_tokens, + world: 1, + min_load_tokens, + chain_check: keys::chain_check(chunk_tokens), + }; + for reader in readers { + stores.add(reader, "model", &report); + } + Arc::new(stores) + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::Ordering; + + use parking_lot::Mutex; + + use super::{ + testing::{stores, Pool}, + *, + }; + use crate::core::BasicWorkerBuilder; + + /// An index that knows each worker's tiers, and keeps the weights it is asked at. + #[derive(Debug)] + struct Index(Vec>, Mutex>); + + impl PrefixMatchProvider for Index { + fn tiered_hits( + &self, + _: &[u32], + _: &[Arc], + weights: &TierWeights, + ) -> Vec> { + self.1.lock().push(*weights); + self.0.clone() + } + } + + const URLS: [&str; 4] = [ + "http://d:8000", + "http://n:8000", + "http://r:8000", + "http://h:8000", + ]; + + /// A decode worker, one the index knows nothing of, one with nothing on its device, + /// and one whose device cache will hold 8 tokens, 4 of them copied in. + fn workers_and_hits() -> (Vec>, Vec>) { + let decode = BasicWorkerBuilder::new(URLS[0]).worker_type(WorkerType::Decode); + let workers: Vec> = vec![ + Arc::new(decode.build()), + Arc::new(BasicWorkerBuilder::new(URLS[1]).build()), + Arc::new(BasicWorkerBuilder::new(URLS[2]).build()), + Arc::new(BasicWorkerBuilder::new(URLS[3]).build()), + ]; + let hit = |device, shared| { + Some(TieredHit { + device, + shared, + stored: Some(0), + }) + }; + (workers, vec![hit(0, 0), None, hit(0, 0), hit(4, 4)]) + } + + /// A decode worker takes the prompt's KV from its prefill worker, and a worker whose + /// device cache the index knows nothing of is not asked for: of four readers of a + /// store, it answers for the last two, each by what its own device cache will hold. + #[tokio::test] + async fn a_store_answers_for_its_readers_the_index_knows_but_decode_workers() { + let (workers, hits) = workers_and_hits(); + let pool = Arc::new(Pool::default()); + // The store holds the 6 chunks of 12 tokens, of which the engine takes 10. With 8 on + // the device, the 2 more are under the 4 it loads at least. + pool.held.store(6, Ordering::Relaxed); + let stores = stores(pool.clone(), &URLS, 2, 4).await; + let tiers = KvTiers::new( + Arc::new(Index(hits.clone(), Mutex::default())), + Some(stores), + ); + let weights = TierWeights { + stored: 1.0, + ..Default::default() + }; + let prompt: Vec = (0..12).collect(); + let got = tiers.tiered_hits(&prompt, &workers, &weights).await; + let loaded = |hit: Option, stored| hit.map(|hit| TieredHit { stored, ..hit }); + let want = vec![hits[0], None, loaded(hits[2], Some(10)), hits[3]]; + assert_eq!(got, want); + let cached: Vec<_> = got + .iter() + .map(|hit| hit.and_then(|hit| hit.cached())) + .collect(); + assert_eq!(cached, [Some(0), None, Some(10), Some(8)]); + // One store, asked once for all its readers. + assert_eq!(pool.asked.load(Ordering::Relaxed), 1); + + // A store that does not answer leaves its readers' loads unknown, not the others'. + pool.fail.store(true, Ordering::Relaxed); + let got = tiers.tiered_hits(&prompt, &workers, &weights).await; + let want = vec![hits[0], None, loaded(hits[2], None), loaded(hits[3], None)]; + assert_eq!(got, want); + } + + /// At a weight of 0 a tier is not asked: no request goes to a store, and the index is + /// told which tiers count, so that it leaves the others out of its walk. + #[tokio::test] + async fn a_tier_that_counts_for_nothing_is_not_asked() { + let recorder = metrics_exporter_prometheus::PrometheusBuilder::new().build_recorder(); + let _recorder = metrics::set_default_local_recorder(&recorder); + let (workers, hits) = workers_and_hits(); + let pool = Arc::new(Pool::default()); + pool.held.store(6, Ordering::Relaxed); + let stores = stores(pool.clone(), &URLS, 2, 4).await; + let index = Arc::new(Index(hits.clone(), Mutex::default())); + let tiers = KvTiers::new(index.clone(), Some(stores)); + let prompt: Vec = (0..12).collect(); + let lookups = || { + recorder + .handle() + .render() + .contains("mesh_kv_storage_lookups_total") + }; + + let unweighed = TierWeights { + shared: 0.0, + stored: 0.0, + }; + for weights in [unweighed, TierWeights::default()] { + assert_eq!(tiers.tiered_hits(&prompt, &workers, &weights).await, hits); + } + assert_eq!(pool.asked.load(Ordering::Relaxed), 0); + assert!(!lookups()); + + let weighed = TierWeights { + shared: 0.0, + stored: 0.5, + }; + let got = tiers.tiered_hits(&prompt, &workers, &weighed).await; + assert_eq!(got[2].and_then(|hit| hit.stored), Some(10)); + assert_eq!(pool.asked.load(Ordering::Relaxed), 1); + assert!(lookups()); + // The index is asked at the policy's weights, each time. + assert_eq!( + *index.1.lock(), + [unweighed, TierWeights::default(), weighed] + ); + + // With no stores to ask, the index answers alone. + let alone = KvTiers::new(index, None); + assert_eq!(alone.tiered_hits(&prompt, &workers, &weighed).await, hits); + assert_eq!(pool.asked.load(Ordering::Relaxed), 1); + } +} diff --git a/atom/mesh/src/routers/factory.rs b/atom/mesh/src/routers/factory.rs index 7f14c74f869..093becd2354 100644 --- a/atom/mesh/src/routers/factory.rs +++ b/atom/mesh/src/routers/factory.rs @@ -12,7 +12,6 @@ use crate::{ app_context::AppContext, config::{PolicyConfig, RoutingMode}, core::ConnectionMode, - policies::PolicyFactory, routers::atom_bridge::AtomBridgeRouter, }; @@ -89,10 +88,12 @@ impl RouterFactory { main_policy_config: &PolicyConfig, ctx: &Arc, ) -> Result, String> { - let prefill_policy = - PolicyFactory::create_from_config(prefill_policy_config.unwrap_or(main_policy_config)); - let decode_policy = - PolicyFactory::create_from_config(decode_policy_config.unwrap_or(main_policy_config)); + let prefill_policy = ctx + .policy_registry + .create_policy(prefill_policy_config.unwrap_or(main_policy_config)); + let decode_policy = ctx + .policy_registry + .create_policy(decode_policy_config.unwrap_or(main_policy_config)); ctx.policy_registry.set_prefill_policy(prefill_policy); ctx.policy_registry.set_decode_policy(decode_policy); @@ -126,10 +127,12 @@ impl RouterFactory { main_policy_config: &PolicyConfig, ctx: &Arc, ) -> Result, String> { - let prefill_policy = - PolicyFactory::create_from_config(prefill_policy_config.unwrap_or(main_policy_config)); - let decode_policy = - PolicyFactory::create_from_config(decode_policy_config.unwrap_or(main_policy_config)); + let prefill_policy = ctx + .policy_registry + .create_policy(prefill_policy_config.unwrap_or(main_policy_config)); + let decode_policy = ctx + .policy_registry + .create_policy(decode_policy_config.unwrap_or(main_policy_config)); ctx.policy_registry.set_prefill_policy(prefill_policy); ctx.policy_registry.set_decode_policy(decode_policy); diff --git a/atom/mesh/tests/common/mod.rs b/atom/mesh/tests/common/mod.rs index df48de961e4..ac454c9e0ad 100644 --- a/atom/mesh/tests/common/mod.rs +++ b/atom/mesh/tests/common/mod.rs @@ -286,7 +286,7 @@ pub async fn create_test_context(config: RouterConfig) -> (Arc, Prep // Initialize registries let worker_registry = Arc::new(WorkerRegistry::new()); - let policy_registry = Arc::new(PolicyRegistry::new(config.policy.clone())); + let policy_registry = Arc::new(PolicyRegistry::for_router(&config)); // Initialize storage backends (Memory for tests) let response_storage = Arc::new(MemoryResponseStorage::new()); @@ -370,7 +370,7 @@ pub async fn create_test_context_with_parsers( // Initialize registries let tokenizer_registry = Arc::new(TokenizerRegistry::new()); let worker_registry = Arc::new(WorkerRegistry::new()); - let policy_registry = Arc::new(PolicyRegistry::new(config.policy.clone())); + let policy_registry = Arc::new(PolicyRegistry::for_router(&config)); // Initialize storage backends (Memory for tests) let response_storage = Arc::new(MemoryResponseStorage::new()); diff --git a/atom/mesh/tests/common/test_app.rs b/atom/mesh/tests/common/test_app.rs index e90410710da..58bccddca69 100644 --- a/atom/mesh/tests/common/test_app.rs +++ b/atom/mesh/tests/common/test_app.rs @@ -42,7 +42,7 @@ pub fn create_test_app( // Initialize registries let worker_registry = Arc::new(WorkerRegistry::new()); - let policy_registry = Arc::new(PolicyRegistry::new(router_config.policy.clone())); + let policy_registry = Arc::new(PolicyRegistry::for_router(router_config)); // Initialize storage backends let response_storage = Arc::new(MemoryResponseStorage::new()); @@ -159,7 +159,7 @@ pub async fn create_test_app_context() -> (Arc, PreparePoolRuntime) // Initialize registries let worker_registry = Arc::new(WorkerRegistry::new()); - let policy_registry = Arc::new(PolicyRegistry::new(router_config.policy.clone())); + let policy_registry = Arc::new(PolicyRegistry::for_router(&router_config)); // Initialize storage backends let response_storage = Arc::new(MemoryResponseStorage::new()); diff --git a/atom/mesh/tests/routing/cache_aware_backward_compat_test.rs b/atom/mesh/tests/routing/cache_aware_backward_compat_test.rs index ae73b50db6b..6b76ee114b1 100644 --- a/atom/mesh/tests/routing/cache_aware_backward_compat_test.rs +++ b/atom/mesh/tests/routing/cache_aware_backward_compat_test.rs @@ -13,6 +13,7 @@ async fn test_backward_compatibility_with_empty_model_id() { balance_rel_threshold: 1.5, eviction_interval_secs: 0, // Disable background eviction for testing max_tree_size: 100, + ..Default::default() }; let policy = CacheAwarePolicy::with_config(config); @@ -62,6 +63,7 @@ async fn test_mixed_model_ids() { balance_rel_threshold: 1.5, eviction_interval_secs: 0, max_tree_size: 100, + ..Default::default() }; let policy = CacheAwarePolicy::with_config(config); diff --git a/atom/mesh/tests/routing/test_pd_routing.rs b/atom/mesh/tests/routing/test_pd_routing.rs index ed91e7c45b6..8daf942fe7f 100644 --- a/atom/mesh/tests/routing/test_pd_routing.rs +++ b/atom/mesh/tests/routing/test_pd_routing.rs @@ -186,7 +186,7 @@ mod pd_routing_unit_tests { // Initialize registries let worker_registry = Arc::new(WorkerRegistry::new()); - let policy_registry = Arc::new(PolicyRegistry::new(config.policy.clone())); + let policy_registry = Arc::new(PolicyRegistry::for_router(&config)); // Initialize storage backends let response_storage = Arc::new(MemoryResponseStorage::new());