Skip to content
BIASED
Back to topic

Optional

KV slots and speculative probability mass

No model or accelerator is run. Token ticks have equal cost by assumption. KV arithmetic excludes weights and workspaces; block waste means final-block slack only. Exact probability correction does not establish a runtime speedup.

Version
v2
Minutes
~20
Evidence
Self-check in the notebook

Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.

Download .ipynb

Download the notebook and run it locally. Its environment requirements are listed inside.

Notebook contents

Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.

KV slots and speculative probability mass / KV-слоты и вероятности speculative decoding

Optional practice; Python standard library only. The core lesson does not require running code. No downloads, network, accounts, models, user data or actual deployments.

Необязательная практика; только стандартная библиотека Python. Для основной темы запуск кода не требуется. Без загрузок, сети, аккаунтов, моделей, пользовательских данных или реальных деплоев.

Authored for the Fedor Pakhurov project with Codex assistance. Case functions and fictional inputs come from the independently reviewed first-party note and fixture at published revision 82b6cb07167b37710c6a786a3a41878a4e928483. New packaging and exact-arithmetic self-checks are added here. No exclusive copyright guarantee is asserted.

Note: https://github.com/fpakhurov/fpakhurov.com/blob/82b6cb07167b37710c6a786a3a41878a4e928483/src/content/notes/mlops/llm-inference-systems.mdx

Fixture: https://github.com/fpakhurov/fpakhurov.com/blob/82b6cb07167b37710c6a786a3a41878a4e928483/scripts/notes/mlops-renewal-cases.py

The note retains primary conceptual citations; no external source-specific dataset, model output, figure or code is included.

Inputs and limits / Входы и границы

No model or accelerator is run. Token ticks have equal cost by assumption. KV arithmetic excludes weights and workspaces; block waste means final-block slack only. Exact probability correction does not establish a runtime speedup.

Модель и ускоритель не запускаются. Стоимость токенного шага одинакова по предположению. Подсчёт KV исключает веса и рабочие буферы; потери блоков означают остаток последнего блока. Точная коррекция вероятности не устанавливает ускорение.

import hashlib
import itertools
import json
import math
 
def inference():
    lengths = [2, 5, 1, 3]
    active = [(0, lengths[0]), (1, lengths[1])]
    next_id, tick, completion = 2, 0, {}
    trace = []
    while active:
        tick += 1
        trace.append([index for index, _ in active])
        remaining = []
        for index, left in active:
            if left == 1:
                completion[index] = tick
            else:
                remaining.append((index, left - 1))
        active = remaining
        while len(active) < 2 and next_id < len(lengths):
            active.append((next_id, lengths[next_id]))
            next_id += 1
    p, q = [0.2, 0.5, 0.3], [0.4, 0.4, 0.2]
    accepted = [min(a, b) for a, b in zip(p, q)]
    rejection = 1 - sum(accepted)
    residual = [max(a - b, 0) / rejection for a, b in zip(p, q)]
    recovered = [a + rejection * r for a, r in zip(accepted, residual)]
    assert all(math.isclose(a, b) for a, b in zip(recovered, p))
    tokens = [33, 65, 10]
    allocated = [math.ceil(length / 32) * 32 for length in tokens]
    return {"output_lengths": lengths, "continuous_trace": trace,
            "continuous_completion_ticks": [completion[i] for i in range(4)],
            "static_completion_ticks": [2, 5, 6, 8],
            "static_slot_utilization": sum(lengths) / 16,
            "continuous_slot_utilization": sum(lengths) / (2 * tick),
            "kv_bytes": 2 * 12 * 4 * 64 * 768 * 2,
            "kv_MiB": 2 * 12 * 4 * 64 * 768 * 2 / 2**20,
            "block_tokens": 32, "sequence_tokens": tokens,
            "allocated_tokens": allocated, "unused_tokens": sum(allocated) - sum(tokens),
            "speculative_p": p, "speculative_q": q, "acceptance_probability": sum(accepted),
            "rejection_distribution": residual, "recovered_p": recovered}
result = inference()
print(json.dumps(result, indent=2, allow_nan=False))

Check independently / Независимая проверка

The checks below use conservation, exact arithmetic or boundary cases in addition to the case function. Passing them establishes these declared examples, not production reliability.

Ниже проверяются сохранение, точная арифметика или граничные случаи сверх функции примера. Их прохождение устанавливает эти заданные примеры, а не надёжность продакшена.

from fractions import Fraction as F
assert result["continuous_completion_ticks"] == [2,5,3,6]
assert sum(map(len,result["continuous_trace"])) == sum(result["output_lengths"]) == 11
assert result["kv_bytes"] == 9 * 2**20
assert result["unused_tokens"] == 84 < 3 * result["block_tokens"]
p = [F(1,5),F(1,2),F(3,10)]; q = [F(2,5),F(2,5),F(1,5)]
a = [min(x,y) for x,y in zip(p,q)]
missing = [max(x-y,F(0)) for x,y in zip(p,q)]
assert sum(a) == F(4,5) and [x+y for x,y in zip(a,missing)] == p
assert [min(x,x) for x in p] == p and sum(max(x-x,F(0)) for x in p) == 0
print("Self-checks passed: work conservation, 9 MiB, 84 slots and exact target mass.")

Change one assumption / Измените одно предположение

Change the block size from 32 to 16 and recompute allocation. Separately set p=q: rejection becomes zero, so no residual distribution should be normalized in that branch.

Измените размер блока с 32 на 16 и пересчитайте выделение. Отдельно задайте p=q: отбрасывание станет нулевым, поэтому в этой ветке не следует нормировать остаточное распределение.