Files
leleka/scripts/ple-cache-reuse.py
T

121 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""Offline upper-bound LRU study for compressed PLE row/block residency.
Input token IDs and any raw traces stay outside Git. This models ideal cache
lookups and bytes admitted; it does not measure storage, CUDA, or model speed.
"""
import argparse
from array import array
from collections import OrderedDict
import hashlib
import json
from pathlib import Path
import re
MASK64 = (1 << 64) - 1
ROW_BYTES = 50 # level-2, group-32, 160-value PLE rows on the target archive
def constants(source: Path, header: Path) -> tuple[list[int], list[int], list[int], int]:
code = source.read_text()
decl = header.read_text()
mult = [int(value) for _, value in sorted(
(int(i), value) for i, value in re.findall(r"c\.mult\[(\d+)\] = (\d+)ull", code))]
groups = []
for name in ("vocab", "offset"):
found = re.search(rf"const uint64_t {name}\[PLE_N_HEADS\] = \{{(.*?)\}};", code,
re.DOTALL)
if not found:
raise ValueError(f"missing PLE {name} constants")
groups.append([int(x) for x in re.findall(r"\d+", found.group(1))])
eos = re.search(r"PLE_EOS_TOKEN_ID\s*=\s*(\d+)", decl)
if len(mult) != 3 or any(len(x) != 16 for x in groups) or not eos:
raise ValueError("PLE hash geometry changed; update this offline study")
return mult, groups[0], groups[1], int(eos.group(1))
def rows_for_tokens(ids: list[int], source: Path, header: Path) -> array:
mult, vocab, offset, eos = constants(source, header)
rows = array("I")
older = newest = -1
for token in ids:
if token < 0:
raise ValueError("token IDs must be non-negative")
cut = newest < 0 or newest == eos
previous = eos if cut else newest
second = eos if cut or older < 0 or older == eos else older
mixed2 = ((token * mult[0]) ^ (previous * mult[1])) & MASK64
mixed3 = (mixed2 ^ (second * mult[2])) & MASK64
rows.extend(int(mixed2 % vocab[h] + offset[h]) for h in range(8))
rows.extend(int(mixed3 % vocab[h] + offset[h]) for h in range(8, 16))
older, newest = newest, token
return rows
def simulate(rows: array, block_rows: int, budget_mib: int) -> dict:
block_bytes = block_rows * ROW_BYTES
capacity = (budget_mib << 20) // block_bytes
cache: OrderedDict[int, None] = OrderedDict()
hits = [0, 0]
misses = [0, 0]
for i, row in enumerate(rows):
block = row // block_rows
group = (i % 16) // 8
if block in cache:
hits[group] += 1
cache.move_to_end(block)
else:
misses[group] += 1
cache[block] = None
if len(cache) > capacity:
cache.popitem(last=False)
total = len(rows)
miss_total = sum(misses)
return {
"block_rows": block_rows,
"budget_mib": budget_mib,
"ideal_blocks_capacity": capacity,
"hit_rate": round(sum(hits) / total, 6),
"bigram_hit_rate": round(hits[0] / (hits[0] + misses[0]), 6),
"trigram_hit_rate": round(hits[1] / (hits[1] + misses[1]), 6),
"misses": miss_total,
"ideal_admission_bytes": miss_total * block_bytes,
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--tokens", type=Path, required=True, help="private JSON array of token IDs")
parser.add_argument("--ngram-source", type=Path, required=True)
parser.add_argument("--ngram-header", type=Path, required=True)
parser.add_argument("--max-tokens", type=int, default=262144)
parser.add_argument("--block-rows", type=int, nargs="+", default=[1, 16, 64])
parser.add_argument("--budgets-mib", type=int, nargs="+", default=[64, 256, 1024])
options = parser.parse_args()
if (options.max_tokens < 1 or any(x < 1 for x in options.block_rows) or
any(x < 1 for x in options.budgets_mib)):
parser.error("all sizes and capacities must be positive")
all_ids = json.loads(options.tokens.read_text())
if not isinstance(all_ids, list) or any(not isinstance(x, int) for x in all_ids):
parser.error("tokens must be a JSON array of integer IDs")
ids = all_ids[:options.max_tokens]
rows = rows_for_tokens(ids, options.ngram_source, options.ngram_header)
result = {
"input_sha256": hashlib.sha256(options.tokens.read_bytes()).hexdigest(),
"ngram_source_sha256": hashlib.sha256(options.ngram_source.read_bytes()).hexdigest(),
"tokens": len(ids),
"row_accesses": len(rows),
"unique_rows": len(set(rows)),
"row_bytes": ROW_BYTES,
"ideal_model_only": True,
"scenarios": [simulate(rows, block, budget)
for block in options.block_rows for budget in options.budgets_mib],
}
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()