Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 49 additions & 2 deletions python/freetoken/engine/cache_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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).

Expand All @@ -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)"
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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),
)
82 changes: 78 additions & 4 deletions python/freetoken/engine/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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."""
Expand Down
Loading