File size: 7,038 Bytes
92e95ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# Copyright 2026 The Robbyant Team Authors. All rights reserved.

"""Paged patch/special KV storage for the native Map2 streaming runtime."""

import collections
import math

import torch


class PagedKVCache:
    """An all-layer append transaction with prefix, window and special-token pages.

    One physical page per frame's patch tokens; all chronological special tokens
    occupy a packed tail. Only page IDs change on eviction or rollback. One free
    patch page and uncommitted special slots protect live state from failed heads.
    Metadata and one FlashInfer plan are shared across all layers.
    """

    def __init__(
        self,
        *,
        layers,
        heads,
        dim,
        patches,
        special=5,
        scale=8,
        window=64,
        capacity=1024,
        device="cuda",
        dtype=torch.bfloat16,
        offload_kv=False,
    ):
        import flashinfer

        if min(layers, heads, dim, patches, special, scale, window) <= 0:
            raise ValueError(
                "paged cache dimensions, prefix and window must be positive"
            )
        if capacity < scale:
            raise ValueError("capacity must accommodate the initialization prefix")
        self.layers, self.heads, self.dim = layers, heads, dim
        self.patches, self.special, self.scale, self.window = (
            patches,
            special,
            scale,
            window,
        )
        self.capacity = capacity
        self.device = torch.device(device)
        self.dtype = dtype
        self.offload_kv = bool(offload_kv)
        # One extra patch page makes failed/transient steps independent of eviction.
        self.patch_pages = min(scale + window, capacity) + 1
        self.special_pages = math.ceil((capacity + 1) * special / patches)
        layer_shape = (self.patch_pages + self.special_pages, 2, patches, heads, dim)
        if self.offload_kv:
            try:
                self.cpu_pool = [
                    torch.empty(layer_shape, device="cpu", dtype=dtype, pin_memory=True)
                    for _ in range(layers)
                ]
            except RuntimeError:
                self.cpu_pool = [
                    torch.empty(layer_shape, device="cpu", dtype=dtype)
                    for _ in range(layers)
                ]
            self.gpu_buf = torch.empty(layer_shape, device=device, dtype=dtype)
            self.pool = None
        else:
            self.cpu_pool = None
            self.gpu_buf = None
            self.pool = [
                torch.empty(layer_shape, device=device, dtype=dtype)
                for _ in range(layers)
            ]
        self.active = collections.deque()
        self.free = list(range(self.patch_pages - 1, -1, -1))
        self.count = 0
        self.pending = None
        self.workspace = torch.empty(64 << 20, dtype=torch.uint8, device=device)
        self.wrapper = flashinfer.BatchPrefillWithPagedKVCacheWrapper(
            self.workspace, kv_layout="NHD", backend="fa2"
        )

    def begin(self):
        if self.pending is not None:
            raise RuntimeError("nested append")
        if self.count >= self.capacity:
            raise ValueError("keyframe capacity reached")
        page = self.free[-1]
        active = list(self.active) + [(self.count, page)]
        active = [
            (i, p)
            for i, p in active
            if i < self.scale or i >= max(self.scale, self.count + 1 - self.window)
        ]
        tokens = (self.count + 1) * self.special
        pages = [p for _, p in active] + list(
            range(self.patch_pages, self.patch_pages + math.ceil(tokens / self.patches))
        )
        self.pending = {"page": page, "active": active, "written": set()}
        self.wrapper.plan(
            torch.tensor(
                [0, self.patches + self.special], dtype=torch.int32, device=self.device
            ),
            torch.tensor([0, len(pages)], dtype=torch.int32, device=self.device),
            torch.tensor(pages, dtype=torch.int32, device=self.device),
            torch.tensor(
                [tokens % self.patches or self.patches],
                dtype=torch.int32,
                device=self.device,
            ),
            self.heads,
            self.heads,
            self.dim,
            self.patches,
            causal=False,
            pos_encoding_mode="NONE",
            q_data_type=self.dtype,
            kv_data_type=self.dtype,
        )

    def write(self, layer, k, v):
        """[patches+special, heads, dim], specials first, post-RoPE K."""
        if self.pending is None or layer in self.pending["written"]:
            raise RuntimeError("invalid write")
        if k.dtype != self.dtype or v.dtype != self.dtype:
            raise TypeError("no silent KV conversion")
        target_pool = self.cpu_pool[layer] if self.offload_kv else self.pool[layer]
        page = self.pending["page"]
        for bank, x in enumerate((k, v)):
            target_pool[page, bank].copy_(x[self.special :])
            start = self.count * self.special
            done = 0
            while done < self.special:
                p, off = divmod(start + done, self.patches)
                take = min(self.special - done, self.patches - off)
                target_pool[self.patch_pages + p, bank, off : off + take].copy_(
                    x[done : done + take]
                )
                done += take
        self.pending["written"].add(layer)

    def run(self, layer, q):
        if layer not in self.pending["written"]:
            raise RuntimeError("query before write")
        if q.dtype != self.dtype:
            raise TypeError("query dtype mismatch")
        if self.offload_kv:
            pool_l = self.cpu_pool[layer]
            used_patch_max = max(p for _, p in self.pending["active"]) + 1
            used_spec = math.ceil((self.count + 1) * self.special / self.patches)
            self.gpu_buf[:used_patch_max].copy_(
                pool_l[:used_patch_max], non_blocking=True
            )
            self.gpu_buf[self.patch_pages : self.patch_pages + used_spec].copy_(
                pool_l[self.patch_pages : self.patch_pages + used_spec],
                non_blocking=True,
            )
            return self.wrapper.run(q.contiguous(), self.gpu_buf)
        return self.wrapper.run(q.contiguous(), self.pool[layer])

    def commit(self):
        if self.pending is None or len(self.pending["written"]) != self.layers:
            raise RuntimeError("incomplete append")
        page = self.free.pop()
        assert page == self.pending["page"]
        self.active.append((self.count, page))
        self.count += 1
        while len(self.active) > self.scale + self.window:
            index, page = self.active[self.scale]
            del self.active[self.scale]
            self.free.append(page)
        self.pending = None

    def rollback(self):
        # Writes affected only a free patch page and invisible special tail slots.
        self.pending = None