digm-vllm 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- digm/__init__.py +18 -0
- digm/compaction.py +41 -0
- digm/config.py +32 -0
- digm/scoring.py +34 -0
- digm/selection.py +100 -0
- digm/vllm_integration.py +224 -0
- digm_vllm-0.2.0.dist-info/METADATA +302 -0
- digm_vllm-0.2.0.dist-info/RECORD +12 -0
- digm_vllm-0.2.0.dist-info/WHEEL +5 -0
- digm_vllm-0.2.0.dist-info/licenses/LICENSE +201 -0
- digm_vllm-0.2.0.dist-info/licenses/NOTICE +5 -0
- digm_vllm-0.2.0.dist-info/top_level.txt +1 -0
digm/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""DIGM: training-free KV-cache eviction inside vLLM.
|
|
2
|
+
|
|
3
|
+
Library layout
|
|
4
|
+
config.py DIGMConfig: every knob in one place
|
|
5
|
+
scoring.py query-free per-head token scores (KeyDiff-style cosine, norms)
|
|
6
|
+
selection.py which prompt positions to keep (budgets, sinks, recency, question)
|
|
7
|
+
compaction.py copy kept K/V into the first slots of a request's own blocks
|
|
8
|
+
vllm_integration.py DIGMvLLM: wires the above into a running vLLM engine
|
|
9
|
+
(block freeing, RoPE offset, preemption restore)
|
|
10
|
+
|
|
11
|
+
The paper's numbers come from paper_artifact/digm_vllm_v18.py, which is kept unchanged.
|
|
12
|
+
This package reproduces its stage-1 and throughput results exactly (see tests/).
|
|
13
|
+
"""
|
|
14
|
+
from .config import DIGMConfig
|
|
15
|
+
from .vllm_integration import DIGMvLLM
|
|
16
|
+
|
|
17
|
+
__all__ = ["DIGMConfig", "DIGMvLLM"]
|
|
18
|
+
__version__ = "0.2.0"
|
digm/compaction.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Move kept tokens' K/V to the first slots of a request's own blocks (paged KV layout).
|
|
2
|
+
|
|
3
|
+
vLLM's KV tensor per layer has shape (num_blocks, H, block_size, 2D): keys in [..., :D], values in [..., D:].
|
|
4
|
+
Keys are stored after RoPE, so a kept token's slot can change freely; positions are fixed separately.
|
|
5
|
+
"""
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def slots_of(block_ids, idx: torch.Tensor, block_size: int, dev):
|
|
10
|
+
"""(block, offset) of token positions `idx` in a request whose blocks are `block_ids`."""
|
|
11
|
+
mx = int(idx.max()) if idx.numel() else 0
|
|
12
|
+
if mx // block_size >= len(block_ids): # clear error instead of a CUDA index assert
|
|
13
|
+
raise RuntimeError(f"slot out of range: token {mx} needs block {mx // block_size}, request has "
|
|
14
|
+
f"{len(block_ids)} blocks (= {len(block_ids) * block_size} slots)")
|
|
15
|
+
b = torch.as_tensor(block_ids, device=dev, dtype=torch.long)
|
|
16
|
+
return b[idx // block_size], idx % block_size
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@torch.no_grad()
|
|
20
|
+
def compact(kv, block_ids, keep: torch.Tensor, block_size: int, H: int, dev) -> torch.Tensor:
|
|
21
|
+
"""Copy kept K/V into slots 0..k-1 in every layer (gather first, then write).
|
|
22
|
+
|
|
23
|
+
keep: 1-D (shared set) or (L, H, k) (composite: slot j of head h holds that head's j-th kept token).
|
|
24
|
+
Returns the positions whose token ids represent the kept tokens (any consistent list; the model
|
|
25
|
+
never reads token ids of already-computed tokens).
|
|
26
|
+
"""
|
|
27
|
+
k = int(keep.shape[-1])
|
|
28
|
+
db, do = slots_of(block_ids, torch.arange(k, device=dev), block_size, dev)
|
|
29
|
+
if keep.dim() == 1:
|
|
30
|
+
sb, so = slots_of(block_ids, keep, block_size, dev)
|
|
31
|
+
for l in range(len(kv)):
|
|
32
|
+
tmp = kv[l][sb, :, so, :].clone()
|
|
33
|
+
kv[l][db, :, do, :] = tmp
|
|
34
|
+
return keep
|
|
35
|
+
hh = torch.arange(H, device=dev).unsqueeze(1)
|
|
36
|
+
dbe, doe = db.unsqueeze(0).expand(H, -1), do.unsqueeze(0).expand(H, -1)
|
|
37
|
+
for l in range(len(kv)):
|
|
38
|
+
sb, so = slots_of(block_ids, keep[l], block_size, dev) # (H, k)
|
|
39
|
+
tmp = kv[l][sb, hh, so, :].clone() # (H, k, 2D)
|
|
40
|
+
kv[l][dbe, hh, doe, :] = tmp
|
|
41
|
+
return keep[0, 0]
|
digm/config.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""All DIGM knobs in one place. Defaults match paper_artifact/digm_vllm_v18.py."""
|
|
2
|
+
from dataclasses import dataclass
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class DIGMConfig:
|
|
8
|
+
keep: float = 0.25 # fraction of the context kept (ignored when budget > 0)
|
|
9
|
+
budget: int = 0 # > 0: keep this many context tokens instead of keep * context
|
|
10
|
+
sel: str = "head:cos" # "head:<kind>" per-head (composite) | "one" DIGM-one | "<kind>/<fusion>" consensus | "stream"
|
|
11
|
+
lstar: int = 4 # layer whose keys drive DIGM-one
|
|
12
|
+
n_sink: int = 4 # attention-sink tokens always kept (DIGM-one, consensus, stream)
|
|
13
|
+
recent_frac: float = 0.5 # DIGM-one: share of the budget given to the most recent tokens
|
|
14
|
+
pool: int = 5 # DIGM-one: max-pool window over scores
|
|
15
|
+
head_sinks: bool = False # per-head mode: also force the first n_sink tokens
|
|
16
|
+
preempt_mode: str = "restore" # "restore" puts the original prompt back on preemption | "naive"
|
|
17
|
+
use_evict_api: bool = True # use vLLM's evict_token_range_for_request when the engine has it
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def from_env(cls, **over):
|
|
21
|
+
"""Read the same DIGM_* environment variables as the paper script."""
|
|
22
|
+
c = cls(
|
|
23
|
+
keep=float(os.environ.get("DIGM_KEEP", "0.25")),
|
|
24
|
+
budget=int(os.environ.get("DIGM_BUDGET", "0")),
|
|
25
|
+
sel=os.environ.get("DIGM_SEL", "head:cos"),
|
|
26
|
+
head_sinks=os.environ.get("DIGM_HEAD_SINKS", "0") == "1",
|
|
27
|
+
preempt_mode=os.environ.get("DIGM_PREEMPT", "restore"),
|
|
28
|
+
use_evict_api=os.environ.get("DIGM_EVICT_API", "1") == "1",
|
|
29
|
+
)
|
|
30
|
+
for k, v in over.items():
|
|
31
|
+
setattr(c, k, v)
|
|
32
|
+
return c
|
digm/scoring.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Query-free token scores. Higher = more worth keeping. Nothing here touches vLLM."""
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn.functional as F
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def list_scores(k: torch.Tensor, v: torch.Tensor, kind: str) -> torch.Tensor:
|
|
7
|
+
"""Per-head scores. k, v: (H, n, D) float. Returns (H, n).
|
|
8
|
+
|
|
9
|
+
cos KeyDiff-style: low cosine similarity to the head's mean (normalised) key = distinctive = keep
|
|
10
|
+
cnorm distance from the mean key
|
|
11
|
+
knorm small key norm = keep
|
|
12
|
+
vk value norm / key norm
|
|
13
|
+
cosv z(cos) + z(log value norm)
|
|
14
|
+
"""
|
|
15
|
+
if kind == "cos":
|
|
16
|
+
return -F.cosine_similarity(k, F.normalize(k, p=2, dim=-1).mean(1, keepdim=True), dim=-1)
|
|
17
|
+
if kind == "cnorm":
|
|
18
|
+
return (k - k.mean(1, keepdim=True)).norm(dim=-1)
|
|
19
|
+
if kind == "knorm":
|
|
20
|
+
return -k.norm(dim=-1)
|
|
21
|
+
if kind == "vk":
|
|
22
|
+
return v.norm(dim=-1) / (k.norm(dim=-1) + 1e-6)
|
|
23
|
+
if kind == "cosv":
|
|
24
|
+
zs = lambda x: (x - x.mean(-1, keepdim=True)) / (x.std(-1, keepdim=True) + 1e-6)
|
|
25
|
+
return zs(list_scores(k, v, "cos")) + zs(v.norm(dim=-1).clamp_min(1e-6).log())
|
|
26
|
+
raise ValueError(f"unknown score kind {kind!r}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def norm_scores(keys: torch.Tensor, pool: int) -> torch.Tensor:
|
|
30
|
+
"""DIGM-one scores from one layer's keys (n, H, D): standardised mean key norm, low norm = keep,
|
|
31
|
+
then max-pooled over a window of `pool` tokens. Returns (n,)."""
|
|
32
|
+
nrm = keys.float().norm(dim=-1).mean(dim=-1)
|
|
33
|
+
s = -(nrm - nrm.mean()) / (nrm.std() + 1e-6)
|
|
34
|
+
return F.max_pool1d(s.view(1, 1, -1), pool, 1, pool // 2).view(-1)
|
digm/selection.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Which prompt positions to keep. Pure tensor code: the caller passes a function that returns one
|
|
2
|
+
layer's K/V for the context tokens, so nothing here depends on vLLM.
|
|
3
|
+
|
|
4
|
+
Every function returns prompt positions in [0, n):
|
|
5
|
+
- a 1-D tensor (one shared set for all layers and heads), or
|
|
6
|
+
- an (L, H, k) tensor (composite: every layer and head keeps its own top-k).
|
|
7
|
+
The question part of the prompt, positions [n_ctx, n), is always kept.
|
|
8
|
+
"""
|
|
9
|
+
from typing import Callable
|
|
10
|
+
import torch
|
|
11
|
+
|
|
12
|
+
from .config import DIGMConfig
|
|
13
|
+
from .scoring import list_scores, norm_scores
|
|
14
|
+
|
|
15
|
+
CtxKV = Callable[[int], torch.Tensor] # layer -> (n_ctx, H, 2D) keys then values
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def ctx_budget(cfg: DIGMConfig, n_ctx: int, lo: int) -> int:
|
|
19
|
+
b = min(cfg.budget, n_ctx) if cfg.budget > 0 else int(n_ctx * cfg.keep)
|
|
20
|
+
return max(b, lo)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def keep_one(cfg: DIGMConfig, ctx_kv: CtxKV, n_ctx: int, n: int, D: int, dev) -> torch.Tensor:
|
|
24
|
+
"""DIGM-one: layer l*'s key norms choose one shared set, plus sinks and the most recent tokens."""
|
|
25
|
+
s = norm_scores(ctx_kv(cfg.lstar)[..., :D], cfg.pool)
|
|
26
|
+
budget = ctx_budget(cfg, n_ctx, cfg.n_sink + 1)
|
|
27
|
+
s[:cfg.n_sink] = float("inf")
|
|
28
|
+
s[-max(int(budget * cfg.recent_frac), 1):] = float("inf")
|
|
29
|
+
keep_ctx = torch.topk(s, budget).indices
|
|
30
|
+
keep = torch.cat([keep_ctx, torch.arange(n_ctx, n, device=dev)])
|
|
31
|
+
return torch.sort(keep).values
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def perhead_scores(cfg: DIGMConfig, ctx_kv: CtxKV, L: int, D: int) -> torch.Tensor:
|
|
35
|
+
"""(L, H, n_ctx) per-head scores of the context tokens (higher = keep)."""
|
|
36
|
+
kind = cfg.sel.split(":", 1)[1]
|
|
37
|
+
out = []
|
|
38
|
+
for l in range(L):
|
|
39
|
+
x = ctx_kv(l)
|
|
40
|
+
s = list_scores(x[..., :D].transpose(0, 1).float(), x[..., D:].transpose(0, 1).float(), kind)
|
|
41
|
+
if cfg.head_sinks:
|
|
42
|
+
s[:, :cfg.n_sink] = float("inf")
|
|
43
|
+
out.append(s)
|
|
44
|
+
return torch.stack(out)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def keep_perhead(cfg: DIGMConfig, ctx_kv: CtxKV, n_ctx: int, n: int, L: int, H: int, D: int, dev) -> torch.Tensor:
|
|
48
|
+
"""Composite: each (layer, head) keeps its own top-k context tokens (same k everywhere, so one block
|
|
49
|
+
table still fits) plus the question. Returns (L, H, k + n - n_ctx)."""
|
|
50
|
+
kind = cfg.sel.split(":", 1)[1]
|
|
51
|
+
budget = ctx_budget(cfg, n_ctx, 1)
|
|
52
|
+
q = torch.arange(n_ctx, n, device=dev)
|
|
53
|
+
out = []
|
|
54
|
+
for l in range(L):
|
|
55
|
+
x = ctx_kv(l)
|
|
56
|
+
s = list_scores(x[..., :D].transpose(0, 1).float(), x[..., D:].transpose(0, 1).float(), kind)
|
|
57
|
+
if cfg.head_sinks:
|
|
58
|
+
s[:, :cfg.n_sink] = float("inf")
|
|
59
|
+
idx = s.topk(budget, dim=-1).indices.sort(dim=-1).values
|
|
60
|
+
out.append(torch.cat([idx, q.unsqueeze(0).expand(H, -1)], dim=-1))
|
|
61
|
+
return torch.stack(out)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def keep_consensus(cfg: DIGMConfig, ctx_kv: CtxKV, n_ctx: int, n: int, L: int, D: int, dev) -> torch.Tensor:
|
|
65
|
+
"""DIGM-C: every (layer, head) scores the context; the scores are fused into ONE shared set."""
|
|
66
|
+
kind, fusion = cfg.sel.split("/")
|
|
67
|
+
budget = ctx_budget(cfg, n_ctx, cfg.n_sink + 1)
|
|
68
|
+
sum_z = torch.zeros(n_ctx, device=dev); vote = torch.zeros(n_ctx, device=dev)
|
|
69
|
+
minr = torch.full((n_ctx,), n_ctx, device=dev, dtype=torch.long); M = 0
|
|
70
|
+
ar = torch.arange(n_ctx, device=dev)
|
|
71
|
+
for l in range(L):
|
|
72
|
+
x = ctx_kv(l)
|
|
73
|
+
s = list_scores(x[..., :D].transpose(0, 1).float(), x[..., D:].transpose(0, 1).float(), kind)
|
|
74
|
+
z = (s - s.mean(-1, keepdim=True)) / (s.std(-1, keepdim=True) + 1e-6)
|
|
75
|
+
rank = torch.empty_like(s, dtype=torch.long)
|
|
76
|
+
rank.scatter_(-1, s.argsort(-1, descending=True), ar.expand_as(s).contiguous())
|
|
77
|
+
sum_z += z.sum(0); vote += (rank < budget).sum(0); minr = torch.minimum(minr, rank.min(0).values); M += s.shape[0]
|
|
78
|
+
zm = sum_z / M
|
|
79
|
+
f = zm.clone() if fusion == "mean" else (vote + 0.01 * torch.tanh(zm) if fusion == "vote"
|
|
80
|
+
else -minr.float() + 0.5 * vote / (M + 1))
|
|
81
|
+
f[:cfg.n_sink] = float("inf")
|
|
82
|
+
keep = torch.cat([f.topk(budget).indices, torch.arange(n_ctx, n, device=dev)])
|
|
83
|
+
return torch.sort(keep).values
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def keep_stream(cfg: DIGMConfig, n_ctx: int, n: int, dev) -> torch.Tensor:
|
|
87
|
+
"""StreamingLLM baseline: sinks + the most recent context tokens + the question."""
|
|
88
|
+
budget = ctx_budget(cfg, n_ctx, cfg.n_sink + 1)
|
|
89
|
+
return torch.cat([torch.arange(cfg.n_sink, device=dev),
|
|
90
|
+
torch.arange(n_ctx - (budget - cfg.n_sink), n, device=dev)])
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def select_keep(cfg: DIGMConfig, ctx_kv: CtxKV, n_ctx: int, n: int, L: int, H: int, D: int, dev) -> torch.Tensor:
|
|
94
|
+
if cfg.sel == "one":
|
|
95
|
+
return keep_one(cfg, ctx_kv, n_ctx, n, D, dev)
|
|
96
|
+
if cfg.sel == "stream":
|
|
97
|
+
return keep_stream(cfg, n_ctx, n, dev)
|
|
98
|
+
if cfg.sel.startswith("head:"):
|
|
99
|
+
return keep_perhead(cfg, ctx_kv, n_ctx, n, L, H, D, dev)
|
|
100
|
+
return keep_consensus(cfg, ctx_kv, n_ctx, n, L, D, dev)
|
digm/vllm_integration.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""DIGMvLLM: real KV eviction inside a running vLLM engine (V1 engine, in-process, single GPU).
|
|
2
|
+
|
|
3
|
+
After a request's prompt is prefilled, `evict(rid, keep, n)`:
|
|
4
|
+
1. compacts the kept K/V into the first k slots of the request's own blocks (every layer),
|
|
5
|
+
2. scheduler: the request now holds k computed tokens; its tail blocks go back to vLLM's pool
|
|
6
|
+
(through vLLM's evict_token_range_for_request when available, PR #53871),
|
|
7
|
+
3. worker: token counts, prefill/prompt lengths and block-table length move to k,
|
|
8
|
+
4. RoPE: tokens computed from now on keep their ORIGINAL positions via a per-request offset.
|
|
9
|
+
On preemption, the original prompt is put back so vLLM recomputes it correctly ("restore").
|
|
10
|
+
|
|
11
|
+
Tested with vLLM 0.30.0, 0.33.0 and the PR #53871 branch. It touches vLLM internals, so
|
|
12
|
+
untested versions may break. Create the LLM with enable_prefix_caching=False and
|
|
13
|
+
VLLM_ENABLE_V1_MULTIPROCESSING=0.
|
|
14
|
+
"""
|
|
15
|
+
import torch
|
|
16
|
+
|
|
17
|
+
from .config import DIGMConfig
|
|
18
|
+
from .compaction import slots_of, compact
|
|
19
|
+
from .selection import select_keep as _select_keep
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def relax_kv_memory_check():
|
|
23
|
+
"""Allow max_model_len larger than the KV pool (for eviction during chunked prefill).
|
|
24
|
+
Call BEFORE creating the LLM."""
|
|
25
|
+
try: # vLLM >= 0.33 moved this check to kv_cache_planning
|
|
26
|
+
import vllm.v1.core.kv_cache_planning as kvu
|
|
27
|
+
kvu._check_enough_kv_cache_memory
|
|
28
|
+
except (ImportError, AttributeError): # vLLM 0.30
|
|
29
|
+
import vllm.v1.core.kv_cache_utils as kvu
|
|
30
|
+
orig = kvu._check_enough_kv_cache_memory
|
|
31
|
+
|
|
32
|
+
def relaxed(available_memory, get_needed_memory, max_model_len, estimate_max_model_len):
|
|
33
|
+
if available_memory <= 0:
|
|
34
|
+
return orig(available_memory, get_needed_memory, max_model_len, estimate_max_model_len)
|
|
35
|
+
kvu._check_enough_kv_cache_memory = relaxed
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class DIGMvLLM:
|
|
39
|
+
def __init__(self, llm, cfg: DIGMConfig, num_kv_heads: int, head_dim: int):
|
|
40
|
+
self.cfg, self.llm = cfg, llm
|
|
41
|
+
self.engine = llm.llm_engine
|
|
42
|
+
core = self.engine.engine_core.engine_core
|
|
43
|
+
self.core = core
|
|
44
|
+
self.runner = core.model_executor.driver_worker.worker.model_runner
|
|
45
|
+
self.sched = core.scheduler
|
|
46
|
+
self.kvm = self.sched.kv_cache_manager
|
|
47
|
+
self.mgr = self.kvm.coordinator.single_type_managers[0]
|
|
48
|
+
self.pool = self.kvm.block_pool
|
|
49
|
+
self.kv = self.runner.kv_caches
|
|
50
|
+
self.L, self.H, self.D = len(self.kv), num_kv_heads, head_dim
|
|
51
|
+
shp = tuple(self.kv[0].shape)
|
|
52
|
+
assert len(shp) == 4 and shp[1] == self.H and shp[-1] == 2 * self.D, f"unexpected KV layout {shp}"
|
|
53
|
+
self.BS = shp[2]
|
|
54
|
+
self.dev = self.kv[0].device
|
|
55
|
+
self.use_evict_api = cfg.use_evict_api and hasattr(self.kvm, "evict_token_range_for_request")
|
|
56
|
+
self.evicted = {} # request_id -> {"orig", "idx", "preempts", "needs"}
|
|
57
|
+
self._install_offset()
|
|
58
|
+
self._install_preempt_restore()
|
|
59
|
+
|
|
60
|
+
# ---------------- RoPE: per-request position offset, applied after slot mapping ----------------
|
|
61
|
+
def _install_offset(self):
|
|
62
|
+
self.offset = torch.zeros(self.runner.req_states.max_num_reqs, dtype=torch.int64, device=self.dev)
|
|
63
|
+
orig, offset = self.runner.prepare_attn, self.offset
|
|
64
|
+
|
|
65
|
+
def prepare_attn_with_offset(input_batch):
|
|
66
|
+
out = orig(input_batch) # slots + lengths use compact indices
|
|
67
|
+
nr = input_batch.num_reqs
|
|
68
|
+
qsl = input_batch.query_start_loc[: nr + 1].long()
|
|
69
|
+
qlen = qsl[1:] - qsl[:-1]
|
|
70
|
+
tok_req = torch.repeat_interleave(input_batch.idx_mapping[:nr].long(), qlen)
|
|
71
|
+
input_batch.positions[: tok_req.numel()] += offset[tok_req] # RoPE sees original positions
|
|
72
|
+
return out
|
|
73
|
+
self.runner.prepare_attn = prepare_attn_with_offset
|
|
74
|
+
|
|
75
|
+
# ---------------- preemption: vLLM recomputes a preempted request from its token ids ----------------
|
|
76
|
+
def _install_preempt_restore(self):
|
|
77
|
+
orig = self.sched._preempt_request
|
|
78
|
+
|
|
79
|
+
def preempt_with_restore(request, timestamp, *a, **kw):
|
|
80
|
+
st = self.evicted.get(request.request_id)
|
|
81
|
+
if st is not None:
|
|
82
|
+
st["preempts"] += 1
|
|
83
|
+
if st["idx"] is not None:
|
|
84
|
+
self.offset[st["idx"]] = 0 # worker slot released; new slot starts at 0
|
|
85
|
+
st["idx"] = None
|
|
86
|
+
if self.cfg.preempt_mode == "restore":
|
|
87
|
+
outs = list(request._output_token_ids)
|
|
88
|
+
request._all_token_ids[:] = list(st["orig"]) + outs
|
|
89
|
+
request.prompt_token_ids = list(st["orig"])
|
|
90
|
+
request.num_prompt_tokens = len(st["orig"])
|
|
91
|
+
st["needs"] = True # evict again after the re-prefill
|
|
92
|
+
return orig(request, timestamp, *a, **kw)
|
|
93
|
+
self.sched._preempt_request = preempt_with_restore
|
|
94
|
+
|
|
95
|
+
# ---------------- helpers ----------------
|
|
96
|
+
def find_rid(self, tag):
|
|
97
|
+
return next((r for r in self.sched.requests if tag in str(r)), None)
|
|
98
|
+
|
|
99
|
+
def block_ids(self, rid):
|
|
100
|
+
return list(self.kvm.get_block_ids(rid)[0])
|
|
101
|
+
|
|
102
|
+
def ctx_kv_fn(self, rid, n_ctx):
|
|
103
|
+
"""layer -> (n_ctx, H, 2D) K/V of the request's first n_ctx tokens."""
|
|
104
|
+
b, o = slots_of(self.block_ids(rid), torch.arange(n_ctx, device=self.dev), self.BS, self.dev)
|
|
105
|
+
return lambda l: self.kv[l][b, :, o, :]
|
|
106
|
+
|
|
107
|
+
def select_keep(self, rid, n_ctx, n):
|
|
108
|
+
return _select_keep(self.cfg, self.ctx_kv_fn(rid, n_ctx), n_ctx, n, self.L, self.H, self.D, self.dev)
|
|
109
|
+
|
|
110
|
+
def release(self, rid):
|
|
111
|
+
"""Call when a request finishes: its worker slot's offset goes back to 0."""
|
|
112
|
+
st = self.evicted.get(rid)
|
|
113
|
+
if st is not None and st["idx"] is not None:
|
|
114
|
+
self.offset[st["idx"]] = 0
|
|
115
|
+
st["idx"] = None
|
|
116
|
+
|
|
117
|
+
def free_tail_blocks(self, rid, keep_nb):
|
|
118
|
+
"""Free a live request's blocks from index keep_nb on. Returns blocks returned to the pool."""
|
|
119
|
+
blocks = self.mgr.req_to_blocks[rid]
|
|
120
|
+
before = self.pool.get_num_free_blocks()
|
|
121
|
+
if self.use_evict_api:
|
|
122
|
+
a, _, _ = self.kvm.evict_token_range_for_request(rid, keep_nb * self.BS, len(blocks) * self.BS)
|
|
123
|
+
assert a == keep_nb * self.BS, (a, keep_nb * self.BS)
|
|
124
|
+
else:
|
|
125
|
+
tail = blocks[keep_nb:]; del blocks[keep_nb:]
|
|
126
|
+
if rid in self.mgr.num_cached_block:
|
|
127
|
+
self.mgr.num_cached_block[rid] = min(self.mgr.num_cached_block[rid], keep_nb)
|
|
128
|
+
self.pool.free_blocks(reversed(tail))
|
|
129
|
+
return self.pool.get_num_free_blocks() - before
|
|
130
|
+
|
|
131
|
+
# ---------------- eviction after prefill ----------------
|
|
132
|
+
@torch.no_grad()
|
|
133
|
+
def evict(self, rid, keep, n, use_offset=True):
|
|
134
|
+
"""keep = prompt positions to keep (1-D shared set, or (L, H, k) composite). Outputs whose KV is
|
|
135
|
+
already computed (e.g. replayed after a preemption) are always kept."""
|
|
136
|
+
req = self.sched.requests[rid]
|
|
137
|
+
comp = int(req.num_computed_tokens)
|
|
138
|
+
if comp > n: # keep already-computed outputs, in order
|
|
139
|
+
extra = torch.arange(n, comp, device=self.dev)
|
|
140
|
+
keep = torch.cat([keep, extra]) if keep.dim() == 1 else \
|
|
141
|
+
torch.cat([keep, extra.view(1, 1, -1).expand(keep.shape[0], keep.shape[1], -1)], dim=-1)
|
|
142
|
+
k = int(keep.shape[-1])
|
|
143
|
+
kp = k - max(comp - n, 0) # kept PROMPT tokens
|
|
144
|
+
block_ids = self.block_ids(rid)
|
|
145
|
+
if rid not in self.evicted:
|
|
146
|
+
self.evicted[rid] = {"orig": list(req.prompt_token_ids), "idx": None, "preempts": 0, "needs": False}
|
|
147
|
+
# 1) KV compaction in every layer
|
|
148
|
+
pos0 = compact(self.kv, block_ids, keep, self.BS, self.H, self.dev)
|
|
149
|
+
d = comp - k
|
|
150
|
+
keep_nb = -(-k // self.BS)
|
|
151
|
+
# 2) scheduler: prompt = kept prompt tokens, outputs unchanged, tail blocks freed
|
|
152
|
+
kept_ids = [req._all_token_ids[i] for i in pos0[:kp].tolist()]
|
|
153
|
+
outs = list(req._output_token_ids)
|
|
154
|
+
req._all_token_ids[:] = kept_ids + outs
|
|
155
|
+
if req.prompt_token_ids is not None:
|
|
156
|
+
req.prompt_token_ids = list(kept_ids) # rebind: never mutate the caller's list
|
|
157
|
+
req.num_prompt_tokens = kp
|
|
158
|
+
req.num_computed_tokens = comp - d
|
|
159
|
+
freed = self.free_tail_blocks(rid, keep_nb)
|
|
160
|
+
# 3) worker state: every counter shifts by -d
|
|
161
|
+
rs = self.runner.req_states
|
|
162
|
+
idx = rs.req_id_to_index[rid]
|
|
163
|
+
if comp == n: # first eviction
|
|
164
|
+
rs.num_computed_tokens.gpu[idx] = k
|
|
165
|
+
rs.num_computed_tokens_np[idx] = k
|
|
166
|
+
rs.num_computed_prefill_tokens[idx] = k
|
|
167
|
+
rs.prefill_len.np[idx] = k
|
|
168
|
+
else: # re-eviction after a restored preemption
|
|
169
|
+
rs.num_computed_tokens.gpu[idx] -= d
|
|
170
|
+
rs.num_computed_tokens_np[idx] -= d
|
|
171
|
+
rs.num_computed_prefill_tokens[idx] -= d
|
|
172
|
+
rs.prefill_len.np[idx] -= d
|
|
173
|
+
rs.prefill_len.copy_to_uva()
|
|
174
|
+
rs.prompt_len.np[idx] = kp; rs.prompt_len.copy_to_uva()
|
|
175
|
+
rs.total_len.gpu[idx] -= d
|
|
176
|
+
rs.max_seq_len[idx] -= d
|
|
177
|
+
row = rs.all_token_ids.gpu[idx]
|
|
178
|
+
row[:kp] = torch.as_tensor(kept_ids, dtype=row.dtype, device=row.device)
|
|
179
|
+
if outs:
|
|
180
|
+
row[kp:kp + len(outs)] = torch.as_tensor(outs, dtype=row.dtype, device=row.device)
|
|
181
|
+
bt = self.runner.block_tables
|
|
182
|
+
bt.num_blocks.np[0, idx] = keep_nb; bt.num_blocks.copy_to_uva()
|
|
183
|
+
# 4) RoPE offset for every token computed from now on (original position = slot + offset)
|
|
184
|
+
self.offset[idx] = (n - kp) if use_offset else 0
|
|
185
|
+
self.evicted[rid]["idx"] = idx; self.evicted[rid]["needs"] = False
|
|
186
|
+
return {"n": n, "k": k, "freed_blocks": freed, "freed_tokens": freed * self.BS, "idx": idx}
|
|
187
|
+
|
|
188
|
+
# ---------------- eviction during chunked prefill ----------------
|
|
189
|
+
@torch.no_grad()
|
|
190
|
+
def evict_mid(self, rid, keep):
|
|
191
|
+
"""keep = positions among the tokens computed so far (all context). The not-yet-computed rest of the
|
|
192
|
+
prompt stays; positions of everything after keep shift by d (offset += d). Returns d."""
|
|
193
|
+
req = self.sched.requests[rid]
|
|
194
|
+
comp = int(req.num_computed_tokens)
|
|
195
|
+
k = int(keep.shape[-1]); d = comp - k
|
|
196
|
+
if d <= 0:
|
|
197
|
+
return 0
|
|
198
|
+
block_ids = self.block_ids(rid)
|
|
199
|
+
if rid not in self.evicted:
|
|
200
|
+
self.evicted[rid] = {"orig": list(req.prompt_token_ids), "idx": None, "preempts": 0, "needs": False}
|
|
201
|
+
pos0 = compact(self.kv, block_ids, keep, self.BS, self.H, self.dev)
|
|
202
|
+
kept_ids = [req._all_token_ids[i] for i in pos0.tolist()]
|
|
203
|
+
rest = list(req._all_token_ids[comp:])
|
|
204
|
+
req._all_token_ids[:] = kept_ids + rest
|
|
205
|
+
req.prompt_token_ids = kept_ids + rest
|
|
206
|
+
req.num_prompt_tokens = len(kept_ids) + len(rest)
|
|
207
|
+
req.num_computed_tokens = k
|
|
208
|
+
keep_nb = -(-k // self.BS)
|
|
209
|
+
self.free_tail_blocks(rid, keep_nb)
|
|
210
|
+
rs = self.runner.req_states; idx = rs.req_id_to_index[rid]
|
|
211
|
+
rs.num_computed_tokens.gpu[idx] = k
|
|
212
|
+
rs.num_computed_tokens_np[idx] = k
|
|
213
|
+
rs.num_computed_prefill_tokens[idx] = k
|
|
214
|
+
rs.prefill_len.np[idx] -= d; rs.prefill_len.copy_to_uva()
|
|
215
|
+
rs.prompt_len.np[idx] -= d; rs.prompt_len.copy_to_uva()
|
|
216
|
+
rs.total_len.gpu[idx] -= d
|
|
217
|
+
rs.max_seq_len[idx] -= d
|
|
218
|
+
row = rs.all_token_ids.gpu[idx]
|
|
219
|
+
row[:k + len(rest)] = torch.as_tensor(kept_ids + rest, dtype=row.dtype, device=row.device)
|
|
220
|
+
bt = self.runner.block_tables
|
|
221
|
+
bt.num_blocks.np[0, idx] = keep_nb; bt.num_blocks.copy_to_uva()
|
|
222
|
+
self.offset[idx] += d
|
|
223
|
+
self.evicted[rid]["idx"] = idx
|
|
224
|
+
return d
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: digm-vllm
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Training-free KV-cache eviction inside vLLM (research prototype)
|
|
5
|
+
Author: Sai Jathin Bhupalam, Naveen N C
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/bhupalamjathin-svg/DIGM
|
|
8
|
+
Project-URL: Source, https://github.com/bhupalamjathin-svg/DIGM
|
|
9
|
+
Project-URL: Issues, https://github.com/bhupalamjathin-svg/DIGM/issues
|
|
10
|
+
Keywords: vllm,kv-cache,llm-inference,llm-serving,kv-cache-compression
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
License-File: NOTICE
|
|
19
|
+
Requires-Dist: torch
|
|
20
|
+
Requires-Dist: vllm<0.34,>=0.30.0
|
|
21
|
+
Provides-Extra: benchmarks
|
|
22
|
+
Requires-Dist: datasets; extra == "benchmarks"
|
|
23
|
+
Requires-Dist: transformers; extra == "benchmarks"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
<h1 align="center">DIGM</h1>
|
|
27
|
+
<p align="center"><b>Dynamic Importance-Gated Memory</b><br>
|
|
28
|
+
KV-cache eviction for LLM serving, built on vLLM</p>
|
|
29
|
+
|
|
30
|
+
<p align="center">
|
|
31
|
+
<img alt="vLLM 0.30.0 | 0.33.0" src="https://img.shields.io/badge/vLLM-0.30.0%20%7C%200.33.0-blue">
|
|
32
|
+
<img alt="status: research prototype" src="https://img.shields.io/badge/status-research%20prototype-orange">
|
|
33
|
+
<img alt="licence: Apache-2.0" src="https://img.shields.io/badge/licence-Apache--2.0-blue">
|
|
34
|
+
</p>
|
|
35
|
+
|
|
36
|
+
<p align="center">
|
|
37
|
+
<a href="#about">About</a> ·
|
|
38
|
+
<a href="#results">Results</a> ·
|
|
39
|
+
<a href="#getting-started">Getting started</a> ·
|
|
40
|
+
<a href="#reproducing-the-paper">Reproducing the paper</a> ·
|
|
41
|
+
<a href="#try-it-on-your-hardware">Try it on your hardware</a> ·
|
|
42
|
+
<a href="#contributing">Contributing</a> ·
|
|
43
|
+
<a href="#citation">Citation</a>
|
|
44
|
+
</p>
|
|
45
|
+
|
|
46
|
+
<p align="center">
|
|
47
|
+
<img src="docs/overview.svg" alt="With a full KV cache, four requests fill GPU memory and two wait. With DIGM, each request keeps only its important tokens, so six requests run in the same memory." width="900">
|
|
48
|
+
</p>
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## About
|
|
53
|
+
|
|
54
|
+
An LLM server keeps a key-value (KV) cache entry for every token of every request. On a busy GPU this cache fills the memory and limits how many requests can run at once.
|
|
55
|
+
|
|
56
|
+
DIGM is an eviction layer for vLLM. It drops the least important cached tokens of a request, only when memory runs short, and it starts with the requests that tolerate eviction best.
|
|
57
|
+
|
|
58
|
+
On three 7–8B models it raises throughput by 1.4–1.8× and shortens time to first token by 17–41%, at a cost of 2–3 LongBench accuracy points. End-to-end latency gets longer; see [Results](#results).
|
|
59
|
+
|
|
60
|
+
## How it works
|
|
61
|
+
|
|
62
|
+
DIGM runs inside a stock vLLM engine, with no kernel changes.
|
|
63
|
+
|
|
64
|
+
| Part | What it does |
|
|
65
|
+
|---|---|
|
|
66
|
+
| **Per-head scoring** | Each attention head scores every cached token from its keys and keeps its own top tokens. No query is needed. |
|
|
67
|
+
| **Packing** | Kept tokens are copied to the front of the request's own blocks. The freed tail blocks go back to vLLM's block pool, so the memory is really returned. |
|
|
68
|
+
| **Position offset** | New tokens keep their original positions, so the model's position encoding stays correct after eviction. |
|
|
69
|
+
| **Preemption and chunked prefill** | An evicted request can still be preempted safely, and a long prompt can be evicted while it is being prefilled. |
|
|
70
|
+
| **Governor** | Eviction happens only when memory runs short. Requests shrink in steps of 12.5% of their context, never below 25%. |
|
|
71
|
+
| **Sensitivity** | A statistic of each request's scores predicts how well it tolerates eviction. Tolerant requests shrink first. |
|
|
72
|
+
|
|
73
|
+
When DIGM keeps every token, the output is identical to full-cache vLLM.
|
|
74
|
+
|
|
75
|
+
## Results
|
|
76
|
+
|
|
77
|
+
**In one line:** keeping only 25% of the KV cache, DIGM keeps 93–96% of LongBench accuracy and lets one GPU serve 1.4–1.8× more tokens per second. Needle-in-a-haystack retrieval (RULER) loses more, and we report that openly.
|
|
78
|
+
|
|
79
|
+
**Setup.** Three 7–8B instruction models (Llama-3.1-8B, Qwen2.5-7B, Mistral-7B), AWQ 4-bit, one RTX 4080 (16 GB), vLLM 0.30.0. "Full" means no eviction. "DIGM 25%" means 75% of the context's KV cache is evicted and its memory is returned to vLLM. Full details and confidence intervals are in the paper.
|
|
80
|
+
|
|
81
|
+
### 1. Accuracy when keeping 25% of the context
|
|
82
|
+
|
|
83
|
+
| Model | LongBench full | LongBench DIGM 25% | kept | RULER-4K full | RULER-4K DIGM 25% | kept |
|
|
84
|
+
|---|---|---|---|---|---|---|
|
|
85
|
+
| Llama-3.1-8B | 48.5 | 46.2 | 95% | 84.3 | 73.8 | 88% |
|
|
86
|
+
| Qwen2.5-7B | 48.9 | 46.9 | 96% | 84.7 | 65.4 | 77% |
|
|
87
|
+
| Mistral-7B | 47.0 | 43.6 | 93% | 82.1 | 68.1 | 83% |
|
|
88
|
+
|
|
89
|
+
"kept" = DIGM score ÷ full score.
|
|
90
|
+
|
|
91
|
+
How to read it:
|
|
92
|
+
- **LongBench** is closest to real use: summarising, answering questions about long documents, few-shot tasks. Here the drop is 2.0–3.4 points.
|
|
93
|
+
- **RULER** hides one or a few exact facts (a "needle") in a long text and asks for them. It is the hardest case for any eviction method: DIGM decides what to keep before it sees the question, so if the needle's tokens were evicted, the answer is wrong. That is why the drop here is 10–19 points.
|
|
94
|
+
- The **sensitivity-aware governor** (it keeps more memory in layers that break easily) beat the plain governor in 37 of 56 paired runs, and lost in 3; the gains were up to 7 accuracy points.
|
|
95
|
+
|
|
96
|
+
### 2. Serving: what the freed memory buys
|
|
97
|
+
|
|
98
|
+
| Measure | Effect of DIGM | Why |
|
|
99
|
+
|---|---|---|
|
|
100
|
+
| Throughput (generated tokens/s) | **1.4–1.8× higher** | each request uses ~4× less KV memory, so vLLM runs more requests at once |
|
|
101
|
+
| Time to first token | **17–41% shorter** | requests wait less in the queue to be admitted |
|
|
102
|
+
| Median end-to-end latency | 15–60% longer | the GPU is shared by more requests at once, so each one finishes a bit later |
|
|
103
|
+
|
|
104
|
+
This is the usual trade-off of serving more users per GPU: total work done goes up and replies start sooner, but a single request takes longer to finish. If you care only about the latency of one request at a time, eviction does not help.
|
|
105
|
+
|
|
106
|
+
### 3. Prompts longer than GPU memory
|
|
107
|
+
|
|
108
|
+
With eviction **during** prefill (`--long`), DIGM can run prompts that do not fit in the KV pool at all. Smaller check: Llama-3.2-3B, RTX 4070 laptop (8 GB), vLLM 0.33.0, 16K-token RULER prompts, a 9.6K-token KV pool, keep budget 2,048 tokens.
|
|
109
|
+
|
|
110
|
+
| Method | Prompts that ran (of 26) | Accuracy | Peak KV |
|
|
111
|
+
|---|---|---|---|
|
|
112
|
+
| Full KV | 0 (does not fit) | – | – |
|
|
113
|
+
| Evict after prefill | 0 (does not fit) | – | – |
|
|
114
|
+
| **DIGM, evict during prefill** | **26** | 52.4 | ~3.1K tokens |
|
|
115
|
+
|
|
116
|
+
### Correctness checks
|
|
117
|
+
|
|
118
|
+
Every run also checks that the eviction machinery itself is exact: with "evict nothing" (identity), DIGM must give the same output as plain vLLM, and it does on every question. Without DIGM's position (RoPE) fix, accuracy collapses (24 vs 52 on the first five questions, Llama-3.2-3B check), which shows the fix matters.
|
|
119
|
+
|
|
120
|
+
## Getting started
|
|
121
|
+
|
|
122
|
+
**Requirements**
|
|
123
|
+
|
|
124
|
+
- Any NVIDIA GPU that runs vLLM, with enough memory for the model you choose.
|
|
125
|
+
- vLLM 0.33.0 (latest tested) or 0.30.0. On 0.33.0 the correctness, throughput, preemption,
|
|
126
|
+
long-prompt and CUDA-graph checks pass; the paper's numbers were measured on 0.30.0.
|
|
127
|
+
DIGM reaches into vLLM internals, so untested versions may break.
|
|
128
|
+
|
|
129
|
+
| Tested so far | Models |
|
|
130
|
+
|---|---|
|
|
131
|
+
| 16 GB desktop GPU (RTX 4080) | Llama-3.1-8B, Qwen2.5-7B, Mistral-7B (AWQ 4-bit) |
|
|
132
|
+
| 8 GB laptop GPU (RTX 4070) | Llama-3.2-3B, Qwen2.5-3B (AWQ 4-bit) |
|
|
133
|
+
|
|
134
|
+
Other GPUs, larger models and unquantized models have not been tested yet. See [Try it on your hardware](#try-it-on-your-hardware).
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
git clone https://github.com/bhupalamjathin-svg/DIGM.git && cd DIGM
|
|
138
|
+
python3 -m venv ~/vllm_env && source ~/vllm_env/bin/activate
|
|
139
|
+
pip install -r requirements.txt
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
To use only the `digm` library (scoring, selection, compaction, vLLM integration) in your own code, install it from PyPI instead:
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
pip install digm-vllm
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
Models and datasets download from Hugging Face on first run (`simonjegou/ruler`, `Xnhyacinth/LongBench`).
|
|
149
|
+
|
|
150
|
+
**Quick check (3B model)**
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
cd paper_artifact
|
|
154
|
+
DIGM_SEL=head:cos python3 digm_vllm_v18.py
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
`DIGM_SEL=head:cos` selects the per-head scoring used in the paper. Without it the script falls back to an older single-layer selection (`one`), kept only for comparison.
|
|
158
|
+
|
|
159
|
+
The script loads `AMead10/Llama-3.2-3B-Instruct-AWQ` and runs each RULER test question four ways:
|
|
160
|
+
|
|
161
|
+
| Check | What it does | What to expect |
|
|
162
|
+
|---|---|---|
|
|
163
|
+
| A | Full KV cache, no eviction | baseline answer |
|
|
164
|
+
| B | "Eviction" that keeps every token | **must equal A exactly** |
|
|
165
|
+
| C | DIGM keeps 25% of the context | answer + number of freed blocks |
|
|
166
|
+
| D | Same as C without the position offset (first 5 questions) | shows why the offset is needed |
|
|
167
|
+
|
|
168
|
+
The script takes the model as its first argument, so you can run the same check on any model vLLM can load:
|
|
169
|
+
|
|
170
|
+
```bash
|
|
171
|
+
DIGM_SEL=head:cos python3 digm_vllm_v18.py <hugging-face-model-id>
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
For reference, with the default 3B model on an 8 GB laptop GPU the check takes under two minutes once the model has downloaded, and ends with:
|
|
175
|
+
|
|
176
|
+
```
|
|
177
|
+
identity eviction reproduces Full KV exactly : 26/26 (must be all)
|
|
178
|
+
per-head PERMUTED slots reproduce Full KV : 26/26
|
|
179
|
+
evicted minus Full KV: -15.9 points, 95% CI [-22.1, -9.7]
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
If the first line is not N out of N, the vLLM version is wrong or something is broken. Stop there.
|
|
183
|
+
The accuracy drop is large here because this check uses RULER on a 3B model. Use `--longbench` for LongBench.
|
|
184
|
+
|
|
185
|
+
## Reproducing the paper
|
|
186
|
+
|
|
187
|
+
**On any GPU.** Leave the request rates out and the script measures what your GPU sustains with a full cache, then tests at 0.5×, 1× and 2× of that:
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
cd paper_artifact
|
|
191
|
+
export VLLM_ATTENTION_BACKEND=FLASH_ATTN VLLM_USE_FLASHINFER_SAMPLER=0
|
|
192
|
+
DIGM_SEL=head:cos DIGM_DEBUG=0 DIGM_NREQ=48 DIGM_GEN=256 \
|
|
193
|
+
DIGM_SENS_FLOOR=0.25 DIGM_SERVE_MODES=full,sens \
|
|
194
|
+
python3 digm_vllm_v18.py --serve <hugging-face-model-id> 4 0.85
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`full` is the normal full cache and `sens` is DIGM's final policy. The last argument is the share of GPU memory vLLM may use.
|
|
198
|
+
|
|
199
|
+
**The paper's exact setting.** Mixed 4K/8K/16K prompts, bursty arrivals, at 1× and 2× of full-cache capacity, Llama-3.1-8B:
|
|
200
|
+
|
|
201
|
+
```bash
|
|
202
|
+
DIGM_SEL=head:cos DIGM_DEBUG=0 \
|
|
203
|
+
DIGM_MIX=4096:0.5,8192:0.3,16384:0.2 DIGM_BURST=2.0 DIGM_MAXLEN=24576 DIGM_NREQ=40 DIGM_GEN=256 \
|
|
204
|
+
DIGM_SEED=0 DIGM_SENS_FLOOR=0.25 DIGM_RATES=0.564,1.128 DIGM_SERVE_MODES=sens \
|
|
205
|
+
python3 digm_vllm_v18.py --serve hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4 4 0.85
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Those rates (`DIGM_RATES`) are what 1× and 2× meant on the 16 GB GPU used for the paper. On other hardware, use the first command.
|
|
209
|
+
|
|
210
|
+
All runs: `bash run_lab_tue.sh`, then `bash run_lab_wed.sh`. They take many hours, skip any run that already finished, and expect the environment at `~/vllm_env`. The summaries they produced for the paper are in `paper_artifact/results/`.
|
|
211
|
+
|
|
212
|
+
**Modes**
|
|
213
|
+
|
|
214
|
+
| Flag | What it runs |
|
|
215
|
+
|---|---|
|
|
216
|
+
| (none) | the quick check above |
|
|
217
|
+
| `--throughput` | all requests submitted at once: full cache vs eviction |
|
|
218
|
+
| `--serve` | timed arrivals: time to first token, per-token time, latency, accuracy |
|
|
219
|
+
| `--stress` | small memory pool: preemption after eviction, with and without restore |
|
|
220
|
+
| `--long` | eviction during chunked prefill, for prompts longer than the memory pool |
|
|
221
|
+
| `--longbench` | LongBench accuracy at a fixed budget |
|
|
222
|
+
|
|
223
|
+
Settings are `DIGM_*` environment variables. They are commented near the top of the script and where each mode starts.
|
|
224
|
+
|
|
225
|
+
## Repository layout
|
|
226
|
+
|
|
227
|
+
```
|
|
228
|
+
digm/ the library
|
|
229
|
+
config.py DIGMConfig: every knob in one place
|
|
230
|
+
scoring.py query-free per-head scores (KeyDiff-style cosine, norms)
|
|
231
|
+
selection.py which tokens to keep: budgets, sinks, recency, question, per-head top-k
|
|
232
|
+
compaction.py copy kept K/V into the first slots of a request's own blocks
|
|
233
|
+
vllm_integration.py DIGMvLLM: block freeing, RoPE offset, preemption restore inside vLLM
|
|
234
|
+
benchmarks/
|
|
235
|
+
stage1.py correctness + RULER accuracy (identity / permutation checks)
|
|
236
|
+
throughput.py many requests at once: Full KV vs DIGM
|
|
237
|
+
tests/
|
|
238
|
+
test_cpu_equivalence.py no GPU needed: library == paper script on random KV
|
|
239
|
+
run_equivalence.sh on a GPU: library and paper script give identical stage-1 results
|
|
240
|
+
paper_artifact/
|
|
241
|
+
digm_vllm_v18.py the exact script behind the paper's numbers (kept unchanged)
|
|
242
|
+
run_lab_tue.sh, run_lab_wed.sh, results/
|
|
243
|
+
docs/overview.svg
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
The paper's numbers come from `paper_artifact/digm_vllm_v18.py`, kept unchanged so they can be reproduced exactly. The `digm/` library gives the same results (checked by `tests/`) and is the code to build on. Stress, long-prompt, LongBench and serving benchmarks and the governor still live in the paper script for now.
|
|
247
|
+
|
|
248
|
+
### Using the library
|
|
249
|
+
|
|
250
|
+
```python
|
|
251
|
+
import os; os.environ["VLLM_ENABLE_V1_MULTIPROCESSING"] = "0"
|
|
252
|
+
from vllm import LLM, SamplingParams
|
|
253
|
+
from digm import DIGMConfig, DIGMvLLM
|
|
254
|
+
|
|
255
|
+
llm = LLM("AMead10/Llama-3.2-3B-Instruct-AWQ", enable_prefix_caching=False, enforce_eager=True, async_scheduling=False)
|
|
256
|
+
digm = DIGMvLLM(llm, DIGMConfig(keep=0.25, sel="head:cos"), num_kv_heads=8, head_dim=128)
|
|
257
|
+
|
|
258
|
+
# after a request's prompt is prefilled (see benchmarks/stage1.py for the full loop):
|
|
259
|
+
# keep = digm.select_keep(rid, n_ctx, n) # n_ctx = context length, n = prompt length
|
|
260
|
+
# digm.evict(rid, keep, n) # frees ~75% of its KV blocks back to vLLM
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## Try it on your hardware
|
|
264
|
+
|
|
265
|
+
DIGM has only been tested on models up to 8B, on single 8 GB and 16 GB GPUs. Results on anything else are welcome, good or bad:
|
|
266
|
+
|
|
267
|
+
- larger models (13B, 32B, 70B) and unquantized models;
|
|
268
|
+
- larger GPUs (24 GB, 48 GB, 80 GB);
|
|
269
|
+
- other model families.
|
|
270
|
+
|
|
271
|
+
Run the quick check and the "any GPU" serving command, then open an issue using the **Share results** template. Reported results will be collected in a table here, with credit.
|
|
272
|
+
|
|
273
|
+
## Limitations
|
|
274
|
+
|
|
275
|
+
- Tested on vLLM 0.30.0 and 0.33.0 only.
|
|
276
|
+
- Single GPU, in-process engine, prefix caching off, async scheduling off.
|
|
277
|
+
- The paper's runs used eager mode (`DIGM_EAGER=1`, the default here).
|
|
278
|
+
- Other figures in the paper came from earlier versions of this script. They are not in this repo yet.
|
|
279
|
+
|
|
280
|
+
## Roadmap
|
|
281
|
+
|
|
282
|
+
- Move the remaining benchmarks and the governor into the library.
|
|
283
|
+
- A vLLM plugin built on vLLM's block-eviction API (PR #53871).
|
|
284
|
+
- Larger models and multi-GPU.
|
|
285
|
+
|
|
286
|
+
## Contributing
|
|
287
|
+
|
|
288
|
+
Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for how to report a bug, what to check before a pull request, and how contributions are licensed.
|
|
289
|
+
|
|
290
|
+
## Citation
|
|
291
|
+
|
|
292
|
+
See [CITATION.cff](CITATION.cff), or use GitHub's "Cite this repository" button. The preprint link will be added here.
|
|
293
|
+
|
|
294
|
+
## Licence
|
|
295
|
+
|
|
296
|
+
[Apache License 2.0](LICENSE). Copyright 2026 Sai Jathin Bhupalam and Naveen N C (see [NOTICE](NOTICE)).
|
|
297
|
+
|
|
298
|
+
## Acknowledgements
|
|
299
|
+
|
|
300
|
+
DIGM is built on [vLLM](https://github.com/vllm-project/vllm). Accuracy is measured on RULER and LongBench.
|
|
301
|
+
|
|
302
|
+
The idea, experiments and results are the authors'. An AI assistant was used to write the code. The authors ran every experiment and checked the results.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
digm/__init__.py,sha256=-9F7bRF2DHKdAS-1Qn2GM6PKmJk2UjOcAgupY5wJbiU,841
|
|
2
|
+
digm/compaction.py,sha256=gNQuIATuf23HWrljJqlghe22WpjTUoArWxwK3pMaodE,2107
|
|
3
|
+
digm/config.py,sha256=umBneAVT9oa9OZZ4rBt7mKup-3SMv-8Aq6NcIyIWzs0,1706
|
|
4
|
+
digm/scoring.py,sha256=2rlCBBf_lrbRXE2ceE6z1f8O9lE6UNqGA-cOGnayNg8,1522
|
|
5
|
+
digm/selection.py,sha256=8fiT7AJhF5KJVZGEBNJbXWUUWQPJc6HOWAVxKeKpoLY,4788
|
|
6
|
+
digm/vllm_integration.py,sha256=UQgoCOQtOO9Oc5Yg6x0X--bbzQ4hxfL5so-pdmO3b_E,11824
|
|
7
|
+
digm_vllm-0.2.0.dist-info/licenses/LICENSE,sha256=MSQpzXs-8lxSuGp8Hrfe83pOEWawqJQyiVPo-j_s5PA,11348
|
|
8
|
+
digm_vllm-0.2.0.dist-info/licenses/NOTICE,sha256=BsgreTCxqg-tTVq7S-xGvd_YYjn_sT0OBSsf2pzuQDY,276
|
|
9
|
+
digm_vllm-0.2.0.dist-info/METADATA,sha256=un6dVgRUlbix51Q0FfjQxaN986TxoWMiV6qENDCVJ1s,15031
|
|
10
|
+
digm_vllm-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
11
|
+
digm_vllm-0.2.0.dist-info/top_level.txt,sha256=F2IrF-KEhDoonh2b-F2nj_z_1PYQX4yt_ghKEuD6a9s,5
|
|
12
|
+
digm_vllm-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024 NVIDIA Corporation
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
DIGM (Dynamic Importance-Gated Memory)
|
|
2
|
+
Copyright 2026 Sai Jathin Bhupalam and Naveen N C
|
|
3
|
+
|
|
4
|
+
This product is licensed under the Apache License, Version 2.0 (see LICENSE).
|
|
5
|
+
It is built to run on vLLM (https://github.com/vllm-project/vllm), which is also licensed under Apache-2.0.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
digm
|