Skip to content
Merged
Show file tree
Hide file tree
Changes from 12 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: 41 additions & 10 deletions megatron/core/inference/contexts/dynamic_context.py
Comment thread
lmcafee-nvidia marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -2929,14 +2929,27 @@ def check_availability(self, req: DynamicInferenceRequest) -> Tuple[bool, bool,
self.total_request_count < self.max_requests and self.paused_request_count == 0
)

(_, num_blocks_from_pool, _, _, _, effective_prefill_chunk_length) = (
(matched_block_ids, num_blocks_from_pool, _, _, _, effective_prefill_chunk_length) = (
self._compute_prefix_match(req, req.remaining_prompt_length)
)

request_tokens_can_be_added = (
self.active_token_count + effective_prefill_chunk_length <= self.max_tokens
)
kv_cache_available = self.kv_block_allocator.is_memory_available(num_blocks_from_pool)
# add_request pins the matched blocks before allocating. Only matches that
# are currently evictable (ref_count == 0) count against the evictable
# pool; matches already pinned by another in-flight request are not in
# get_evictable_block_count() and pinning them frees nothing. Reserve only
# the ref_count == 0 matches so availability is not under-reported.
reserved_evictable = 0
if matched_block_ids:
matched_tensor = torch.tensor(matched_block_ids, dtype=torch.int32, device='cpu')
reserved_evictable = int(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

name change: potential_matched_count

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

(self.kv_block_allocator.block_ref_counts[matched_tensor] == 0).sum()
)
kv_cache_available = self.kv_block_allocator.is_memory_available(
num_blocks_from_pool, reserved_evictable=reserved_evictable
)
return request_can_be_added, request_tokens_can_be_added, kv_cache_available

def _find_kv_match_count(
Expand Down Expand Up @@ -3037,19 +3050,31 @@ def add_request(
# Slice tokens to skip matched prefix
this_round_tokens = req.remaining_prompt_tokens[prefix_skip_tokens:prefill_chunk_length]

new_block_ids = None
if num_blocks_from_pool > 0:
new_block_ids = self.kv_block_allocator.allocate_memory_blocks(num_blocks_from_pool)
if new_block_ids is None or len(new_block_ids) != num_blocks_from_pool:
raise BlockOverflowError(req.request_id)

# Increment ref counts and update timestamps for matched (shared) blocks
# Pin matched (shared) blocks BEFORE allocation. allocate_memory_blocks()
# may trigger LRU eviction, and a matched block still at ref_count == 0
# would be an eviction candidate — descendant-first LRU could evict a
# matched leaf and immediately reuse its ID for a new block, leaving the
# block table with a duplicate ID and a dangling parent. Incrementing ref
# counts first removes matched blocks from the evictable set (see
# evict_lru_blocks / get_evictable_block_count), so eviction falls back to
# genuinely unused cached blocks.
matched_tensor = None
if num_matched_blocks > 0:
matched_tensor = torch.tensor(matched_block_ids, dtype=torch.int32, device='cpu')
self.kv_block_allocator.block_ref_counts[matched_tensor] += 1
if self.prefix_caching_eviction_policy == PrefixCachingEvictionPolicy.LRU:
self.kv_block_allocator.update_timestamps(matched_tensor)

new_block_ids = None
if num_blocks_from_pool > 0:
new_block_ids = self.kv_block_allocator.allocate_memory_blocks(num_blocks_from_pool)
if new_block_ids is None or len(new_block_ids) != num_blocks_from_pool:
# Roll back the pin so a failed add does not leak ref counts on
# the matched blocks (which would make them permanently unevictable).
if matched_tensor is not None:
self.kv_block_allocator.block_ref_counts[matched_tensor] -= 1
raise BlockOverflowError(req.request_id)

# Note that we decremented the total_request_count for the chunked prefill request
# in update_requests, so setting current_id to the total_request_count will again
# make the last request the continuing chunked prefill request if one exists.
Expand Down Expand Up @@ -3151,8 +3176,14 @@ def _register_range(start: int, end: int):
return
block_ids_to_hash = self.request_to_kv_block_ids[current_id][start:end].tolist()
block_hashes_slice = req.precomputed_block_hashes[start:end]
# Parent hash of block k is the hash of block k-1 in the chain;
# block 0 is a root (parent hash 0). Enables LRU eviction to keep
# parents cached until their children are gone.
parent_hashes_slice = [
req.precomputed_block_hashes[k - 1] if k > 0 else 0 for k in range(start, end)
]
self.kv_block_allocator.register_kv_block_hashes(
block_ids_to_hash, block_hashes_slice
block_ids_to_hash, block_hashes_slice, parent_hashes_slice
)

# Range 1: prior-chunk partial block that this chunk just completed
Expand Down
120 changes: 110 additions & 10 deletions megatron/core/inference/contexts/kv_block_allocator.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ def __init__(
# Hash-to-block mapping for O(1) prefix lookup
self.kv_hash_to_block_id: Dict[int, int] = {}

# Parent hash per block for prefix-chain bookkeeping: 0 = no parent
# (root block or unregistered). Block hashes are parent-chained, so a
# cached block whose hash is some other cached block's parent must not
# be evicted before its child (see evict_lru_blocks). Valid hashes are
# in [1, 2^63-1], so 0 is a safe "no parent" sentinel.
self.block_parent_hashes = torch.zeros(
(self.total_count,), dtype=torch.int64, device='cpu'
)

# Reference count per block: 0 = cached (evictable), >0 = actively used
self.block_ref_counts = torch.zeros(
(self.total_count,), dtype=torch.int32, device='cpu'
Expand Down Expand Up @@ -128,13 +137,20 @@ def get_paused_avail(self):
"""Compute number of paused blocks available."""
return self.paused_count - self.get_paused_used()

def is_memory_available(self, num_blocks: int) -> bool:
def is_memory_available(self, num_blocks: int, reserved_evictable: int = 0) -> bool:
"""Check if memory blocks are available.

Includes both free pool blocks and evictable cached blocks (ref_count == 0).

Args:
num_blocks (int): Number of blocks to check.
reserved_evictable (int): Number of currently-evictable cached blocks
that must NOT be counted toward availability because the caller
will pin them before allocating (e.g. prefix-matched blocks that
get their ref counts bumped in add_request). These blocks are
ref_count == 0 now, so they are included in the evictable count,
but they will be protected from eviction, so they cannot supply
the requested ``num_blocks``.

Return:
(bool) Is memory available?
Expand All @@ -146,8 +162,8 @@ def is_memory_available(self, num_blocks: int) -> bool:
return False
if self.prefix_caching_eviction_policy == PrefixCachingEvictionPolicy.REF_ZERO:
return False # RZ: no cached blocks to evict
# Also count evictable cached blocks
evictable_count = self.get_evictable_block_count()
# Also count evictable cached blocks, excluding those the caller will pin.
evictable_count = int(self.get_evictable_block_count()) - reserved_evictable
return (self.total_avail + evictable_count) >= num_blocks

def allocate_memory_blocks(self, num_blocks: int) -> Optional[Tensor]:
Expand Down Expand Up @@ -253,6 +269,7 @@ def reset(self) -> None:

# Reset prefix caching state
self.kv_hash_to_block_id.clear()
self.block_parent_hashes.fill_(0)
self.block_ref_counts.fill_(0)
if self.prefix_caching_eviction_policy == PrefixCachingEvictionPolicy.LRU:
self.block_timestamps.fill_(0)
Expand All @@ -264,18 +281,32 @@ def reset(self) -> None:
# Prefix caching methods
# =========================================================================

def register_kv_block_hashes(self, block_ids: list[int], block_hashes: list[int]) -> None:
def register_kv_block_hashes(
self,
block_ids: list[int],
block_hashes: list[int],
parent_hashes: Optional[list[int]] = None,
) -> None:
"""Register blocks in the hash-to-block mapping for discovery (batch).

Args:
block_ids: List of block IDs.
block_hashes: List of computed hash values (same length as block_ids).
parent_hashes: Parent hash for each block in the prefix chain (same
length as block_ids); 0 marks a root block with no parent. Used
by LRU eviction to avoid evicting a parent before its children.
If None, parents default to 0.
"""
if not block_ids:
return
id_tensor = torch.tensor(block_ids, dtype=torch.int64, device=self.block_hashes.device)
hash_tensor = torch.tensor(block_hashes, dtype=torch.int64, device=self.block_hashes.device)
self.block_hashes[id_tensor] = hash_tensor
if parent_hashes is not None:
assert len(parent_hashes) == len(block_ids)
self.block_parent_hashes[id_tensor] = torch.tensor(
parent_hashes, dtype=torch.int64, device=self.block_hashes.device
)
self.kv_hash_to_block_id.update(zip(block_hashes, block_ids))

def _deregister_blocks(self, block_ids: Tensor) -> None:
Expand Down Expand Up @@ -307,6 +338,7 @@ def _deregister_blocks(self, block_ids: Tensor) -> None:

# Reset block state (batched tensor ops)
self.block_hashes[block_ids] = -1
self.block_parent_hashes[block_ids] = 0
self.block_ref_counts[block_ids] = 0
if self.prefix_caching_eviction_policy == PrefixCachingEvictionPolicy.LRU:
self.block_timestamps[block_ids] = 0
Expand Down Expand Up @@ -340,7 +372,28 @@ def get_evictable_block_count(self) -> Tensor:
def evict_lru_blocks(self, num_blocks_needed: int) -> bool:
"""Evict LRU cached blocks to free up space in the pool.

Evicts blocks with ref_count == 0, starting with oldest timestamps.
Evicts blocks with ref_count == 0, least-recently-used first, while never
evicting a parent before its children. Block hashes are parent-chained,
and ``_find_kv_match_count`` relies on the invariant that a cached child
block always has all of its ancestors cached too. A naive oldest-first
eviction breaks this: with chunked prefill, earlier chunks are allocated
first (older timestamps) yet are ancestors of later chunks (newer
timestamps), so once the request finishes and its blocks are cached, an
ancestor can be older than its descendant and get evicted first, leaving a
dangling child.

To preserve the invariant, we key each cached block by the *maximum*
timestamp over its subtree (itself plus all cached descendants): a cached
prefix is as recently used as the most-recently-used block extending it.
This makes every parent's key >= all of its descendants' keys, so evicting
an ascending-key prefix is always "descendant closed" — a parent is only
evicted once all of its children have been. Ties are broken by depth
(deeper first) so a parent never precedes a child at equal key.

Note: because a request holds a contiguous block prefix [0..k], any in-use
(ref_count > 0) block keeps all of its ancestors in use too. Hence a cached
(ref_count == 0) block can only have cached children, and considering the
cached set alone is sufficient to avoid dangling children.

Args:
num_blocks_needed: Number of blocks to evict.
Expand All @@ -352,13 +405,60 @@ def evict_lru_blocks(self, num_blocks_needed: int) -> bool:
cached_mask = (self.block_ref_counts == 0) & (self.block_hashes != -1)
cached_block_ids = torch.nonzero(cached_mask, as_tuple=True)[0]

if cached_block_ids.numel() < num_blocks_needed:
num_cached = cached_block_ids.numel()
if num_cached < num_blocks_needed:
return False # Not enough cached blocks to evict

# Sort by timestamp (ascending = oldest first)
cached_timestamps = self.block_timestamps[cached_block_ids]
sorted_indices = torch.argsort(cached_timestamps)
blocks_to_evict = cached_block_ids[sorted_indices[:num_blocks_needed]]
own_ts = self.block_timestamps[cached_block_ids]
hashes = self.block_hashes[cached_block_ids]
parents = self.block_parent_hashes[cached_block_ids]

# Resolve each block's parent hash to the local index of the parent block,
# or -1 when the parent is not cached (root block with parent hash 0, or a
# parent still in use). Hashes are unique per cached block, so a single
# sorted lookup suffices.
sorted_hashes, sort_order = torch.sort(hashes)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

How about maintaining parent_idx?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

pos = torch.searchsorted(sorted_hashes, parents).clamp(max=num_cached - 1)
found = sorted_hashes[pos] == parents
parent_idx = torch.where(found, sort_order[pos], torch.full_like(pos, -1))
has_parent = parent_idx >= 0
parent_safe = parent_idx.clamp(min=0) # -1 -> 0 for masked-out gathers

# Propagate subtree-max timestamp and depth up/down the parent chain via
# repeated vectorized scatter/gather. Converges in <= max-chain-depth
# iterations (bounded by prompt_len / block_size); no per-element Python.
#
# The iteration count is capped at num_cached. A valid parent graph is a
# forest, so depth can never exceed num_cached and the loop fixes well
# before the cap. The cap is a safety bound: were a hash collision to
# create a parent cycle, the depth recurrence would otherwise never
# converge and spin forever. With the cap we stop at a bounded (if
# arbitrary) ordering instead of hanging; correctness still degrades
# gracefully to "some valid block set is evicted".
#
# TODO(perf): this relaxation is O(max_depth) iterations, each O(num_cached)
# work — so O(num_cached * max_depth) per eviction. For very long single
# chains (e.g. a 1M-token prompt at block_size 256 is ~4k blocks -> ~4k
# iterations) this can get expensive under memory pressure. If it shows up
# in profiling, switch to pointer-jumping / path-doubling to converge in
# O(log max_depth) iterations instead.
subtree_max = own_ts.clone()
depth = torch.zeros(num_cached, dtype=torch.int64)
for _ in range(num_cached):
new_subtree_max = subtree_max.clone()
new_subtree_max.scatter_reduce_(
0, parent_idx[has_parent], subtree_max[has_parent], reduce="amax"
)
new_depth = torch.where(has_parent, depth[parent_safe] + 1, depth)
if torch.equal(new_subtree_max, subtree_max) and torch.equal(new_depth, depth):
break
subtree_max, depth = new_subtree_max, new_depth
Comment thread
santhnm2 marked this conversation as resolved.
Resolved

# Order by (subtree_max asc, depth desc) so children precede their parents.
# Two stable sorts compose into the desired lexicographic order.
by_depth = torch.argsort(depth, descending=True, stable=True)
order = by_depth[torch.argsort(subtree_max[by_depth], stable=True)]
blocks_to_evict = cached_block_ids[order[:num_blocks_needed]]

self._deregister_blocks(blocks_to_evict)

Expand Down
Loading