#!/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 rows_from_trace(path: Path, max_tokens: int) -> tuple[array, int]: """Read the engine's private, newline-delimited 16-row trace.""" rows = array("I") tokens = 0 with path.open() as source: for line_number, line in enumerate(source, 1): if not line.strip() or line.startswith("#"): continue try: batch = [int(item) for item in line.split()] except ValueError as exc: raise ValueError(f"invalid row ID on trace line {line_number}") from exc if len(batch) != 16 or any(row < 0 or row > 0xFFFFFFFF for row in batch): raise ValueError(f"expected sixteen u32 row IDs on trace line {line_number}") rows.extend(batch) tokens += 1 if tokens >= max_tokens: break if not tokens: raise ValueError("PLE row trace has no data") return rows, tokens 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__) input_group = parser.add_mutually_exclusive_group(required=True) input_group.add_argument("--tokens", type=Path, help="private JSON array of token IDs") input_group.add_argument("--rows-trace", type=Path, help="private trace emitted by Strata") parser.add_argument("--ngram-source", type=Path, help="required with --tokens") parser.add_argument("--ngram-header", type=Path, help="required with --tokens") 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") if options.tokens: if not options.ngram_source or not options.ngram_header: parser.error("--tokens requires --ngram-source and --ngram-header") 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) tokens = len(ids) input_path = options.tokens else: rows, tokens = rows_from_trace(options.rows_trace, options.max_tokens) input_path = options.rows_trace result = { "input_sha256": hashlib.sha256(input_path.read_bytes()).hexdigest(), "ngram_source_sha256": (hashlib.sha256(options.ngram_source.read_bytes()).hexdigest() if options.ngram_source else None), "input_kind": "tokens" if options.tokens else "rows_trace", "tokens": tokens, "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()