"""
paged.py -- managing the KV cache of an LLM server: contiguous reservations vs PagedAttention's fixed-size blocks,
in a continuous-batching serving simulation with fragmentation statistics, preemption and prefix sharing
=================================================================================================================

[Why we need it]
    During decoding every sequence keeps its keys and values for all past tokens: the KV cache. Its final size is
    unknown when the request arrives (generation stops at an end-of-sequence token), so early serving systems
    RESERVED a contiguous region for the maximum possible length. Most of it was never used (reservation waste),
    reservations of different sizes left unusable holes (external fragmentation), and the batch size -- which sets
    the throughput of memory-bound decoding (Lecture 1) -- was limited by memory that held nothing.
    PagedAttention (Kwon et al., SOSP 2023) borrows virtual memory from operating systems: the KV cache of a
    sequence is a list of fixed-size BLOCKS (e.g. 16 tokens) anywhere in memory, found through a BLOCK TABLE;
    blocks are allocated as tokens are generated and freed when the sequence ends. The only waste is the unfilled
    part of each sequence's last block, and blocks can be SHARED between sequences with the same prefix.

[Main pieces]
    Request, make_requests              : a synthetic request trace (lognormal prompt and output lengths)
    ContiguousAllocator                 : first-fit allocation of contiguous token ranges (with free-range merging)
    PagedAllocator                      : a free list of blocks and per-request block tables
    simulate(...)                       : iteration-level (continuous) batching: each step admits waiting requests
                                          while memory allows, runs one decode step for every running request,
                                          grows paged caches block by block (preempting the newest request when
                                          memory runs out), and frees finished requests
    step_time(...)                      : the time of one decode step on a GPU (roofline: weights + KV read)
    sharing_savings(...)                : blocks saved by sharing a prompt among parallel samples

[Edge cases]
    - Time is counted in decode steps; a request's prompt is processed (prefill) in its first step, and that
      prefill's compute time (2 x params FLOPs per prompt token) is added to the step's time.
    - Contiguous policies: "max" reserves prompt + max_new tokens; "oracle" reserves prompt + the TRUE output
      length (impossible in practice; it isolates external fragmentation).
    - A preempted request (paged policy) loses its cache and is recomputed from scratch when readmitted (vLLM's
      recomputation policy); its generated tokens are kept.
"""

import math
from dataclasses import dataclass, field

import numpy as np


@dataclass
class Request:
    """One request: id, arrival step, prompt and output lengths (tokens), progress."""
    rid: int
    arrival: int
    prompt: int
    output: int
    generated: int = 0
    start: int = -1
    finish: int = -1
    preempted: int = 0

    @property
    def length(self):
        """Tokens currently in its KV cache once running: prompt + generated so far."""
        return self.prompt + self.generated


def make_requests(n, seed=0, mean_prompt=400, mean_output=250, max_prompt=2048, max_new=2048, rate=4.0):
    """
    A synthetic trace: Poisson arrivals (`rate` per decode step), lognormal prompt and output lengths with the given
    means (heavy-tailed, like chat traces), clipped to the maxima.
    """
    rng = np.random.default_rng(seed)
    arrivals = np.cumsum(rng.exponential(1 / rate, n)).astype(int)
    sig = 0.9
    prompt = np.clip(rng.lognormal(math.log(mean_prompt) - sig ** 2 / 2, sig, n), 4, max_prompt).astype(int)
    output = np.clip(rng.lognormal(math.log(mean_output) - sig ** 2 / 2, sig, n), 1, max_new).astype(int)
    return [Request(i, int(a), int(p), int(o)) for i, (a, p, o) in enumerate(zip(arrivals, prompt, output))]


# =====================================================================================================================
# Allocators
# =====================================================================================================================

class ContiguousAllocator:
    """
    Contiguous token ranges in a cache of `capacity` tokens, first fit, merging neighbouring free ranges.

    [Methods] alloc(rid, size) -> bool; free(rid); free_tokens(); largest_hole()
    """

    def __init__(self, capacity):
        self.capacity = capacity
        self.holes = [(0, capacity)]                       # sorted (start, size)
        self.owned = {}

    def alloc(self, rid, size):
        for i, (s, z) in enumerate(self.holes):
            if z >= size:
                self.owned[rid] = (s, size)
                if z == size:
                    del self.holes[i]
                else:
                    self.holes[i] = (s + size, z - size)
                return True
        return False

    def free(self, rid):
        s, z = self.owned.pop(rid)
        self.holes.append((s, z))
        self.holes.sort()
        merged = []
        for h in self.holes:
            if merged and merged[-1][0] + merged[-1][1] == h[0]:
                merged[-1] = (merged[-1][0], merged[-1][1] + h[1])
            else:
                merged.append(h)
        self.holes = merged

    def free_tokens(self):
        return sum(z for _, z in self.holes)

    def largest_hole(self):
        return max((z for _, z in self.holes), default=0)

    def reserved(self):
        return self.capacity - self.free_tokens()


class PagedAllocator:
    """
    Fixed-size blocks of `block` tokens; each request owns a block table (a list of block ids), grown on demand.

    [Methods] blocks_needed(tokens); grow(rid, tokens) -> bool (make the table cover `tokens`); free(rid)
    """

    def __init__(self, capacity, block):
        self.block = block
        self.n_blocks = capacity // block
        self.free_list = list(range(self.n_blocks))[::-1]
        self.tables = {}

    def blocks_needed(self, tokens):
        return math.ceil(tokens / self.block)

    def grow(self, rid, tokens):
        table = self.tables.setdefault(rid, [])
        need = self.blocks_needed(tokens) - len(table)
        if need > len(self.free_list):
            return False
        for _ in range(need):
            table.append(self.free_list.pop())
        return True

    def free(self, rid):
        self.free_list.extend(self.tables.pop(rid, []))

    def reserved(self):
        return (self.n_blocks - len(self.free_list)) * self.block


# =====================================================================================================================
# Serving simulation
# =====================================================================================================================

@dataclass
class ServeResult:
    """
    Outcome of a serving simulation.

    [Fields] steps; tokens (generated); finished (requests); mean_batch; max_batch_seen; util (mean fraction of the
        cache holding real KV entries); reserved (mean fraction reserved); waste breakdown (dict); preemptions;
        mean_latency (steps from arrival to finish); recomputed (KV tokens thrown away by preemption, to be
        recomputed by a later prefill); seconds (sum of step_time over the steps: Llama 3 8B on an H100 by default);
        batch_trace. [Property] tokens_per_s
    """
    steps: int
    tokens: int
    finished: int
    mean_batch: float
    max_batch_seen: int
    util: float
    reserved: float
    waste: dict
    preemptions: int
    mean_latency: float
    recomputed: int = 0
    seconds: float = 0.0
    batch_trace: list = field(default_factory=list)

    @property
    def tokens_per_s(self):
        return self.tokens / self.seconds if self.seconds else 0.0


def simulate(requests, capacity, policy="paged", block=16, max_new=2048, max_batch=512, max_steps=200_000,
             watermark=0.0):
    """
    Continuous batching with a KV cache of `capacity` tokens.

    [Idea] Each step: (1) admit waiting requests in arrival order while their initial memory fits and the batch is
        below max_batch -- contiguous policies reserve prompt + max_new ("max") or prompt + true output ("oracle")
        at once; paged reserves blocks for the prompt only; (2) every running request generates one token; paged
        caches grow by a block when they cross a block boundary -- if none is free, the most recently started
        request is PREEMPTED (its blocks freed, recomputed later); (3) finished requests free their memory.
        watermark (paged only): admit a request only if this fraction of all blocks stays free afterwards -- room
        for the running requests to grow, which trades a smaller batch for fewer preemptions.
    [Returns] ServeResult
    """
    reqs = [Request(r.rid, r.arrival, r.prompt, r.output) for r in requests]
    waiting = list(reqs)
    running = []
    if policy == "paged":
        alloc = PagedAllocator(capacity, block)
    else:
        alloc = ContiguousAllocator(capacity)
    step = 0
    tokens = 0
    finished = []
    batch_trace, used_trace, res_trace = [], [], []
    waste_acc = {"reserved but unused (contiguous)": 0.0, "last-block slack (paged)": 0.0, "free": 0.0}
    preemptions = 0
    recomputed = 0
    seconds = 0.0
    while (waiting or running) and step < max_steps:
        # 1. admission (an admitted request's prompt -- and, after a preemption, its generated tokens -- is
        #    prefilled in this step: compute-bound, 2 x params FLOPs per token)
        prefill = 0
        while waiting and waiting[0].arrival <= step and len(running) < max_batch:
            r = waiting[0]
            if policy == "paged":
                ok = (len(alloc.free_list) - alloc.blocks_needed(r.length + 1) >= watermark * alloc.n_blocks
                      and alloc.grow(r.rid, r.length + 1))
            else:
                size = r.prompt + (max_new if policy == "max" else r.output)
                ok = alloc.alloc(r.rid, size)
            if not ok:
                break
            waiting.pop(0)
            if r.start < 0:
                r.start = step
            prefill += r.length
            running.append(r)
        # 2. one decode step for everybody
        evicted = set()                                      # rids preempted during this step
        for r in list(running):
            if r.rid in evicted:                             # preempted earlier in this loop: it now waits,
                continue                                     # holds no blocks and generates nothing
            if policy == "paged" and not alloc.grow(r.rid, r.length + 1):
                victim = running[-1]                         # preempt the newest request
                alloc.free(victim.rid)
                running.remove(victim)
                evicted.add(victim.rid)
                victim.preempted += 1
                preemptions += 1
                recomputed += victim.length
                waiting.insert(0, victim)
                if victim is r:
                    continue
                if not alloc.grow(r.rid, r.length + 1):
                    continue
            r.generated += 1
            tokens += 1
        # 3. finished requests leave
        for r in list(running):
            if r.generated >= r.output:
                alloc.free(r.rid)
                running.remove(r)
                r.finish = step
                finished.append(r)
        used = sum(r.length for r in running)
        reserved = alloc.reserved()
        seconds += (step_time(len(running), used) if running else 0.0) + prefill * 16.06e9 / 989.4e12
        batch_trace.append(len(running))
        used_trace.append(used / capacity)
        res_trace.append(reserved / capacity)
        if policy == "paged":
            waste_acc["last-block slack (paged)"] += (reserved - used) / capacity
        else:
            waste_acc["reserved but unused (contiguous)"] += (reserved - used) / capacity
        waste_acc["free"] += 1 - reserved / capacity
        step += 1
    n = max(step, 1)
    lat = [r.finish - r.arrival for r in finished]
    return ServeResult(step, tokens, len(finished), float(np.mean(batch_trace)), int(max(batch_trace)),
                       float(np.mean(used_trace)), float(np.mean(res_trace)), {k: v / n for k, v in waste_acc.items()},
                       preemptions, float(np.mean(lat)) if lat else 0.0, recomputed, seconds, batch_trace)


def step_time(batch, kv_tokens, weight_bytes=16.06e9, kv_bytes_per_token=131072, bw=3.35e12, flops_per_token=16.06e9,
              peak=989.4e12):
    """
    One decode step on a GPU, roofline style: read all weights once and every running sequence's KV cache once;
    compute 2 x params FLOPs per token. Defaults: Llama 3 8B in bf16 (16.06 GB of weights; 2 x 32 layers x 8 KV
    heads x 128 x 2 bytes = 128 KiB of KV per token) on an H100 (3.35 TB/s, 989 TFLOPS).
    """
    t_mem = (weight_bytes + kv_tokens * kv_bytes_per_token) / bw
    t_comp = batch * flops_per_token / peak
    return max(t_mem, t_comp)


def sharing_savings(prompt, samples, out_len, block=16):
    """
    KV entries needed by `samples` parallel samples of one prompt (e.g. best-of-n or beam search):
    contiguous copies vs paged blocks with the prompt's full blocks SHARED (reference-counted; the partly filled last
    prompt block is copied on write when the samples diverge).

    [Returns] (contiguous tokens, paged tokens reserved)
    """
    contiguous = samples * (prompt + out_len)
    full_prompt_blocks = prompt // block
    shared = full_prompt_blocks * block
    per_sample = math.ceil((prompt - shared + out_len) / block) * block
    return contiguous, shared + samples * per_sample


# =====================================================================================================================
# Self-test
# =====================================================================================================================

if __name__ == "__main__":
    # contiguous allocator: first fit, holes merge on free
    a = ContiguousAllocator(100)
    assert a.alloc(1, 30) and a.alloc(2, 30) and a.alloc(3, 30) and not a.alloc(4, 20)
    a.free(2)
    assert a.largest_hole() == 30 and not a.alloc(5, 31) and a.alloc(5, 25)
    a.free(1)
    a.free(5)
    assert a.largest_hole() == 60
    # paged allocator: blocks on demand
    p = PagedAllocator(64, 16)
    assert p.grow(1, 17) and len(p.tables[1]) == 2 and p.grow(2, 32) and not p.grow(3, 1)
    p.free(1)
    assert p.grow(3, 30)
    # serving: paged keeps more requests running and wastes less than max reservation
    reqs = make_requests(400, seed=1)
    rm = simulate(reqs, 60_000, "max")
    rp = simulate(reqs, 60_000, "paged", block=16)
    assert rp.finished == rm.finished == 400
    assert rp.mean_batch > 2 * rm.mean_batch and rp.steps < rm.steps, (rp.mean_batch, rm.mean_batch, rp.steps, rm.steps)
    assert rp.waste["last-block slack (paged)"] < 0.05
    # every generated token is accounted for
    assert rp.tokens == sum(r.output for r in reqs) and rm.tokens == sum(r.output for r in reqs)
    c, pg = sharing_savings(1000, 4, 200, 16)
    assert pg < 0.5 * c
    print("paged.py self-test passed")
    print(f"  400 requests, 60k-token cache: contiguous(max) mean batch {rm.mean_batch:.1f}, {rm.steps} steps; "
          f"paged mean batch {rp.mean_batch:.1f}, {rp.steps} steps, {rp.preemptions} preemptions")
