Download source/src/deepedu_decision/prefix_cache.py from DeepEduVN/bungpt-open: direct link, hf CLI and curl.
- Browser
- Download file 4.7 kB
-
https://huggingface.co/DeepEduVN/bungpt-open/resolve/main/source/src/deepedu_decision/prefix_cache.py
- Command line
-
hf download hf://DeepEduVN/bungpt-open/source/src/deepedu_decision/prefix_cache.py
-
curl -L -o prefix_cache.py https://huggingface.co/DeepEduVN/bungpt-open/resolve/main/source/src/deepedu_decision/prefix_cache.py
4.7 kB
| """Cross-request prefix cache for the fork path: per-layer model state at token-exact checkpoints of a prefix. | |
| A checkpoint after the first ``c`` tokens ``ids[:c]`` of a prefix holds what a causal model carries across that | |
| point: the last conv inputs and recurrent state of every Gated DeltaNet layer, and the keys/values of the ``ids[c_prev:c]`` | |
| tokens of every full-attention layer (``fork.Past``). Checkpoints chain: each stores only the keys/values of | |
| its own segment and names its parent, so a prefix cached at 1024, 2048 and 2500 tokens holds its keys/values once. | |
| Keys are the hash of the token ids ``ids[:c]`` (never the text), so a hit is token-exact by construction: the cached | |
| state is the state of exactly those tokens. | |
| ``lookup(ids)`` returns the longest stored checkpoint ``c <= len(ids)`` whose ids equal ``ids[:c]``. The memory cap | |
| is in bytes of GPU tensors; eviction removes the least recently used checkpoint that no other checkpoint chains | |
| from (a leaf), so a chain is never left with a missing parent. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| from dataclasses import dataclass | |
| import numpy as np | |
| import torch | |
| from .fork import Past, chain_past | |
| Key = tuple[int, bytes] | |
| def _nbytes(past: Past) -> int: | |
| return sum(t.numel() * t.element_size() for d in (past.conv, past.state, past.k, past.v) for t in d.values()) | |
| class Entry: | |
| length: int # tokens of the whole prefix up to this checkpoint | |
| segment: Past # state at the checkpoint; keys/values of this segment's tokens only | |
| parent: Key | None | |
| nbytes: int | |
| children: int = 0 | |
| used: int = 0 | |
| class PrefixCache: | |
| def __init__(self, max_bytes: int, every: int = 1024): | |
| self.max_bytes, self.every = max_bytes, every | |
| self.entries: dict[Key, Entry] = {} | |
| self.lengths: set[int] = set() | |
| self.bytes = 0 | |
| self.tick = 0 | |
| self.stats = {"lookups": 0, "hits": 0, "hit_tokens": 0, "stored": 0, "evicted": 0} | |
| def _ids(ids: list[int]) -> np.ndarray: | |
| return np.asarray(ids, dtype=np.int32) | |
| def key(self, ids: list[int] | np.ndarray, length: int) -> Key: | |
| arr = self._ids(ids) if not isinstance(ids, np.ndarray) else ids | |
| return length, hashlib.blake2b(arr[:length].tobytes(), digest_size=16).digest() | |
| def lookup(self, ids: list[int]) -> tuple[int, Past | None, Key | None]: | |
| """-> (cached length, the prefix's ``Past`` for ``ids[:length]``, its key); (0, None, None) on a miss.""" | |
| self.stats["lookups"] += 1 | |
| arr = self._ids(ids) | |
| best: Key | None = None | |
| h, at = hashlib.blake2b(digest_size=16), 0 | |
| for c in sorted(x for x in self.lengths if x <= len(arr)): | |
| h.update(arr[at:c].tobytes()) | |
| at = c | |
| key = (c, h.copy().digest()) | |
| if key in self.entries: | |
| best = key | |
| if best is None: | |
| return 0, None, None | |
| chain, k = [], best | |
| self.tick += 1 | |
| while k is not None: | |
| e = self.entries[k] | |
| e.used = self.tick | |
| chain.append(e.segment) | |
| k = e.parent | |
| self.stats["hits"] += 1 | |
| self.stats["hit_tokens"] += best[0] | |
| return best[0], chain_past(chain[::-1]), best | |
| def put(self, ids: list[int], length: int, segment: Past, parent: Key | None) -> Key: | |
| """Store the checkpoint after ``ids[:length]``; ``segment`` covers ``ids[parent length:length]``.""" | |
| key = self.key(ids, length) | |
| if key in self.entries: | |
| return key | |
| if parent is not None and parent not in self.entries: | |
| return key # the parent was evicted since the lookup: a chained segment cannot be stored without it | |
| entry = Entry(length, segment, parent, _nbytes(segment), 0, self.tick) | |
| if parent is not None: | |
| self.entries[parent].children += 1 | |
| self.entries[key] = entry | |
| self.lengths.add(length) | |
| self.bytes += entry.nbytes | |
| self.stats["stored"] += 1 | |
| self._evict(protect=key) | |
| return key | |
| def _evict(self, protect: Key) -> None: | |
| while self.bytes > self.max_bytes: | |
| leaves = [(e.used, k) for k, e in self.entries.items() if e.children == 0 and k != protect] | |
| if not leaves: | |
| return | |
| _, k = min(leaves) | |
| e = self.entries.pop(k) | |
| if e.parent is not None: | |
| self.entries[e.parent].children -= 1 | |
| if not any(x.length == e.length for x in self.entries.values()): | |
| self.lengths.discard(e.length) | |
| self.bytes -= e.nbytes | |
| self.stats["evicted"] += 1 | |