diff --git a/python/freetoken/engine/cache_budget.py b/python/freetoken/engine/cache_budget.py index 1e85f1ec55..7290d63c37 100644 --- a/python/freetoken/engine/cache_budget.py +++ b/python/freetoken/engine/cache_budget.py @@ -50,6 +50,30 @@ def net_cache_budget_bytes( return int(memory_ratio * baseline_free) - weights_bytes - fixed_cache_size +def prefill_working_bytes( + tokens: int, *, hidden: int, key_dim: int, value_dim: int, value_heads: int, head_dim: int, chunk: int, itemsize: int +) -> int: + """GPU bytes the temporaries of a prefill of ``tokens`` tokens hold at their peak, on a model with GatedDeltaNet layers. + + The peak is in one of those layers, where the chunk kernel allocates its output (layers/linear_attn/gdn.py, + kernel/fla/chunk.py): every term below is a tensor alive there, in elements per token. The count is from tensor + shapes. Other architectures are not counted here; the caller plans without a reserve for them. + """ + conv = 2 * key_dim + value_dim + per_token = ( + 4 * hidden # the layer's input and residual, and the normed input and summed residual made from them + + conv + value_dim # in_proj: q, k, v before the conv, and the output gate z + + conv # the conv's output + + conv # q, k, v copied out of it head by head + + 2 * key_dim # q and k l2-normalised + + value_heads * chunk # A, the solved chunk-local matrix + + value_heads * head_dim + value_dim # w and u + + 2 * value_dim # v_new and the output o + ) + states = div_ceil(tokens, chunk) * value_heads * head_dim * head_dim # h: the recurrent state entering each kernel chunk + return (tokens * per_token + states) * itemsize + + def required_bytes( moe_cache_size: int, num_pages: int, per_expert_bytes: int, cache_per_page: int ) -> int: @@ -67,6 +91,8 @@ def plan_cache_budget( kv_reserve_pages: int, max_slots: int, min_slots: int = 0, + reserve_bytes: int = 0, + kv_soft_pages: int = 0, ) -> tuple[int, int, bool]: """Split ``budget_bytes`` MoE-first into (moe_cache_size, num_pages, prefill_overlap). @@ -75,6 +101,15 @@ def plan_cache_budget( Experts greedily fill the budget after reserving ``kv_reserve_pages`` for KV, clamped to ``[floor, min(total_experts, max_slots)]`` (floor is ``2*num_experts`` when prefill overlap is feasible else ``num_experts``, and at least ``min_slots``); KV pages take whatever remains. + + ``reserve_bytes`` are left out of both caches (the working memory of a prefill chunk). + KV pages above ``kv_reserve_pages`` pay for them first and expert slots pay the rest; + neither goes under its floor, so a budget that cannot afford the whole reserve keeps + less of it rather than failing. + + ``kv_soft_pages`` is a KV floor that cannot fail a plan: KV gets that many pages ahead + of the expert slots above their floor when the budget has them after the reserve, and + what it has otherwise, never under ``kv_reserve_pages``. """ assert per_expert_bytes > 0, "per_expert_bytes must be positive" assert cache_per_page > 0, "cache_per_page must be positive (owned-KV models unsupported here)" @@ -87,8 +122,14 @@ def plan_cache_budget( assert hi >= lo, f"slot cap {hi} below the minimum {lo} slots" kv_reserve_bytes = kv_reserve_pages * cache_per_page - # MoE-priority: reserve KV first, then experts greedily take the remaining budget. - raw = (budget_bytes - kv_reserve_bytes) // per_expert_bytes + # Off the budget before the split: experts fill first and KV takes what is left, so the + # bytes come out of KV's pages above the floor, then out of expert slots. The floors are + # the slot floor and the KV reserve, or the two pages the plan needs at least. + floors = lo * per_expert_bytes + max(kv_reserve_pages, 2) * cache_per_page + budget_bytes -= max(0, min(reserve_bytes, budget_bytes - floors)) + # MoE-priority: reserve KV first, then experts greedily take the remaining budget. A soft + # floor the budget cannot pay puts the slots at their floor (the clamp below), no lower. + raw = (budget_bytes - max(kv_reserve_bytes, kv_soft_pages * cache_per_page)) // per_expert_bytes moe_cache_size = max(lo, min(raw, hi)) # A tiny budget may have forced moe_cache_size below 2*num_experts even with overlap on. overlap = overlap and moe_cache_size >= 2 * num_experts @@ -123,10 +164,14 @@ def resolve_moe_cache_auto( page_size: int, max_slots: int | None = None, min_slots: int = 0, + reserve_bytes: int = 0, + kv_soft_tokens: int = 0, ) -> tuple[int, int, bool]: """Resolve --moe-cache-auto into (moe_cache_size, num_pages, prefill_overlap). ``max_slots`` is the expert kernel's addressable slot limit; the plan never exceeds it. + ``reserve_bytes`` is plan_cache_budget's: bytes neither cache may take. ``kv_soft_tokens`` + is its soft KV floor, in tokens. Applies memory_ratio to the persisted pre-model baseline exactly once, then defers the MoE-vs-KV split to plan_cache_budget. The (1-memory_ratio) remainder is the @@ -145,4 +190,6 @@ def resolve_moe_cache_auto( kv_reserve_pages=kv_reserve_pages, max_slots=max_slots, min_slots=min_slots, + reserve_bytes=reserve_bytes, + kv_soft_pages=div_ceil(kv_soft_tokens, page_size), ) diff --git a/python/freetoken/engine/engine.py b/python/freetoken/engine/engine.py index 9b8930b882..69f1780261 100644 --- a/python/freetoken/engine/engine.py +++ b/python/freetoken/engine/engine.py @@ -40,7 +40,7 @@ from freetoken.kvcache.base import CacheRebuildRejected from freetoken.kvcache.cache_status import _supports_swa_ratio from freetoken.kvcache.linear_state_pool import ( - _linear_pool_min_slots, _linear_pool_num_slots, state_pool_bytes, + _linear_local_dims, _linear_pool_min_slots, _linear_pool_num_slots, state_pool_bytes, ) logger = init_logger(__name__) @@ -119,6 +119,38 @@ def _startup_kv_budget(memory_ratio: float, init_free_memory: int, new_free_memo return int(memory_ratio * init_free_memory) - (init_free_memory - new_free_memory) +def _prefill_working_bytes(config) -> tuple[int, int]: + """(tokens, bytes): the longest prefill chunk (--max-prefill-length, at most the context) and the GPU memory its + temporaries hold at their peak on ``config``'s model, per rank (cache_budget.prefill_working_bytes). The bytes + are 0 for a model whose prefill is not counted there, which is any model without GatedDeltaNet layers: its plan + and its startup stay as they were.""" + from freetoken.engine.cache_budget import prefill_working_bytes + + model = config.model_config + tokens = min(config.max_forward_len, config.max_seq_len) + group = model.linear_attention_group() + if group is None or group.variant != "gdn": + return tokens, 0 + from freetoken.kernel.fla.chunk import CHUNK_SIZE + + _, _, value_heads, key_heads = _linear_local_dims(group, config.tp_info.size) + return tokens, prefill_working_bytes( + tokens, hidden=model.hidden_size, key_dim=key_heads * group.key_head_dim, + value_dim=value_heads * group.value_head_dim, value_heads=value_heads, head_dim=group.value_head_dim, + chunk=CHUNK_SIZE, itemsize=config.dtype.itemsize, + ) + + +def _prefill_kv_tokens(config, chunk: int) -> int: + """KV tokens the --moe-cache-auto plan holds ahead of expert slots next to its prefill reserve, so that a prompt of + one ``chunk`` is answered: the prompt, 1024 tokens of reply, and the rows a verify step adds (_seq_limits). The + default --kv-reserve-tokens is the default chunk, and a pool of exactly that refuses such a prompt for length. + 0 when the KV size is the user's: a --kv-reserve-tokens other than the default, or a typed --num-tokens / --num-pages.""" + if config.kv_reserve_tokens != EngineConfig.kv_reserve_tokens or config.num_page_override is not None: + return 0 + return chunk + 1024 + config.decode_rows_per_req - 1 + + def _page_table_width(max_seq_len: int, page_size: int) -> int: """Column count for the page table. ``_write_page_table`` writes WHOLE trailing pages, so the highest column touched is ``align_ceil(max_seq_len, page_size) - 1`` -- which the 32-alignment @@ -691,6 +723,23 @@ def __init__(self, config: EngineConfig): if config.attention_backend.split(",")[0] == "triton": # Prefill runs on the first comma part; warm its autotune cache. self._warmup_prefill() + self._warn_if_prefill_short(config) + + def _warn_if_prefill_short(self, config: EngineConfig) -> None: + """One warning when startup or a cache resize left less GPU memory free than one prefill chunk works in. + --moe-cache-auto keeps that much out of its plan; a typed cache size, a resize, a model with resident experts + and a plan held at its floors do not.""" + tokens, need = _prefill_working_bytes(config) + if not need: + return + # what the driver has free and what the allocator holds unused: the caches stay as they are + free = get_free_memory(self.device) + torch.cuda.memory_reserved(self.device) - torch.cuda.memory_allocated(self.device) + if free < need: + logger.warning_rank0( + f"{mem_GB(free)} of GPU memory is free with the caches in place, and a prefill chunk of {tokens} tokens " + f"works in about {mem_GB(need)}: a prompt that long can end the server with a CUDA out-of-memory error. " + "Lower --max-prefill-length, or leave more free (a smaller --moe-cache-size or --num-tokens, a lower --memory-ratio)" + ) def _init_communication(self, config: EngineConfig) -> torch.distributed.ProcessGroup: if config.tp_info.size == 1 or config.use_pynccl: @@ -810,11 +859,14 @@ def _run_mm_encoder(self, batch: Batch) -> None: if parts: batch.mm_embeds = torch.cat([p.to(self.dtype) for p in parts], dim=0) - def _resolve_auto_moe_cache_size(self, config: EngineConfig, banks, method=None, max_slots=None, min_slots=0) -> tuple[int, int, bool]: + def _resolve_auto_moe_cache_size( + self, config: EngineConfig, banks, method=None, max_slots=None, min_slots=0, reserve_bytes: int = 0, kv_soft_tokens: int = 0 + ) -> tuple[int, int, bool]: """Resolve --moe-cache-auto into (moe_cache_size, num_pages, prefill_overlap). Pure glue over the Phase-1 budget policy; isolated here so it is unit-testable - without a GPU. Reused by the Phase-2 runtime rebuild. + without a GPU. Reused by the Phase-2 runtime rebuild. ``reserve_bytes`` stay out + of both caches and ``kv_soft_tokens`` is the soft KV floor (plan_cache_budget). """ from freetoken.engine.cache_budget import expert_bytes_per_slot, resolve_moe_cache_auto @@ -840,6 +892,8 @@ def _resolve_auto_moe_cache_size(self, config: EngineConfig, banks, method=None, kv_reserve_tokens=max(config.kv_reserve_tokens, min_reserve), page_size=page_tokens, max_slots=max_slots if max_slots is not None or method is None else method.slot_limit(), + reserve_bytes=reserve_bytes, + kv_soft_tokens=kv_soft_tokens, ) def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: @@ -937,7 +991,26 @@ def _init_offload_moe_cache(self, config: EngineConfig) -> OffloadMoeCache: if config.moe_cache_auto: # experts of several formats: the cache must still stage one whole layer of each through the shared bank bytes floor = stage_floor(layer_bank_bytes(banks.sources), pools, config.model_config.num_experts, self._moe_expert_counts) - size, pages, overlap = self._resolve_auto_moe_cache_size(config, banks, method, max_slots=size_cap, min_slots=floor) + # The (1 - memory_ratio) headroom does not grow with the prefill chunk: on a small card it is less than + # the chunk's temporaries, and a long prompt then ends the server. The plan keeps them out of the caches. + chunk, reserve = _prefill_working_bytes(config) + # A plan that keeps a chunk's working memory free also keeps the KV a prompt of one chunk needs. + kv_hold = _prefill_kv_tokens(config, chunk) if reserve else 0 + size, pages, overlap = self._resolve_auto_moe_cache_size( + config, banks, method, max_slots=size_cap, min_slots=floor, reserve_bytes=reserve, kv_soft_tokens=kv_hold + ) + if reserve: + plain = self._resolve_auto_moe_cache_size(config, banks, method, max_slots=size_cap, min_slots=floor) + page_bytes, _, page_tokens, _ = self._pool_cls.kv_cost(config) + # the plan takes the reserve from KV pages above the floor first; a typed --num-tokens / --num-pages drops + # those pages, so only the slots' share is kept and the startup warning covers the rest + kv_pages = 0 if config.num_page_override is not None else plain[1] - pages + kept = (plain[0] - size) * expert_bytes_per_slot(banks.sources) + kv_pages * (page_bytes + self._spec_budget(config)[1]) + held = f" and {pages * page_tokens} KV tokens for a prompt that long" if 0 < kv_hold <= pages * page_tokens else "" + logger.info_rank0( + f"--moe-cache-auto keeps {mem_GB(kept)} free for a prefill chunk of {chunk} tokens (--max-prefill-length; " + f"it works in about {mem_GB(reserve)}){held}: {-kv_pages * page_tokens:+d} KV tokens, {size - plain[0]:+d} expert slots" + ) object.__setattr__(config, "moe_cache_size", size) object.__setattr__(config, "moe_prefill_overlap", overlap) if config.num_page_override is None: @@ -1395,6 +1468,7 @@ def rebuild_runtime_cache( self.spec.attach(self) # reuse the startup-resolved bs set (see above) self.graph_runner = self._make_graph_runner(prior_graph_bs, free_min, aligned_max_seq_len) + self._warn_if_prefill_short(config) def _make_graph_runner(self, cuda_graph_bs, free_memory: int, max_seq_len: int) -> GraphRunner: """The target's graphs: the decode family, or with speculative decoding the verify family in its place.""" diff --git a/tests/engine/test_cache_budget.py b/tests/engine/test_cache_budget.py index bad246c130..e54b100ae5 100644 --- a/tests/engine/test_cache_budget.py +++ b/tests/engine/test_cache_budget.py @@ -80,6 +80,60 @@ def test_budget_too_small_for_min_moe_plus_reserve_raises(): ) # min moe = 4 slots (400 B) + reserve (10 pages = 100 B) = 500 B > 300 B budget +@pytest.mark.parametrize( + "reserve, soft, slots, pages", + [ + (0, 0, 10, 100), # every expert cached, KV holds 90 pages above its floor of 10 + (300, 0, 10, 70), # the pages above the floor cover the reserve: the slots are untouched + (900, 0, 10, 10), # exactly the pages above the floor + (1200, 0, 7, 10), # 300 B more than those pages: three slots pay the rest + (5000, 0, 4, 10), # more than the plan can give: both caches at their floors, and the plan still stands + # a soft KV floor of 30 pages + (300, 30, 10, 70), # KV is above it after the reserve: the plan without it + (900, 30, 8, 30), # the reserve would leave KV at 10: two slots pay for the 20 pages + (1400, 30, 4, 20), # the slot floor leaves 20 pages: KV gets those and the plan still stands + (5000, 30, 4, 10), # the reserve comes first: nothing is left for the soft floor + ], +) +def test_reserve_comes_out_of_kv_above_its_floor_before_expert_slots(reserve, soft, slots, pages): + plan = dict( + budget_bytes=2000, per_expert_bytes=100, cache_per_page=10, num_experts=2, total_experts=10, + prefill_overlap=True, kv_reserve_pages=10, max_slots=10, + ) + assert plan_cache_budget(**plan, reserve_bytes=reserve, kv_soft_pages=soft)[:2] == (slots, pages) + # what is left out of the caches is the reserve, or all the floors (4 slots, 10 pages) leave of it + assert 2000 - slots * 100 - pages * 10 >= min(reserve, 2000 - 4 * 100 - 10 * 10) + # a budget the floors do not fit fails as it does without a reserve + with pytest.raises(AssertionError, match="budget too small"): + plan_cache_budget(**{**plan, "budget_bytes": 480}, reserve_bytes=reserve, kv_soft_pages=soft) + + +def test_kv_soft_floor_costs_slots_only_where_kv_is_short_of_it(): + # a slot is about 79 KV tokens, a page 16 tokens; the soft floor of 9219 tokens is 577 pages over a hard floor of 512 + pe, pp, lo, soft_pages, reserve = 1264, 256, 512, 577, 800_000 + plan = dict( + weights_bytes=0, memory_ratio=1.0, fixed_cache_size=0, per_expert_bytes=pe, cache_per_page=pp, num_experts=256, + total_experts=10240, prefill_overlap=True, kv_reserve_tokens=8192, page_size=16, reserve_bytes=reserve, + ) + floors = lo * pe + 512 * pp + equal = 0 + # from both caches at their floors to every expert cached with KV to spare + for budget in range(floors, 10240 * pe + 700 * pp + reserve, 997): + old = resolve_moe_cache_auto(baseline_free=budget, **plan) + new = resolve_moe_cache_auto(baseline_free=budget, **plan, kv_soft_tokens=9219) + # the soft floor never comes out of the reserve + assert budget - new[0] * pe - new[1] * pp >= min(reserve, budget - floors) + if old[1] >= soft_pages: + assert new == old + equal += 1 + continue + # KV reaches the soft floor, or gets every page the slots above their floor can pay for + assert new[1] >= min(soft_pages, old[1] + (old[0] - lo) * pe // pp) + # and no more slots go than the missing pages cost + assert 0 <= (old[0] - new[0]) * pe < (soft_pages - old[1]) * pp + pe + assert equal + + def test_prefill_overlap_false_is_honored(): # Even when the cache could fit 2*num_experts, an explicit False stays False. size, pages, overlap = plan_cache_budget( @@ -356,6 +410,67 @@ def slot_limit(self): size, _, _ = engine._resolve_auto_moe_cache_size(StubConfig(), StubBanks(), StubMethod()) assert size == 5 + # a reserve reaches the planner as bytes neither cache takes: here KV pays all of it and every expert stays + reserved = engine._resolve_auto_moe_cache_size(StubConfig(), StubBanks(), reserve_bytes=64 * cache_per_page) + assert reserved == (8, expected[1] - 64, True) + + +def test_prefill_working_bytes_counts_gdn_models_only(): + from freetoken.engine.cache_budget import prefill_working_bytes + from freetoken.engine.engine import _prefill_working_bytes + from freetoken.models.config import LinearGatedDeltaGroupConfig + + # Qwen3.6-35B-A3B in bf16: hidden 2048, 16 key and 32 value heads of 128, the chunk kernel's 64-token chunks + group = LinearGatedDeltaGroupConfig( + name="linear", layer_ids=(0, 1, 2), num_key_heads=16, num_value_heads=32, key_head_dim=128, value_head_dim=128, + conv_kernel_dim=4, output_gate="silu", + ) + shapes = dict(hidden=2048, key_dim=2048, value_dim=4096, value_heads=32, head_dim=128, chunk=64, itemsize=2) + + def config(group, chunk=8192, context=262144): + model = SimpleNamespace(hidden_size=2048, linear_attention_group=lambda: group) + return SimpleNamespace( + model_config=model, max_forward_len=chunk, max_seq_len=context, dtype=torch.bfloat16, tp_info=SimpleNamespace(size=1) + ) + + assert _prefill_working_bytes(config(group)) == (8192, prefill_working_bytes(8192, **shapes)) + # a server with 0.43 GiB free after its CUDA graphs ran out of memory in this layer on a 3785-token prompt + assert prefill_working_bytes(3785, **shapes) > 0.43 * 2**30 + # no chunk is longer than the context + assert _prefill_working_bytes(config(group, context=4096)) == (4096, prefill_working_bytes(4096, **shapes)) + # two ranks hold half the heads each + halved = {**shapes, "key_dim": 1024, "value_dim": 2048, "value_heads": 16} + two_ranks = config(group) + two_ranks.tp_info.size = 2 + assert _prefill_working_bytes(two_ranks)[1] == prefill_working_bytes(8192, **halved) + # not counted: no linear attention layers, or the KDA kernels. No reserve, no warning + from dataclasses import replace + + assert _prefill_working_bytes(config(None))[1] == 0 + assert _prefill_working_bytes(config(replace(group, variant="kda")))[1] == 0 + + +@pytest.mark.parametrize("rows", [1, 4]) # no drafts, and MTP with 3 draft tokens +def test_prefill_kv_hold_leaves_a_prompt_of_one_chunk_its_reply(rows): + from freetoken.engine.config import EngineConfig + from freetoken.engine.engine import _prefill_kv_tokens, _seq_limits + + def config(**over): + fields = dict( + kv_reserve_tokens=EngineConfig.kv_reserve_tokens, num_page_override=None, decode_rows_per_req=rows, + max_seq_len=262144, page_size=1, + ) + return SimpleNamespace(**{**fields, **over}) + + # the scheduler refuses a prompt that is not under the longest request, and caps the reply at the difference: + # a pool of the default floor refuses a prompt of the default chunk, the held pool gives it 1024 tokens + assert _seq_limits(config(), EngineConfig.kv_reserve_tokens)[0] - 8192 <= 0 + assert _seq_limits(config(), _prefill_kv_tokens(config(), 8192))[0] - 8192 == 1024 + # a floor or a KV size the user typed is left as typed + assert _prefill_kv_tokens(config(kv_reserve_tokens=2048), 8192) == 0 + assert _prefill_kv_tokens(config(kv_reserve_tokens=131072), 8192) == 0 + assert _prefill_kv_tokens(config(num_page_override=8192), 8192) == 0 + # --------------------------------------------------------------------------- # offload-cache sizing guard + auto-resolution (_require_offload_cache_size / _adjust_config),