File size: 13,422 Bytes
0d91a92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
"""Token-level radix-cache replay simulator for arXiv 2611.09715v1 Fig. 6a (ShareChat).

Faithful to SGLang's UnifiedRadixCache semantics for the hit-rate metric: token-level
radix tree, longest-common-prefix lookup counts the hit, the full prompt (+1 generated
token, max_tokens=1) is inserted after lookup, capacity is in tokens, eviction removes
leaf nodes only until the tree fits. Policies:

  lru    evict min (last_access)                    [SGLang default]
  lfu    evict min (use_count)
  gdsf   evict min (freq*size - age)                [GreedyDual-Size-Frequency]
  tbs    evict min (1[next_arrival - now < Threshold], size)   [offline oracle]
  iac    evict min (1[age < M_{i,t}], P(t+1|i,t), size)        [paper Eq. 1]
  iac_full  evict min (reuse_within(p, mu, sigma, age, 40), size) [released variant]
  lpc    evict min decayed continuation prob        [LPC, NeurIPS 2025, scale=0.01]

Segments are numpy int32 arrays; prefix compares run in C. Runs are parallelized with a
fork Pool; results.json is rewritten after every completed (policy, capacity) pair.
"""
from __future__ import annotations

import argparse
import csv
import json
import math
import multiprocessing as mp
import os
import sys

import numpy as np

REPO_DIR = os.environ.get("IAC_REPO", os.path.join(os.path.dirname(os.path.abspath(__file__)), "iac-repo"))
sys.path.insert(0, REPO_DIR)
from iac.stats import ReuseStats  # noqa: E402
from iac.policy import reuse_within  # noqa: E402

INF = float("inf")
LPC_SCALE = 0.01  # LPC paper: scale = 1 / average inter-turn interval (~100 s)
MAX_CTX = 8191   # Llama-3-70B context is 8192; SGLang truncates prompts to fit (max_tokens=1)


class Node:
    __slots__ = ("seg", "parent", "children", "created", "last_access", "use_count",
                 "intent", "turn", "next_arrival", "p", "req_id")

    def __init__(self, seg, parent, req_id=0, created=0.0):
        self.seg = seg              # np.int32 array of tokens in this segment
        self.parent = parent
        self.children = {}          # first_token(int) -> Node
        self.created = created
        self.last_access = created
        self.use_count = 0
        self.intent = None
        self.turn = 0
        self.next_arrival = INF
        self.p = 0.0
        self.req_id = req_id

    @property
    def size(self):
        return len(self.seg)


class Cache:
    def __init__(self, policy, capacity, stats=None, threshold=120.0, horizon=40.0):
        self.policy = policy
        self.capacity = capacity
        self.stats = stats
        self.threshold = threshold
        self.horizon = horizon
        self.root = Node(np.empty(0, dtype=np.int32), None)
        self.total = 0
        self.leaves = []            # candidate leaf nodes (root excluded), scan-min evicted
        self._leaf_ids = set()

    def _maybe_leaf(self, node):
        if node.children or node is self.root:
            return
        if id(node) not in self._leaf_ids:
            self._leaf_ids.add(id(node))
            self.leaves.append(node)

    def _unleaf(self, node):
        if id(node) in self._leaf_ids:
            self._leaf_ids.discard(id(node))
            self.leaves.remove(node)

    def _split(self, node, offset):
        """Split node.seg at `offset`; returns the prefix node."""
        tail = Node(node.seg[offset:], node, node.req_id, node.created)
        tail.last_access, tail.use_count = node.last_access, node.use_count
        tail.intent, tail.turn = node.intent, node.turn
        tail.next_arrival, tail.p = node.next_arrival, node.p
        node.seg = node.seg[:offset]
        node.children = {int(tail.seg[0]): tail}
        tail.parent = node
        self._unleaf(node)
        self._maybe_leaf(tail)
        return node

    def lookup(self, tokens, now, intent=None, turn=0):
        """tokens: np.int32 slice. Return (node fully consumed, matched token count)."""
        node = self.root
        matched = 0
        i = 0
        n = len(tokens)
        while i < n:
            child = node.children.get(int(tokens[i]))
            if child is None:
                break
            seg = child.seg
            k = min(len(seg), n - i)
            diff = np.flatnonzero(seg[:k] != tokens[i:i + k])
            j = int(diff[0]) if len(diff) else k
            if j == len(seg):
                node = child
                matched += len(seg)
                i += len(seg)
            elif j == 0:
                break
            else:
                node = self._split(child, j)
                matched += j
                i += j
                break
        end_node = node
        while node is not None and node is not self.root:
            node.last_access = now
            node.use_count += 1
            node.created = now      # stamp propagation: a hit re-stamps the matched path
            node.intent, node.turn = intent, turn  # and re-tags it with this request
            node = node.parent
        return end_node, matched

    def insert(self, tokens, matched_node, matched, now, intent, turn, next_arrival, p, req_id):
        node = matched_node
        i = matched
        n = len(tokens)
        while i < n:
            child = node.children.get(int(tokens[i]))
            if child is None:
                new = Node(tokens[i:].copy(), node, req_id, now)
                new.intent, new.turn = intent, turn
                new.next_arrival, new.p = next_arrival, p
                new.last_access, new.use_count = now, 1
                node.children[int(tokens[i])] = new
                self.total += n - i
                self._maybe_leaf(new)
                node = new
                i = n
                break
            seg = child.seg
            k = min(len(seg), n - i)
            diff = np.flatnonzero(seg[:k] != tokens[i:i + k])
            j = int(diff[0]) if len(diff) else k
            if j == len(seg):
                node = child
                i += len(seg)
            elif j == 0:
                break
            else:
                node = self._split(child, j)
                i += j

    def evict(self, now):
        while self.total > self.capacity:
            # prune stale candidates: a valid leaf is childless and still linked to its parent
            self.leaves = [n for n in self.leaves
                           if not n.children and n.parent is not None
                           and n.parent.children.get(int(n.seg[0])) is n]
            self._leaf_ids = {id(n) for n in self.leaves}
            if not self.leaves:
                break
            best, best_key = None, None
            for leaf in self.leaves:
                key = self._priority(leaf, now)
                if best_key is None or key < best_key:
                    best, best_key = leaf, key
            self.total -= best.size
            parent = best.parent
            del parent.children[int(best.seg[0])]
            self._unleaf(best)
            self._maybe_leaf(parent)

    def _priority(self, node, now):
        pol = self.policy
        if pol == "lru":
            return (node.last_access, node.req_id)
        if pol == "lfu":
            return (node.use_count, node.last_access, node.req_id)
        if pol == "gdsf":
            return (node.use_count * node.size - (now - node.last_access), node.req_id)
        if pol == "tbs":
            delta = node.next_arrival - now
            ind = 0 if delta < self.threshold else 1
            return (ind, node.size, node.req_id)
        if pol == "iac":
            if node.intent is None:
                return (0.0, node.size, node.req_id)
            p, mu, sigma = self.stats.lookup_dist(node.intent, node.turn)
            ind = 0 if (now - node.created) < math.exp(mu) else 1
            return (ind, p, node.size, node.req_id)
        if pol == "iac_full":
            if node.intent is None:
                return (0.0, node.size, node.req_id)
            p, mu, sigma = self.stats.lookup_dist(node.intent, node.turn)
            score = reuse_within(p, mu, sigma, now - node.created, self.horizon)
            return (score, node.size, node.req_id)
        if pol == "lpc":
            d = math.exp(-(now - node.last_access) * LPC_SCALE)
            num = node.p * d
            return (num / (num + (1.0 - node.p)) if num + (1.0 - node.p) > 0 else 0.0, node.req_id)
        raise ValueError(pol)


def load_inputs(trace_dir, tokens_npz, intents_json, lpc_json, stats_path):
    from iac.data import Trace

    trace = Trace.load(trace_dir)
    z = np.load(tokens_npz)
    token_ids = z["ids"]
    offsets = z["offsets"]

    intents = json.load(open(intents_json)) if intents_json else {}
    lpc = json.load(open(lpc_json)) if lpc_json else {}
    stats = ReuseStats.load(stats_path) if stats_path else None

    reqs = []
    for r in trace.requests:
        reqs.append({
            "req_id": r.req_id, "conv_id": r.conv_id, "turn": r.turn,
            "arrival": r.arrival, "next_arrival": r.next_arrival,
            "s": int(offsets[r.req_id]), "e": int(offsets[r.req_id + 1]),
            "intent": intents.get(str(r.req_id)),
            "p": float(lpc.get(str(r.req_id), 0.0)),
        })
    return reqs, token_ids, stats


def run(policy, capacity, reqs, token_ids, stats, threshold, horizon):
    cache = Cache(policy, capacity, stats=stats, threshold=threshold, horizon=horizon)
    records = []
    for r in reqs:
        tokens = token_ids[r["s"]:r["e"]]
        if len(tokens) > MAX_CTX:
            tokens = tokens[:MAX_CTX]
        if len(tokens) == 0:
            continue
        node, matched = cache.lookup(tokens, r["arrival"], r["intent"], r["turn"])
        records.append((r["req_id"], r["arrival"], len(tokens), matched))
        # SGLang inserts prompt + the single generated token (max_tokens=1)
        insert = np.concatenate([tokens, np.ones(1, dtype=np.int32)])
        cache.insert(insert, node, matched, r["arrival"], r["intent"], r["turn"],
                     r["next_arrival"], r["p"], r["req_id"])
        cache.evict(r["arrival"])
    return records


WINDOWS = [
    ("full", 0.0, INF, 0.0),          # all requests, no warmup
    ("warmup300", 0.0, INF, 300.0),   # warmup [0,300s), measure [300, end)
    ("repo", 1800.0, 3030.0, 2100.0), # repo replay.py defaults
]


def summarize(records, lo, hi, warmup_end):
    prompt = hit = n = 0
    for _, arrival, ptok, ctok in records:
        if not (lo <= arrival < hi and arrival >= warmup_end):
            continue
        n += 1
        prompt += ptok
        hit += ctok
    return {"requests": n, "prompt_tokens": prompt, "cached_tokens": hit,
            "hit_rate": hit / prompt if prompt else 0.0}


def run_one(task):
    policy, cap, thr, tag = task
    records = run(policy, cap, GLOBAL["reqs"], GLOBAL["token_ids"], GLOBAL["stats"],
                  thr or 0.0, 40.0)
    path = os.path.join(GLOBAL["out"], "records", f"{tag}.csv")
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["req_id", "arrival", "prompt_tokens", "cached_tokens"])
        w.writerows(records)
    key = f"{tag}@{cap}"
    return key, {name: summarize(records, lo, hi, we) for name, lo, hi, we in WINDOWS}


GLOBAL = {}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--trace", default="traces/sharechat_r3")
    ap.add_argument("--tokens", default="artifacts/tokens_llama3.npz")
    ap.add_argument("--intents", default="artifacts/replay_intents.json")
    ap.add_argument("--lpc", default="artifacts/replay_lpc_p.json")
    ap.add_argument("--stats", default="artifacts/stats_sharechat.json")
    ap.add_argument("--policies", default="iac,lpc,lru,lfu,gdsf,tbs,iac_full")
    ap.add_argument("--capacities", type=int, nargs="+", default=[140000, 80000, 110000, 170000])
    ap.add_argument("--thresholds", type=float, nargs="+", default=[30.0, 60.0, 120.0, 240.0])
    ap.add_argument("--jobs", type=int, default=4)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--out", default="results")
    args = ap.parse_args()

    reqs, token_ids, stats = load_inputs(args.trace, args.tokens, args.intents, args.lpc, args.stats)
    if args.limit:
        reqs = reqs[: args.limit]
    os.makedirs(args.out, exist_ok=True)
    GLOBAL.update(reqs=reqs, token_ids=token_ids, stats=stats, out=args.out)

    tasks = []
    for policy in args.policies.split(","):
        thresholds = args.thresholds if policy == "tbs" else [None]
        for thr in thresholds:
            pol = policy if policy != "tbs" else f"tbs(thr={thr:g})"
            tag = pol.replace("=", "").replace("@", "_").replace(".", "p").replace("(", "").replace(")", "")
            for cap in args.capacities:
                tasks.append((policy, cap, thr, tag))
    ctx = mp.get_context("fork")
    results = {}
    with ctx.Pool(min(args.jobs, len(tasks))) as pool:
        for key, summaries in pool.imap_unordered(run_one, tasks):
            results[key] = summaries
            hr = summaries["warmup300"]["hit_rate"]
            print(f"DONE {key}: warmup300={hr:.4f} full={summaries['full']['hit_rate']:.4f}", flush=True)
            with open(os.path.join(args.out, "results.json"), "w") as f:
                json.dump(results, f, indent=1)
    print(json.dumps({k: v["warmup300"] for k, v in sorted(results.items())}, indent=1))


if __name__ == "__main__":
    main()