diff --git a/benchmark/kv_offload/copy_bench.py b/benchmark/kv_offload/copy_bench.py index f1b9853a43..1974dbb897 100644 --- a/benchmark/kv_offload/copy_bench.py +++ b/benchmark/kv_offload/copy_bench.py @@ -26,10 +26,10 @@ import torch from mstar.engine.resources.kv import cpu_page_pool, page_copier +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import PagedKVConfig from mstar.engine.resources.kv.cpu_page_pool import PageCopies -from mstar.engine.resources.kv.manager import PageArena def sleep_cycles_per_ms() -> float: diff --git a/docs/adding_models.rst b/docs/adding_models.rst index b67d4c0932..eb6d13f8f0 100644 --- a/docs/adding_models.rst +++ b/docs/adding_models.rst @@ -490,9 +490,19 @@ the pool's ``resources:`` key. Each snapshot slot costs as much as a request slo least recently used snapshot that no request holds. Snapshots stay off without ``prefix_slots``, and also above one rank, without a named KV -cache, or when that cache's ``prefix_cache`` is off; in those three cases the pool allocates -no snapshot slots. Every cache on the node then stays shut, and the engine logs which -resource kept it shut. +cache, when that cache isn't on every node of the pool, or when its ``prefix_cache`` is +off or can't open at the pool's world size; in those cases the pool allocates no snapshot +slots. Neither does a pool whose cache the engine keeps shut for another reason, such as a +model that names no checkpoint and sets no salt. Every cache on the node of a pool without +snapshots stays shut, and the engine logs which pool kept it shut. +``opening_prefix_caches`` in ``mstar/engine/resources/kv/config.py`` is that rule over the +specs. The engine evaluates it once, before it builds any resource, and opens exactly the +caches it returns of those it holds; the conductor's routing and the API server's prompt +hashing take, for each rank, the caches the rank holds and its engine opens +(``prefix_caches_by_rank``). Each spec answers for itself: +``NodeResourceSpec.keeps_prefix_cache`` says whether the resource keeps a prefix cache of +its own, and ``restores_prefix`` marks one whose state a hit must restore (the pool, and +the resource over it), so another resource takes part through its spec alone. A model with a keyed label is checked at load time. Loading fails in two more cases: @@ -1972,6 +1982,49 @@ example, ``configs/qwen3tts.yaml`` selects FA2 under ``talker_attn``, with a message describing the migration. Move the block under ``resources:``, keyed by the resource name. +Routing across data-parallel replicas +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When a node group has several replicas, the conductor sends each new request to the +replica where it is cheapest (see "Data-parallel routing" in :doc:`serving`). A resource +whose state makes a request cheaper on one replica than another takes part through its +spec, so models declare nothing for it. + +**The hook.** ``NodeResourceSpec.routing_mirror(ctx)`` returns a ``RoutingMirror`` or +``None``, the default. The router asks once per set of node groups with replicas that +holds one of the spec's nodes, and ``ctx`` (a ``RoutingContext``) gives the replica count, +the walks of the worker graphs there that hold the spec's nodes, the resource's keyed +labels with the walks that key each (empty for a resource that is not a KV cache), and +whether every replica's engine opens its prefix cache, which the router derives with +``prefix_caches_by_rank``. +A mirror is conductor-side bookkeeping that follows the resource's own rules as far as +the conductor's inputs allow. The module that defines one must stay free of kernels, +since the conductor builds it. + +**The mirror's methods.** Each is given the request's ``ResourceReqConfig`` for the +resource, which the conductor builds and validates before the pick. + +- ``facts(config)`` reports the request's ``RoutingFacts`` on each replica: named counts, + such as ``work`` (prompt positions) and ``kv_hit`` (of those, the ones predicted cached). + The router adds every mirror's row on a replica field by field, then prices the sum + once with ``routing_cost`` in ``mstar/conductor/routing.py``, one term per + ``routing_weights`` key, each 0 when its facts are absent. +- ``add_request(config, replica)`` records the placement once the request is dispatched, + and returns a handle. +- ``remove_request(handle, ran)`` releases it when the request leaves. ``ran`` says + whether a pass came back for one of the request's partitions with a walk on the + resource's node groups. + +**Adding a resource.** A new resource adds its fields to ``RoutingFacts``, its mirror, +and its term to ``routing_cost`` and ``RoutingWeights``. ``ReplicaRouter`` changes only +if its fields are not counts that add, or if its mirror reads a model declaration other +than the KV ones, which then becomes a ``RoutingContext`` field that ``ReplicaRouter`` +fills. ``KVSpec`` with a ``PagedKVConfig`` is the one implementation. Its mirror runs the +worker's own ``PrefixIndex`` and ``PageArena`` per replica, with no storage, takes each +request's lease, pages and index entries at dispatch, an item's end inside a page among +them, and exists only where a walk keying the cache runs and ``opening_prefix_caches`` +says the workers open it. + Preprocessing threads ~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/metrics.rst b/docs/metrics.rst index 4d91481f26..c1a3dcce14 100644 --- a/docs/metrics.rst +++ b/docs/metrics.rst @@ -232,6 +232,14 @@ From the conductor's status message, sent every second while metrics are on. conductor dispatched and has not heard back from. The conductor sees whole passes, so a node running a request's decode loop counts it once for the loop. +``mstar_routing_predicted_saving_total{model_name, term}`` + Counter, up to a second old. Per term of the data-parallel replica cost (see + "Data-parallel routing" in :doc:`serving`), the saving predicted on the replica each + request was sent to, in request-equivalents, unweighted. For ``prefix``, each request + adds the share of its prompt predicted cached there, so its rate over the request rate + is a mean of per-request shares, not the token ratio the workers' prefix-cache counters + give. + ``mstar_conductor_status_age_seconds{model_name}`` Gauge, seconds, computed at scrape time. Time since the API server received the conductor's last status message, or since metrics were enabled if none arrived yet. diff --git a/docs/serving.rst b/docs/serving.rst index 3ea4e8d64b..be13f258a8 100644 --- a/docs/serving.rst +++ b/docs/serving.rst @@ -248,6 +248,16 @@ A config maps the model's computation-graph nodes to physical GPU ranks. The key - *(optional)* How many requests run at once. Requests past the cap wait in the conductor's queue, except a live call (open client input), which is refused with a 503. + * - ``routing_weights`` + - *(optional)* The weights of the data-parallel replica pick (see below), one per + term: ``load`` for the live requests on a replica, and ``prefix`` for the share of + the prompt predicted in its KV prefix cache. Each is a number from 0 to 1e6; ``load`` + defaults to 1.0 and ``prefix`` to 8.0. Any other key, or ``load: 0`` while another + weight is above 0, fails loading. ``prefix: 0`` picks by load alone, and ``prefix: 1`` + or less keeps a hit below one live request, so it only breaks ties. At data + parallelism, warmup copies run with ``prefix_cache=False``, so + they still spread but do not warm the prefill that starts from cached pages; a + warmup spec that sets ``prefix_cache`` keeps its own value. * - ``gpu_memory_fraction`` - *(optional)* The share of its GPU each worker may hold once CUDA-graph capture is done, for workers that share a GPU (see below). Unset, capture plans against @@ -408,6 +418,37 @@ copied to the host once no request holds it, and a later request whose prefix th evicted copies it back from there. So the host pool should hold more pages than the device's prefix cache. +**Data-parallel routing.** A node group whose ``ranks`` hold several lockstep instances +(``tp_size * sp_size`` ranks each, or one rank) runs each request on one of them, its +replica. The conductor picks it per request, at ingest, as the replica with the lowest +cost: ``routing_weights.load`` times the live requests on the replica (counted per set of +groups that pick together, for each request with a partition on them that is not done at +ingest), plus the price of what the conductor predicts about the request there. Ties go +at random. Every term is in request-equivalents. Groups whose replicas sit on the same +ranks, replica for replica, take one pick together. + +Today the one prediction is the KV prefix cache's, on the replicas that run any walk a +KV label keys the cache on (``kv_labels``): ``routing_weights.prefix`` +times minus the share of the request's prompt positions (every label's, keyed or not) +the replica's caches are predicted to hold, all the caches on the replica together. At +the default weights a prompt held whole is worth up to 8 live requests: a request +follows its prefix to a busier replica, and a hot prefix spreads once its replica runs +about 8 times its hit share more requests than another. The term is a share rather than +a token count so that one weight fits models whose prefill and decode costs differ. + +The prediction runs the worker's own prefix index and page ownership (``PrefixIndex``, +``PageArena``) per replica, with no storage, and takes a request's steps at dispatch: its +lease of the matched pages, its own pages, evicting on a shortfall, the index entries of +its whole pages, and the page of an image or other item that ends inside one, cached up +to the item's end. Its end releases its pages; a request that ends before a pass of it +comes back (aborted while queued, say) also takes back the entries only it made. Workers send +nothing for it, so it does not see admit timing, decode growth, preemption or a reply's +tokens, and it is approximate: a wrong prediction makes a request slower, never wrong. +With no cache that opens (one replica, ``prefix_cache: false``, no walk that keys it, +replicas above one rank, where the cache stays off: ``prefix_cache_tp`` on a pool with +replicas fails at startup, or a keyed node whose recurrent state pool keeps no snapshots, +``prefix_slots: 0``) the pick is the replica with the fewest live requests. + **Single GPU.** Everything on rank 0: .. code-block:: yaml @@ -765,6 +806,10 @@ second old: ``node_names`` of the config's ``node_groups``), running requests with a pass on that node that the conductor dispatched and has not heard back from. The conductor sees whole passes, so a node running a request's decode loop counts it once for the loop. +- ``mstar_routing_predicted_saving_total{model_name, term}``: counter, per term of the + data-parallel replica cost, the saving predicted on the replica each request went to, + in request-equivalents. For ``prefix``, each request adds the share of its prompt + predicted cached there. - ``mstar_conductor_status_age_seconds{model_name}``: seconds since the API server received the last status message, or since metrics were enabled before the first one. More than a few seconds means the conductor stopped reporting. diff --git a/examples/observability/grafana/dashboards/mstar.json b/examples/observability/grafana/dashboards/mstar.json index 9e86ee736d..7ae4425edd 100644 --- a/examples/observability/grafana/dashboards/mstar.json +++ b/examples/observability/grafana/dashboards/mstar.json @@ -2040,13 +2040,71 @@ } ] }, + { + "id": 46, + "type": "timeseries", + "title": "Predicted routing saving", + "description": "Per term of the replica cost, the saving the data-parallel replica pick predicted on the replica each request went to, in request-equivalents per second (for prefix, the predicted share of each prompt cached there). Empty unless a node group has replicas and a resource mirror.", + "datasource": { + "type": "prometheus", + "uid": "prom" + }, + "gridPos": { + "x": 0, + "y": 108, + "w": 12, + "h": 8 + }, + "fieldConfig": { + "defaults": { + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "stacking": { + "mode": "none", + "group": "A" + }, + "showPoints": "never", + "spanNulls": true + }, + "color": { + "mode": "palette-classic" + }, + "unit": "short" + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "calcs": [] + }, + "tooltip": { + "mode": "multi", + "sort": "none" + } + }, + "targets": [ + { + "refId": "A", + "datasource": { + "type": "prometheus", + "uid": "prom" + }, + "expr": "sum by (term) (rate(mstar_routing_predicted_saving_total{model_name=~\"$model\"}[1m]))", + "legendFormat": "{{term}}", + "range": true + } + ] + }, { "type": "row", "title": "Engine workers", "collapsed": false, "gridPos": { "x": 0, - "y": 108, + "y": 116, "w": 24, "h": 1 }, @@ -2063,7 +2121,7 @@ }, "gridPos": { "x": 0, - "y": 109, + "y": 117, "w": 12, "h": 8 }, @@ -2151,7 +2209,7 @@ }, "gridPos": { "x": 12, - "y": 109, + "y": 117, "w": 12, "h": 8 }, @@ -2219,7 +2277,7 @@ }, "gridPos": { "x": 0, - "y": 117, + "y": 125, "w": 12, "h": 8 }, @@ -2277,7 +2335,7 @@ }, "gridPos": { "x": 12, - "y": 117, + "y": 125, "w": 12, "h": 8 }, @@ -2358,7 +2416,7 @@ }, "gridPos": { "x": 0, - "y": 125, + "y": 133, "w": 12, "h": 8 }, @@ -2453,7 +2511,7 @@ }, "gridPos": { "x": 12, - "y": 125, + "y": 133, "w": 12, "h": 8 }, @@ -2507,7 +2565,7 @@ "collapsed": false, "gridPos": { "x": 0, - "y": 133, + "y": 141, "w": 24, "h": 1 }, @@ -2524,7 +2582,7 @@ }, "gridPos": { "x": 0, - "y": 134, + "y": 142, "w": 12, "h": 8 }, @@ -2582,7 +2640,7 @@ }, "gridPos": { "x": 12, - "y": 134, + "y": 142, "w": 12, "h": 8 }, @@ -2650,7 +2708,7 @@ }, "gridPos": { "x": 0, - "y": 142, + "y": 150, "w": 12, "h": 8 }, @@ -2722,7 +2780,7 @@ }, "gridPos": { "x": 12, - "y": 142, + "y": 150, "w": 12, "h": 8 }, @@ -2790,7 +2848,7 @@ "collapsed": false, "gridPos": { "x": 0, - "y": 150, + "y": 158, "w": 24, "h": 1 }, @@ -2808,7 +2866,7 @@ }, "gridPos": { "x": 0, - "y": 151, + "y": 159, "w": 12, "h": 8 }, @@ -2987,7 +3045,7 @@ }, "gridPos": { "x": 12, - "y": 151, + "y": 159, "w": 12, "h": 8 }, @@ -3043,7 +3101,7 @@ }, "gridPos": { "x": 0, - "y": 159, + "y": 167, "w": 24, "h": 8 }, diff --git a/mstar/api_server/data_worker.py b/mstar/api_server/data_worker.py index 9a0a36b260..7f649a2850 100644 --- a/mstar/api_server/data_worker.py +++ b/mstar/api_server/data_worker.py @@ -43,10 +43,10 @@ NameToTensorList, create_tensor_communication_manager, ) -from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig +from mstar.engine.resources.kv.config import KVSpec, prefix_caches_by_rank from mstar.engine.resources.kv.keys import PageItem, chain, end_key, fingerprint, page_items from mstar.engine.resources.spec import apply_yaml_overrides -from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels +from mstar.model.base import ClientChunk, Model, PrefixKeys, ProcessPromptOutput, Span, keyed_labels, names_checkpoint from mstar.model.media_limits import ( RequestMediaBudget, charge_decoded_audio, @@ -109,6 +109,12 @@ def _file_state(path: str) -> tuple[int, int, int]: return stat.st_ino, stat.st_size, stat.st_mtime_ns +def _prefix_cache(model_kwargs: dict) -> bool: + """A client's prefix_cache: unset or None is on, otherwise its truth.""" + value = model_kwargs.get("prefix_cache") + return value is None or bool(value) + + class _FileChangedError(Exception): """A file was rewritten between its load and its hash.""" @@ -189,13 +195,18 @@ def _preprocess_loop(**kwargs): def _kv_page_sizes(model: Model, model_config: dict) -> dict[str, int]: - """Page size per KV resource whose prefix cache is on, after this deployment's YAML has been applied.""" + """Page size per KV resource whose prefix cache some rank's engine opens, after this deployment's + YAML has been applied.""" specs = model.get_node_resources() apply_yaml_overrides(specs, model_config) + groups = [ + (group["ranks"], int(group.get("tp_size", 1)) * int(group.get("sp_size", 1)), group["node_names"]) + for group in model_config.get("node_groups") or [] + ] + opened = frozenset().union(*prefix_caches_by_rank(specs, groups, names_checkpoint(model)).values()) return { - spec.resource_key: spec.config.tokens_per_page - for spec in specs - if isinstance(spec, KVSpec) and isinstance(spec.config, PagedKVConfig) and spec.config.prefix_cache + spec.resource_key: spec.config.tokens_per_page for spec in specs + if isinstance(spec, KVSpec) and spec.resource_key in opened } @@ -813,7 +824,7 @@ def _process_input( model_kwargs["kv_layout"] = rows # after the update: the chain keys the tensors the request will # actually be prefilled with - if model_kwargs.get("prefix_cache") is not False: + if _prefix_cache(model_kwargs): model_kwargs.update(self._prefix_keys( tensors, layouts, rows, input.file_paths, file_states, )) diff --git a/mstar/api_server/entrypoint.py b/mstar/api_server/entrypoint.py index 330a56d9db..65f2103a4c 100644 --- a/mstar/api_server/entrypoint.py +++ b/mstar/api_server/entrypoint.py @@ -17,7 +17,7 @@ import time import uuid from collections.abc import Callable, Collection, Iterable -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from functools import cached_property from pathlib import Path from typing import Any, NamedTuple, Optional, Protocol @@ -1894,7 +1894,10 @@ def _run_warmup_requests( concurrent requests to different replicas (the least-loaded one each). When some worker graph has fewer replicas than that, each spec first runs once alone, since that graph would batch the copies and miss its - one-request shape. + one-request shape. Past one copy, they run with ``prefix_cache=False`` + unless the spec sets it, so no predicted hit (``routing_weights.prefix``) + gathers them on one replica; the cost is that they leave a prefill from + cached pages unwarmed. """ if not isinstance(specs, list): logger.warning("warmup_requests must be a list; ignoring %r", type(specs).__name__) @@ -1933,6 +1936,8 @@ async def _all(request: WarmupRequest, base_id: str, n: int) -> None: "warmup request %d/%d (%s) done in %.1f s alone", index + 1, len(specs), ",".join(request.output_modalities), time.perf_counter() - t0, ) + if replicas.most > 1: + request = replace(request, model_kwargs={"prefix_cache": False, **(request.model_kwargs or {})}) t0 = time.perf_counter() try: asyncio.run(_all(request, f"warmup-{index}", replicas.most)) diff --git a/mstar/conductor/conductor.py b/mstar/conductor/conductor.py index a7ac0603c7..e88fabdb4f 100644 --- a/mstar/conductor/conductor.py +++ b/mstar/conductor/conductor.py @@ -6,10 +6,9 @@ import signal import socket import time -from collections import Counter, defaultdict, deque +from collections import defaultdict, deque from dataclasses import dataclass, field, replace -import numpy as np import torch import yaml @@ -29,6 +28,7 @@ StreamingConnectionState, merge_publish_info, ) +from mstar.conductor.routing import ReplicaRouter, RoutingHandle from mstar.conductor.workers import accelerator_type, deployment_workers from mstar.distributed.base import ShardingConfig from mstar.distributed.communication import GlobalParallelConfig, WorkerParallelGroups @@ -328,9 +328,8 @@ class RequestData: # resource label -> the config this request's resources were opened with resource_configs: dict[str, ResourceReqConfig] sharding_config: ShardingConfig | None = None - # node group id -> the DP replica it runs on; counted in the conductor's - # replica load while the request is live - dp_replicas: dict[int, int] = field(default_factory=dict) + # what the replica pick recorded for the request; released in _drop_request + routing: RoutingHandle | None = None # set once a NewRequest goes out; before that a failed ingest has nothing to drain dispatched: bool = False # set once request_complete goes out; after that the client must never get @@ -434,9 +433,6 @@ def __init__( status_interval_s: float | None = None, ): self.requests: dict[str, RequestData] = {} - # (node group id, DP replica index) -> requests in self.requests it - # serves, for the replica pick; kept by _register_request / _drop_request - self._replica_load: Counter[tuple[int, int]] = Counter() # Requests in teardown: kept in self.requests (so they still count toward # concurrency until their GPU state is freed) with barrier state here. self.draining: dict[str, DrainingRequest] = {} @@ -600,6 +596,10 @@ def __init__( wg_id: tuple(wg.section.get_nodes()) for wg_id, wg in self.worker_graphs.items() } self._components = sorted({n for nodes in self._wg_nodes.values() for n in nodes}) + self._router = ReplicaRouter( + model, self.worker_graphs.values(), specs=self._node_resources(), + weights=self.model_config.get("routing_weights"), + ) self._requests_gauge = Gauge(catalog.CONDUCTOR_REQUESTS) self._in_flight_gauge = Gauge(catalog.COMPONENT_IN_FLIGHT) # worker id -> its latest WorkerStatus snapshots (cumulative) @@ -946,29 +946,10 @@ def _fail_all_requests(self, error_message: str, status: int = 503) -> None: ), ) - def _pick_replicas(self) -> dict[int, int]: - """A new request's DP replica in each node group: the one serving the - fewest live requests, ties at random. A random pick alone puts two of - two concurrent requests on one replica half the time, leaving the other - idle. Load is counted per (group, replica), so groups that share - workers don't skew each other's picks.""" - replicas: dict[int, int] = {} - for wg in self.worker_graphs.values(): - if wg._group_id in replicas: - continue - n = len(wg.replica_ranks) - if n == 1: - replicas[wg._group_id] = 0 - continue - loads = [self._replica_load[(wg._group_id, i)] for i in range(n)] - least = min(loads) - replicas[wg._group_id] = int(np.random.choice([i for i, k in enumerate(loads) if k == least])) - return replicas - def _assign_worker_graphs_to_workers(self, replicas: dict[int, int]) -> dict[int, list[str]]: """ For a request, assign worker graphs to the workers of their group's - replica in ``replicas`` (``_pick_replicas``). DP picks are coordinated + replica in ``replicas`` (``ReplicaRouter.pick``). DP picks are coordinated by ``_group_id`` so all wgs derived from the same node_group land on the same (replica's) workers — without this, two wgs sharing a TP group could end up on different DP replicas and break model topology. @@ -1263,9 +1244,6 @@ def _do_ingest_request( None if self._status_interval_s is None else self._queued_since.pop(body.request_id, ingest_time) ) - dp_replicas = self._pick_replicas() - worker_graph_to_workers = self._assign_worker_graphs_to_workers(dp_replicas) - model_kwargs = body.model_kwargs or {} max_output_tokens = self._max_output_tokens(model_kwargs) loop_caps = self._loop_caps(model_kwargs) @@ -1293,44 +1271,6 @@ def _do_ingest_request( random_seed=seed, ) - # Build per-connection streaming state. None for a client stream: the - # data worker sends and ends it itself. - streaming_connections: dict[tuple[str, str, str], StreamingConnectionState] = {} - for conn in topology.connections: - if conn.from_partition == CLIENT: - continue - # a tuple: names may hold ":" or "->" ("C:x" + "y" vs "C" + "x:y") - key = (conn.from_partition, conn.to_partition, conn.edge_name) - streaming_connections[key] = StreamingConnectionState( - from_partition=conn.from_partition, - to_partition=conn.to_partition, - edge_name=conn.edge_name, - ) - - # Collect all worker_graph_ids per worker for the NewRequest - worker_to_worker_graph_ids: dict[str, list[int]] = defaultdict(list) - for wg_id, worker_ids in worker_graph_to_workers.items(): - for worker_id in worker_ids: - worker_to_worker_graph_ids[worker_id].append(wg_id) - - request_data = RequestData( - persist_signals=body.initial_signals, - persist_signal_ref_cnt={}, - worker_graph_to_workers=worker_graph_to_workers, - all_worker_graph_ids=set(worker_graph_to_workers.keys()), - max_output_tokens=max_output_tokens, - random_seed=seed, - partition_states=partition_states, - partition_definitions=partition_definitions, - streaming_connections=streaming_connections, - resource_configs={}, - sharding_config=self._build_request_sharding_config(worker_graph_to_workers), - dp_replicas=dp_replicas, - conductor_ingest_time=ingest_time, - conductor_arrival_time=arrival_time, - ) - self._register_request(body.request_id, request_data) - # Kick off all partitions by calling get_initial_forward_pass_args per partition partition_fwd_args: dict[str, ForwardPassArgs] = {} for p in partitions: @@ -1347,14 +1287,12 @@ def _do_ingest_request( pstate.metadata = fwd_args.full_metadata pstate.metadata.kwargs.update(fwd_args.step_metadata) - self._set_partition_worker_graph_ids( - body.request_id, p.name, fwd_args.full_metadata.graph_walk, - ) partition_fwd_args[p.name] = fwd_args # after the initial fwd args: the configs are derived from them (BAGEL - # reads `requires_cfg` off the metadata the model just settled) - request_data.resource_configs = self._get_resource_configs( + # reads `requires_cfg` off the metadata the model just settled), and + # before the replica pick, which scores the request from them + resource_configs = self._get_resource_configs( model_kwargs, partition_fwd_args ) # keyed by resource, so each config is handed only its own chain @@ -1366,8 +1304,8 @@ def _do_ingest_request( if not all(partition_states[name].is_done for name in self._streamed_partitions()): prefix_cache = False kv_layout = kwargs.get("kv_layout") or {} - refuse_undeclared_labels(type(self.model).__name__, self._kv_labels, kv_layout, request_data.resource_configs) - for key, cfg in request_data.resource_configs.items(): + refuse_undeclared_labels(type(self.model).__name__, self._kv_labels, kv_layout, resource_configs) + for key, cfg in resource_configs.items(): cfg.apply_conductor_config( seed=seed, resource_key=key, @@ -1379,15 +1317,68 @@ def _do_ingest_request( loop_caps=loop_caps, ) if not any(model_kwargs.get(key) is not None for key in self.model.LENGTH_KWARGS): - request_data.max_output_tokens, loop_caps = self._fit_loop_caps( - model_kwargs, request_data.resource_configs, max_output_tokens, + max_output_tokens, loop_caps = self._fit_loop_caps( + model_kwargs, resource_configs, max_output_tokens, ) - for key, cfg in request_data.resource_configs.items(): + for key, cfg in resource_configs.items(): cfg.apply_conductor_config(seed=seed, resource_key=key, loop_caps=loop_caps) for specs in self._resource_specs(): - for key, cfg in request_data.resource_configs.items(): + for key, cfg in resource_configs.items(): cfg.validate(specs.get(key)) + # a partition done from the start runs none of its nodes, so it adds no + # load to their replicas + groups_run = self._router.groups_run( + name for name, fwd_args in partition_fwd_args.items() if not fwd_args.request_done + ) + placement = self._router.pick(resource_configs, groups_run) + worker_graph_to_workers = self._assign_worker_graphs_to_workers(placement.replicas) + + # Build per-connection streaming state. None for a client stream: the + # data worker sends and ends it itself. + streaming_connections: dict[tuple[str, str, str], StreamingConnectionState] = {} + for conn in topology.connections: + if conn.from_partition == CLIENT: + continue + # a tuple: names may hold ":" or "->" ("C:x" + "y" vs "C" + "x:y") + key = (conn.from_partition, conn.to_partition, conn.edge_name) + streaming_connections[key] = StreamingConnectionState( + from_partition=conn.from_partition, + to_partition=conn.to_partition, + edge_name=conn.edge_name, + ) + + # Collect all worker_graph_ids per worker for the NewRequest + worker_to_worker_graph_ids: dict[str, list[int]] = defaultdict(list) + for wg_id, worker_ids in worker_graph_to_workers.items(): + for worker_id in worker_ids: + worker_to_worker_graph_ids[worker_id].append(wg_id) + + request_data = RequestData( + persist_signals=body.initial_signals, + persist_signal_ref_cnt={}, + worker_graph_to_workers=worker_graph_to_workers, + all_worker_graph_ids=set(worker_graph_to_workers.keys()), + max_output_tokens=max_output_tokens, + random_seed=seed, + partition_states=partition_states, + partition_definitions=partition_definitions, + streaming_connections=streaming_connections, + resource_configs=resource_configs, + sharding_config=self._build_request_sharding_config(worker_graph_to_workers), + conductor_ingest_time=ingest_time, + conductor_arrival_time=arrival_time, + ) + self._register_request(body.request_id, request_data) + + for p in partitions: + self._set_partition_worker_graph_ids( + body.request_id, p.name, partition_fwd_args[p.name].full_metadata.graph_walk, + ) + + # only now: a request refused before this leaves nothing in the mirrors + request_data.routing = self._router.add(placement, resource_configs, groups_run) + # Send NewRequest to each worker with the appropriate partition's inputs request_data.dispatched = True for worker_id, worker_graph_ids in worker_to_worker_graph_ids.items(): @@ -1491,13 +1482,14 @@ def _request_workers(self, request_data: RequestData) -> set[str]: def _register_request(self, request_id: str, request_data: RequestData) -> None: self.requests[request_id] = request_data - self._replica_load.update(request_data.dp_replicas.items()) def _drop_request(self, request_id: str) -> None: - """The one way a request leaves ``self.requests``, so ``_replica_load`` cannot leak.""" + """The one way a request leaves ``self.requests``, so what the replica pick recorded cannot leak.""" request_data = self.requests.pop(request_id, None) - if request_data is not None: - self._replica_load.subtract(request_data.dp_replicas.items()) + if request_data is not None and request_data.routing is not None: + self._router.remove(request_data.routing, [ + name for name, pstate in request_data.partition_states.items() if pstate.fwd_pass_number + ]) def _register_draining( self, request_id: str, expected_acks: set[str], participants: set[str], @@ -2224,7 +2216,7 @@ def _status(self) -> ConductorStatus: for snap in snapshots: by_family.setdefault(snap.name, []).append(snap) return ConductorStatus(metrics=[ - states.snapshot(), self._in_flight_gauge.snapshot(), + states.snapshot(), self._in_flight_gauge.snapshot(), self._router.predicted_saving.snapshot(), *(merge(family, by_family.get(name, ())) for name, family in catalog.WORKER_FAMILIES.items()), ]) diff --git a/mstar/conductor/routing.py b/mstar/conductor/routing.py new file mode 100644 index 0000000000..88fbe5ed4a --- /dev/null +++ b/mstar/conductor/routing.py @@ -0,0 +1,232 @@ +"""Choosing a new request's data-parallel replica in each node group. + +A replica is one lockstep instance of a group: its ``tp_size * sp_size`` ranks, +or one rank. A replica's cost for the request is ``routing_weights.load`` times +its live requests, plus ``routing_cost`` of the facts the mirrors predict for +the request there: + +- the live requests are counted per set of groups that pick together, so + groups on other ranks that share a worker don't skew each other's picks, and + only for a request one of whose partitions, not done at ingest, has a walk on + the set; +- a resource whose spec offers a mirror for the set + (``NodeResourceSpec.routing_mirror``) reports ``RoutingFacts``, a row per + replica, such as a paged KV cache's predicted prefix hit. The rows of every + mirror on the set add up before they are priced. + +Every cost is in request-equivalents. The cheapest replica wins, ties at +random. Groups whose replicas sit on the same ranks, replica for replica, pick +one index together, so a request's walks stay on one set of workers. A +prediction never changes outputs: a wrong one makes a request slower. +""" + +import logging +import random +from collections import Counter +from collections.abc import Iterable, Mapping +from typing import Any, NamedTuple + +from mstar.engine.resources.kv.config import prefix_caches_by_rank +from mstar.engine.resources.spec import ( + NodeResourceSpec, + ResourceReqConfig, + RoutingContext, + RoutingFacts, + RoutingMirror, +) +from mstar.model.base import Model, keyed_labels, names_checkpoint +from mstar.observability import catalog +from mstar.observability.recorders import Counter as MetricCounter + +logger = logging.getLogger(__name__) + +Instance = tuple[int, ...] + + +class RoutingWeights(NamedTuple): + """The serving config's ``routing_weights``: one weight per term of the cost.""" + load: float = 1.0 + # provisional: the best weight in simulations of BAGEL and Qwen3.5 0.8B and 9B + # that credit Qwen3.5's hits whole, as the KV mirror does, where its workers + # serve them only up to a recurrent snapshot; above 16 a hot prefix piles + # onto one replica + prefix: float = 8.0 + + +def routing_cost(facts: RoutingFacts, weights: RoutingWeights) -> float: + """What a replica's facts add to its cost. A term is 0 where its facts are + absent, so a resource with no mirror drops out. + + ``prefix`` is minus the share of the request's positions the replica's KV + caches are predicted to hold: a prompt held whole is worth up to ``prefix`` + live requests. A share, not a token count, so one weight fits models whose + prefill and decode costs differ. + """ + return -weights.prefix * facts.kv_hit / facts.work if facts.work else 0.0 + + +def _add(a: RoutingFacts, b: RoutingFacts) -> RoutingFacts: + return RoutingFacts(*map(sum, zip(a, b, strict=True))) + + +# each term's weight alone, to count what it predicted on the picked replica +_TERMS = { + term: RoutingWeights(**{name: float(name == term) for name in RoutingWeights._fields}) + for term in RoutingWeights._fields if term != "load" +} + + +class Placement(NamedTuple): + """A new request's pick, for ``ReplicaRouter.add`` to record once the request dispatches.""" + # node group -> its replica + replicas: dict[int, int] + # unit index -> the facts on its picked replica + facts: dict[int, RoutingFacts] + + +class _Mirror(NamedTuple): + key: str + # the unit's groups holding the resource's nodes: a request that runs none skips it + groups: frozenset[int] + mirror: RoutingMirror + + +class _Held(NamedTuple): + mirror: _Mirror + handle: Any + + +class RoutingHandle(NamedTuple): + """What placing one request recorded, for ``ReplicaRouter.remove``.""" + # (unit index, replica) it counts on + load: tuple[tuple[int, int], ...] + mirrors: tuple[_Held, ...] + + +class _Unit(NamedTuple): + """Node groups placed on the same ranks, replica for replica: one pick places them all.""" + groups: tuple[int, ...] + instances: tuple[Instance, ...] + mirrors: tuple[_Mirror, ...] + + +class ReplicaRouter: + def __init__( + self, + model: Model, + worker_graphs: Iterable, + specs: Iterable[NodeResourceSpec] = (), + weights: Mapping[str, Any] | None = None, + ): + """``weights`` are the serving config's ``routing_weights``, which + ``validate_deployment`` checked. Each spec is asked for a mirror once per + set of groups with replicas that holds one of its nodes.""" + worker_graphs, specs = list(worker_graphs), list(specs) + self._weights = RoutingWeights(**{name: float(w) for name, w in (weights or {}).items()}) + units: dict[tuple[Instance, ...], list] = {} + for wg in worker_graphs: + units.setdefault(tuple(map(tuple, wg.replica_ranks)), []).append(wg) + # the KV declarations a mirror reads: keyed_labels as the engine reads them, and + # names_checkpoint in place of the engine's checkpoint_path() is not None + keyed = { + key: {label: kv_label.keys.walks for label, kv_label in labels.items()} + for key, labels in keyed_labels(model).items() + } + by_rank = prefix_caches_by_rank( + specs, ((wg.ranks, wg.tp_size, wg.section.get_nodes()) for wg in worker_graphs), names_checkpoint(model), + ) + self._units: list[_Unit] = [] + for instances, wgs in units.items(): + # what every replica's engines open + opened = frozenset.intersection(*(by_rank[rank] for instance in instances for rank in instance)) + mirrors = [] + for spec in specs if len(instances) > 1 else (): + holding = [wg for wg in wgs if not spec.nodes.isdisjoint(wg.section.get_nodes())] + if not holding: + continue + walks = frozenset().union(*(wg.graph_walks for wg in holding)) + mirror = spec.routing_mirror(RoutingContext( + len(instances), walks, keyed.get(spec.resource_key, {}), spec.resource_key in opened, + )) + if mirror is not None: + mirrors.append(_Mirror(spec.resource_key, frozenset(wg._group_id for wg in holding), mirror)) + groups = tuple(dict.fromkeys(wg._group_id for wg in wgs)) + self._units.append(_Unit(groups, instances, tuple(mirrors))) + if any(len(unit.instances) > 1 for unit in self._units): + logger.info( + "Replica pick: weights %s; mirrors %s", self._weights._asdict(), + [(m.key, unit.instances) for unit in self._units for m in unit.mirrors], + ) + self._partition_groups = { + p.name: frozenset(wg._group_id for wg in worker_graphs if wg.graph_walks & p.graph_walks) + for p in model.get_partitions() + } + # live requests per (unit index, replica) + self._load: Counter[tuple[int, int]] = Counter() + self.predicted_saving = MetricCounter(catalog.ROUTING_PREDICTED_SAVING) + + def groups_run(self, partitions: Iterable[str]) -> frozenset[int]: + """The node groups of these partitions: what a request whose other partitions are done runs.""" + return frozenset().union(*(self._partition_groups[p] for p in partitions)) + + def pick(self, configs: Mapping[str, ResourceReqConfig], groups_run: frozenset[int]) -> Placement: + """Each node group's replica for a new request that runs ``groups_run`` + and opens its resources with ``configs``. Records nothing.""" + replicas: dict[int, int] = {} + picked: dict[int, RoutingFacts] = {} + for u, unit in enumerate(self._units): + choice = 0 + if len(unit.instances) > 1: + # the facts on each replica, every mirror's fields added + row: list[RoutingFacts] | None = None + for m in unit.mirrors: + if m.key in configs and not groups_run.isdisjoint(m.groups): + facts = m.mirror.facts(configs[m.key]) + row = facts if row is None else list(map(_add, row, facts)) + cost = [ + self._weights.load * self._load[(u, i)] + + (0.0 if row is None else routing_cost(row[i], self._weights)) + for i in range(len(unit.instances)) + ] + least = min(cost) + choice = random.choice([i for i, c in enumerate(cost) if c == least]) + if row is not None: + picked[u] = row[choice] + for group in unit.groups: + replicas[group] = choice + return Placement(replicas, picked) + + def add( + self, placement: Placement, configs: Mapping[str, ResourceReqConfig], groups_run: frozenset[int], + ) -> RoutingHandle: + """Record a request placed by ``placement``, in every mirror of the groups it runs.""" + load = [] + handles = [] + for u, unit in enumerate(self._units): + if groups_run.isdisjoint(unit.groups): + continue + replica = placement.replicas[unit.groups[0]] + load.append((u, replica)) + for m in unit.mirrors: + if m.key in configs and not groups_run.isdisjoint(m.groups): + mirror_handle = m.mirror.add_request(configs[m.key], replica) + if mirror_handle is not None: + handles.append(_Held(m, mirror_handle)) + if placement.facts: + # the facts of every set of replicas it was placed on, priced once: a share of its whole prompt + facts = RoutingFacts(*map(sum, zip(*placement.facts.values(), strict=True))) + for term, alone in _TERMS.items(): + saving = -routing_cost(facts, alone) + if saving: + self.predicted_saving.inc((term,), saving) + handle = RoutingHandle(tuple(load), tuple(handles)) + self._load.update(handle.load) + return handle + + def remove(self, handle: RoutingHandle, ran: Iterable[str]) -> None: + """Release a request recorded by ``add``. ``ran`` names its partitions + with a pass that came back.""" + self._load.subtract(handle.load) + groups_ran = self.groups_run(ran) + for held in handle.mirrors: + held.mirror.mirror.remove_request(held.handle, not groups_ran.isdisjoint(held.mirror.groups)) diff --git a/mstar/engine/engine.py b/mstar/engine/engine.py index 3e6db3f75f..82132a9718 100644 --- a/mstar/engine/engine.py +++ b/mstar/engine/engine.py @@ -38,6 +38,7 @@ SubmoduleStep, ) from mstar.engine.resources.base import EngineResourceInfo, KeyedWalks, build_resource +from mstar.engine.resources.kv.config import instance_size, opening_prefix_caches, unrestorable from mstar.engine.resources.kv.keys import fingerprint from mstar.engine.resources.kv.transfer import TransferEngineInfo from mstar.engine.resources.spec import resolve_spec_dependencies @@ -531,6 +532,10 @@ def load_model( # resource -> every node declaring it, on this worker or another declared_by: dict[str, frozenset[str]] = {} specs_by_key = resolve_spec_dependencies(specs) + instance = {node: parallel_groups.get_joint_group_for_node(node).world_size for node in node_names} + checkpoint = model.checkpoint_path() if model is not None else None + # a cache only another engine holds counts here at one rank: its own engine sizes it + prefix_caches = opening_prefix_caches(specs, instance, checkpoint_named=checkpoint is not None) self._classify_tp_roles(node_names, parallel_groups) @@ -563,6 +568,7 @@ def load_model( max_rows_in_combined=self._max_rows_in_combined( spec.resource_key, relevant_nodes, submodules, model, ), + prefix_caches=prefix_caches, ), ) @@ -584,7 +590,7 @@ def load_model( declared_by=declared_by, ) - self._open_prefix_caches(specs_by_key, model) + self._open_prefix_caches(specs_by_key, model, instance, prefix_caches, checkpoint) for node_name, submodule in submodules.items(): # Inference only. `exec` is under no_grad, but `prepare_inputs` and @@ -881,44 +887,36 @@ def _build_piecewise_runners( runners[label] = runner return runners - def _open_prefix_caches(self, specs_by_key, model) -> None: - """Root each resource's cache in the weights, the preprocessing, and the - config of every resource its pages were planned against.""" - checkpoint = model.checkpoint_path() if model is not None else None + def _open_prefix_caches( + self, specs_by_key, model, instance: Mapping[str, int], opened: frozenset[str], checkpoint: str | None, + ) -> None: + """Open the caches built here that ``opened`` names, and close the rest. + ``opened`` is `opening_prefix_caches` over ``instance``, the lockstep + instance of each node here, for ``model``'s ``checkpoint``. Each cache is + rooted in the weights, the preprocessing, and the config of every + resource its pages were planned against.""" shared = [ checkpoint_identity(checkpoint) if checkpoint is not None else b"", model.preprocess_fingerprint() if model is not None else "", ] declared = keyed_labels(model) if model is not None else {} self._prefix_model = type(model).__name__ - # node -> the walks a probe may run on, from the keys of every label on a cache the node uses + opened_keys = opened & declared.keys() + self._log_shut_caches(specs_by_key, declared.keys() - opened, opened, instance, checkpoint is not None) + # node -> the walks a probe may run on, from the keys of every label on an open cache the node uses self._keyed_walks: dict[str, set[str]] = {} - for key, by_label in declared.items(): + for key in opened_keys: for node in specs_by_key[key].nodes: self._keyed_walks.setdefault(node, set()).update( - walk for label in by_label.values() for walk in label.keys.walks + walk for label in declared[key].values() for walk in label.keys.walks ) - # a cache another engine holds is taken as open when its config says so - opened_keys = { - key for key in declared - if key not in self._resources and specs_by_key[key].config.prefix_cache - } - # resources that aren't keyed but opened, such as a recurrent pool's snapshots - restoring: set[str] = set() for key, spec in specs_by_key.items(): if key in self._resources and spec.depends_on() <= self._resources.keys(): self._resources[key].bind_dependencies({dep: self._resources[dep] for dep in spec.depends_on()}) for key, resource in self._resources.items(): - if checkpoint is None and declared.get(key): - config = specs_by_key[key].config - if config.prefix_cache and not config.prefix_cache_salt: - logger.info( - "KV %s: prefix cache off: %s names no checkpoint, so " - "builds that differ only in their weights cannot be " - "told apart; set prefix_cache_salt to enable it", - key, self._prefix_model, - ) - continue + if key not in opened: + resource.close_prefix_cache() + continue # its own, then its dependents' in key order, so the root does not # move with the order the engine happened to build them in parts = [resource.fingerprint()] @@ -928,15 +926,12 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: mark = built.fingerprint() if built is not None else None if mark is not None: parts.append(mark) - opened = resource.enable_prefix_cache(fingerprint(*shared, *parts), { + resource.enable_prefix_cache(fingerprint(*shared, *parts), { label: KeyedWalks( kv_label.keys.walks, tuple(walk for walk, _ in kv_label.growth if kv_label.keys.growth), ) for label, kv_label in declared.get(key, {}).items() }) - if opened: - (opened_keys if declared.get(key) else restoring).add(key) - self._close_unservable_nodes(specs_by_key, opened_keys, restoring) for key in sorted(opened_keys & self._resources.keys()): resource = self._resources[key] nodes = ", ".join(sorted(specs_by_key[key].nodes)) @@ -963,35 +958,37 @@ def _open_prefix_caches(self, specs_by_key, model) -> None: nodes = model.get_graph_walk_graphs()[walk].get_nodes() self._item_encoders.update(set(nodes) - specs_by_key[key].nodes) - def _close_unservable_nodes( - self, specs_by_key: dict[str, NodeResourceSpec], opened_keys: set[str], restoring: set[str], + def _log_shut_caches( + self, specs_by_key: dict[str, NodeResourceSpec], shut: set[str], opened: frozenset[str], + instance: Mapping[str, int], checkpoint_named: bool, ) -> None: - """Close every prefix cache on a keyed node with a resource that can't - serve a cached prefix. - - A resource that opened but isn't keyed serves a hit only when every cache - it depends on opened, and so does a resource that depends only on such - resources. - """ - restorers = {key for key in restoring if specs_by_key[key].depends_on() <= opened_keys} - serving = opened_keys | restorers | { - key for key, resource in self._resources.items() if resource.prefix_skip_safe - } | { - key for key, spec in specs_by_key.items() - if spec.depends_on() and spec.depends_on() <= restorers - } - for node in sorted(self._keyed_walks): - on_node = {key for key, spec in specs_by_key.items() if node in spec.nodes and key in self._resources} - if on_node <= serving: + """Say why each keyed cache here that asks for a prefix cache stays shut, + from the pieces of `opening_prefix_caches` that shut it.""" + for key in sorted(shut & self._resources.keys()): + spec = specs_by_key[key] + # the cache is on at all: it opens at one rank for a model that names its checkpoint + if not spec.keeps_prefix_cache(1, checkpoint_named=True): continue - del self._keyed_walks[node] - for key in sorted(on_node - serving): - logger.info("%s on %s can't serve a cached prefix: the prefix caches on %s stay off", - key, node, node) - for key in sorted(on_node & (opened_keys | restoring)): - self._resources[key].close_prefix_cache() - opened_keys.discard(key) - restoring.discard(key) + size = instance_size(spec, instance) + nodes = ", ".join(sorted(spec.nodes)) + if not spec.keeps_prefix_cache(size, checkpoint_named=True): + logger.info("KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", key, size) + elif not spec.keeps_prefix_cache(size, checkpoint_named): + logger.info( + "KV %s: prefix cache off: %s names no checkpoint, so " + "builds that differ only in their weights cannot be " + "told apart; set prefix_cache_salt to enable it", + key, self._prefix_model, + ) + else: + restoring = sorted( + over.resource_key for over in unrestorable(specs_by_key, opened) + if not over.nodes.isdisjoint(spec.nodes) + ) + logger.info( + "KV %s: prefix cache off: %s on %s can't restore a cached prefix", + key, ", ".join(restoring) or "a resource", nodes, + ) def prepare_inputs(self, batch: ExecutingBatch) -> None: """Per-rid ``submodule.prepare_inputs``, onto ``batch.inputs``. diff --git a/mstar/engine/resources/base.py b/mstar/engine/resources/base.py index 09fa40b990..19363d4b9d 100644 --- a/mstar/engine/resources/base.py +++ b/mstar/engine/resources/base.py @@ -73,6 +73,9 @@ class EngineResourceInfo: max_rows_in_combined: "Mapping[str, int | None]" = field( default_factory=dict ) + # the prefix caches this engine opens (`opening_prefix_caches`), decided + # before any resource is built, for one that sizes itself by its own + prefix_caches: frozenset[str] = frozenset() @property def head_shards(self) -> int: @@ -127,13 +130,14 @@ def can_capture(self) -> bool: # stays correct when a hit skips the front of a request; required of every resource on a keyed node prefix_skip_safe: bool = False - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: - """Open whatever this resource keeps across requests, under ``root``; - True if anything opened.""" - return False + def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> None: + """Open whatever this resource keeps across requests, under ``root``. The + engine calls it, before any request, on the caches `opening_prefix_caches` opens.""" + return def close_prefix_cache(self) -> None: - """Undo `enable_prefix_cache`. Called before any request.""" + """Keep nothing across requests. The engine calls it, before any + request, on every other resource.""" return def bind_dependencies(self, resources: Mapping[str, "Resource"]) -> None: diff --git a/mstar/engine/resources/kv/arena.py b/mstar/engine/resources/kv/arena.py new file mode 100644 index 0000000000..592da5fb71 --- /dev/null +++ b/mstar/engine/resources/kv/arena.py @@ -0,0 +1,80 @@ +"""A KV pool's page ownership: who holds each page, and when it goes back to the +free list. + +Free of the cache and its kernels, so the conductor's routing mirror +(``kv/routing.py``) keeps each replica's pages by the worker's own rules. +""" + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from mstar.engine.resources.kv.cache import KVCache, PageAllocator + from mstar.engine.resources.kv.host_writes import HostWrites + from mstar.engine.resources.kv.prefix_index import PrefixIndex + + +@dataclass +class PageArena: + """physical storage, free list, and per-page ownership + + A page goes back to the allocator when its last owner releases it, not its + first. A sealed page is never written again, so a second owner may read it; + freeing clears the seal. Every caller holds the manager's `_lock`, or is the + conductor's one thread, so the counts and seals need none of their own. + """ + kv_cache: "KVCache | None" + allocator: "PageAllocator" + num_owners: list[int] = field(init=False, repr=False) + sealed: list[bool] = field(init=False, repr=False) + index: "PrefixIndex | None" = field(default=None, init=False, repr=False) + trail: tuple[int, int] | None = field(default=None, init=False, repr=False) + # queues each page a release leaves to the index alone, for a copy to the host + writes: "HostWrites | None" = field(default=None, init=False, repr=False) + + def __post_init__(self): + self.num_owners = [0] * self.allocator.max_num_pages + self.sealed = [False] * self.allocator.max_num_pages + + def acquire(self, n: int) -> list[int] | None: + pages = self.allocator.try_allocate(n) + if pages is not None: + for page in pages: + self.num_owners[page] = 1 + if self.trail is not None: + self.trail = (self.trail[0] + 1, hash((self.trail, *pages))) + return pages + + def retain(self, pages: list[int]) -> None: + for page in pages: + self.num_owners[page] += 1 + if self.num_owners[page] == 2 and self.index is not None: + self.index.set_shared(page, True) + + def seal(self, pages: list[int]) -> None: + for page in pages: + self.sealed[page] = True + + def any_sealed(self, pages: list[int]) -> bool: + return any(self.sealed[page] for page in pages) + + def release(self, pages: list[int]) -> None: + freed = [] + for page in pages: + assert self.num_owners[page] > 0, f"page {page} released with no owner" + self.num_owners[page] -= 1 + if self.num_owners[page] == 0: + self.sealed[page] = False + freed.append(page) + elif self.num_owners[page] == 1 and self.index is not None: + self.index.set_shared(page, False) + if self.writes is not None: + self.writes.queue(self.index.key_of(page)) + self.allocator.free(freed) + + def copy_pages(self, src: list[int], dst: list[int]) -> None: + self.kv_cache.copy_pages(src, dst) + + @property + def num_free(self): + return self.allocator.num_free diff --git a/mstar/engine/resources/kv/config.py b/mstar/engine/resources/kv/config.py index 58a6218830..2b77082765 100644 --- a/mstar/engine/resources/kv/config.py +++ b/mstar/engine/resources/kv/config.py @@ -6,12 +6,12 @@ import math from abc import ABC, abstractmethod -from collections.abc import Collection, Mapping +from collections.abc import Collection, Iterable, Mapping, Sequence from dataclasses import dataclass, field, replace from enum import Enum from typing import TYPE_CHECKING -from mstar.engine.resources.spec import NodeResourceSpec, ResourceReqConfig +from mstar.engine.resources.spec import NodeResourceSpec, ResourceReqConfig, RoutingContext from mstar.engine.resources.step import ResourceStep if TYPE_CHECKING: @@ -191,6 +191,17 @@ def _arena_page(self) -> int: # tokens of every layer in an arena page, a page of the first group's layers return self.tokens_per_page * len(self.groups[0].layers) + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + """`NodeResourceSpec.keeps_prefix_cache` for a pool of this config. + Above one rank only with ``prefix_cache_tp``, and a model that names no + checkpoint needs a salt, or builds that differ only in their weights + could not be told apart.""" + return ( + self.prefix_cache + and (world_size == 1 or self.prefix_cache_tp) + and (checkpoint_named or bool(self.prefix_cache_salt)) + ) + @property def request_pages(self) -> int: """Arena pages requests can hold: all but the sink page the KV manager takes at build.""" @@ -512,6 +523,80 @@ def without_layouts(configs: Mapping[str, ResourceReqConfig]) -> dict[str, Resou for key, config in configs.items() } + +def instance_size(spec: NodeResourceSpec, instance: Mapping[str, int]) -> int: + """What `opening_prefix_caches` sizes ``spec`` at: the smallest lockstep + instance of its nodes in ``instance``, 1 where it has none.""" + return min((instance[node] for node in spec.nodes if node in instance), default=1) + + +def unrestorable(specs: Mapping[str, NodeResourceSpec], opened: Collection[str]) -> list[NodeResourceSpec]: + """The resources that can't restore what a hit skips while ``opened`` open: + those that set `NodeResourceSpec.restores_prefix` and keep no open cache of + their own, unless they are over open caches that restore. Each keeps every + cache on its nodes shut.""" + return [ + spec for spec in specs.values() + if spec.restores_prefix and spec.resource_key not in opened and not ( + spec.depends_on() and all(dep in opened and specs[dep].restores_prefix for dep in spec.depends_on()) + ) + ] + + +def opening_prefix_caches( + specs: Iterable[NodeResourceSpec], instance: Mapping[str, int], checkpoint_named: bool, +) -> frozenset[str]: + """The prefix caches that open: those each spec keeps of its own + (`NodeResourceSpec.keeps_prefix_cache`), less those a resource on their + nodes keeps from serving a hit. Every input is fixed at startup, so the + engines, the conductor's routing and the data worker agree. + + ``instance`` is the lockstep instance of each node the caller places + (`instance_size`). A cache over other caches, such as a recurrent pool's + snapshots over its KV cache's pages, keeps only where they open on all of + its nodes. A node carrying a resource that can't restore what a hit skips + (`unrestorable`) keeps every cache on it shut: a hit there would skip + tokens its state never saw. Closing one cache can close others, so the rule + runs until nothing changes. + """ + by_key = {spec.resource_key: spec for spec in specs} + opened = { + key for key, spec in by_key.items() if spec.keeps_prefix_cache(instance_size(spec, instance), checkpoint_named) + } + while True: + kept = { + key for key in opened + if all(dep in opened and by_key[key].nodes <= by_key[dep].nodes for dep in by_key[key].depends_on()) + } + blocked = {node for spec in unrestorable(by_key, kept) for node in spec.nodes} + now = {key for key in kept if by_key[key].nodes.isdisjoint(blocked)} + if now == opened: + return frozenset(now) + opened = now + + +def prefix_caches_by_rank( + specs: Iterable[NodeResourceSpec], + groups: Iterable[tuple[Sequence[int], int, Collection[str]]], + checkpoint_named: bool, +) -> dict[int, frozenset[str]]: + """The caches each rank's engine opens: `opening_prefix_caches` over the + nodes on the rank, each at its lockstep instance size, as `Engine.load_model` + evaluates it, less the caches with no node there, which that engine counts at + one rank for its item encoders but never builds. ``groups`` gives each node + group's ranks, instance size and nodes.""" + specs = list(specs) + local: dict[int, dict[str, int]] = {} + for ranks, size, nodes in groups: + for rank in ranks: + local.setdefault(rank, {}).update(dict.fromkeys(nodes, size)) + return { + rank: opening_prefix_caches(specs, nodes, checkpoint_named) + & {spec.resource_key for spec in specs if not spec.nodes.isdisjoint(nodes)} + for rank, nodes in local.items() + } + + @dataclass class KVSpec(NodeResourceSpec): config: KVConfig @@ -535,6 +620,18 @@ def apply_yaml_overrides(self, **kwargs): storage strategy, so the config answers for them.""" self.config.apply_yaml_overrides(**kwargs) + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + return isinstance(self.config, PagedKVConfig) and self.config.keeps_prefix_cache(world_size, checkpoint_named) + + def routing_mirror(self, ctx: RoutingContext): + """A mirror of the prefix cache where it opens and a walk that keys it runs.""" + labels = [label for label, walks in ctx.keyed.items() if ctx.walks.intersection(walks)] + if not labels or not ctx.prefix_cache_opens: + return None + from mstar.engine.resources.kv.routing import KVRoutingMirror + + return KVRoutingMirror(ctx.num_replicas, self.config.num_units, self.config.tokens_per_page, labels) + def derive(self, specs: Mapping[str, NodeResourceSpec]) -> list[str]: # the attentions over a pool decide what it keeps, and their module imports this one from mstar.engine.resources.attn.config import derive_kv_groups diff --git a/mstar/engine/resources/kv/cpu_page_pool.py b/mstar/engine/resources/kv/cpu_page_pool.py index 544111fc37..9417f55071 100644 --- a/mstar/engine/resources/kv/cpu_page_pool.py +++ b/mstar/engine/resources/kv/cpu_page_pool.py @@ -23,7 +23,7 @@ from mstar.engine.resources.kv.prefix_index import PrefixIndex if TYPE_CHECKING: - from mstar.engine.resources.kv.manager import PageArena + from mstar.engine.resources.kv.arena import PageArena logger = logging.getLogger(__name__) diff --git a/mstar/engine/resources/kv/manager.py b/mstar/engine/resources/kv/manager.py index 6b175f9f13..b52671248b 100644 --- a/mstar/engine/resources/kv/manager.py +++ b/mstar/engine/resources/kv/manager.py @@ -20,6 +20,7 @@ KeyedWalks, PublishedInfo, ) +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import GroupPages, KVCache, PageAllocator, held_pages, on_pages from mstar.engine.resources.kv.config import ( KVGroup, @@ -84,72 +85,6 @@ class RoomMark(NamedTuple): taken: int -@dataclass -class PageArena: - """physical storage, free list, and per-page ownership - - A page goes back to the allocator when its last owner releases it, not its - first. A sealed page is never written again, so a second owner may read it; - freeing clears the seal. Every caller holds the manager's `_lock`, so the - counts and seals need none of their own. - """ - kv_cache: KVCache | None - allocator: PageAllocator - num_owners: list[int] = field(init=False, repr=False) - sealed: list[bool] = field(init=False, repr=False) - index: PrefixIndex | None = field(default=None, init=False, repr=False) - trail: tuple[int, int] | None = field(default=None, init=False, repr=False) - # queues each page a release leaves to the index alone, for a copy to the host - writes: HostWrites | None = field(default=None, init=False, repr=False) - - def __post_init__(self): - self.num_owners = [0] * self.allocator.max_num_pages - self.sealed = [False] * self.allocator.max_num_pages - - def acquire(self, n: int) -> list[int] | None: - pages = self.allocator.try_allocate(n) - if pages is not None: - for page in pages: - self.num_owners[page] = 1 - if self.trail is not None: - self.trail = (self.trail[0] + 1, hash((self.trail, *pages))) - return pages - - def retain(self, pages: list[int]) -> None: - for page in pages: - self.num_owners[page] += 1 - if self.num_owners[page] == 2 and self.index is not None: - self.index.set_shared(page, True) - - def seal(self, pages: list[int]) -> None: - for page in pages: - self.sealed[page] = True - - def any_sealed(self, pages: list[int]) -> bool: - return any(self.sealed[page] for page in pages) - - def release(self, pages: list[int]) -> None: - freed = [] - for page in pages: - assert self.num_owners[page] > 0, f"page {page} released with no owner" - self.num_owners[page] -= 1 - if self.num_owners[page] == 0: - self.sealed[page] = False - freed.append(page) - elif self.num_owners[page] == 1 and self.index is not None: - self.index.set_shared(page, False) - if self.writes is not None: - self.writes.queue(self.index.key_of(page)) - self.allocator.free(freed) - - def copy_pages(self, src: list[int], dst: list[int]) -> None: - self.kv_cache.copy_pages(src, dst) - - @property - def num_free(self): - return self.allocator.num_free - - @dataclass class PrefixChain: """The keys that name a stream's pages, and how far the index holds them.""" @@ -792,7 +727,7 @@ def _static_plan_state(self, slot: int, label: tuple[str, int]) -> KVPlanState: ) return state - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: + def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> None: """Open the index under ``root``, the identity every key hangs from.""" self._keyed_walks = {} for label, named in (walks or {}).items(): @@ -802,14 +737,6 @@ def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = if self._world_size == 1: keyed.update(named.growth) self._keyed_walks[label] = frozenset(keyed) - if not self.config.prefix_cache: - return False - if self._world_size > 1 and not self.config.prefix_cache_tp: - logger.info( - "KV %s: prefix cache off at world size %d (prefix_cache_tp opts in)", - self.name, self._world_size, - ) - return False self._prefix_root = root self._index = PrefixIndex(self._arena) if self._world_size == 1: @@ -818,7 +745,6 @@ def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = self._arena.index = self._index if self._cpu_pool is not None: self._open_host_writes() - return True def _open_host_writes(self) -> None: self._host_writes = HostWrites(self._cpu_pool, self._index, self.kv_cache.tensor[:, 0].nbytes) diff --git a/mstar/engine/resources/kv/prefix_index.py b/mstar/engine/resources/kv/prefix_index.py index 3e92b80729..bebc063e26 100644 --- a/mstar/engine/resources/kv/prefix_index.py +++ b/mstar/engine/resources/kv/prefix_index.py @@ -7,7 +7,8 @@ entry however often it is read, and an entry that surfaces under an older stamp is pushed back under the page's own. -Every caller holds the manager's lock, so none of this takes one of its own. +Every caller holds the manager's lock, or is the conductor's one thread, so none +of this takes one of its own. """ import copy @@ -16,7 +17,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from mstar.engine.resources.kv.manager import PageArena + from mstar.engine.resources.kv.arena import PageArena class PrefixIndex: @@ -219,6 +220,15 @@ def evict(self, n: int, spare: Callable[[bytes], bool] | None = None) -> list[by heapq.heappush(self._leaves, entry) return dropped + def drop(self, entries: Sequence[tuple[bytes, int]]) -> None: + """Remove these ``(key, page)`` entries, last first, each only while the + key still names the page and it is a leaf the index alone holds: what the + routing mirror predicted a request would index, taken back once the + request ended without running.""" + for key, page in reversed(entries): + if self._by_key.get(key) == page and not self._children[page] and self._arena.num_owners[page] == 1: + self._remove(page) + def _pop_leaf(self) -> tuple[int, int] | None: while self._leaves: stamp, page = heapq.heappop(self._leaves) diff --git a/mstar/engine/resources/kv/routing.py b/mstar/engine/resources/kv/routing.py new file mode 100644 index 0000000000..619b02cb01 --- /dev/null +++ b/mstar/engine/resources/kv/routing.py @@ -0,0 +1,213 @@ +"""A paged KV cache's routing mirror: which prompt pages each replica's prefix +cache is predicted to hold, so a request goes where its prefix already is. + +Each replica runs the worker's own ``PrefixIndex`` and ``PageArena``, with no +storage, and a request takes the steps ``KVManager`` takes for it, all at +dispatch: the lease of its matched pages, its own pages (evicting on a +shortfall), the index entries of its whole keyed pages, and the page of its +last item that ends inside one, up to that end. Its end releases its pages, and +takes back the entries of a request whose walk never ran. + +It predicts from what the conductor sees, a request's layout and page keys +when it is placed and its end, and is approximate for that reason: + +- the worker's pool and index also move with admit timing, decode growth, + scratch positions, chunked commits and preemption, and it keys a reply's + tokens, which the conductor never sees: a later turn's hit on an earlier + reply is under-predicted; +- a request the pool cannot hold yet waits on the worker, but here indexes only + the pages it could take; +- each replica's pool is charged every label of the request's layout, also + those whose pages another node group's pool holds, so it evicts early; +- each replica's pool is taken to be written by this set of groups alone: a KV + node whose groups sit on overlapping but different rank sets feeds one pool + from two sets, each mirror sees only its own, and both over-predict free + pages and hits there; +- ``ran`` is per partition: a pass of a walk that skips the cache counts as + run, and a pass that wrote the prompt but was aborted before it came back + does not; +- an entry belongs to the request placed first, where the worker's belongs to + the one that ran first: requests sharing a prefix that all end unrun leave + the entries a later one leased, and when only a later one runs, the first + one's end takes back an entry the worker keeps. +- on a node with a recurrent state pool a hit is served only up to the longest + snapshot of that state the pool holds under it (``cap_cached_prefix``), and + the pool keeps a few per prefill in ``prefix_slots``; the mirror counts the + KV hit whole, so it over-predicts there. + +Only the GPU pool is modelled. With a host pool (``cpu_offload_pages``) a +cached page the GPU evicted can come back from the host, so it under-predicts +hits there. + +Kernel-free, since the conductor builds it. +""" + +from collections.abc import Collection, Sequence +from typing import TYPE_CHECKING, NamedTuple + +from mstar.engine.resources.kv.arena import PageArena +from mstar.engine.resources.kv.prefix_index import PrefixIndex +from mstar.engine.resources.spec import RoutingFacts + +if TYPE_CHECKING: + from mstar.engine.resources.kv.config import KVReqConfig + + +class _FreePages: + """The free list a replica's `PageArena` takes from: `PageAllocator`'s, + without the queue and lock that cost the conductor's one thread about 3 µs + a page.""" + + def __init__(self, num_pages: int): + self.max_num_pages = num_pages + # every page but SINK_PAGE (0), which the pool never hands out + self._free = list(range(1, num_pages)) + + @property + def num_free(self) -> int: + return len(self._free) + + def try_allocate(self, n: int) -> list[int] | None: + if n > len(self._free): + return None + pages = self._free[len(self._free) - n:] + del self._free[len(self._free) - n:] + return pages + + def free(self, pages: list[int]) -> None: + self._free.extend(pages) + + +class _Keyed(NamedTuple): + """One label's prompt as the worker's ``PrefixChain`` keys it.""" + keys: Sequence[bytes] + # how many of its pages are whole: the only ones the worker indexes (``PrefixChain.keyed_pages``) + whole: int + # its keyed positions + total: int + # where each item that ends inside a page ends, and the key of that page up to there + ends: list[tuple[int, bytes]] + + +class _Placed(NamedTuple): + replica: int + # every page the request holds: its lease and its own + pages: list[int] + # the (key, page) entries it filed, which the worker files only once the walk runs. + # An item's end page is the index's alone, so it may be evicted and refiled under another key + indexed: list[tuple[bytes, int]] + + +class KVRoutingMirror: + """`RoutingMirror` of one paged KV resource, for the keyed ``labels`` whose + walks run on these replicas.""" + + def __init__(self, num_replicas: int, num_pages: int, page_size: int, labels: Collection[str]): + self._page_size = page_size + self._labels = labels + self._arenas = [PageArena(kv_cache=None, allocator=_FreePages(num_pages)) for _ in range(num_replicas)] + self._indexes = [PrefixIndex(arena) for arena in self._arenas] + for arena, index in zip(self._arenas, self._indexes, strict=True): + # as `KVManager.enable_prefix_cache` at one rank, the only size a mirror is built for + arena.index = index + + def _keyed(self, config: "KVReqConfig") -> dict[str, _Keyed]: + if not config.prefix_cache: + return {} + layouts = config.kv_layout or {} + keyed = {} + for label, keys in (config.prefix_keys or {}).items(): + layout = layouts.get(label) + if not keys or layout is None or label not in self._labels: + continue + total, ends = 0, [] + for span in layout.spans[:layout.keyed_spans]: + total += span.length + if span.end_key is not None: + ends.append((total, span.end_key)) + whole = total // self._page_size + if layout.retention is not None: + whole = min(whole, layout.retention.protected_prefix // self._page_size) + keyed[label] = _Keyed(keys, whole, total, ends) + return keyed + + def _image_end(self, keyed: _Keyed, held: int) -> tuple[int, bytes] | None: + """`KVManager._image_end`: the last item that ends inside the page after ``held`` positions.""" + for end, key in reversed(keyed.ends): + if held < end < min(held + self._page_size, keyed.total): + return end, key + return None + + def _hit(self, index: PrefixIndex, keyed: _Keyed) -> int: + """The positions `KVManager._lease` would hold: the matched pages but the + prompt's last, so the walk has input left, then up to the end of an item + cached inside the next page.""" + held = min(len(index.pages_for(keyed.keys)), len(keyed.keys) - 1) * self._page_size + end = self._image_end(keyed, held) + return end[0] if end is not None and index.page_for(end[1]) is not None else held + + def facts(self, config: "KVReqConfig") -> list[RoutingFacts]: + keyed = self._keyed(config) + # every prompt position of every label the request opens, keyed or not: + # a hit saves that share of its prefill + work = sum(span.length for layout in (config.kv_layout or {}).values() for span in layout.spans) + return [ + RoutingFacts(work, sum(self._hit(index, label) for label in keyed.values())) + for index in self._indexes + ] + + def add_request(self, config: "KVReqConfig", replica: int) -> _Placed | None: + keyed = self._keyed(config) + pages = { + label: -(-sum(span.length for span in layout.spans) // self._page_size) + for label, layout in (config.kv_layout or {}).items() + } + if not pages: + return None + arena, index = self._arenas[replica], self._indexes[replica] + held, indexed = [], [] + for label, total in pages.items(): + prompt = keyed.get(label, _Keyed((), 0, 0, [])) + keys = prompt.keys + # `KVManager._lease`, then its `_alloc`, `_index_filled_pages` and `_cache_image_end` + leased = index.lookup(keys)[:len(keys) - 1] if keys else [] + end = self._image_end(prompt, len(leased) * self._page_size) + if end is not None: + # the lease reads the cached item end, and copies it into a page of its own + index.lookup([end[1]]) + arena.retain(leased) + need = total - len(leased) + if need > arena.num_free: + index.evict(need - arena.num_free) + own = arena.acquire(min(need, arena.num_free)) + run = max(0, min(prompt.whole - len(leased), len(own))) + if run: + filed = keys[len(leased):len(leased) + run] + index.insert_run(filed, own[:run], leased[-1] if leased else None) + indexed += [ + (key, page) for key, page in zip(filed, own[:run], strict=True) if index.page_for(key) == page + ] + if prompt.ends: + indexed += self._file_item_end(index, arena, prompt) + held += leased + own + return _Placed(replica, held, indexed) + + def _file_item_end(self, index: PrefixIndex, arena: PageArena, prompt: _Keyed) -> list[tuple[bytes, int]]: + """`KVManager._cache_image_end` for the prompt's last item that ends inside + a page: that page up to the item's end, in a free page, never an evicted + one, filed under the page before it. Returns the entry it filed.""" + end, key = prompt.ends[-1] + page = end // self._page_size + parent = index.page_for(prompt.keys[page - 1]) if page else None + if (page and parent is None) or index.page_for(key) is not None or not arena.num_free: + return [] + copy = arena.acquire(1) + index.insert(key, copy[0], parent) + # the index is its one owner, as on the worker + arena.release(copy) + return [(key, copy[0])] + + def remove_request(self, handle: _Placed, ran: bool) -> None: + self._arenas[handle.replica].release(handle.pages) + if not ran: + self._indexes[handle.replica].drop(handle.indexed) diff --git a/mstar/engine/resources/linear_attn/config.py b/mstar/engine/resources/linear_attn/config.py index e3914bcc9e..fc471fc6d0 100644 --- a/mstar/engine/resources/linear_attn/config.py +++ b/mstar/engine/resources/linear_attn/config.py @@ -72,6 +72,11 @@ def writes_prefix_snapshots(self) -> bool: # only the GDN wrapper writes state checkpoints into the pool's snapshot slots return self.config.variant is LinearAttnVariant.GDN + @property + def restores_prefix(self) -> bool: + # its state is the pool's + return True + @property def resource_class(self) -> "type[Resource]": from mstar.engine.resources.linear_attn.base import LinearAttnManager diff --git a/mstar/engine/resources/recurrent/config.py b/mstar/engine/resources/recurrent/config.py index e5d428b2d7..12086954ed 100644 --- a/mstar/engine/resources/recurrent/config.py +++ b/mstar/engine/resources/recurrent/config.py @@ -298,6 +298,14 @@ def resource_class(self) -> "type[Resource]": def depends_on(self) -> set[str]: return {self.config.kv_cache} if self.config.kv_cache else set() + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + # snapshots are keyed by `kv_cache`'s pages, and kept at one rank only + return bool(self.config.prefix_slots) and self.config.kv_cache is not None and world_size == 1 + + @property + def restores_prefix(self) -> bool: + return True + def apply_yaml_overrides( self, max_slots: int | None = None, state_dtype: str | None = None, prefix_slots: int | None = None, diff --git a/mstar/engine/resources/recurrent/pool.py b/mstar/engine/resources/recurrent/pool.py index 5bac3fc638..7787f8b5ae 100644 --- a/mstar/engine/resources/recurrent/pool.py +++ b/mstar/engine/resources/recurrent/pool.py @@ -21,7 +21,6 @@ CGSlotKey, CGSlotSpec, EngineResourceInfo, - KeyedWalks, Resource, ) from mstar.engine.resources.kv.keys import fingerprint @@ -139,11 +138,9 @@ def build( ) -> "RecurrentStatePool": config = spec.config config.shard(info.head_shards) - group = info.joint_comm_group - world_size = group.world_size if group is not None else 1 - kv = info.dependencies.get(config.kv_cache) - if world_size > 1 or kv is None or not kv.config.prefix_cache: - # no snapshot slots where the prefix cache can't open + world_size = 1 if info.joint_comm_group is None else info.joint_comm_group.world_size + # no snapshot slots where the engine keeps them from serving a hit + if spec.resource_key not in info.prefix_caches: config = replace(config, prefix_slots=0) # resolved here, not written back: the config is the model's, shared by its specs return cls( @@ -659,14 +656,9 @@ def keyed_walks(self, label: str) -> frozenset[str]: return self._kv.keyed_walks(label) if self._kv is not None else frozenset() def bind_kv(self, kv: "KVManager") -> None: - """Key snapshots by the page chains of ``kv``, the cache `config.kv_cache` names.""" - self._kv = kv - - def enable_prefix_cache(self, root: bytes, walks: dict[str, KeyedWalks] | None = None) -> bool: - del root, walks - if not self.config.prefix_slots: - self._kv = None - return self._kv is not None + """Key snapshots by the page chains of ``kv``, the cache `config.kv_cache` names. + A pool with no snapshot slots keys none.""" + self._kv = kv if self.config.prefix_slots else None def close_prefix_cache(self) -> None: self._kv = None diff --git a/mstar/engine/resources/spec.py b/mstar/engine/resources/spec.py index b7cc6554f9..0bb5e84414 100644 --- a/mstar/engine/resources/spec.py +++ b/mstar/engine/resources/spec.py @@ -11,7 +11,7 @@ from abc import ABC, abstractmethod from collections.abc import Collection, Mapping, Sequence from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, NamedTuple, Protocol if TYPE_CHECKING: from mstar.engine.resources.base import Resource @@ -47,6 +47,54 @@ def max_prefill_rows( return min(total, bucket_rows) +class RoutingContext(NamedTuple): + """The data-parallel replicas a routing mirror is built for, and what a + mirror reads of the model's KV declarations, which ``ReplicaRouter`` fills.""" + num_replicas: int + # the walks of the worker graphs that hold the resource's nodes on these replicas + walks: frozenset[str] + # the resource's keyed labels, each with the walks whose writes it keys + keyed: Mapping[str, Collection[str]] + # whether every replica's engine opens the resource's prefix cache (`prefix_caches_by_rank`), + # derived by the router rather than declared + prefix_cache_opens: bool + + +class RoutingFacts(NamedTuple): + """What a mirror predicts for a new request on one replica, by name, for + the conductor's ``routing_cost`` to price. Every field is a count whose + identity is 0: a mirror leaves the fields it does not report at 0, and the + router adds the rows of every mirror on the replica field by field before + pricing them once.""" + # the positions the request's prompt writes, every KV label's + work: int = 0 + # of those, the positions a KV prefix cache is predicted to hold + kv_hit: int = 0 + + +class RoutingMirror(Protocol): + """A conductor-side prediction of one resource's state on each data-parallel + replica, for choosing a new request's replica. It holds bookkeeping only, + never the resource's data, follows the resource's own rules on what the + conductor sees, and a wrong prediction makes a request slower, never wrong. + + ``config`` is the request's config for the resource, as the conductor + opens it with: built and validated before the pick. + """ + + def facts(self, config: "ResourceReqConfig") -> list[RoutingFacts]: + """The request's facts on each replica.""" + + def add_request(self, config: "ResourceReqConfig", replica: int) -> Any: + """Record the request as placed on ``replica``; the handle comes back to ``remove_request``.""" + + def remove_request(self, handle: Any, ran: bool) -> None: + """Release what ``add_request`` recorded, once the request is gone. + ``ran`` says whether a pass came back for one of the request's + partitions with a walk on the resource's node groups (not necessarily a + walk that uses the resource), so the resource may hold what it left.""" + + @dataclass class NodeResourceSpec(ABC): resource_key: str @@ -70,6 +118,20 @@ def writes_prefix_snapshots(self) -> bool: """Fills the snapshot slots of the recurrent pool it depends on, so a hit can restore them.""" return False + def keeps_prefix_cache(self, world_size: int, checkpoint_named: bool) -> bool: + """Whether the resource keeps a prefix cache of its own on a lockstep + instance of ``world_size`` ranks, for a model that names its checkpoint + or not. False (the default) keeps nothing across requests. + `opening_prefix_caches` weighs it against the resources on its nodes.""" + return False + + @property + def restores_prefix(self) -> bool: + """A hit needs state the resource holds from the skipped tokens, so it + serves one only from a prefix cache of its own, or, keeping none, from + those of the resources it depends on that restore.""" + return False + @property @abstractmethod def resource_class(self) -> "type[Resource]": @@ -80,6 +142,11 @@ def resource_class(self) -> "type[Resource]": `AttentionManager`, whose `build` picks a backend subclass. """ + def routing_mirror(self, ctx: RoutingContext) -> RoutingMirror | None: + """A mirror of this resource for the replicas ``ctx`` describes; None + (the default) leaves the resource out of the replica pick there.""" + return None + def derive(self, specs: Mapping[str, "NodeResourceSpec"]) -> list[str]: """Set what this spec takes from the specs that read it (a KV pool keeps the window its attentions declare), after a deployment's overrides; return what is wrong with it. diff --git a/mstar/model/base.py b/mstar/model/base.py index 9adbef441b..d18d59b98e 100644 --- a/mstar/model/base.py +++ b/mstar/model/base.py @@ -179,6 +179,12 @@ def keyed_labels(model: "Model") -> dict[str, dict[str, KVLabel]]: return keyed +def names_checkpoint(model: "Model") -> bool: + """Whether ``model`` overrides ``checkpoint_path``, read without calling it, + which may download the checkpoint (BAGEL's does).""" + return type(model).checkpoint_path is not Model.checkpoint_path + + def video_metadata_dict(metadata_obj) -> dict: # torchcodec>=0.9 reports pixel_aspect_ratio as a Fraction, which the wire codec rejects. return {k: float(v) if isinstance(v, Fraction) else v for k, v in asdict(metadata_obj).items()} @@ -201,8 +207,9 @@ class WorkerGraph: # for data parallelism). ``_tp_ranks`` are the mesh rows (tensor-parallel # comm groups: sharded heads/weights, all-reduce); ``_sp_ranks`` are the # columns (sequence-parallel comm groups: Ulysses all-to-all); - # ``_instance_ranks`` are the whole instances (the conductor's lockstep - # routing unit — every rank of an instance runs a request together). With + # ``_instance_ranks`` are the whole instances (every rank of an instance runs + # a request together; empty without TP/SP, so the data-parallel replicas the + # conductor routes to are ``replica_ranks``). With # sp_size==1 this reduces to the old ``ranks`` chunked by ``tp_size`` # (trivial SP groups; instance == TP row). ``tp_size`` is rewritten in # __post_init__ to the instance size (tp*sp) so the conductor — which models @@ -591,6 +598,8 @@ def checkpoint_path(self) -> str | None: The prefix cache hashes the checkpoint's manifest into its root. None leaves the weights out, so the cache stays shut unless the deployment sets a salt. + An override returns a path: processes that must not download it read the + override alone (``names_checkpoint``). """ return None diff --git a/mstar/model/canary/canary_model.py b/mstar/model/canary/canary_model.py index 7804495ed1..77fde98bf3 100644 --- a/mstar/model/canary/canary_model.py +++ b/mstar/model/canary/canary_model.py @@ -84,7 +84,7 @@ def __init__(self, model_path_hf: str, cache_dir: str | None = None, **kwargs): self._detokenizer = SentencePieceDetokenizer(tokenizer) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) # ------------------------------------------------------------------- diff --git a/mstar/model/canary_qwen/canary_qwen_model.py b/mstar/model/canary_qwen/canary_qwen_model.py index 40ef3c97b6..abc62208ee 100644 --- a/mstar/model/canary_qwen/canary_qwen_model.py +++ b/mstar/model/canary_qwen/canary_qwen_model.py @@ -122,7 +122,7 @@ def __init__(self, model_path_hf: str, cache_dir: str | None = None, **kwargs): self._detokenizer = ByteLevelDetokenizer(self.tokenizer) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) # ------------------------------------------------------------------- diff --git a/mstar/model/ltx2_5/ltx2_5_model.py b/mstar/model/ltx2_5/ltx2_5_model.py index b2b451d8a2..a5841ce185 100644 --- a/mstar/model/ltx2_5/ltx2_5_model.py +++ b/mstar/model/ltx2_5/ltx2_5_model.py @@ -191,7 +191,7 @@ def config(self) -> LTX25Config: def set_config(self, config: LTX25Config) -> None: self._config = config - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.snapshot) # ------------------------------------------------------------ structure diff --git a/mstar/model/parakeet/parakeet_model.py b/mstar/model/parakeet/parakeet_model.py index 15eafa05e7..93c9456c16 100644 --- a/mstar/model/parakeet/parakeet_model.py +++ b/mstar/model/parakeet/parakeet_model.py @@ -77,7 +77,7 @@ def __init__( ) self._submodule_cache: dict[str, NodeSubmodule | None] = {} - def checkpoint_path(self) -> str | None: + def checkpoint_path(self) -> str: return str(self.local_dir) def _num_frames(self, num_samples: int) -> int: diff --git a/mstar/observability/catalog.py b/mstar/observability/catalog.py index 15c75784eb..983147cf62 100644 --- a/mstar/observability/catalog.py +++ b/mstar/observability/catalog.py @@ -44,6 +44,13 @@ class Family: "dispatched and whose completion it has not received yet.", ("component",), ) +ROUTING_PREDICTED_SAVING = Family( + "mstar_routing_predicted_saving_total", COUNTER, + "Per term of the data-parallel replica cost, the saving the mirrors " + "predicted on the replica each request was sent to, in request-equivalents: " + "for prefix, the share of the request's prompt predicted cached there.", + ("term",), +) REQUEST_QUEUE_SECONDS = Family( "mstar_request_queue_seconds", HISTOGRAM, "Successful requests: the conductor taking the request in to admitting it " @@ -152,5 +159,5 @@ class Family: #: Families the conductor's status message carries, exported from the latest #: message. STATUS_FAMILIES: dict[str, Family] = { - f.name: f for f in (CONDUCTOR_REQUESTS, COMPONENT_IN_FLIGHT) + f.name: f for f in (CONDUCTOR_REQUESTS, COMPONENT_IN_FLIGHT, ROUTING_PREDICTED_SAVING) } | WORKER_FAMILIES diff --git a/mstar/validation/__init__.py b/mstar/validation/__init__.py index 96a2290927..83e1700264 100644 --- a/mstar/validation/__init__.py +++ b/mstar/validation/__init__.py @@ -14,7 +14,7 @@ from mstar.model.base import Model, WorkerGraph from mstar.validation.client_streams import check_client_streams from mstar.validation.knobs import check_knobs -from mstar.validation.placement import check_worker_graphs, node_groups_problems +from mstar.validation.placement import check_worker_graphs, node_groups_problems, routing_weights_problems from mstar.validation.resources import check_resources, resources_shape_problem @@ -82,6 +82,7 @@ def validate_deployment( except _UNREADABLE as e: problems.append(_unreadable("validate_config_yaml", e)) + problems += routing_weights_problems(config) malformed = node_groups_problems(config) problems += malformed deployment = None diff --git a/mstar/validation/placement.py b/mstar/validation/placement.py index bf7bd6d1e6..1accc82f74 100644 --- a/mstar/validation/placement.py +++ b/mstar/validation/placement.py @@ -1,9 +1,11 @@ """Placement checks: walks and partitions, ``node_groups``, the worker graphs -they divide into, and the parallel groups each worker is handed.""" +they divide into, the parallel groups each worker is handed, and the weights +that pick a request's replica among them.""" from collections.abc import Iterator, Mapping, Sequence from typing import Any +from mstar.conductor.routing import RoutingWeights from mstar.distributed.base import ShardingConfig from mstar.distributed.communication import GlobalParallelConfig from mstar.engine.resources.spec import NodeResourceSpec @@ -28,6 +30,37 @@ def node_groups_problems(config: Mapping[str, Any]) -> list[str]: ] +# Far above any useful weight, and low enough that no replica's cost overflows to inf, where +# inf - inf would make it NaN and fail every pick. +_MAX_ROUTING_WEIGHT = 1e6 + + +def routing_weights_problems(config: Mapping[str, Any]) -> list[str]: + """``routing_weights``, the data-parallel replica pick's: one per term of + the cost, each a number from 0 to ``_MAX_ROUTING_WEIGHT``, since the cost + is a sum of weighted terms, and ``load`` above 0 when another term is, or + nothing would spread a hot prefix.""" + weights = config.get("routing_weights") + if weights is None: + return [] + if not isinstance(weights, Mapping): + return [f"routing_weights must be a mapping of {list(RoutingWeights._fields)}; got {weights!r}"] + problems = [] + unknown = sorted(set(weights) - set(RoutingWeights._fields), key=str) + if unknown: + problems.append(f"routing_weights names {unknown}; it takes {list(RoutingWeights._fields)}") + for name, weight in weights.items(): + if isinstance(weight, bool) or not isinstance(weight, (int, float)) or not 0 <= weight <= _MAX_ROUTING_WEIGHT: + problems.append( + f"routing_weights.{name} must be a number from 0 to {_MAX_ROUTING_WEIGHT:g}; got {weight!r}" + ) + if not problems and not weights.get("load", RoutingWeights._field_defaults["load"]) and any( + weights.get(name, default) for name, default in RoutingWeights._field_defaults.items() if name != "load" + ): + problems.append("routing_weights.load must be above 0 while another weight is") + return problems + + def _is_count(value: Any, least: int) -> bool: return isinstance(value, int) and not isinstance(value, bool) and value >= least @@ -191,11 +224,9 @@ def _input_limits(walk_to_wgs: Mapping[str, list[WorkerGraph]]) -> Iterator[str] def _on_same_workers(wgs: list[WorkerGraph]) -> bool: """Whether every request runs all of these worker graphs on the same - workers: the conductor picks one replica per node_group, so they share a - node_group, or each is a single instance on the same ranks.""" - if len({wg._group_id for wg in wgs}) == 1: - return True - return all(len(wg.replica_ranks) == 1 and wg.ranks == wgs[0].ranks for wg in wgs) + workers: the conductor picks one replica for every node_group on the same + lockstep instances (``ReplicaRouter``), so they share those instances.""" + return len({tuple(map(tuple, wg.replica_ranks)) for wg in wgs}) == 1 def _stream_driven_walks(model: Model, walk_to_wgs: Mapping[str, list[WorkerGraph]]) -> Iterator[str]: @@ -235,8 +266,8 @@ def _stream_driven_walks(model: Model, walk_to_wgs: Mapping[str, list[WorkerGrap f"{[sorted(wg.section.get_nodes()) for wg in wgs]} on ranks " f"{[wg.ranks for wg in wgs]}. Across worker graphs a stream-driven walk " "is served only with every consumer gated on a non-streamed input that " - "arrives once per pass and every worker graph on the same workers (one " - "node_group, or one instance on the same ranks); otherwise run it as " + "arrives once per pass and every worker graph on the same workers (node_groups " + "on the same ranks, instance for instance); otherwise run it as " "one worker graph, or move the work after the consumer into a " "downstream partition fed by a StreamingGraphEdge." ) diff --git a/test/modular/test_admit_rollback.py b/test/modular/test_admit_rollback.py index e162c5d1a3..d86a9faa58 100644 --- a/test/modular/test_admit_rollback.py +++ b/test/modular/test_admit_rollback.py @@ -20,10 +20,11 @@ from mstar.engine.engine import Engine, ExecutingBatch, SubmoduleManagement from mstar.engine.resources.base import EngineResourceInfo from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import KVStep, PagedKVConfig from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.recurrent.config import ( RecurrentBlockConfig, diff --git a/test/modular/test_conductor_replica_assignment.py b/test/modular/test_conductor_replica_assignment.py index 8d3ff72b2d..5e4c1d31f0 100644 --- a/test/modular/test_conductor_replica_assignment.py +++ b/test/modular/test_conductor_replica_assignment.py @@ -1,34 +1,107 @@ -"""Data-parallel replica choice: a new request goes to the replica serving the -fewest live requests, so concurrent requests spread over the replicas instead of -landing on one at random. The load is per-(node group, replica) counters the -conductor keeps as requests register and drop.""" -from collections import Counter +"""Data-parallel replica choice: a new request goes to the replica where its cost +is lowest, the live requests on the replica plus ``routing_cost`` of the facts +the mirrors predict there (a KV cache: minus the share of the prompt it already +holds). With no mirror that is the replica serving the fewest live requests, so +concurrent requests spread over the replicas instead of landing on one at random.""" +import math from types import SimpleNamespace import pytest -pytest.importorskip("torch") +torch = pytest.importorskip("torch") from mstar.conductor.conductor import Conductor # noqa: E402 +from mstar.conductor.routing import ReplicaRouter, RoutingWeights, routing_cost # noqa: E402 +from mstar.engine.resources.kv import manager as manager_mod # noqa: E402 +from mstar.engine.resources.kv.config import ( # noqa: E402 + KVReqConfig, + KVSpec, + KVStep, + PagedKVConfig, + PrefixSpan, + StreamLayout, +) +from mstar.engine.resources.kv.keys import chain # noqa: E402 +from mstar.engine.resources.kv.manager import KVManager # noqa: E402 +from mstar.engine.resources.recurrent.config import ( # noqa: E402 + RecurrentBlockConfig, + RecurrentStateConfig, + RecurrentStateSpec, +) +from mstar.engine.resources.spec import RoutingContext, RoutingFacts # noqa: E402 +from mstar.engine.resources.step import Segment, StepContext # noqa: E402 from mstar.model.base import WorkerGraph # noqa: E402 +from mstar.model.submodule_base import ARNodeInputs # noqa: E402 +PAGE = 4 -def _wg(group_id, ranks, sp_size=1): - return WorkerGraph(section=None, graph_walks=set(), ranks=list(ranks), sp_size=sp_size, _group_id=group_id) +@pytest.fixture(autouse=True, params=["first", "last"]) +def tie(request, monkeypatch): + """Ties go to the first replica, then to the last, so a case that a tie would + pass by luck fails under one of them when what it tests is gone.""" + pick = (lambda seq: seq[0]) if request.param == "first" else (lambda seq: seq[-1]) + monkeypatch.setattr("mstar.conductor.routing.random.choice", pick) -def _conductor(worker_graphs): + +def _wg(group_id, ranks, sp_size=1, nodes=("llm",), walk="prefill"): + return WorkerGraph( + section=SimpleNamespace(get_nodes=lambda: dict.fromkeys(nodes)), graph_walks={walk}, + ranks=list(ranks), sp_size=sp_size, _group_id=group_id, + ) + + +class _Model: + """What the router reads of a model: its partitions, and the walks that key each KV label.""" + + def __init__(self, keyed=None, partitions=None): + self._keyed = {"kv": {"main": ("prefill",)}} if keyed is None else keyed + self._partitions = partitions or [SimpleNamespace(name="default", graph_walks={"prefill"})] + + def get_partitions(self): + return self._partitions + + def kv_labels(self): + return { + key: {label: SimpleNamespace(keys=SimpleNamespace(walks=walks)) for label, walks in labels.items()} + for key, labels in self._keyed.items() + } + + def checkpoint_path(self): + return "/a/checkpoint" + + +def _conductor(worker_graphs, specs=(), weights=None, model=None): conductor = object.__new__(Conductor) conductor.worker_graphs = worker_graphs conductor.requests = {} - conductor._replica_load = Counter() + conductor._router = ReplicaRouter(model or _Model(), worker_graphs.values(), specs=specs, weights=weights) return conductor -def _admit(conductor, rid): - replicas = conductor._pick_replicas() - conductor._register_request(rid, SimpleNamespace(dp_replicas=replicas)) - return conductor._assign_worker_graphs_to_workers(replicas) +def _configs(model_kwargs: dict) -> dict: + """The request's resource configs, opened as ``_do_ingest_request`` opens them.""" + configs = {} + for key, keys in model_kwargs.get("prefix_keys", {}).items(): + configs[key] = KVReqConfig(needed_labels=["main"]) + configs[key].apply_conductor_config( + prefix_keys=keys, kv_layout=model_kwargs["kv_layout"][key], prefix_cache=model_kwargs.get("prefix_cache"), + ) + return configs + + +def _admit(conductor, rid, model_kwargs=None, passes=1): + """What ``_do_ingest_request`` does for the pick, and nothing else. The + request's partition has had ``passes`` passes come back when it ends.""" + configs = _configs(model_kwargs or {}) + router = conductor._router + groups_run = router.groups_run(["default"]) + placement = router.pick(configs, groups_run) + conductor._register_request(rid, SimpleNamespace( + routing=router.add(placement, configs, groups_run), + partition_states={"default": SimpleNamespace(fwd_pass_number=passes)}, + )) + return conductor._assign_worker_graphs_to_workers(placement.replicas) def test_requests_alternate_over_dp_replicas(): @@ -42,7 +115,7 @@ def test_requests_alternate_over_dp_replicas(): # a request leaving frees its replica's count, once conductor._drop_request("a") conductor._drop_request("a") - assert sorted(conductor._replica_load.values()) == [0, 1] + assert sorted(conductor._router._load.values()) == [0, 1] assert _admit(conductor, "c")[0] == first[0] @@ -59,3 +132,406 @@ def test_groups_sharing_a_worker_balance_independently(): conductor = _conductor({0: _wg(0, [0]), 1: _wg(1, [0, 1])}) picks = [_admit(conductor, rid)[1][0] for rid in "abcd"] assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] + + +# ── the KV cache's mirror ──────────────────────────────────────────────── + + +def _kv_spec(): + return KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=64, page_size=PAGE, + )) + + +def _kv_conductor(weights=None): + spec = _kv_spec() + conductor = _conductor({0: _wg(0, [0, 1])}, specs=[spec], weights=weights) + # the model's specs, then each worker's, as `_node_resources` and `_resource_specs` build them + conductor._node_resources_cache = [spec] + conductor._resource_specs_cache = [{"kv": spec}] + return conductor + + +def _prompt(prefix: str, pages: int = 4, unkeyed: int = 0, keys=("kv",)) -> dict: + """The kwargs of a request whose prompt is ``pages`` whole pages keyed under + ``prefix``, then ``unkeyed`` positions the data worker leaves unkeyed, in + each KV resource of ``keys``.""" + spans = [(pages * PAGE, pages * PAGE, "prefill")] + [(unkeyed, unkeyed, "prefill")] * bool(unkeyed) + return { + "prefix_keys": {key: {"main": [f"{prefix}{i}".encode() for i in range(pages)]} for key in keys}, + "kv_layout": {key: {"main": (spans, (), 0, None, 1)} for key in keys}, + } + + +def _replica(conductor, rid, model_kwargs, passes=1) -> str: + return _admit(conductor, rid, model_kwargs, passes)[0][0] + + +def _mirrors(router): + return [m.mirror for unit in router._units for m in unit.mirrors] + + +def _held(mirror) -> int: + """The pages live requests hold, over every replica: each indexed page has the index as one owner.""" + pools = zip(mirror._arenas, mirror._indexes, strict=True) + return sum(sum(arena.num_owners) - index.num_pages() for arena, index in pools) + + +def _cached(mirror) -> int: + return sum(index.num_pages() for index in mirror._indexes) + + +def _place_a(conductor) -> str: + """Request "a" (prefix P) on the replica a tie would not pick, with the + replicas left equally loaded and nothing of P's on the other one.""" + _replica(conductor, "x", _prompt("X")) + a = _replica(conductor, "a", _prompt("P")) + conductor._drop_request("x") + return a + + +def test_same_prefix_requests_co_locate_before_any_completion(): + conductor = _kv_conductor() + # a burst: no request has completed, so only placements fed the mirror + a = _place_a(conductor) + assert _replica(conductor, "b", _prompt("Q")) != a, ( + "a request with nothing cached anywhere went to the busier replica" + ) + assert _replica(conductor, "c", _prompt("P")) == a, ( + "with equal load, a request did not follow its prefix to the replica placed with it" + ) + + +def test_a_hot_prefix_follows_its_hit_until_load_outweighs_it(): + conductor = _kv_conductor() + a = _place_a(conductor) + _replica(conductor, "b", _prompt("Q")) + # each request matches 4 of its 5 pages on replica a, worth 0.8 * prefix live requests + picks = [_replica(conductor, f"p{i}", _prompt("P", pages=5)) for i in range(16)] + stayed = picks.index(next(p for p in picks if p != a)) + assert stayed == math.ceil(0.8 * RoutingWeights().prefix) > 1, ( + f"a hot prefix took {stayed} more requests on its replica before one spread" + ) + + +def test_two_caches_on_one_replica_credit_a_hit_less_than_one_request(): + # two keyed caches whose nodes share the replicas: their hits are one share of the prompt, not one each + specs = [ + KVSpec(resource_key=key, nodes={node}, config=_kv_spec().config) + for key, node in (("kv", "llm"), ("kv2", "llm2")) + ] + model = _Model(keyed={"kv": {"main": ("prefill",)}, "kv2": {"main": ("prefill",)}}) + conductor = _conductor({0: _wg(0, [0, 1], nodes=("llm", "llm2"))}, specs=specs, model=model, + weights={"prefix": 1}) + both = ("kv", "kv2") + _replica(conductor, "x", _prompt("X", keys=both)) + a = _replica(conductor, "a", _prompt("P", keys=both)) + conductor._drop_request("x") + _replica(conductor, "b", _prompt("Q", keys=both)) + assert _replica(conductor, "c", _prompt("P", keys=both)) == a + assert _replica(conductor, "d", _prompt("P", keys=both)) != a, ( + "two caches' hits outweighed a live request, so a hot prefix stayed on the busier replica" + ) + + +def test_a_request_that_ends_before_a_pass_comes_back_leaves_nothing_cached(): + # aborted while queued, say: the worker never indexed its pages + conductor = _kv_conductor() + a = _place_a(conductor) + _replica(conductor, "q", _prompt("Q")) + # P's 4 pages, then 2 more that only b indexes + assert _replica(conductor, "b", _prompt("P", pages=6), passes=0) == a + conductor._drop_request("b") + (mirror,) = _mirrors(conductor._router) + assert mirror.facts(_configs(_prompt("P", pages=6))["kv"])[int(a[-1])].kv_hit == 4 * PAGE, ( + "the pages only the unrun request indexed are still predicted cached" + ) + + +def test_warmup_copies_of_one_prompt_spread_over_the_replicas(): + # as the startup warmup sends one copy per replica, before any completes, + # with the prefix cache off so that no predicted hit gathers them + conductor = _kv_conductor() + picks = [_replica(conductor, rid, {**_prompt("P"), "prefix_cache": False}) for rid in "abcd"] + assert sorted(picks) == ["worker_0", "worker_0", "worker_1", "worker_1"] + + +def test_a_hit_is_priced_as_its_share_of_the_whole_prompt(): + conductor = _kv_conductor() + # as BAGEL lays out a generation: a keyed text span, then image positions the data worker leaves unkeyed + kwargs = _prompt("P", pages=2, unkeyed=4000) + a = int(_replica(conductor, "a", kwargs)[-1]) + (mirror,) = [m.mirror for unit in conductor._router._units for m in unit.mirrors] + facts = mirror.facts(_configs(kwargs)["kv"]) + # the worker matches one of the two keyed pages, which saves PAGE of 2 * PAGE + 4000 positions + assert facts[a] == RoutingFacts(work=2 * PAGE + 4000, kv_hit=PAGE) + assert facts[1 - a] == RoutingFacts(work=2 * PAGE + 4000, kv_hit=0) + weights = RoutingWeights() + assert routing_cost(facts[a], weights) == pytest.approx(-weights.prefix * PAGE / (2 * PAGE + 4000)) + assert routing_cost(facts[1 - a], weights) == 0 + # a node no mirror reports on prices at 0 + assert routing_cost(RoutingFacts(), weights) == 0 + + +def test_a_hit_runs_on_to_an_item_cached_inside_the_next_page(): + def kwargs(after: bytes) -> dict: + # as BAGEL lays out an image that ends inside a page: a page of text, the + # image's last PAGE // 2 positions, keyed apart up to its end, then other text + spans = [(PAGE, PAGE, "prefill"), (PAGE // 2, PAGE // 2, "prefill", 0, b"image", b"image end"), + (3 * PAGE // 2, 3 * PAGE // 2, "prefill")] + return { + "prefix_keys": {"kv": {"main": [b"text", after + b"1", after + b"2"]}}, + "kv_layout": {"kv": {"main": (spans, (), 0, None, 3)}}, + } + + conductor = _kv_conductor() + a = int(_replica(conductor, "a", kwargs(b"A"))[-1]) + (mirror,) = _mirrors(conductor._router) + assert mirror.facts(_configs(kwargs(b"B"))["kv"])[a].kv_hit == PAGE + PAGE // 2, ( + "a prompt sharing an image cached up to its end inside a page was predicted to stop at the page before" + ) + + +def test_a_request_that_ends_unrun_leaves_what_another_filed_in_its_items_end_page(): + # four pages: a holds two and the index a third, its image's end + mirror = KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=5, page_size=PAGE, + )).routing_mirror(RoutingContext(1, frozenset({"prefill"}), {"main": ("prefill",)}, True)) + + def config(keys, *spans): + return KVReqConfig(prefix_keys={"main": keys}, kv_layout={"main": StreamLayout(spans, keyed_spans=len(spans))}) + + a = mirror.add_request(config( + [b"A0", b"A1"], PrefixSpan(PAGE, PAGE, "prefill"), + PrefixSpan(PAGE // 2, PAGE // 2, "prefill", 0, b"image", b"image end"), + ), 0) + # b evicts a's image end and files its own second page in that page, then runs + b = [b"B0", b"B1", b"B2"] + mirror.remove_request(mirror.add_request(config(b[:2], PrefixSpan(2 * PAGE, 2 * PAGE, "prefill")), 0), True) + # a, aborted while queued + mirror.remove_request(a, False) + (facts,) = mirror.facts(config(b, PrefixSpan(3 * PAGE, 3 * PAGE, "prefill"))) + assert facts.kv_hit == 2 * PAGE, "a request that never ran took back an entry another request filed" + + +def test_a_prefix_weight_of_0_picks_by_load_alone(): + picks = [] + for conductor in (_conductor({0: _wg(0, [0, 1])}), _kv_conductor(weights={"prefix": 0})): + _place_a(conductor) + # equal loads, then a request whose prefix only a's replica holds + picks.append([_replica(conductor, rid, _prompt(prefix)) for rid, prefix in (("b", "Q"), ("c", "P"))]) + assert picks[0] == picks[1] + + +def test_a_dropped_request_releases_its_reservation_once_and_its_pages_stay_cached(): + conductor = _kv_conductor() + a = _place_a(conductor) + # dropped twice, as an abort racing a completion can + conductor._drop_request("a") + conductor._drop_request("a") + assert not any(conductor._router._load.values()) + (mirror,) = _mirrors(conductor._router) + assert not _held(mirror), "a dropped request still holds its pages" + # with both replicas idle, the prefix it left cached decides + assert _replica(conductor, "b", _prompt("P")) == a + + +def test_a_request_that_runs_none_of_a_resources_nodes_takes_no_part_in_its_mirror(): + # an encoder group and the LLM's on the same ranks pick together; the cache is the LLM's + router = ReplicaRouter( + _Model(partitions=[SimpleNamespace(name="encoder", graph_walks={"encode"}), + SimpleNamespace(name="default", graph_walks={"prefill"})]), + [_wg(0, [0, 1], nodes=("enc",), walk="encode"), _wg(1, [0, 1])], specs=[_kv_spec()], + ) + configs = _configs(_prompt("P")) + groups_run = router.groups_run(["encoder"]) + router.add(router.pick(configs, groups_run), configs, groups_run) + (mirror,) = _mirrors(router) + assert not _held(mirror), ( + "a request that runs only the encoder reserved pages in the LLM's cache" + ) + + +def test_a_request_refused_at_ingest_leaves_nothing_in_the_mirrors(): + conductor = _kv_conductor() + walk = SimpleNamespace(request_done=False, step_metadata={}, full_metadata=SimpleNamespace( + graph_walk="prefill", kwargs={}, + )) + conductor.model = SimpleNamespace( + LENGTH_KWARGS=("max_output_tokens",), + get_partitions=lambda: [SimpleNamespace(name="default", graph_walks={"prefill"})], + get_partition_topology=lambda: SimpleNamespace(connections=[]), + get_initial_forward_pass_args=lambda **kw: walk, + get_max_output_tokens=lambda **kw: 8, + get_loop_caps=lambda **kw: {}, + get_request_resource_configs=lambda **kw: {}, + # what ingest reads for the partitions a keyed node streams into + kv_labels=_Model().kv_labels, + get_graph_walk_graphs=lambda: {}, + ) + conductor._status_interval_s = None + conductor._loop_max_iters = {} + conductor._kv_labels = {"kv": ("main",)} + conductor._build_request_sharding_config = lambda workers: None + refused = [] + conductor._reject_request = lambda rid, error, status: refused.append(status) + conductor._admit_request(SimpleNamespace( + # 80 prompt positions, past the pool's max_seq_len of 64: a 400 in validate + request_id="a", client_request_id=None, model_kwargs=_prompt("P", unkeyed=64), initial_signals={}, + initial_input_modalities=["text"], initial_output_modalities=["text"], + )) + assert refused == [400] and not conductor.requests + (mirror,) = _mirrors(conductor._router) + assert not _held(mirror) and not _cached(mirror), ( + "a request refused before dispatch left its prefix predicted cached" + ) + assert not any(conductor._router._load.values()) + + +@pytest.mark.parametrize("worker_graphs,nodes,walks,where", [ + # BAGEL with CFG-parallel nodes: its `kv` spans LLM, LLM_cfg_text and + # LLM_cfg_img, each its own group, and only LLM runs the keyed walks + ([_wg(0, [0, 1], nodes=("LLM",), walk="prefill_text"), _wg(0, [0, 1], nodes=("vit", "LLM"), walk="prefill_vit"), + _wg(1, [2, 3], nodes=("LLM_cfg_text",), walk="image_gen_cfg"), + _wg(2, [4, 5], nodes=("LLM_cfg_img",), walk="image_gen_cfg")], + {"LLM", "LLM_cfg_text", "LLM_cfg_img"}, ("prefill_text", "prefill_vit"), [(0, 1)]), + # the same, with the CFG nodes in LLM's group + ([_wg(0, [0, 1], nodes=("LLM", "LLM_cfg_text"), walk="prefill_text"), + _wg(0, [0, 1], nodes=("LLM_cfg_text",), walk="image_gen_cfg")], + {"LLM", "LLM_cfg_text"}, ("prefill_text",), [(0, 1)]), + # keyed walks on two of the spec's nodes, in groups on other ranks: a mirror on each + ([_wg(0, [0, 1], nodes=("X",), walk="prefill_text"), _wg(1, [2, 3], nodes=("Y",), walk="prefill_vit")], + {"X", "Y"}, ("prefill_text", "prefill_vit"), [(0, 1), (2, 3)]), + # no walk keys the cache: no mirror to keep + ([_wg(0, [0, 1], nodes=("LLM",), walk="prefill")], {"LLM"}, (), []), + # one node at one rank for one walk and at two for another: without prefix_cache_tp + # the two-rank replicas keep the cache shut, so only the one-rank set has a mirror + ([_wg(0, [0, 1], walk="prefill_text"), _wg(1, [2, 3, 4, 5], sp_size=2, walk="prefill_vit")], + {"llm"}, ("prefill_text", "prefill_vit"), [(0, 1)]), +], ids=[ + "bagel_cfg_parallel", "cfg_nodes_in_the_llm_group", "keyed_walks_on_two_nodes", "unkeyed", "tp1_and_tp2_groups", +]) +def test_a_cache_has_a_mirror_where_a_walk_that_keys_it_runs(worker_graphs, nodes, walks, where): + spec = KVSpec(resource_key="kv", nodes=nodes, config=_kv_spec().config) + every_walk = set().union(*(wg.graph_walks for wg in worker_graphs)) + model = _Model( + keyed={"kv": {"main": walks}} if walks else {}, + partitions=[SimpleNamespace(name="default", graph_walks=every_walk)], + ) + router = ReplicaRouter(model, worker_graphs, specs=[spec]) + assert [unit.instances[0] for unit in router._units for _ in unit.mirrors] == [(rank,) for rank, _ in where] + if not where: + return + groups_run = router.groups_run(["default"]) + + def place(prefix): + configs = _configs(_prompt(prefix)) + placement = router.pick(configs, groups_run) + return placement.replicas[0], router.add(placement, configs, groups_run) + + # as _place_a, then one request on the other replica, so the loads are equal + _, x = place("X") + a, _ = place("P") + router.remove(x, ["default"]) + assert place("Q")[0] != a + assert place("P")[0] == a, "a request did not follow its prefix to the replica its node cached it on" + + +def test_a_request_mirrored_on_two_sets_of_replicas_saves_one_share_of_its_prompt(): + # the keyed_walks_on_two_nodes shape: the cache's nodes in groups on other ranks, a mirror for each + walks = ("prefill_text", "prefill_vit") + router = ReplicaRouter( + _Model(keyed={"kv": {"main": walks}}, partitions=[SimpleNamespace(name="default", graph_walks=set(walks))]), + [_wg(0, [0, 1], nodes=("X",), walk=walks[0]), _wg(1, [2, 3], nodes=("Y",), walk=walks[1])], + specs=[KVSpec(resource_key="kv", nodes={"X", "Y"}, config=_kv_spec().config)], + ) + configs = _configs(_prompt("P")) + groups_run = router.groups_run(["default"]) + for _ in range(2): + router.add(router.pick(configs, groups_run), configs, groups_run) + # the second request is predicted to hold 3 of its 4 pages on the replica it went to, in each set + assert router.predicted_saving._values[("prefix",)] == pytest.approx(0.75), ( + "a request added a share of its prompt per set of replicas, not one" + ) + + +@pytest.mark.parametrize("prefix_slots, mirrored", [(0, False), (2, True)]) +def test_a_cache_on_a_node_whose_recurrent_pool_keeps_no_snapshots_has_no_mirror(prefix_slots, mirrored): + """As Qwen3.5's GDN state beside its KV cache: without snapshots the workers + keep the node's caches shut, so a mirror would predict hits nothing serves.""" + pool = RecurrentStateSpec(resource_key="state", nodes={"llm"}, config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=None)}, + prefix_slots=prefix_slots, kv_cache="kv", + )) + router = ReplicaRouter(_Model(), [_wg(0, [0, 1])], specs=[_kv_spec(), pool]) + assert bool(_mirrors(router)) == mirrored + + +# ── the KV mirror beside the real cache ────────────────────────────────── + + +class _NoTransfer: + def __init__(self, transfer_engine_info, kv_cache, **kwargs): + pass + + def remove_request(self, request_id): + pass + + def cleanup(self): + pass + + +def test_the_kv_mirror_predicts_the_hits_the_real_cache_serves(monkeypatch): + """One replica's ``KVManager`` and its mirror over the same requests: every + prediction is the hit the cache serves. Each prompt is four keyed pages and a + one-token tail page, in room for two, so ends and evictions interleave: the + index evicts its oldest stamp first (a hit or an insert, not an end), and + counts the pages no key names.""" + monkeypatch.setattr(manager_mod, "KVTransferManager", _NoTransfer) + page, node, walk = 16, "LLM", "prefill" + config = PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, max_num_pages=2 * 5 + 1, page_size=page, + ) + kv = KVManager( + cfg=config, name="kv", joint_comm_group=None, transfer_engine_info=None, + device=torch.device("cpu"), dtype=torch.float32, + ) + kv.enable_prefix_cache(b"a root") + mirror = KVSpec(resource_key="kv", nodes={node}, config=config).routing_mirror( + RoutingContext(1, frozenset({walk}), {"main": (walk,)}, True), + ) + + def request_config(first): + tokens = list(range(first, first + 4 * page + 1)) + return tokens, KVReqConfig( + # as the data worker keys a prompt: every page, the partial last one included + prefix_keys={"main": chain([tokens[at:at + page] for at in range(0, len(tokens), page)])}, + prefix_tail={"main": tokens[4 * page:]}, + kv_layout={"main": StreamLayout(spans=(PrefixSpan(len(tokens), len(tokens), walk),), keyed_spans=1)}, + ) + + live, predicted, served = {}, [], [] + for event, rid, first in [ + ("add", "a", 0), ("add", "b", 1000), ("end", "b", 0), ("end", "a", 0), ("add", "c", 2000), + ("end", "c", 0), ("add", "a2", 0), ("end", "a2", 0), ("add", "b2", 1000), ("end", "b2", 0), + ("add", "c2", 2000), + ]: + if event == "end": + kv.remove_request(rid) + mirror.remove_request(live.pop(rid), True) + continue + tokens, cfg = request_config(first) + (facts,) = mirror.facts(cfg) + predicted.append(facts.kv_hit) + live[rid] = mirror.add_request(cfg, 0) + kv.ingest_request(rid, request_config(first)[1]) + hit = kv.resolve_cached_prefix(rid, node, walk, ARNodeInputs(input_seq_len=len(tokens))) + served.append(hit.tokens if hit else 0) + # the walk runs what the cache does not hold + step = KVStep(segments=(Segment(rid, "main", len(tokens) - served[-1]),)) + ctx = StepContext(request_ids=(rid,), graph_walk=walk, slot=0, capture=False) + assert kv.admit(step, ctx).ok + kv.plan(step, ctx) + kv.commit(step, ctx) + assert any(served), "no request hit, so the sequence pins nothing" + assert predicted == served diff --git a/test/modular/test_conductor_tick_exception.py b/test/modular/test_conductor_tick_exception.py index 1ad563c446..c5d4feaed1 100644 --- a/test/modular/test_conductor_tick_exception.py +++ b/test/modular/test_conductor_tick_exception.py @@ -7,7 +7,7 @@ tick carries on. """ import re -from collections import Counter, deque +from collections import deque from types import SimpleNamespace import pytest @@ -106,7 +106,6 @@ def _conductor(*ticks, requests): c._startup_message_backlog = [] c.requests = dict(requests) c.draining = {} - c._replica_load = Counter() c.waiting_queue = [] c.max_concurrent_requests = None c._early_reads_done = {} diff --git a/test/modular/test_gdn_prefix_snapshots.py b/test/modular/test_gdn_prefix_snapshots.py index a6b56c690b..35f9ef235f 100644 --- a/test/modular/test_gdn_prefix_snapshots.py +++ b/test/modular/test_gdn_prefix_snapshots.py @@ -55,9 +55,10 @@ def _build(device): kv = KVSpec("kv", {"llm"}, PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4 * PAGE, page_size=PAGE, )) - pool = RecurrentStatePool.build(spec, EngineResourceInfo(device=device, dependencies={"kv": kv})) + pool = RecurrentStatePool.build( + spec, EngineResourceInfo(device=device, dependencies={"kv": kv}, prefix_caches=frozenset({POOL, "kv"})), + ) pool.bind_kv(_StubChains()) - assert pool.enable_prefix_cache(b"a root") manager = LinearAttnManager.build( LinearAttnSpec(GDN, {"llm"}, LinearAttnConfig(recurrent_state=POOL, variant=LinearAttnVariant.GDN)), EngineResourceInfo(device=device, dependencies={POOL: spec}), diff --git a/test/modular/test_kv_admission.py b/test/modular/test_kv_admission.py index 0704944807..74cfdc2aab 100644 --- a/test/modular/test_kv_admission.py +++ b/test/modular/test_kv_admission.py @@ -36,6 +36,7 @@ from mstar.engine.resources import StepRunner from mstar.engine.resources.base import CachedPrefix, EngineResourceInfo from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import ( KVReqConfig, @@ -47,7 +48,7 @@ StreamLayout, ) from mstar.engine.resources.kv.keys import chain, fingerprint -from mstar.engine.resources.kv.manager import KVManager, KVSequenceInfo, PageArena, PublishedKVInfo +from mstar.engine.resources.kv.manager import KVManager, KVSequenceInfo, PublishedKVInfo from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.recurrent.config import ( RecurrentBlockConfig, diff --git a/test/modular/test_kv_host_index.py b/test/modular/test_kv_host_index.py index 0f44863451..51e47d21a9 100644 --- a/test/modular/test_kv_host_index.py +++ b/test/modular/test_kv_host_index.py @@ -11,11 +11,12 @@ import torch from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import PageAllocator from mstar.engine.resources.kv.config import KVReqConfig, KVStep, PagedKVConfig, PrefixSpan, StreamLayout from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool from mstar.engine.resources.kv.keys import chain -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.step import Segment, StepContext from mstar.model.submodule_base import ARNodeInputs diff --git a/test/modular/test_kv_layout_intake.py b/test/modular/test_kv_layout_intake.py index a68d554380..69e15b7c81 100644 --- a/test/modular/test_kv_layout_intake.py +++ b/test/modular/test_kv_layout_intake.py @@ -62,6 +62,9 @@ class _Model(Model): def __init__(self, layout=LAYOUT, max_seq_len=4096): self._layout, self._max_seq_len = layout, max_seq_len + def checkpoint_path(self): + return "/a/checkpoint" + def get_node_resources(self): return [KVSpec(resource_key="kv", nodes={"llm"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=self._max_seq_len, max_num_pages=64, page_size=PS, @@ -119,11 +122,14 @@ def get_submodule(self, *args, **kwargs): return None -def _preprocess(model: _Model, model_kwargs: dict) -> dict: +def _preprocess(model: _Model, model_kwargs: dict, **config) -> dict: worker = PreprocessWorkerThread( *(queue.Queue() for _ in range(8)), stop_event=threading.Event(), communicator=_Comm(), tensor_manager=_StubTensorManager(), model=model, - model_config={"model": "stub", "resources": {"kv": {"page_size": PS}}}, + model_config={ + "model": "stub", "resources": {"kv": {"page_size": PS}}, + "node_groups": [{"node_names": ["llm", "talker"], "ranks": [0]}], **config, + }, ) worker._process_input(PreprocessInput( request_id="r", text="hello", file_paths=None, input_modalities=["text"], @@ -189,6 +195,24 @@ def test_a_layout_reaches_its_streams_as_footprints(tmp_path, monkeypatch, prefi assert kv._ensure_label("r", "uncond").footprint == -(-(10 + 2 * 40 + 7) // PS) +class _NamesNoCheckpoint(_Model): + checkpoint_path = Model.checkpoint_path + + +@pytest.mark.parametrize("model,config,model_kwargs,keyed", [ + (_Model, {}, {}, True), + # replicas of two ranks: the pool keeps its cache closed (prefix_cache_tp is refused with replicas) + (_Model, {"node_groups": [{"node_names": ["llm", "talker"], "ranks": [0, 1, 2, 3], "tp_size": 2}]}, {}, False), + # off, as the worker reads KVReqConfig.prefix_cache + (_Model, {}, {"prefix_cache": 0}, False), + # no checkpoint and no salt to root the cache in: the engine keeps it closed + (_NamesNoCheckpoint, {}, {}, False), +], ids=["keyed", "dp_tp", "prefix_cache_0", "no_checkpoint"]) +def test_a_prompt_is_keyed_only_where_its_cache_opens(model, config, model_kwargs, keyed): + kwargs = _preprocess(model(), model_kwargs, **config) + assert ("prefix_keys" in kwargs) == keyed + + def test_a_cap_past_its_loop_is_refused(tmp_path, monkeypatch): model = _Model() diff --git a/test/modular/test_kv_page_ownership.py b/test/modular/test_kv_page_ownership.py index 420a5d5dc1..26012d1383 100644 --- a/test/modular/test_kv_page_ownership.py +++ b/test/modular/test_kv_page_ownership.py @@ -21,9 +21,10 @@ import torch from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import KVStep, PagedKVConfig -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.plan import SINK_PAGE from mstar.engine.resources.step import Segment, StepContext diff --git a/test/modular/test_kv_prefix_index.py b/test/modular/test_kv_prefix_index.py index 60c0b86be4..22c4df0022 100644 --- a/test/modular/test_kv_prefix_index.py +++ b/test/modular/test_kv_prefix_index.py @@ -17,9 +17,9 @@ import pytest import torch +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator from mstar.engine.resources.kv.config import PagedKVConfig -from mstar.engine.resources.kv.manager import PageArena from mstar.engine.resources.kv.prefix_index import PrefixIndex PAGE_SIZE = 16 diff --git a/test/modular/test_kv_prefix_logs.py b/test/modular/test_kv_prefix_logs.py index bd3941bb53..be3657901b 100644 --- a/test/modular/test_kv_prefix_logs.py +++ b/test/modular/test_kv_prefix_logs.py @@ -78,7 +78,8 @@ def _manager(prefix_cache: bool = True, walks=None) -> KVManager: ), device=torch.device("cpu"), dtype=torch.float32, ) - kv.enable_prefix_cache(ROOT, walks) + if prefix_cache: # as the engine opens only the caches that open + kv.enable_prefix_cache(ROOT, walks) return kv diff --git a/test/modular/test_kv_prefix_request_keys.py b/test/modular/test_kv_prefix_request_keys.py index 8af7d6be03..11c6554a92 100644 --- a/test/modular/test_kv_prefix_request_keys.py +++ b/test/modular/test_kv_prefix_request_keys.py @@ -20,7 +20,7 @@ import torch from test_ingest_unpersist import _conductor, _ToyModel -from mstar.api_server.data_worker import PreprocessWorkerThread +from mstar.api_server.data_worker import PreprocessWorkerThread, _kv_page_sizes from mstar.api_server.request_types import PreprocessInput from mstar.conductor.conductor import Conductor from mstar.conductor.request_info import CurrentForwardConductorMetadata, PartitionDefinition @@ -99,6 +99,10 @@ def kv_labels(self): def max_input_files(self): return {} + def checkpoint_path(self): + # a model that names no checkpoint and sets no salt keys nothing + return "/a/checkpoint" + def get_node_resources(self): return [KVSpec( resource_key="kv", nodes={"LLM"}, @@ -131,7 +135,10 @@ def _worker(model, model_config: dict | None) -> PreprocessWorkerThread: def _deployment(page_size: int = PAGE_SIZE) -> dict: - return {"model": "stub", "resources": {"kv": {"page_size": page_size}}} + return { + "model": "stub", "resources": {"kv": {"page_size": page_size}}, + "node_groups": [{"node_names": ["LLM"], "ranks": [0]}], + } def _apply_chain(cfg, key: str, model_kwargs: dict | None) -> None: @@ -332,6 +339,30 @@ def test_each_resource_config_is_handed_only_its_own_chain(): ) +def test_a_cache_every_engine_holding_it_keeps_shut_is_not_keyed(): + class _Thinker: + """A cache on a two-rank node without prefix_cache_tp, so its engines keep it shut.""" + + def get_node_resources(self): + return [KVSpec("kv", {"Thinker"}, PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, page_size=PAGE_SIZE, + ))] + + def checkpoint_path(self): + return "/a/checkpoint" + + # qwen3omni_thinker_tp2's placement: rank 2 holds none of the cache's nodes + config = {"node_groups": [ + {"node_names": ["Thinker"], "ranks": [0, 1], "tp_size": 2}, + {"node_names": ["audio_encoder", "vision_encoder"], "ranks": [0]}, + {"node_names": ["Talker"], "ranks": [2]}, + {"node_names": ["Code2Wav"], "ranks": [2]}, + ]} + assert _kv_page_sizes(_Thinker(), config) == {}, ( + "every prompt was keyed and its media hashed for a cache no engine opens" + ) + + # ── one request opting out ────────────────────────────────────────────── diff --git a/test/modular/test_kv_prefix_root.py b/test/modular/test_kv_prefix_root.py index e704318be9..fbcebfb8d5 100644 --- a/test/modular/test_kv_prefix_root.py +++ b/test/modular/test_kv_prefix_root.py @@ -21,6 +21,7 @@ import logging import re import sys +from dataclasses import dataclass from types import SimpleNamespace sys.path.insert(0, ".") @@ -30,9 +31,16 @@ from mstar.conductor.request_info import PartitionDefinition from mstar.engine.engine import Engine -from mstar.engine.resources import Resource +from mstar.engine.resources import NodeResourceSpec, Resource from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVReqConfig, KVSpec, PagedKVConfig, PrefixSpan, StreamLayout +from mstar.engine.resources.kv.config import ( + KVReqConfig, + KVSpec, + PagedKVConfig, + PrefixSpan, + StreamLayout, + opening_prefix_caches, +) from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.position.config import PositionConfig, PositionSpec from mstar.engine.resources.position.manager import RopeManager @@ -115,9 +123,10 @@ def _checkpoint(root, config: bytes) -> str: def _kv(dtype=torch.float32, **overrides) -> KVManager: + """A salted pool, so it opens for a model that names no checkpoint.""" cfg = dict( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, - max_num_pages=16, page_size=16, + max_num_pages=16, page_size=16, prefix_cache_salt="a salt", ) cfg.update(overrides) return KVManager( @@ -132,8 +141,16 @@ def _rope(**overrides) -> RopeManager: return rope -def _root(kv=None, rope=None, model=None) -> bytes: - """Run the engine's fold over one KV resource and one resource above it.""" +def _open_caches(engine: Engine, specs: dict, model, instance: dict) -> None: + """`Engine._open_prefix_caches` given the rule's caches, as `Engine.load_model` evaluates them.""" + checkpoint = model.checkpoint_path() + opened = opening_prefix_caches(specs.values(), instance, checkpoint_named=checkpoint is not None) + engine._open_prefix_caches(specs, model, instance, opened, checkpoint) + + +def _root(kv=None, rope=None, model=None, instance=None) -> bytes: + """Run the engine's fold over one KV resource and one resource above it, on + nodes whose lockstep instances are ``instance`` (one rank by default).""" kv = kv or _kv() rope = rope or _rope() engine = Engine.__new__(Engine) @@ -144,7 +161,7 @@ def _root(kv=None, rope=None, model=None) -> bytes: resource_key=ROPE, nodes={"LLM"}, config=rope._config, ), } - engine._open_prefix_caches(specs, model or _Model()) + _open_caches(engine, specs, model or _Model(), instance or {"LLM": 1}) return kv._prefix_root @@ -195,9 +212,8 @@ def test_the_root_changes_with_the_checkpoint(tmp_path): def test_a_rank_above_one_never_opens_its_index(): kv = _kv() - kv._world_size = 2 - _root(kv=kv) + _root(kv=kv, instance={"LLM": 2}) assert kv._index is None and kv._prefix_root is None, ( "the index opened at a world size that cannot agree on a match length" @@ -215,7 +231,7 @@ def test_a_deployment_can_turn_the_cache_off(): def test_a_model_naming_no_checkpoint_keeps_its_cache_shut(caplog): - kv = _kv() + kv = _kv(prefix_cache_salt="") with caplog.at_level(logging.INFO, logger=Engine.__module__): _root(kv=kv, model=_Declaring()) @@ -239,7 +255,7 @@ def test_a_salt_opens_the_cache_of_a_model_naming_no_checkpoint(): def test_a_model_naming_a_checkpoint_opens_its_cache(tmp_path): - kv = _kv() + kv = _kv(prefix_cache_salt="") _root(kv=kv, model=_Declaring(checkpoint=_checkpoint(tmp_path / "a", b"{}"))) @@ -367,44 +383,52 @@ def test_the_engine_hands_each_cache_the_walks_its_streams_name(): # ── which resources are offered the root ──────────────────────────────── -class _Recording(Resource): - """Keeps state across requests of its own, and records the root it is handed.""" - - def __init__(self): - self.roots: list[bytes] = [] +class _Plain(Resource): + """Keeps nothing across requests, so has nothing to open.""" @classmethod def build(cls, spec, info): raise NotImplementedError + +class _Recording(_Plain): + """Keeps state across requests of its own, and records the root it is handed.""" + + def __init__(self): + self.roots: list[bytes] = [] + def enable_prefix_cache(self, root, walks=None): self.roots.append(root) -class _Plain(Resource): - """Keeps nothing across requests, so has nothing to open.""" +@dataclass +class _KeepingSpec(NodeResourceSpec): + """Declares a prefix cache of its own, and is neither a KV cache nor a recurrent pool.""" - @classmethod - def build(cls, spec, info): - raise NotImplementedError + def keeps_prefix_cache(self, world_size, checkpoint_named): + return True + + @property + def resource_class(self): + return _Recording -def _open(resources: dict) -> None: +def _open(resources: dict, specs: dict | None = None) -> None: engine = Engine.__new__(Engine) engine._resources = resources kv = resources[KV] - engine._open_prefix_caches( - {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config)}, _Model(), + _open_caches( + engine, {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv.config), **(specs or {})}, _Model(), {"LLM": 1}, ) -def test_every_resource_is_offered_the_root_not_just_the_kv_cache(): +def test_a_resource_whose_spec_keeps_a_cache_is_offered_the_root(): other = _Recording() - _open({KV: _kv(), "other": other}) + _open({KV: _kv(), "other": other}, {"other": _KeepingSpec(resource_key="other", nodes={"LLM"})}) assert len(other.roots) == 1 and isinstance(other.roots[0], bytes), ( - "a resource that is not a KVManager was never asked to open its cache" + "a resource that keeps a cache, but is not a KV cache or a pool, was never asked to open it" ) @@ -484,11 +508,14 @@ def test_a_keyed_node_that_streams_into_another_partition_loads(): ) -def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(monkeypatch): +# the model names no checkpoint, so the cache, another engine's, opens only with a salt +@pytest.mark.parametrize(("salt", "vit"), [("s", True), ("", None)], ids=["salted", "unsalted"]) +def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(monkeypatch, salt, vit): engine = Engine.__new__(Engine) engine._resources = {} engine._device = torch.device("cuda") - engine._open_prefix_caches({KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=_kv().config)}, _laid_out()) + kv = _kv(prefix_cache_salt=salt).config + _open_caches(engine, {KV: KVSpec(resource_key=KV, nodes={"LLM"}, config=kv)}, _laid_out(), {}) # "vae" is an encoder that no layout walk runs, like an edit's. engine._submodules = { name: SimpleNamespace(submodule=SimpleNamespace(forward=None, forward_batched=None)) @@ -500,7 +527,7 @@ def test_only_a_node_whose_output_is_cached_under_a_digest_is_compiled_dynamic(m engine._compile_submodules() compiled = {name: mgmt.forward for name, mgmt in engine._submodules.items()} - assert compiled == {"vit": True, "LLM": None, "vae": None}, ( + assert compiled == {"vit": vit, "LLM": None, "vae": None}, ( "an image encoder left to recompile caches KV it no longer computes for the same " "file, or a node the cache never keys from lost the compile main gives it" ) @@ -515,7 +542,7 @@ def test_an_encoder_that_marks_its_own_dims_compiles_with_the_default_while_its_ spec = KVSpec(resource_key=KV, nodes={"LLM"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, )) - engine._open_prefix_caches({KV: spec}, _laid_out()) + _open_caches(engine, {KV: spec}, _laid_out(), {}) vit = SimpleNamespace(forward="eager", forward_batched="eager", marks_dynamic_dims=True) engine._submodules = {"vit": SimpleNamespace(submodule=vit, forward="eager")} diff --git a/test/modular/test_kv_prefix_tp.py b/test/modular/test_kv_prefix_tp.py index 9272ff1d68..a16f2071a5 100644 --- a/test/modular/test_kv_prefix_tp.py +++ b/test/modular/test_kv_prefix_tp.py @@ -21,7 +21,7 @@ from mstar.engine.resources import StepRunner, apply_yaml_overrides from mstar.engine.resources.base import KeyedWalks from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVSpec, KVStep, PagedKVConfig +from mstar.engine.resources.kv.config import KVSpec, KVStep, PagedKVConfig, opening_prefix_caches from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.step import Segment, StepContext from mstar.model.submodule_base import ARNodeInputs, ARNodeSubmodule @@ -304,22 +304,16 @@ def test_above_one_rank_a_commit_caches_no_image_end(): ) -def test_above_one_rank_the_cache_stays_off_unless_the_deployment_opts_in(): - assert _manager(0, opt_in=False)._index is None - assert _manager(0)._index is not None - - -def test_the_serving_config_turns_on_prefix_cache_tp(): +def test_above_one_rank_the_cache_opens_only_where_the_serving_config_opts_in(): spec = KVSpec(resource_key="kv", nodes={NODE}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=4096, num_qo_heads=2, max_num_pages=32, page_size=PAGE_SIZE, )) + assert "kv" not in opening_prefix_caches([spec], {NODE: 2}, checkpoint_named=True) apply_yaml_overrides([spec], yaml.safe_load("resources:\n kv:\n prefix_cache_tp: true\n")) - kv = KVManager( - cfg=spec.config, name="kv", joint_comm_group=SimpleNamespace(rank=0, world_size=2), - transfer_engine_info=None, device=torch.device("cpu"), dtype=torch.float32, + assert "kv" in opening_prefix_caches([spec], {NODE: 2}, checkpoint_named=True), ( + "the serving config's prefix_cache_tp never reached the rule" ) - assert kv.enable_prefix_cache(ROOT, WALKS), "the serving config's prefix_cache_tp never reached the pool" def test_host_offload_or_a_pool_on_more_than_one_tp_group_is_refused_at_load(monkeypatch): diff --git a/test/modular/test_kv_release.py b/test/modular/test_kv_release.py index 9aeb6f1c0d..86889eb48c 100644 --- a/test/modular/test_kv_release.py +++ b/test/modular/test_kv_release.py @@ -20,12 +20,18 @@ from mstar.communication.tensors import LocalTransferEngine from mstar.engine.resources.attn.config import AttentionConfig, AttentionSpec -from mstar.engine.resources.base import KeyedWalks from mstar.engine.resources.kv import manager as manager_mod +from mstar.engine.resources.kv.arena import PageArena from mstar.engine.resources.kv.cache import KVCache, PageAllocator -from mstar.engine.resources.kv.config import KVSpec, KVStep, PagedKVConfig, RetentionPolicy +from mstar.engine.resources.kv.config import ( + KVSpec, + KVStep, + PagedKVConfig, + RetentionPolicy, + opening_prefix_caches, +) from mstar.engine.resources.kv.cpu_page_pool import CPUPagePool -from mstar.engine.resources.kv.manager import KVManager, PageArena +from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.kv.plan import SINK_PAGE from mstar.engine.resources.kv.prefix_index import PrefixIndex from mstar.engine.resources.kv.transfer import TransferEngineInfo @@ -554,7 +560,8 @@ def test_window_pool_refusals_and_tp_offload(monkeypatch) -> None: # a model that keys labels still starts, without a prefix cache (a limitation for now) m = _window_manager() assert not m.config.prefix_cache - assert not m.enable_prefix_cache(b"root", {"main": KeyedWalks(("prefill",))}) and m._index is None + # so the startup rule leaves it shut, for the engines and the router's mirrors alike + assert not opening_prefix_caches([KVSpec(resource_key="kv", nodes={"LLM"}, config=m.config)], {"LLM": 1}, True) m.ingest_request("r") free = m._arena.num_free step = KVStep(segments=(Segment("r", "main", 4),), pre_forks=(("main", "other"),)) diff --git a/test/modular/test_process_liveness.py b/test/modular/test_process_liveness.py index fb566b18da..365d2081a7 100644 --- a/test/modular/test_process_liveness.py +++ b/test/modular/test_process_liveness.py @@ -12,7 +12,6 @@ import signal import threading import time -from collections import Counter from types import SimpleNamespace from unittest import mock @@ -106,7 +105,6 @@ def _conductor(procs, inbox=()): c._next_liveness_check = 0.0 c.requests = {} c.draining = {} - c._replica_load = Counter() c.waiting_queue = [] return c diff --git a/test/modular/test_recurrent_prefix_snapshots.py b/test/modular/test_recurrent_prefix_snapshots.py index 3fa89aa837..ddeb0ef676 100644 --- a/test/modular/test_recurrent_prefix_snapshots.py +++ b/test/modular/test_recurrent_prefix_snapshots.py @@ -20,7 +20,7 @@ from mstar.engine.engine import Engine from mstar.engine.resources.base import CachedPrefix, EngineResourceInfo, Resource from mstar.engine.resources.kv import manager as manager_mod -from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig +from mstar.engine.resources.kv.config import KVSpec, PagedKVConfig, opening_prefix_caches from mstar.engine.resources.kv.keys import chain from mstar.engine.resources.kv.manager import KVManager from mstar.engine.resources.linear_attn.config import LinearAttnConfig, LinearAttnSpec, LinearAttnVariant @@ -70,10 +70,12 @@ def _build(config: RecurrentStateConfig, world_size: int = 1, prefix_cache: bool kv = _specs(0)["kv"] kv.config.prefix_cache = prefix_cache group = type("Group", (), {"world_size": world_size})() if world_size > 1 else None - return RecurrentStatePool.build( - RecurrentStateSpec(resource_key="state", nodes={NODE}, config=config), - EngineResourceInfo(device=torch.device("cpu"), joint_comm_group=group, dependencies={"kv": kv}), - ) + spec = RecurrentStateSpec(resource_key="state", nodes=set(kv.nodes), config=config) + return RecurrentStatePool.build(spec, EngineResourceInfo( + device=torch.device("cpu"), joint_comm_group=group, dependencies={"kv": kv}, + # as the engine decides it for a node with the pool and its cache + prefix_caches=opening_prefix_caches([spec, kv], dict.fromkeys(kv.nodes, world_size), checkpoint_named=True), + )) def _pool(prefix_slots: int = 2, world_size: int = 1, prefix_cache: bool = True) -> RecurrentStatePool: @@ -83,7 +85,6 @@ def _pool(prefix_slots: int = 2, world_size: int = 1, prefix_cache: bool = True) ) pool = _build(config, world_size, prefix_cache) pool.bind_kv(_StubChains()) - pool.enable_prefix_cache(b"a root") return pool @@ -171,9 +172,24 @@ def test_a_full_set_evicts_the_oldest_snapshot_nothing_holds(): @pytest.mark.parametrize("closed", [{"world_size": 2}, {"prefix_cache": False}, {"prefix_slots": 0}]) def test_snapshots_stay_off_and_unallocated_where_the_cache_cant_open(closed): pool = _pool(**closed) - assert not pool.enable_prefix_cache(b"a root") + assert pool._kv is None, "a pool that can't restore keys snapshots" assert pool.block("state", 0).shape[0] == pool.config.max_slots, "allocated snapshot slots nothing can use" - assert _pool().enable_prefix_cache(b"a root") + assert _pool()._kv is not None + + +def test_a_pool_keeps_snapshot_slots_only_for_a_cache_the_engine_opens(): + # its own cache would open, but the engine shuts it, as for a node whose other pool keeps no snapshots + kv = _specs(0)["kv"] + pool = RecurrentStatePool.build( + RecurrentStateSpec(resource_key="state", nodes=set(kv.nodes), config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, + max_slots=4, prefix_slots=2, kv_cache="kv", + )), + EngineResourceInfo(device=torch.device("cpu"), dependencies={"kv": kv}, prefix_caches=frozenset({"kv"})), + ) + assert pool.block("state", 0).shape[0] == pool.config.max_slots, ( + "allocated snapshot slots for a pool the engine keeps shut" + ) def test_a_negative_prefix_slots_override_is_refused(): @@ -286,9 +302,10 @@ def _specs(prefix_slots: int) -> dict[str, NodeResourceSpec]: max_slots=4, prefix_slots=prefix_slots, kv_cache="kv", ) return { + # prefix_cache_tp, so above one rank only the pool keeps the cache shut "kv": KVSpec(resource_key="kv", nodes={"LLM"}, config=PagedKVConfig( num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=8, - page_size=PAGE, prefix_cache_salt="a salt", + page_size=PAGE, prefix_cache_salt="a salt", prefix_cache_tp=True, )), "state": RecurrentStateSpec(resource_key="state", nodes={"LLM"}, config=state), "gdn": LinearAttnSpec(resource_key="gdn", nodes={"LLM"}, config=LinearAttnConfig( @@ -307,7 +324,9 @@ def _open(monkeypatch, prefix_slots: int = 2, world_size: int = 1) -> Engine: "state": _build(specs["state"].config, world_size), "gdn": _StubGDN(), } - engine._open_prefix_caches(specs, _Keyed()) + instance = {"LLM": world_size} + opened = opening_prefix_caches(specs.values(), instance, checkpoint_named=False) + engine._open_prefix_caches(specs, _Keyed(), instance, opened, None) return engine @@ -327,6 +346,104 @@ def test_a_node_whose_pool_keeps_no_snapshots_opens_no_cache(monkeypatch, caplog assert "state on LLM" in caplog.text +def _kv_spec(key: str, nodes: set[str], **overrides) -> KVSpec: + return KVSpec(resource_key=key, nodes=nodes, config=PagedKVConfig( + num_layers=1, num_kv_heads=1, head_dim=8, max_seq_len=64, max_num_pages=8, + page_size=PAGE, prefix_cache_salt="a salt", **overrides, + )) + + +def _pool_specs( + nodes: set[str], kv_cache: str = "kv", prefix_slots: int = 2, suffix: str = "", +) -> list[NodeResourceSpec]: + """A pool and the GDN resource over it, keyed ``state`` and ``gdn`` with ``suffix``.""" + return [ + RecurrentStateSpec(resource_key=f"state{suffix}", nodes=nodes, config=RecurrentStateConfig( + num_layers=1, blocks={"state": RecurrentBlockConfig(shape=(3,), dtype=torch.float32)}, + max_slots=4, prefix_slots=prefix_slots, kv_cache=kv_cache, + )), + LinearAttnSpec(resource_key=f"gdn{suffix}", nodes=nodes, config=LinearAttnConfig( + recurrent_state=f"state{suffix}", variant=LinearAttnVariant.GDN, + )), + ] + + +class _KeyedOn(_Keyed): + def __init__(self, keys): + self._keys = keys + + def kv_labels(self): + return {key: super(_KeyedOn, self).kv_labels()["kv"] for key in self._keys} + + +# specs, the keyed caches, each local node's lockstep instance, and the caches that open here +_SHAPES = { + "snapshots": ([_kv_spec("kv", {"LLM"}), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 1}, {"kv", "state"}), + "no_prefix_slots": ([_kv_spec("kv", {"LLM"}), *_pool_specs({"LLM"}, prefix_slots=0)], {"kv"}, {"LLM": 1}, set()), + "two_ranks": ( + [_kv_spec("kv", {"LLM"}, prefix_cache_tp=True), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 2}, set(), + ), + "kv_not_opening": ( + [_kv_spec("kv", {"LLM"}, prefix_cache=False), *_pool_specs({"LLM"})], {"kv"}, {"LLM": 1}, set(), + ), + "node_shared_by_two_caches": ( + [_kv_spec("kv", {"LLM"}), _kv_spec("kv2", {"LLM"}), *_pool_specs({"LLM"}, prefix_slots=0)], + {"kv", "kv2"}, {"LLM": 1}, set(), + ), + "kv_cache_names_another_key": ( + [_kv_spec("kv", {"LLM"}), _kv_spec("kv2", {"LLM"}), *_pool_specs({"LLM"}, kv_cache="kv2")], + {"kv", "kv2"}, {"LLM": 1}, {"kv", "kv2", "state"}, + ), + # the pool's cache is on a node another engine holds, so nothing here keys its snapshots + "cross_engine_pool": ( + [_kv_spec("kv", {"Y"}), _kv_spec("kv2", {"X"}), *_pool_specs({"X"})], {"kv2"}, {"X": 1}, set(), + ), + # B's pool keeps no snapshots, which shuts kv, so A's pool keeps none either, and kv2 beside it stays shut + "a_cache_shut_beside_a_pool_its_cache_closed": ( + [_kv_spec("kv", {"A", "B"}), _kv_spec("kv2", {"A"}), *_pool_specs({"A"}), + *_pool_specs({"B"}, prefix_slots=0, suffix="_b")], + {"kv", "kv2"}, {"A": 1, "B": 1}, set(), + ), +} + + +@pytest.mark.parametrize(("specs", "keyed", "instance", "opens"), _SHAPES.values(), ids=_SHAPES.keys()) +def test_the_engine_opens_the_caches_the_startup_rule_opens(monkeypatch, specs, keyed, instance, opens): + """The conductor's routing and the data worker read the rule, so a cache the + engine kept shut would be mirrored and hashed for hits nothing serves.""" + monkeypatch.setattr(manager_mod, "KVTransferManager", _StubTransfer) + by_key = {spec.resource_key: spec for spec in specs} + local = [spec for spec in specs if not spec.nodes.isdisjoint(instance)] + # as Engine.load_model evaluates it, once, for the builds and for opening + rule = opening_prefix_caches(specs, instance, checkpoint_named=False) + engine = Engine.__new__(Engine) + engine._resources = {} + for spec in local: + size = min(instance[node] for node in spec.nodes & instance.keys()) + if isinstance(spec, KVSpec): + engine._resources[spec.resource_key] = KVManager( + cfg=spec.config, name=spec.resource_key, joint_comm_group=None, + transfer_engine_info=None, device=torch.device("cpu"), + ) + elif isinstance(spec, RecurrentStateSpec): + group = type("Group", (), {"world_size": size})() if size > 1 else None + engine._resources[spec.resource_key] = RecurrentStatePool.build(spec, EngineResourceInfo( + device=torch.device("cpu"), joint_comm_group=group, + dependencies={dep: by_key[dep] for dep in spec.depends_on()}, + prefix_caches=rule, + )) + else: + engine._resources[spec.resource_key] = _StubGDN() + engine._open_prefix_caches(by_key, _KeyedOn(keyed), instance, rule, None) + opened = { + key for key, resource in engine._resources.items() + if (isinstance(resource, KVManager) and resource._index is not None) + or (isinstance(resource, RecurrentStatePool) and resource._kv is not None) + } + assert opened == rule & engine._resources.keys() + assert opened == opens + + def test_a_keyed_node_loads_with_a_recurrent_pool_and_the_resource_over_it(): specs = _specs(prefix_slots=0) assert not list(_unskippable_resources(list(specs.values()), _Keyed())), ( diff --git a/test/modular/test_startup_graph_validation.py b/test/modular/test_startup_graph_validation.py index 8ea6520b40..b649d8fddc 100644 --- a/test/modular/test_startup_graph_validation.py +++ b/test/modular/test_startup_graph_validation.py @@ -399,8 +399,8 @@ def test_colocated_successor_reports_the_final_stream(tmp_path): (_gated_vocoder_then_post, _ONE, _ONE, True), # one TP instance on the same ranks shares the flag too (_gated_vocoder_then_post, _TP2, _TP2, True), - # each node_group picks its own replica, so a request can split across them - (_gated_vocoder_then_post, {"ranks": [1, 2]}, {"ranks": [1, 2]}, False), + # node_groups on the same ranks, replica for replica, pick one replica together + (_gated_vocoder_then_post, {"ranks": [1, 2]}, {"ranks": [1, 2]}, True), ], ids=["self_triggered", "gated", "self_triggered_colocated", "gated_colocated", "gated_colocated_tp", "gated_dp_replicas"]) def test_consumer_walk_across_worker_graphs(chunk_walk, vocoder, post, accepted, tmp_path, monkeypatch): diff --git a/test/modular/test_startup_warmup.py b/test/modular/test_startup_warmup.py index a290cc2142..c0a842b521 100644 --- a/test/modular/test_startup_warmup.py +++ b/test/modular/test_startup_warmup.py @@ -197,6 +197,8 @@ def replicas(node_groups): fake = _FakeServer() entrypoint._run_warmup_requests(fake, [{"text": "a"}, {"text": "b"}], entrypoint.DataParallelReplicas(2, 2)) assert [s["request_id"] for s in fake.submitted] == ["warmup-0.0", "warmup-0.1", "warmup-1.0", "warmup-1.1"] + # off the prefix cache, so a prefix weight above load's cannot put the copies on one replica + assert all(s["model_kwargs"] == {"prefix_cache": False} for s in fake.submitted) def test_replicated_warmup_runs_one_request_alone_first() -> None: diff --git a/test/modular/test_teardown_barrier.py b/test/modular/test_teardown_barrier.py index 01b1b1d735..52e6cc84f8 100644 --- a/test/modular/test_teardown_barrier.py +++ b/test/modular/test_teardown_barrier.py @@ -7,7 +7,7 @@ """ import types -from collections import Counter, deque +from collections import deque import pytest import torch @@ -36,7 +36,6 @@ def _request_data(workers=("w0",), persist_signals=None, ref_cnts=None): # Post-resource-pool refactor: requests carry per-resource configs # rather than a sampling_config. The barrier never reads them. resource_configs={}, - dp_replicas={0: 0}, ) @@ -59,7 +58,6 @@ def _conductor(requests, drain_ttl_s=120.0): send=lambda entity_id, msg: c.sent.append((entity_id, msg)) ) c.requests = {} - c._replica_load = Counter() for rid, request_data in requests.items(): c._register_request(rid, request_data) c.draining = {} @@ -121,8 +119,6 @@ def test_abort_drains_all_participants_then_removes(): assert _remove_targets(c, "r1") == {"w0", "w1", PREPROCESS} assert "r1" not in c.requests and "r1" not in c.draining assert c.admits == 1 - # the DP replica pick no longer counts it - assert not any(c._replica_load.values()) def test_abort_of_unknown_request_sends_nothing(): @@ -305,7 +301,6 @@ def bad_config(body): c._do_ingest_request = bad_config c._ingest_request(_new_request("r1")) assert "r1" not in c.requests and c.draining == {} - assert not any(c._replica_load.values()) assert _remove_targets(c, "r1") == {PREPROCESS} [failure] = _failures(c, "r1") assert failure.status == 400 and "top_p" in failure.error_message diff --git a/test/modular/test_validate_deployment.py b/test/modular/test_validate_deployment.py index 8f2b006ea2..e3375fb535 100644 --- a/test/modular/test_validate_deployment.py +++ b/test/modular/test_validate_deployment.py @@ -481,8 +481,22 @@ def test_resource_over_local_nodes_in_different_parallel_groups_is_refused(tmp_p ([_Spec("kv", {"llm"}, deps={"kv"})], {}, r"resource 'kv' depends on itself"), ([_Spec("a", {"llm"}, deps={"b"}), _Spec("b", {"llm"}, deps={"a"})], {}, r"dependency cycle among resources \['a', 'b'\]"), + # NaN would make every replica's cost NaN, and every DP ingest fail + ([_Spec("kv", {"llm"})], {"routing_weights": {"prefix": float("nan")}}, + r"routing_weights.prefix must be a number from 0 to 1e\+06; got nan"), + # finite, but a busy replica's cost overflows to inf, and inf - inf is NaN + ([_Spec("kv", {"llm"})], {"routing_weights": {"load": 1e308, "prefix": 1e308}}, + r"routing_weights.load must be a number from 0 to 1e\+06; got 1e\+308"), + # a weight is per term of the cost, not per resource + ([_Spec("kv", {"llm"})], {"routing_weights": {"kv": 2.0}}, + r"routing_weights names \['kv'\]; it takes \['load', 'prefix'\]"), + # named on its own, not as a config the resource checks could not read, empty too + ([_Spec("kv", {"llm"})], {"routing_weights": []}, r"routing_weights must be a mapping"), + # nothing would spread a hot prefix + ([_Spec("kv", {"llm"})], {"routing_weights": {"load": 0}}, r"routing_weights.load must be above 0"), ], ids=["top_level_kv_cache", "unknown_resource", "bad_override", "duplicate_key", "missing_dependency", - "self_dependency", "cycle"]) + "self_dependency", "cycle", "routing_weight_not_finite", "routing_weights_overflow", + "routing_weight_per_resource", "routing_weights_not_a_mapping", "routing_load_0"]) def test_resource_problem_is_refused_in_the_conductor(specs, extra, pattern, tmp_path, monkeypatch): """EngineManager.build and Engine.load_model raised these on every worker.""" with pytest.raises(DeploymentError, match=pattern):