mstar.engine.resources.kv.config#
What a model declares about a KV cache: its shape, its spec, its step.
Kept free of the manager and its kernels so a submodule can declare a step without pulling FlashInfer in behind it.
Functions
|
What opening_prefix_caches sizes |
|
Mark every KV config in |
|
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. |
|
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. |
|
Why rebuild rows can't write a request's laid-out labels again, or None. |
|
The model is at fault and not the client, so this raises RuntimeError, which fails the request with a 500. |
|
Where the step that writes |
|
The resources that can't restore what a hit skips while |
|
Only the KV manager's ingest reads the layouts and caps, so they are dropped before the configs go out with every frame between workers. |
Classes
|
The model geometry every KV storage strategy needs, and nothing else. |
|
Layers of a paged pool that share a page size and a retention (PagedKVConfig.groups). |
|
|
|
|
|
|
|
|
|
Fixed-size pages, appended to as a sequence grows. |
|
One write to a keyed stream, as the preprocess worker laid it out. |
|
FIFO retention for a stream that keeps committing (windowed / rolling generation): once the committed tokens behind |
|
A fixed horizon of frame slots per layer, overwritten in place. |
|
One layer's ring geometry. |
|
One ring clock per request in the step's batch. |
|
One write to a KV stream. |
|
What a span writes: token |
|
LabelLayout as the KV manager holds it. |
- class mstar.engine.resources.kv.config.KVConfig(*, num_layers, num_kv_heads, head_dim, num_qo_heads=None)[source]#
Bases:
ABCThe model geometry every KV storage strategy needs, and nothing else.
What a cache holds (layers, heads, head dim) is a checkpoint fact and lives here; how it is stored — paged or ringed, is storage policy and lives in a subclass.
KVSpecdispatches on which one it was handed.kw_onlyis load-bearing, not style:num_qo_headscarries a default here while both subclasses add required fields, which is an invalid positional dataclass field order.- abstractmethod apply_yaml_overrides(**kwargs)[source]#
Patch this deployment’s tunables; see
NodeResourceSpec.Abstract so each storage policy names exactly what it accepts and lets the rest raise — a paged key against a ring config is a typo, and the spec’s contract is that a typo is loud.
- Return type:
None
- capacity_problem(spec, requests, request, axis_sizes=())[source]#
Why
spec’s pool can’t holdrequestsrequests at once, each opened withrequest, on node groups ofaxis_sizes(as NodeResourceSpec.capacity_problem takes them), or None. None by default, for a pool its window sizes rather than its requests.
- shard(num_shards)[source]#
Narrow the head counts to one rank’s slice of
num_shards(EngineResourceInfo.head_shards).Idempotent because one KVConfig is shared by the KV resource and the attention resources planned against it, and each shards on construction; a second count is an error, since the cache was sized by the first.
- Parameters:
num_shards (int)
- Return type:
None
- class mstar.engine.resources.kv.config.KVGroup(layers, page_size, retention=None)[source]#
Bases:
objectLayers of a paged pool that share a page size and a retention (PagedKVConfig.groups).
- Parameters:
page_size (int)
retention (RetentionPolicy | None)
- retention: RetentionPolicy | None = None#
- class mstar.engine.resources.kv.config.KVLayout(*values)[source]#
Bases:
Enum- MLA = 'MLA'#
- NHD = 'NHD'#
- class mstar.engine.resources.kv.config.KVReqConfig(needed_labels: list[str] | None = None, needed_labels_per_node: dict[str, list[str]] = <factory>, needed_labels_per_node_walk: dict[tuple[str, str], list[str]] = <factory>, publish_labels_per_node_walk: dict[tuple[str, str], list[str]] | None = None, final_publish_labels_per_node_walk: dict[tuple[str, str], list[str]] | None = None, prefix_keys: dict[str, list[bytes]] | None = None, prefix_tail: dict[str, list[int]] | None = None, prefix_decode: dict[str, str] | None = None, prefix_root: bytes = b'', prefix_cache: bool = True, kv_layout: dict[str, 'StreamLayout'] | None = None, loop_caps: dict[str, int] | None = None, unpausable: bool = False, rebuildable: bool = True)[source]#
Bases:
ResourceReqConfig- Parameters:
needed_labels_per_node_walk (dict[tuple[str, str], list[str]])
publish_labels_per_node_walk (dict[tuple[str, str], list[str]] | None)
final_publish_labels_per_node_walk (dict[tuple[str, str], list[str]] | None)
prefix_root (bytes)
prefix_cache (bool)
kv_layout (dict[str, StreamLayout] | None)
unpausable (bool)
rebuildable (bool)
- apply_conductor_config(prefix_keys=None, prefix_tail=None, prefix_decode=None, prefix_root=None, prefix_cache=None, kv_layout=None, loop_caps=None, **kwargs)[source]#
- keyed_layouts()[source]#
Its layouts, each keying none of its spans where the request has no keys for the label, as with the prefix cache off for the request or for the server.
- Return type:
- keys_of(label)[source]#
label’s prefix keys, or None when the request keys nothing there, as withprefix_cacheoff.
- kv_layout: dict[str, StreamLayout] | None = None#
- loop_room(spec=None)[source]#
The most iterations each loop can run before the request outgrows the resource built from
spec. A loop the resource doesn’t bound is left out.
- opened_labels(nodes=None)[source]#
The labels the request opens on
nodes, or on every node whennodesis None.- Parameters:
nodes (Collection[str] | None)
- Return type:
- pages(nodes, caps, pool)[source]#
The most arena pages the request holds in
pool, shared bynodes, atcaps.- Parameters:
nodes (Collection[str] | None)
pool (PagedKVConfig)
- Return type:
- validate(spec=None)[source]#
ValueError(a 400) when a label would hold more positions at the request’s caps than its pool’smax_seq_len. A label under retention is left out, since Cosmos3, the one model that declares one, computes its positions in each forward.Also when the labels
spec.nodesopen would hold more pages at the caps than the pool has for requests. The pool admits a preemptible request on its prompt alone, so a request this large would be admitted and then could not finish even alone in an empty pool.- Parameters:
spec (KVSpec | None)
- Return type:
None
- class mstar.engine.resources.kv.config.KVSpec(resource_key: str, nodes: set[str], config: mstar.engine.resources.kv.config.KVConfig, leader: str | None = None)[source]#
Bases:
NodeResourceSpec- apply_yaml_overrides(**kwargs)[source]#
Forwarded to the config: which keys are legal is a property of the storage strategy, so the config answers for them.
- capacity_problem(requests, request, axis_sizes=())[source]#
Forwarded to the config, as apply_yaml_overrides is: how requests fill a pool is the storage strategy’s.
- derive(specs)[source]#
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. Idempotent: it runs wherever the specs resolve (resolve_spec_dependencies).
- Parameters:
specs (Mapping[str, NodeResourceSpec])
- Return type:
- keeps_prefix_cache(world_size, checkpoint_named)[source]#
Whether the resource keeps a prefix cache of its own on a lockstep instance of
world_sizeranks, 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.
- property resource_class: type[Resource]#
What builds this spec. Imported inside the property, so declaring a resource stays free of the manager and its kernels.
The builder, not necessarily the class built: an attention spec names AttentionManager, whose build picks a backend subclass.
- routing_mirror(ctx)[source]#
A mirror of the prefix cache where it opens and a walk that keys it runs.
- Parameters:
ctx (RoutingContext)
- split_step_refusals(node, shard, tp, sp, specs)[source]#
What this resource can’t run on
node, whose stepsshardsplits overspSP ranks (tpTP ranks each), amongspecs(every spec, by key); each a sentence.- Parameters:
node (str)
shard (SeqShardSpec)
tp (int)
sp (int)
specs (Mapping[str, NodeResourceSpec])
- Return type:
- property storage: Storage | None#
by_head(each rank a slice of the heads, over TP x SP),by_position(each a share of every page’s token positions over ranks that would otherwise hold the same heads, heads over TP:mstar.engine.resources.context_parallel), orcopied(heads over TP, every SP rank the whole state: a recurrent pool). None for one holding none. A resource over pools that are allcopiedshards its heads over TP (EngineResourceInfo.head_shards), and a node whose pools store by position runs copied unless its shard’s exchange splits it. From raw fields, as the shard’s hooks.- Type:
How this resource stores its per-request state over a node’s ranks
- class mstar.engine.resources.kv.config.KVStep(segments: tuple[mstar.engine.resources.step.Segment, ...] | None = None, commit: bool = True, eager_write: bool = False, pre_forks: tuple[tuple[str, str], ...] = (), post_forks: tuple[tuple[str, str], ...] = (), fork_rids: frozenset | None = None, sink: frozenset[tuple[str, str]] = frozenset(), retention: collections.abc.Mapping[tuple[str, str], mstar.engine.resources.kv.config.RetentionPolicy] = <factory>, *, combined_labels: dict[tuple[str, ...], str] = <factory>)[source]#
Bases:
ResourceStep
- class mstar.engine.resources.kv.config.PagedKVConfig(*, num_layers, num_kv_heads, head_dim, num_qo_heads=None, max_seq_len, max_num_pages=2048, page_size=None, layout=KVLayout.NHD, cpu_offload_pages=0, prefix_cache_salt='', prefix_cache=True, prefix_cache_tp=False, context_parallel=False, kv_lora_rank=None, qk_rope_head_dim=None)[source]#
Bases:
KVConfigFixed-size pages, appended to as a sequence grows. The default.
- Parameters:
num_layers (int)
num_kv_heads (int)
head_dim (int)
num_qo_heads (int | None)
max_seq_len (int)
max_num_pages (int)
page_size (int | None)
layout (KVLayout)
cpu_offload_pages (int)
prefix_cache_salt (str)
prefix_cache (bool)
prefix_cache_tp (bool)
context_parallel (bool)
kv_lora_rank (int | None)
qk_rope_head_dim (int | None)
- apply_yaml_overrides(max_num_pages=None, page_size=None, max_seq_len=None, cpu_offload_pages=None, prefix_cache_salt=None, prefix_cache=None, prefix_cache_tp=None, context_parallel=None)[source]#
How much cache this deployment gets, and how it is cut up.
- capacity_problem(spec, requests, request, axis_sizes=())[source]#
Each request holds the pages
requestlays out at its caps, or one stream ofmax_seq_lenwhere it lays out none, next to the sink page.
- context_parallel_size(pool, tp, sp)[source]#
How many ranks
context_parallelstripes each page over on a node oftpxspranks: its SP ranks when it has more than one, else the TP ranks sharing a KV head. RaisesValueErrorwhen they can’t;validate_deploymentchecks it fromnode_groupsbefore any worker starts.
- keep_window(window, layers)[source]#
Keep about
windowtokens per request oflayers, some of the pool’s, and every token of the rest;layersempty keeps every token of every layer.A page of either group is the same bytes, so both draw from one arena: with F full and S sliding layers, a page holds
tokens_per_pagetokens of the full layers ortokens_per_page·F/Sof the sliding ones. Derived, it is (S/g)·k, g = gcd(F, S), for the smallest k that puts at least MIN_GROUP_PAGE tokens in a page of either group.
- keeps_prefix_cache(world_size, checkpoint_named)[source]#
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.
- property num_units: int#
the bytes of
max_num_pages.- Type:
Arena pages, each a page of one group’s layers
- paged_for(pool, tp, sp)[source]#
This config as a rank of a node of
tpxspranks pages it (place): a copy with the groups placed whencontext_parallelis on, else this config. What the conductor counts a request’s pages with, so its count is the worker’s.- Parameters:
- Return type:
- pages_of(units, round_up=False)[source]#
unitsarena pages in pages asmax_num_pagescounts them, rounded down (what they hold), or withround_upup (what holds them).
- place(joint, pool)[source]#
This rank’s placement of the pool, resolved from
context_parallel; None when it is off.The KV cache holds it (
KVCache.placement), not this config, which every rank’s resources share. The partners are the node’s SP ranks when it has more than one, and otherwise the block of TP ranks holding this rank’s KV head (kv_head_replicas).- Parameters:
joint (JointGroups | None)
pool (str)
- Return type:
ContextParallel | None
- placed_groups(pool, size)[source]#
The pool’s groups (keep_window) with its positions placed over
sizepartners: the first group’s slots stripe over them, and each window group stays whole on every partner, so a decode step attends it with no collective. An arena page then holds1/sizeof a first-group page’s slots a rank, so a window group’s page is1/sizeof its unplaced tokens; its retention (whole unplaced pages) still keeps the window. From the groupskeep_windowderived, so it can run again.
- property request_pages: int#
all but the sink page the KV manager takes at build.
- Type:
Arena pages requests can hold
- stream_pages(layout, caps)[source]#
The most arena pages a stream laid out as
layoutholds atcaps: its pages in every group, each window group’s under that group’s retention.- Parameters:
layout (StreamLayout)
- Return type:
- class mstar.engine.resources.kv.config.PrefixSpan(length, advance, walk, scratch=0, digest=None, end_key=None, opens_step=True, kind=SpanKind.IDS)[source]#
Bases:
objectOne write to a keyed stream, as the preprocess worker laid it out.
lengthis how many slots the write fills andadvanceis how far it moves the position counter.kindis the span’s Span.kind.digestis an item’s digest, and None for ids.end_keyis set for an item that ends inside a page, and keys that page up to the item’s end.opens_stepis False for a span the step of the span before it writes too, in one row.- Parameters:
- class mstar.engine.resources.kv.config.RetentionPolicy(context_budget, protected_prefix=0)[source]#
Bases:
objectFIFO retention for a stream that keeps committing (windowed / rolling generation): once the committed tokens behind
protected_prefixexceedcontext_budget, the oldest unprotected pages are released.A committing step declares it for its stream on
KVStep.retentionandKVManager.commitapplies it, so the release happens between steps as far as every planner is concerned: a pre-plan of the next step gates on this commit and sees the compacted stream. Whole pages only (the page straddling the prefix boundary and a partial tail page stay), so the realized context can run over the budget by up to a page; the excess is re-offered at the next commit.protected_prefixtokens at the head (a text prompt, say) are never released.- max_pages(page_size, step=0)[source]#
The most pages of
page_sizea stream under this policy holds, with a step ofsteptokens past its prefix. KVManager._apply_retention leaves less than a page over the budget, so the window peaks at the protected prefix plus the budget, or at the prefix rounded up to a page if that is larger, plus a page of overrun and the step.
- class mstar.engine.resources.kv.config.RingKVConfig(*, num_layers, num_kv_heads, head_dim, num_qo_heads=None, tokens_per_frame, layers, num_sessions=1)[source]#
Bases:
KVConfigA fixed horizon of frame slots per layer, overwritten in place.
Every layer’s storage is allocated once and reused for the life of the process, and a write to an occupied slot is the intended behaviour.
- Parameters:
- apply_yaml_overrides(num_sessions=None, **kwargs)[source]#
num_sessionsonly. Nothing else here is a deployment knob.- Parameters:
num_sessions (int | None)
- Return type:
None
- layers: tuple[RingKVLayerConfig, ...]#
- property total_sessions: int#
Resident sessions plus one shared scratch session for padding rows.
A replay padded to its capture bucket parks the dummy tail on this session (see
RingKVManager.plan); it is never handed to a request, so resident capacity staysnum_sessionsand the deployment knob keeps its meaning. The ring buffer and the flex mask both size on this count so the padding session is a real, addressable span.
- class mstar.engine.resources.kv.config.RingKVLayerConfig(ring_frames, ring_buckets, pinned_dilation)[source]#
Bases:
objectOne layer’s ring geometry. Layers can hold frames at different strides.
- class mstar.engine.resources.kv.config.RingKVStep(segments=None, *, combined_labels=<factory>, frames)[source]#
Bases:
ResourceStepOne ring clock per request in the step’s batch.
- Parameters:
- class mstar.engine.resources.kv.config.Span(kind, walk, length, advance, source, params=(), scratch=0, opens_step=True)[source]#
Bases:
NamedTupleOne write to a KV stream. A layout lists them in the order the walks write.
Each span is one step’s row, unless a span sets
opens_stepFalse: the step of the span before it then writes it too, in the same row, as text around an attachment is. That span is of the same walk, since a step runs one.lengthis how many KV slots the write fills, andadvanceis how far it moves the position counter, which is the length for text.sourceis the tensor whose next entry an ids span keys, or the file of a digest span as(modality, index).paramsare the preprocessing arguments that change the tensors made from the file. Arowsspan writes KV made from anything else, such as another node’s outputs, and is never keyed.scratchis the most a non-committing step writes before the span commits into those slots, as a denoised window does.- Parameters:
- class mstar.engine.resources.kv.config.SpanKind(*values)[source]#
Bases:
StrEnumWhat a span writes: token
IDS, a file’s KV keyed by itsDIGEST, orROWSof anything else.- DIGEST = 'digest'#
- IDS = 'ids'#
- ROWS = 'rows'#
- class mstar.engine.resources.kv.config.StreamLayout(spans=(), growth=(), scratch=0, retention=None, keyed_spans=0, max_growth=None)[source]#
Bases:
objectLabelLayout as the KV manager holds it.
- Parameters:
spans (tuple[PrefixSpan, ...])
scratch (int)
retention (RetentionPolicy | None)
keyed_spans (int)
max_growth (int | None)
- pages(caps, page_size, retention=None)[source]#
The most pages the stream can hold, where
capsgives each growth loop’s iterations; underretention(the layout’s own where None), its window with the largest step past the prefix.
- rebuilt(slots)[source]#
This layout once a rebuild has written
slotsslots into it: the last span, which rebuild_refusal requires to be ids, grows by the slots past the layout, the ids sampled since it was laid out.- Parameters:
slots (int)
- Return type:
- retention: RetentionPolicy | None = None#
- spans: tuple[PrefixSpan, ...] = ()#
- steps()[source]#
The spans grouped by the step that writes them (step_end), in walk order.
- Return type:
tuple[tuple[PrefixSpan, …], …]
- mstar.engine.resources.kv.config.instance_size(spec, instance)[source]#
What opening_prefix_caches sizes
specat: the smallest lockstep instance of its nodes ininstance, 1 where it has none.- Parameters:
spec (NodeResourceSpec)
- Return type:
- mstar.engine.resources.kv.config.mark_unpausable(configs, unpausable)[source]#
Mark every KV config in
configs, since a pause in any pool is heard.- Parameters:
configs (Mapping[str, ResourceReqConfig])
unpausable (bool)
- Return type:
None
- mstar.engine.resources.kv.config.opening_prefix_caches(specs, instance, checkpoint_named)[source]#
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.
instanceis 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.
- mstar.engine.resources.kv.config.prefix_caches_by_rank(specs, groups, checkpoint_named)[source]#
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.
groupsgives each node group’s ranks, instance size and nodes.
- mstar.engine.resources.kv.config.rebuild_refusal(layouts)[source]#
Why rebuild rows can’t write a request’s laid-out labels again, or None.
The rows write one label, grown by one loop, one row per prefill step its layout lays out, in order. They write every span from what its step read, and the ids sampled since at the end of the last span, which must be ids. A keyed label is keyed again by extending its keys, which needs them to cover every span. A layout keys only the spans its request has keys for (KVReqConfig.keyed_layouts).
- Parameters:
layouts (Iterable[StreamLayout])
- Return type:
str | None
- mstar.engine.resources.kv.config.refuse_undeclared_labels(model, declared, kv_layout, configs)[source]#
The model is at fault and not the client, so this raises RuntimeError, which fails the request with a 500.
- mstar.engine.resources.kv.config.step_end(spans, start)[source]#
Where the step that writes
spans[start]stops. One step writes a span and each span after it in the same walk that doesn’t open a step, in one row, as text around an attachment is written.- Parameters:
spans (Sequence[PrefixSpan])
start (int)
- Return type:
- mstar.engine.resources.kv.config.unrestorable(specs, opened)[source]#
The resources that can’t restore what a hit skips while
openedopen: 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. A dependency that plans from the step a hit trimmed (prefix_skip_safe, a sequence shard’s say) holds nothing to restore.- Parameters:
specs (Mapping[str, NodeResourceSpec])
opened (Collection[str])
- Return type:
- mstar.engine.resources.kv.config.without_layouts(configs)[source]#
Only the KV manager’s ingest reads the layouts and caps, so they are dropped before the configs go out with every frame between workers.
- Parameters:
configs (Mapping[str, ResourceReqConfig])
- Return type: