Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 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
7 changes: 7 additions & 0 deletions .github/benchmark/models_atomesh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1807,6 +1807,10 @@ models:
eval_concurrency: [64, 256]

- name: minimax-m3-fp4-2p1d-dpa-tp4
# Drop these two keys to restore the is_agentic_dpa dp_sticky control.
router:
prefill_policy: agentic
decode_policy: least_load
topology: 2p1d_dpa
pd_worker_layout: multi_node
nodes: "${ATOMESH_2P1D_NODES}"
Expand Down Expand Up @@ -2171,8 +2175,11 @@ models:
# Only plain Mooncake connectors; no LMCache CPU/NVMe offload pool.
- &dsv4_0813_agentic_dpa_no_offload
name: ds-v4-0813-1p1d-dpa-tp8-dspark3-agentic-no-offload-c128
# Drop prefill_policy and decode_policy to restore cache_aware on both sides.
router:
policy: cache_aware
prefill_policy: agentic
decode_policy: least_load
topology: 1p1d_dpa
display_topology: 1P1D-DPA-TP8-DSPARK3
pd_worker_layout: multi_node
Expand Down
20 changes: 19 additions & 1 deletion .github/scripts/atomesh/pd_server_atom.sh
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ PREFILL_PORT="${PREFILL_PORT:-8010}"
DECODE_PORT="${DECODE_PORT:-8020}"
ROUTER_PORT="${ROUTER_PORT:-8000}"
ROUTER_POLICY="${ROUTER_POLICY:-random}"
ROUTER_PREFILL_POLICY="${ROUTER_PREFILL_POLICY:-}"
ROUTER_DECODE_POLICY="${ROUTER_DECODE_POLICY:-}"
ATOM_PD_RANK_MAPPING_POLICY="${ATOM_PD_RANK_MAPPING_POLICY:-none}"
PROMETHEUS_PORT="${PROMETHEUS_PORT:-29100}"
HANDSHAKE_PORT="${HANDSHAKE_PORT:-6301}"
Expand Down Expand Up @@ -2178,6 +2180,14 @@ start_router() {
fi
local -a router_dp_aware_args=()
local -a router_prefill_policy_args=()
local -a explicit_policy_args=()
if [[ -n "${ROUTER_PREFILL_POLICY}" ]]; then
explicit_policy_args+=(--prefill-policy "${ROUTER_PREFILL_POLICY}")
fi
if [[ -n "${ROUTER_DECODE_POLICY}" ]]; then
explicit_policy_args+=(--decode-policy "${ROUTER_DECODE_POLICY}")
fi
if [[ ${#explicit_policy_args[@]} -eq 0 ]]; then
if is_agentic_dpa; then
# Respect explicit cache-aware routing for DPA workloads.
if [[ "${router_policy}" != "cache_aware" ]]; then
Expand All @@ -2192,8 +2202,15 @@ start_router() {
elif [[ "${#router_rank_mapping_args[@]}" -gt 0 ]]; then
router_dp_aware_args=(--dp-aware)
fi
else
# A case that names prefill_policy or decode_policy keeps that choice.
# Omitting both restores dp_sticky / cache_aware.
if is_agentic_dpa || [[ ${#router_rank_mapping_args[@]} -gt 0 ]]; then
router_dp_aware_args=(--dp-aware)
fi
fi
local -a router_policy_args=(--policy "${router_policy}")
if [[ "${router_policy}" == "cache_aware" ]]; then
if [[ ${#explicit_policy_args[@]} -eq 0 && "${router_policy}" == "cache_aware" ]]; then
# Keep the InferenceX defaults, with a case-level absolute-load override.
router_policy_args+=(
--prefill-policy cache_aware --decode-policy cache_aware
Expand All @@ -2213,6 +2230,7 @@ start_router() {
"${decode_args[@]}"
"${router_policy_args[@]}"
"${router_prefill_policy_args[@]}"
"${explicit_policy_args[@]}"
"${router_rank_mapping_args[@]}"
"${router_dp_aware_args[@]}"
--backend atom
Expand Down
2 changes: 2 additions & 0 deletions .github/scripts/atomesh/pd_submit.sh
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ exports = {
"DECODE_PORT": decode.get("port", 8020),
"ROUTER_PORT": router.get("port", 8000),
"ROUTER_POLICY": router.get("policy", "random"),
"ROUTER_PREFILL_POLICY": router.get("prefill_policy", ""),
"ROUTER_DECODE_POLICY": router.get("decode_policy", ""),
"ROUTER_BALANCE_ABS_THRESHOLD": router.get("balance_abs_threshold", ""),
"PROMETHEUS_PORT": router.get("prometheus_port", 29100),
"KV_CACHE_DTYPE": server_args.get("kv_cache_dtype", "fp8"),
Expand Down
8 changes: 8 additions & 0 deletions .github/workflows/atomesh-mocker-benchmark.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,14 @@ jobs:
--target-dir atom/mesh/mocker/target/mesh \
--profile ci --test api_tests -- kv_events_test

- name: Test agentic prefill cost
run: |
set -euo pipefail
cargo test \
--manifest-path atom/mesh/Cargo.toml \
--target-dir atom/mesh/mocker/target/mesh \
--profile ci --lib policies::agentic

# The mocker is its own cargo root: atom/mesh's profiles, ci included,
# do not apply, and its release profile is cargo's default (no fat LTO).
- name: Run Atomesh test harness
Expand Down
1 change: 1 addition & 0 deletions atom/mesh/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,7 @@ Supported tool parsers: `json`, `python`, `xml`.
| `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, 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 |
| `agentic` | Prefill and regular pools. Lowest prefill cost: queued prefill tokens, plus the prompt tokens the worker's GPU cache does not hold (from `--kv-events`, or a text tree for requests the index cannot match), plus `--agentic-request-token-equivalent` (512) per in-flight request. See [agentic routing](docs/agentic_cost.md) |

In PD mode, use `--prefill-policy` and `--decode-policy` for per-mode overrides.

Expand Down
57 changes: 57 additions & 0 deletions atom/mesh/docs/agentic_cost.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Agentic routing

`agentic` places each request on the worker (`url@rank`) with the lowest
prefill cost, so a long multi-turn prompt stays where its KV lives until that
worker's queue costs more than prefilling the prompt elsewhere:

```text
uncached_tokens = max(prompt_tokens - cached_tokens, 0)
cost = inflight_prefill_tokens + uncached_tokens
+ request_token_equivalent * inflight_requests
```

The minimum cost wins, ties at random. A hit saves only the prefill it covers,
with no extra bonus, as in the engine's `least_tokens` DP balancer.

| Input | Source |
| --- | --- |
| `prompt_tokens` | The request's tokens (`--model-path` or `--tokenizer-path`, prompts up to `--prepare-max-tokenize-bytes`); without them, its text bytes / 4. |
| `cached_tokens` | The KV event index (`--kv-events`): the leading prompt tokens each worker's GPU cache holds. A request the index cannot match (no tokens, media, or no candidate's events indexed) uses a text tree of past placements: the worker with the longest text match is credited its bytes / 4. The tree shares `--eviction-interval` and `--max-tree-size` (a per-worker cap) with `cache_aware`. |
| `inflight_prefill_tokens` | Tokens charged to the worker whose prefill has not finished, `mesh_worker_prefill_tokens{worker}`. |
| `inflight_requests` | `mesh_worker_requests_active{worker}`. |
| `request_token_equivalent` | `--agentic-request-token-equivalent` (512). Keep it equal to the engine's `ATOM_DP_LB_REQ_EQUIV`. |

The selected worker is charged its `uncached_tokens`, released when its P/D
prefill response completes or at a streaming response's first frame.
Non-streaming regular, gRPC and ext-proc single-worker requests are not
charged, so their prefills weigh only through `inflight_requests`. Under
idx2idx the planner selects decode first, so `agentic` chooses among the
prefill workers on its rank. For a request the index can match, `agentic`
predicts the selected worker's blocks (`on_routed`) and reports an estimated
hit ratio, reconciled with the cached tokens the engine reports.

## Branches

| Branch | Meaning |
| --- | --- |
| `hit`, `relocate`, `miss` | By the index: the selected worker holds the longest prefix; another worker holds a longer one but its queue outweighs the reuse; no candidate holds any. |
| `text_hit`, `text_relocate`, `text_miss` | The same, by the text tree. |
| `unmatched` | Neither tokens nor text. |

## Requirements and limits

- Prefill and regular pools only: configuration rejects `agentic` for decode,
including `--policy agentic` in P/D mode without `--decode-policy`.
- DP engines need `--dp-aware` for their KV events to be followed. Messages and
Responses requests carry `data_parallel_rank` only with the `mesh.apis` label;
otherwise the engine picks a rank and the router charges `agentic`'s choice.
- Token routing wants `--prepare-max-tokenize-bytes` around 4 MiB and
`--tokenizer-cache-enable-l1`; longer prompts use the text tree.
- Not covered: cache tiers below the GPU (Mooncake Store, LMCache), atomic
selection and charge, and a session-owner layer.

```sh
atomesh launch --pd-disaggregation --prefill http://p:8000 --decode http://d:8000 \
--model-path <model> --kv-events --prepare-max-tokenize-bytes 4194304 \
--tokenizer-cache-enable-l1 --prefill-policy agentic --decode-policy dp_sticky
```
11 changes: 9 additions & 2 deletions atom/mesh/docs/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ skipped after a failed prefill adds none.
| Metric | Type / unit | Labels | Recorded when |
| --- | --- | --- | --- |
| `mesh_route_branch_total` | Counter, decisions | `pool`, `policy`, `branch` (see [Branches](#branches)) | Every selection, including one in a pool without candidates. |
| `mesh_route_prefix_match_ratio` | Histogram, ratio 0 to 1 | `pool`, `policy` | `cache_aware` branches `affinity` and `relocate`. |
| `mesh_route_prefix_match_ratio` | Histogram, ratio 0 to 1 | `pool`, `policy` | `cache_aware` branches `affinity` and `relocate`; every `agentic` branch except `unmatched`. |
| `mesh_route_selected_worker_active_requests` | Histogram, active requests | `pool`, `policy`, `branch` | Every selection that picks a worker, before the router adds the request (see [below](#selected-workers-active-requests)). |
| `mesh_session_worker_change_total` | Counter, requests | `pool`, `reason`: `rebind`, `expired`, `rank_mapping` | A `dp_sticky` session request is sent to a different worker (URL and DP rank) than the session's previous request (see [below](#worker-changes)). |
| `mesh_selected_dp_rank_total` | Counter, dispatches | `pool`, `worker` (base URL), `dp_rank` (rank or `none`) | HTTP routers send a request, after DP rank mapping (see [below](#dp-ranks)). |
| `mesh_route_cache_tokens_total` | Counter, tokens | `pool` (`regular` or `prefill`), `kind`: `prompt`, `cached` | HTTP routers; the response reported cached tokens. Any policy (see [below](#router-estimate-and-engine-reported-cached-tokens)). |
| `mesh_route_cache_estimate_tokens_total` | Counter, tokens | `pool`, `kind`: `prompt`, `estimated`, `actual` | The same, when the policy also estimated a hit on the worker the prompt ran on; today only `cache_aware`. |
| `mesh_route_cache_estimate_tokens_total` | Counter, tokens | `pool`, `kind`: `prompt`, `estimated`, `actual` | The same, when the policy also estimated a hit on the worker the prompt ran on: `cache_aware` and `agentic`. |
| `mesh_route_cache_estimate_error_ratio` | Histogram, ratio -1 to 1 | `pool` | Same requests: (estimated - actual) / prompt tokens. |
| `mesh_kv_events_dropped_predictions_total` | Counter, prompts | `model`, `pool` | `--kv-events`: a prompt routed to a worker is left out of the KV index's predictions, as the writer of its partition is behind. The first drop in a partition also logs a warning. |
| `mesh_prefix_hash_policy_branch_total` | Counter, decisions | `branch` | `prefix_hash`, the same branches without `pool`. Deprecated by [#3141] for `mesh_route_branch_total{policy="prefix_hash"}`. |
Expand Down Expand Up @@ -109,6 +109,13 @@ Defaults are the CLI defaults.
| | `no_tokens` | The request has no tokens: no worker. | |
| `dp_sticky` | `hit`, `new`, `rebind`, `expired` | See [session affinity](#session-affinity). | |
| | `no_session` | No `x-session-id` header: the least-loaded worker. | |
| `agentic` | `hit` | The lowest [prefill cost](agentic_cost.md); the KV event index says it holds the longest prefix. | ratio, estimate |
| | `relocate` | The lowest cost, though the index says another worker holds a longer prefix: that worker's queue outweighs the reuse. | ratio, estimate when the index knows the worker |
| | `miss` | The lowest cost; by the index, no candidate holds any of the prompt. | ratio, estimate when the index knows the worker |
| | `text_hit` | The request cannot match the index (no tokens, media, or no candidate's events indexed): the lowest cost, crediting the worker holding the longest match in the text tree. | ratio, estimate |
| | `text_relocate` | The same, but another worker holds the longest text match. | ratio |
| | `text_miss` | The same; nothing in the text tree matches. | ratio |
| | `unmatched` | Neither tokens nor text: the lowest cost by load. | |

## Reading the values

Expand Down
27 changes: 15 additions & 12 deletions atom/mesh/src/app_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,18 +422,21 @@ impl AppContextBuilder {
.client
.as_ref()
.expect("client must be set before load monitor");
self.load_monitor = Some(Arc::new(LoadMonitor::new(
self.worker_registry
.as_ref()
.expect("worker_registry must be set")
.clone(),
self.policy_registry
.as_ref()
.expect("policy_registry must be set")
.clone(),
client.clone(),
config.worker_startup_check_interval_secs,
)));
self.load_monitor = Some(Arc::new(
LoadMonitor::new(
self.worker_registry
.as_ref()
.expect("worker_registry must be set")
.clone(),
self.policy_registry
.as_ref()
.expect("policy_registry must be set")
.clone(),
client.clone(),
config.load_sample_interval_secs(),
)
.with_backend(config.backend),
));
self
}

Expand Down
35 changes: 32 additions & 3 deletions atom/mesh/src/cliargs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ pub struct CliArgs {
#[arg(
long,
default_value = "cache_aware",
value_parser = ["random", "round_robin", "dp_sticky", "cache_aware", "power_of_two", "prefix_hash"],
value_parser = ["random", "round_robin", "dp_sticky", "cache_aware", "power_of_two", "prefix_hash", "agentic", "least_load"],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

least_load outside PD just degrades to in-flight load silently? either reject it in validation or carry the reservation through PlacementPlan::Single..

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Rejected in validation. least_load is PD decode only: a regular router, or a prefill policy that falls back to it, now fails config validation instead of dropping the selection reservation and keeping just the in-flight count. --decode-policy least_load with another prefill policy still passes. 6d9fb853c

help_heading = "Routing Policy"
)]
pub policy: String,
Expand Down Expand Up @@ -264,6 +264,11 @@ pub struct CliArgs {
#[arg(long, default_value_t = 1.25, help_heading = "Routing Policy")]
pub prefix_hash_load_factor: f64,

/// Tokens the agentic policy charges per in-flight request; keep it equal to
/// the engine's ATOM_DP_LB_REQ_EQUIV
#[arg(long, default_value_t = 512, help_heading = "Routing Policy")]
pub agentic_request_token_equivalent: u64,

/// Enable data parallelism aware scheduling
#[arg(long, default_value_t = false, help_heading = "Routing Policy")]
pub dp_aware: bool,
Expand All @@ -286,15 +291,15 @@ pub struct CliArgs {
/// Specific policy for prefill nodes in PD mode
#[arg(
long,
value_parser = ["random", "round_robin", "dp_sticky", "cache_aware", "power_of_two", "prefix_hash"],
value_parser = ["random", "round_robin", "dp_sticky", "cache_aware", "power_of_two", "prefix_hash", "agentic", "least_load"],
help_heading = "PD Disaggregation"
)]
pub prefill_policy: Option<String>,

/// Specific policy for decode nodes in PD mode
#[arg(
long,
value_parser = ["random", "round_robin", "dp_sticky", "cache_aware", "power_of_two", "prefix_hash"],
value_parser = ["random", "round_robin", "dp_sticky", "cache_aware", "power_of_two", "prefix_hash", "agentic", "least_load"],
help_heading = "PD Disaggregation"
)]
pub decode_policy: Option<String>,
Expand Down Expand Up @@ -556,6 +561,14 @@ impl CliArgs {
prefix_token_count: self.prefix_token_count,
load_factor: self.prefix_hash_load_factor,
},
"agentic" => PolicyConfig::Agentic {
request_token_equivalent: self.agentic_request_token_equivalent,
eviction_interval_secs: self.eviction_interval,
max_tree_size: self.max_tree_size,
},
"least_load" => PolicyConfig::LeastLoad {
request_token_equivalent: self.agentic_request_token_equivalent,
},
_ => PolicyConfig::RoundRobin,
}
}
Expand Down Expand Up @@ -869,6 +882,21 @@ mod tests {
PolicyConfig::DpSticky
));
}

#[test]
fn cli_accepts_agentic_with_its_request_weight() {
let flags = "atomesh --pd-disaggregation --prefill-policy agentic \
--agentic-request-token-equivalent 256";
let cli = Cli::try_parse_from(flags.split_whitespace());
let args = cli.expect("agentic is a prefill policy").router_args;
let expected = PolicyConfig::Agentic {
request_token_equivalent: 256,
eviction_interval_secs: 120,
max_tree_size: 67108864,
};
let parsed = args.parse_policy(args.prefill_policy.as_deref().unwrap());
assert_eq!(format!("{parsed:?}"), format!("{expected:?}"));
}
}

impl Default for CliArgs {
Expand All @@ -888,6 +916,7 @@ impl Default for CliArgs {
max_tree_size: 67_108_864,
prefix_token_count: 256,
prefix_hash_load_factor: 1.25,
agentic_request_token_equivalent: 512,
dp_aware: false,
kv_events: false,
pd_disaggregation: false,
Expand Down
Loading
Loading