diff --git a/tests/test_measured_capacity.py b/tests/test_measured_capacity.py new file mode 100644 index 00000000..3f4df296 --- /dev/null +++ b/tests/test_measured_capacity.py @@ -0,0 +1,493 @@ +"""Measured KV capacity (RFC #192 step 2 handoff) and the publish gate. + +``measured_kv_capacity`` consumes the step-1 preparation report; the expected +values below are hand-computed from the KV layout and the stated margins, not +from the implementation. +""" + +from types import SimpleNamespace + +import pytest +import torch + +from vllm_rlt.core.kv_cache_manager import KVCacheManager +from vllm_rlt.core.memory import ( + commit_measured_capacity, + measured_kv_capacity, + transient_allowance, +) + +MIB = 1 << 20 +GIB = 1024 * MIB +LAYERS, KV_HEADS, HEAD_DIM, BLOCK = 2, 1, 4, 2 + + +def report(*, free, total, gaps=(), blocks=None): + """One drained, post-cleanup sample as ``prepare_runtime`` reports it.""" + sample = dict( + phases=[ + dict( + name="prepared", + driver_free_bytes=free, + device_total_bytes=total, + allocated_bytes=0, + reserved_bytes=0, + ) + ], + coverage_gaps=tuple(gaps), + ) + if blocks is not None: + sample["num_blocks"] = blocks + return sample + + +def plan(**overrides): + parameters = dict( + report=report(free=60 * GIB, total=80 * GIB), + bytes_per_block=3 * MIB, + useful_blocks=10**6, + gpu_memory_utilization=0.9, + transient_bytes=4 * GIB, + safety_bytes=256 * MIB, + ) + parameters.update(overrides) + return measured_kv_capacity(**parameters) + + +def test_blocks_follow_the_measured_budget_without_double_counting(): + blocks, record = plan() + # resident = 80 - 60 = 20 GiB; cap = 72 GiB; remaining = min(60, 72 - 20) = 52 GiB + # budget = 52 GiB - 4 GiB - 256 MiB = 48896 MiB; 48896 // 3 = 16298 blocks + assert (record["resident_bytes"], record["utilization_cap_bytes"]) == (20 * GIB, int(72 * GIB)) + assert record["remaining_instance_bytes"] == 52 * GIB + assert record["kv_budget_bytes"] == 53248 * MIB - 4096 * MIB - 256 * MIB + assert blocks == 16298 + assert record["source"] == "measured_warmup" + assert blocks * record["bytes_per_block"] <= record["kv_budget_bytes"] + + +def test_driver_free_memory_is_bounded_by_the_utilization_cap(): + # Only 1 GiB is resident, so the 0.5 cap (40 GiB) binds before free memory. + blocks, record = plan( + report=report(free=79 * GIB, total=80 * GIB), + gpu_memory_utilization=0.5, + bytes_per_block=MIB, + transient_bytes=0, + safety_bytes=0, + ) + assert record["remaining_instance_bytes"] == 39 * GIB + assert blocks == 39 * 1024 + + +def test_each_margin_reduces_capacity_exactly(): + free = 20 * GIB + base, _ = plan( + report=report(free=free, total=80 * GIB), + transient_bytes=0, + safety_bytes=0, + gpu_memory_utilization=1.0, + ) + transient, _ = plan( + report=report(free=free, total=80 * GIB), + transient_bytes=1024 * 3 * MIB, + safety_bytes=0, + gpu_memory_utilization=1.0, + ) + safety, _ = plan( + report=report(free=free, total=80 * GIB), + transient_bytes=0, + safety_bytes=1024 * 3 * MIB, + gpu_memory_utilization=1.0, + ) + assert base - transient == 1024 + assert base - safety == 1024 + + +def test_useful_blocks_cap_the_measured_budget(): + blocks, record = plan(useful_blocks=100) + assert blocks == 100 + assert record["max_useful_blocks"] == 100 + + +def test_coverage_gaps_travel_with_the_plan(): + gaps = ("contexts beyond the reported workloads retain the estimated reserve",) + _, record = plan(report=report(free=60 * GIB, total=80 * GIB, gaps=gaps)) + assert record["coverage_gaps"] == gaps + + +def test_a_budget_below_one_block_is_rejected_with_the_margins(): + with pytest.raises(ValueError, match="remaining=.*transient=.*safety=.*block="): + plan( + report=report(free=8 * MIB, total=80 * GIB), + transient_bytes=0, + safety_bytes=0, + ) + + +@pytest.mark.parametrize( + "bad_report", + [None, {}, dict(phases=[]), dict(phases=[dict(driver_free_bytes=1)])], +) +def test_a_missing_or_incomplete_report_is_rejected(bad_report): + with pytest.raises(ValueError, match="report|phase"): + plan(report=bad_report) + + +@pytest.mark.parametrize( + "overrides, message", + [ + (dict(bytes_per_block=0), "bytes_per_block"), + (dict(useful_blocks=0), "useful_blocks"), + (dict(transient_bytes=-1), "transient_bytes"), + (dict(safety_bytes=-1), "safety_bytes"), + (dict(gpu_memory_utilization=0.0), "gpu_memory_utilization"), + ], +) +def test_invalid_inputs_are_rejected(overrides, message): + with pytest.raises(ValueError, match=message): + plan(**overrides) + + +class FakeStorage: + """Mapped storage stand-in: only ``committed_blocks`` has backing.""" + + def __init__( + self, + *, + max_blocks, + committed=0, + dtype=torch.float32, + kv_cache_dtype="auto", + with_scales=False, + ): + self.kv_cache_dtype = kv_cache_dtype + if kv_cache_dtype == "auto": + vector = HEAD_DIM * torch.empty((), dtype=dtype).element_size() + stored = dtype + else: + # FP8 stores one byte per element plus a float32 scale per vector. + vector = HEAD_DIM + 4 + stored = torch.float8_e4m3fn + self.bytes_per_block = 2 * LAYERS * BLOCK * KV_HEADS * vector + shape = (max_blocks, LAYERS, BLOCK, KV_HEADS, HEAD_DIM) + self.tensors = ( + torch.zeros(shape, dtype=stored), + torch.zeros(shape, dtype=stored), + ) + self.scale_tensors = None + if with_scales: + scale_shape = (max_blocks, LAYERS, BLOCK, KV_HEADS) + self.scale_tensors = ( + torch.ones(scale_shape, dtype=torch.float32), + torch.ones(scale_shape, dtype=torch.float32), + ) + self.max_blocks = max_blocks + self.dtype = dtype + self.committed_blocks = 0 + self.committed_bytes = 0 + self.commit(committed) + + def commit(self, blocks): + self.committed_blocks = max(self.committed_blocks, blocks) + self.committed_bytes = self.committed_blocks * self.bytes_per_block + return self.committed_blocks + + +def make_cache(storage=None, num_blocks=4, **kwargs): + parameters = dict( + num_layers=LAYERS, + num_kv_heads=KV_HEADS, + head_dim=HEAD_DIM, + num_blocks=num_blocks, + block_size=BLOCK, + max_loops=1, + ) + parameters.update(kwargs) + return KVCacheManager(**parameters, storage=storage) + + +def test_storage_backed_cache_starts_at_its_committed_capacity(): + storage = FakeStorage(max_blocks=10, committed=4) + cache = make_cache(storage, num_blocks=4) + assert (cache.published_blocks, cache.committed_blocks, cache.max_blocks) == (4, 4, 10) + assert cache.num_blocks == 4 + assert cache.num_free_blocks == 4 + assert cache.key_cache.shape == storage.tensors[0].shape + + +def test_publish_requires_committed_memory_and_grows_the_free_pool(): + storage = FakeStorage(max_blocks=10, committed=2) + cache = make_cache(storage, num_blocks=2) + assert cache.allocate("a", 4) # two published blocks + assert cache.allocate("b", 2) is False + with pytest.raises(ValueError, match="committed 2"): + cache.publish_capacity(8) + assert (cache.published_blocks, cache.num_free_blocks) == (2, 0) + + storage.commit(10) + assert cache.publish_capacity(10) == 10 + assert cache.num_free_blocks == 8 + assert cache.allocate("b", 2) + blocks = cache.get_block_table("b", 0) + assert set(blocks) & set(range(2, 10)), "growth must hand out the newly backed blocks" + key = torch.full((1, KV_HEADS, HEAD_DIM), 3.0) + cache.write(0, ["b"], [0], [0], key, key + 1) + assert torch.equal(cache.key_cache[blocks[0], 0, 0], key[0]) + + +def test_publish_is_monotonic_and_bounded(): + storage = FakeStorage(max_blocks=10, committed=10) + cache = make_cache(storage, num_blocks=2) + assert cache.publish_capacity(6) == 6 + with pytest.raises(ValueError, match="only grow"): + cache.publish_capacity(4) + with pytest.raises(ValueError, match="reservation holds"): + cache.publish_capacity(11) + assert cache.publish_capacity(6) == 6 # idempotent + assert cache.num_blocks == 6 + + +def test_publish_requires_storage(): + cache = make_cache(None) + with pytest.raises(RuntimeError, match="mapped storage"): + cache.publish_capacity(8) + + +def test_plain_cache_keeps_fixed_capacity(): + cache = make_cache(None, num_blocks=6) + assert cache.storage is None + assert (cache.max_blocks, cache.committed_blocks, cache.published_blocks) == (6, 6, 6) + + +def test_storage_must_be_committed_before_the_cache_is_built(): + storage = FakeStorage(max_blocks=10, committed=2) + with pytest.raises(ValueError, match="commit the pool"): + make_cache(storage, num_blocks=4) + + +def test_storage_must_cover_the_requested_blocks_and_layout(): + coarse = FakeStorage(max_blocks=2, committed=2) + with pytest.raises(ValueError, match="reserves"): + make_cache(coarse, num_blocks=4) + wrong_dtype = FakeStorage(max_blocks=10, committed=10, dtype=torch.bfloat16) + with pytest.raises(ValueError, match="do not match the KV layout"): + make_cache(wrong_dtype, num_blocks=4) + + +def test_existing_bootstrap_blocks_are_counted_once_in_the_total(): + # The bootstrap prefix is already mapped, so it sits outside `free` and must + # extend the measured delta rather than being sized from free again. + capacity, record = plan(existing_blocks=100) + assert record["additional_blocks"] == 16298 + assert capacity == 16398 + assert record["existing_blocks"] == 100 + # Only the new part spends budget. + assert (capacity - 100) * record["bytes_per_block"] <= record["kv_budget_bytes"] + + +def test_bootstrap_only_capacity_is_usable_without_growth(): + capacity, record = plan( + report=report(free=8 * MIB, total=80 * GIB), + existing_blocks=8, + transient_bytes=0, + safety_bytes=0, + ) + assert capacity == 8 + assert record["additional_blocks"] == 0 + assert record["limited_by"] == "budget" + + +def test_the_reservation_truncates_the_measured_capacity(): + capacity, record = plan(reservation_blocks=1000) + assert capacity == 1000 + assert record["limited_by"] == "reservation" + assert any("exceeds the reservation" in gap for gap in record["coverage_gaps"]) + + +def test_the_useful_block_cap_binds_before_the_reservation(): + capacity, record = plan(useful_blocks=100, reservation_blocks=1000) + assert capacity == 100 + assert record["limited_by"] == "useful_blocks" + assert not any("exceeds the reservation" in gap for gap in record["coverage_gaps"]) + + +def test_coverage_gaps_reject_a_zero_transient_allowance(): + gaps = ("random block speculation retains the estimated transient reserve",) + with pytest.raises(ValueError, match="coverage gaps require an explicit transient"): + plan( + report=report(free=60 * GIB, total=80 * GIB, gaps=gaps), + transient_bytes=0, + safety_bytes=0, + ) + # The same report is accepted once an allowance is stated, and the gap travels with it. + _, record = plan(report=report(free=60 * GIB, total=80 * GIB, gaps=gaps)) + assert record["coverage_gaps"] == gaps + + +def test_storage_may_not_report_more_committed_blocks_than_it_reserves(): + storage = FakeStorage(max_blocks=4, committed=4) + storage.committed_blocks = 5 # a storage-side accounting bug + with pytest.raises(ValueError, match="reserves only"): + make_cache(storage, num_blocks=4) + + +def test_transient_allowance_takes_the_larger_of_measured_and_estimate(): + phases = [ + dict(name="initialized", allocated_bytes=100 * MIB, peak_allocated_bytes=400 * MIB), + dict(name="prepared", allocated_bytes=300 * MIB, peak_allocated_bytes=500 * MIB), + ] + value, record = transient_allowance({"phases": phases}, estimate_bytes=64 * MIB) + assert record["measured_transient_bytes"] == 300 * MIB # max(300, 500 - 300) + assert value == 300 * MIB + assert record["sampled_phases"] == 2 + + value, _ = transient_allowance({"phases": phases}, estimate_bytes=512 * MIB) + assert value == 512 * MIB # an unexercised path keeps the estimate + + value, _ = transient_allowance({"phases": phases}, estimate_bytes=0, overlap_factor=2) + assert value == 600 * MIB # a serial peak does not bound a concurrent envelope + + +def test_transient_allowance_ignores_phases_without_peak_samples(): + value, record = transient_allowance({"phases": [dict(name="cpu")]}, estimate_bytes=MIB) + assert record["sampled_phases"] == 0 + assert value == MIB + + +@pytest.mark.parametrize( + "kwargs", [dict(estimate_bytes=-1), dict(estimate_bytes=0, overlap_factor=0)] +) +def test_transient_allowance_rejects_invalid_inputs(kwargs): + with pytest.raises(ValueError): + transient_allowance({"phases": []}, **kwargs) + + +def commit_args(**kwargs): + """Arguments for ``commit_measured_capacity`` on the 60/80 GiB sample.""" + options = dict( + report=report(free=60 * GIB, total=80 * GIB, blocks=1000), + bytes_per_block=3 * MIB, + useful_blocks=131072, + gpu_memory_utilization=0.9, + transient_bytes=4 * GIB, + safety_bytes=256 * MIB, + ) + options.update(kwargs) + return options + + +def test_commit_measured_capacity_maps_the_plan_and_returns_backed_blocks(): + storage = FakeStorage(max_blocks=131072, committed=1000) + backed, record = commit_measured_capacity(storage, **commit_args()) + assert backed == 1000 + 16298 + assert storage.committed_blocks == backed + assert record["committed_blocks"] == backed + assert record["storage"] == "mapped" + assert record["limited_by"] == "budget" + + +def test_commit_measured_capacity_requires_the_report_to_describe_this_pool(): + storage = FakeStorage(max_blocks=131072, committed=1000) + drifted = report(free=60 * GIB, total=80 * GIB, blocks=999) + with pytest.raises(ValueError, match="storage backs"): + commit_measured_capacity(storage, **commit_args(report=drifted)) + no_pool = report(free=60 * GIB, total=80 * GIB) + with pytest.raises(ValueError, match="num_blocks"): + commit_measured_capacity(storage, **commit_args(report=no_pool)) + + +def test_commit_measured_capacity_rejects_a_storage_that_under_commits(): + storage = FakeStorage(max_blocks=131072, committed=1000) + storage.commit = lambda blocks: storage.committed_blocks + with pytest.raises(RuntimeError, match="after committing"): + commit_measured_capacity(storage, **commit_args()) + + +def test_commit_measured_capacity_rejects_backing_beyond_the_reservation(): + storage = FakeStorage(max_blocks=131072, committed=1000) + storage.commit = lambda blocks: storage.max_blocks + 1 + with pytest.raises(RuntimeError, match="beyond its"): + commit_measured_capacity(storage, **commit_args()) + + +def test_commit_measured_capacity_refuses_to_truncate_to_the_estimate(): + # Decision: the reservation must be sized from the useful cap. If the + # measured capacity would be clamped back to the estimate, startup fails + # rather than shipping a pool that can never grow. + storage = FakeStorage(max_blocks=5000, committed=1000) + with pytest.raises(RuntimeError, match="reserve the useful cap"): + commit_measured_capacity(storage, **commit_args()) + + +def test_commit_measured_capacity_can_truncate_when_explicitly_allowed(): + storage = FakeStorage(max_blocks=5000, committed=1000) + backed, record = commit_measured_capacity( + storage, **commit_args(allow_reservation_truncation=True) + ) + assert record["limited_by"] == "reservation" + assert backed == 5000 + assert any("exceeds the reservation" in gap for gap in record["coverage_gaps"]) + + +def test_commit_measured_capacity_requires_a_backed_trial_pool(): + storage = FakeStorage(max_blocks=131072, committed=0) + empty = report(free=60 * GIB, total=80 * GIB, blocks=0) + with pytest.raises(ValueError, match="trial pool must back at least one block"): + commit_measured_capacity(storage, **commit_args(report=empty)) + + +def stub_attention(): + return SimpleNamespace( + info={"selected_backend": "stub"}, + capabilities=SimpleNamespace(fp8_kv=True, fp8_kv_static=True), + ) + + +def test_a_mapped_pool_binds_per_vector_fp8_scales(): + storage = FakeStorage(max_blocks=10, committed=4, kv_cache_dtype="fp8_e4m3", with_scales=True) + cache = make_cache( + storage, + num_blocks=4, + kv_cache_dtype="fp8_e4m3", + attention=stub_attention(), + ) + assert cache.key_cache.dtype == torch.float8_e4m3fn + assert cache.key_scale is storage.scale_tensors[0] + assert cache.value_scale is storage.scale_tensors[1] + assert cache._fixed_scale is None + + +def test_a_mapped_pool_accepts_a_fixed_fp8_scale_without_scale_planes(): + storage = FakeStorage(max_blocks=10, committed=4, kv_cache_dtype="fp8_e4m3") + cache = make_cache( + storage, + num_blocks=4, + kv_cache_dtype="fp8_e4m3", + fp8_scale=0.5, + attention=stub_attention(), + ) + assert cache.key_scale is None + assert float(cache._fixed_scale) == 0.5 + + +def test_fp8_over_a_pool_without_scale_support_names_the_hook(): + storage = FakeStorage(max_blocks=10, committed=4, kv_cache_dtype="fp8_e4m3") + with pytest.raises(ValueError, match="scale_tensors"): + make_cache( + storage, + num_blocks=4, + kv_cache_dtype="fp8_e4m3", + attention=stub_attention(), + ) + + +def test_the_pool_must_declare_the_format_it_carries(): + storage = FakeStorage(max_blocks=10, committed=4) # declares "auto" + with pytest.raises(ValueError, match="must declare the format it carries"): + make_cache( + storage, + num_blocks=4, + kv_cache_dtype="fp8_e4m3", + fp8_scale=0.5, + attention=stub_attention(), + ) diff --git a/tests/test_rfc192_joint_contracts.py b/tests/test_rfc192_joint_contracts.py new file mode 100644 index 00000000..3723b8eb --- /dev/null +++ b/tests/test_rfc192_joint_contracts.py @@ -0,0 +1,652 @@ +"""Joint-scheme contracts for RFC #192: measured capacity on a growing mapped pool. + +These tests are written from the design goals, not from the implementation: + +* G1 the plan never exceeds the whole-device utilization cap and leaves the + transient allowance plus the safety margin free; +* G2 capacity never falls below the trial pool that already exists; +* G3 the reservation is sized to the useful cap, so it does not truncate the + measurement, and a truncation is an error unless it is asked for; +* G5 only backed blocks reach the scheduler: ``published <= committed <= max``, + publishing is monotone and needs backing; +* G6 FP8 binds its scale planes from the pool, and a pool that cannot supply + them is refused; +* G7 the estimate stays in force for paths the preparation did not exercise; +* G9 every violation fails at startup, before anything is mapped or published. + +The pool below is a *fake* only in the sense that it allocates no device memory. +It reproduces the arithmetic that makes the scheme non-trivial: physical memory +arrives in whole allocation granules, so the effective block count is what the +slowest plane can back, not what the caller requested. +""" + +from types import SimpleNamespace + +import pytest +import torch + +from vllm_rlt.core.kv_cache_manager import KVCacheManager +from vllm_rlt.core.memory import ( + bootstrap_blocks, + commit_measured_capacity, + measured_kv_capacity, + torch_attention_scratch_bytes, + transient_allowance, +) + +MIB = 1 << 20 +GIB = 1024 * MIB +LAYERS, KV_HEADS, HEAD_DIM, BLOCK = 2, 1, 4, 2 +GRANULE = 400 # bytes; a fake allocation granule, not a real 2 MiB one + + +def round_up(value, multiple): + return -(-value // multiple) * multiple + + +class Plane: + """One pool: a reserved address range that gains physical memory in granules.""" + + def __init__(self, shape, dtype, max_blocks, granule): + self.shape, self.dtype = tuple(shape), dtype + self.block_bytes = torch.empty((), dtype=dtype).element_size() * int( + torch.tensor(list(shape)).prod() + ) + self.reserved_bytes = round_up(max_blocks * self.block_bytes, granule) + self.mapped_bytes = 0 + self.granule = granule + self.grow_calls = 0 + + @property + def backed_blocks(self): + return self.mapped_bytes // self.block_bytes + + def grow(self, blocks): + target = round_up(blocks * self.block_bytes, self.granule) + if target <= self.mapped_bytes: + return + self.grow_calls += 1 + self.mapped_bytes = min(target, self.reserved_bytes) + + +class GranularPool: + """A multi-plane mapped pool with CUDA VMM's granule and reporting semantics.""" + + def __init__(self, planes, *, max_blocks, granule=GRANULE, initial_blocks=1): + self.max_blocks = max_blocks + self.kv_cache_dtype = "auto" + self._data = [Plane(spec, dtype, max_blocks, granule) for spec, dtype in planes] + self._all = list(self._data) + for plane in self._data: + plane.grow(initial_blocks) + self.tensors = tuple( + torch.zeros((max_blocks, *plane.shape), dtype=plane.dtype) for plane in self._data + ) + self.scale_tensors = None + self.committed_blocks = 0 + self.begin() + + def begin(self): + self.commit(0) + + def commit(self, blocks): + if blocks > self.max_blocks: + raise ValueError(f"cannot commit {blocks} blocks, max_blocks is {self.max_blocks}") + for plane in self._all: + plane.grow(blocks) + self.committed_blocks = min( + [self.max_blocks] + [plane.backed_blocks for plane in self._all] + ) + return self.committed_blocks + + @property + def committed_bytes(self): + return sum(plane.mapped_bytes for plane in self._all) + + +def fp8_pool(planes, *, max_blocks, granule=GRANULE, initial_blocks=1): + """An FP8 pool: data planes plus one per-vector scale plane per direction.""" + pool = GranularPool( + planes, max_blocks=max_blocks, granule=granule, initial_blocks=initial_blocks + ) + pool.kv_cache_dtype = "fp8_e4m3" + return pool + + +def report(*, free, total, blocks, gaps=(), phases=None, allocated=0, peak_allocated=0): + if phases is None: + phases = [ + dict( + name="cleaned", + driver_free_bytes=free, + device_total_bytes=total, + allocated_bytes=allocated, + peak_allocated_bytes=peak_allocated, + ) + ] + return dict(phases=phases, coverage_gaps=tuple(gaps), num_blocks=blocks, status="prepared") + + +def stub_attention(): + return SimpleNamespace( + info={"selected_backend": "contracts"}, + capabilities=SimpleNamespace(fp8_kv=True, fp8_kv_static=True), + ) + + +def make_cache(pool, num_blocks, **kwargs): + parameters = dict( + num_layers=LAYERS, + num_kv_heads=KV_HEADS, + head_dim=HEAD_DIM, + num_blocks=num_blocks, + block_size=BLOCK, + max_loops=1, + dtype=torch.float32, + attention=stub_attention(), + storage=pool, + ) + parameters.update(kwargs) + return KVCacheManager(**parameters) + + +DATA = ((LAYERS, BLOCK, KV_HEADS, HEAD_DIM), torch.float32) +SCALE = ((LAYERS, BLOCK, KV_HEADS), torch.float32) + + +# G1: the budget comes from the device, not from a free-floating number. + + +def test_the_utilization_cap_bounds_the_whole_device_not_the_free_bytes(): + # 80 GiB device, 0.9 cap, 20 GiB already resident, 60 GiB free. + capacity, record = measured_kv_capacity( + report=report(free=60 * GIB, total=80 * GIB, blocks=0), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=0.9, + transient_bytes=4 * GIB, + safety_bytes=256 * MIB, + ) + # The cap allows 72 GiB total; 20 GiB is resident, so 52 GiB is the ceiling. + assert record["remaining_instance_bytes"] == 52 * GIB + assert record["kv_budget_bytes"] == 52 * GIB - 4 * GIB - 256 * MIB + assert capacity == (52 * GIB - 4 * GIB - 256 * MIB) // (3 * MIB) + + +def test_a_lower_cap_does_not_hand_back_memory_the_driver_already_gave_up(): + # With 0.5 the cap is 40 GiB and 20 GiB is resident: 20 GiB remain, which is + # less than the 60 GiB the driver reports as free. + capacity, record = measured_kv_capacity( + report=report(free=60 * GIB, total=80 * GIB, blocks=0), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=0.5, + transient_bytes=GIB, + safety_bytes=64 * MIB, + ) + assert record["remaining_instance_bytes"] == 20 * GIB + assert capacity == (20 * GIB - GIB - 64 * MIB) // (3 * MIB) + + +def test_the_cap_trims_its_headroom_from_whatever_free_memory_reports(): + # With a cap below 1 the ceiling is min(free, cap - resident), and resident + # is total - free, so the cap side is the smaller one on any device that is + # not nearly empty: the plan may use free memory minus the (1 - cap) share + # of the whole device. On a shared device the neighbour's memory is already + # out of `free`, and the cap trims its share again rather than handing it + # back. + _, record = measured_kv_capacity( + report=report(free=10 * GIB, total=80 * GIB, blocks=0), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=64 * MIB, + ) + assert record["resident_bytes"] == 70 * GIB + assert record["remaining_instance_bytes"] == 2 * GIB + + +def test_a_cap_of_one_uses_the_measured_free_memory_as_it_stands(): + _, record = measured_kv_capacity( + report=report(free=10 * GIB, total=80 * GIB, blocks=0), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=1, + transient_bytes=GIB, + safety_bytes=64 * MIB, + ) + assert record["remaining_instance_bytes"] == 10 * GIB + + +# G2: the trial pool is a floor, never a casualty of the measurement. + + +def test_a_negative_budget_keeps_the_trial_pool_instead_of_shrinking_it(): + capacity, record = measured_kv_capacity( + report=report(free=1 * MIB, total=80 * GIB, blocks=512), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=0.9, + transient_bytes=8 * GIB, + safety_bytes=GIB, + existing_blocks=512, + ) + assert capacity == 512 + assert record["additional_blocks"] == 0 + + +def test_the_useful_cap_binds_before_the_reservation(): + _, record = measured_kv_capacity( + report=report(free=60 * GIB, total=80 * GIB, blocks=0), + bytes_per_block=3 * MIB, + useful_blocks=1000, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=MIB, + reservation_blocks=4096, + ) + assert record["limited_by"] == "useful_blocks" + + +# G3: a reservation that would clamp the measurement is a startup error. + + +def test_a_reservation_at_the_trial_pool_is_refused_as_a_dead_end(): + pool = GranularPool([DATA, DATA], max_blocks=64, initial_blocks=8) + # 64 GiB free and 64 blocks reserved: the measurement wants far more. + with pytest.raises(RuntimeError, match="reserve the useful cap"): + commit_measured_capacity( + pool, + report=report(free=60 * GIB, total=80 * GIB, blocks=pool.committed_blocks), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=MIB, + ) + + +def test_an_intended_truncation_still_maps_only_the_reservation(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=8) + backed, record = commit_measured_capacity( + pool, + report=report(free=60 * GIB, total=80 * GIB, blocks=pool.committed_blocks), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=MIB, + allow_reservation_truncation=True, + ) + assert backed == 1024 + assert record["limited_by"] == "reservation" + assert any("truncated" in gap for gap in record["coverage_gaps"]) + + +# The granule: what the pool backs is not what was asked for. + + +def test_the_pool_reports_granule_blocks_and_the_planner_must_believe_it(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=1) + # One requested block is rounded up to a granule, which backs several blocks. + assert pool.committed_blocks > 1 + plan, _ = commit_measured_capacity( + pool, + report=report(free=60 * GIB, total=80 * GIB, blocks=pool.committed_blocks), + bytes_per_block=3 * MIB, + useful_blocks=1024, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=MIB, + ) + assert plan == 1024 + + +def test_a_report_that_describes_the_request_instead_of_the_backing_is_refused(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=1) + with pytest.raises(ValueError, match="storage backs"): + commit_measured_capacity( + pool, + report=report(free=60 * GIB, total=80 * GIB, blocks=1), + bytes_per_block=3 * MIB, + useful_blocks=1024, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=MIB, + ) + + +def test_a_partially_committed_pool_never_publishes_the_rounded_up_tail(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=8) + cache = make_cache(pool, pool.committed_blocks) + # Three more blocks are requested; a granule backs more than that. + backed = pool.commit(pool.committed_blocks + 3) + assert backed > pool.committed_blocks - 1 + cache.publish_capacity(backed) + with pytest.raises(ValueError, match="committed"): + cache.publish_capacity(backed + 1) + + +def test_the_slowest_plane_sets_the_effective_count(): + # A wide data plane and a narrow scale plane do not round up by the same + # number of blocks, so the pool must report the smaller of the two. + pool = fp8_pool( + [((LAYERS, BLOCK, KV_HEADS, HEAD_DIM * 16), torch.float8_e4m3fn), SCALE], + max_blocks=4096, + granule=GRANULE, + initial_blocks=1, + ) + pool.tensors = pool.tensors + expected = min(plane.mapped_bytes // plane.block_bytes for plane in pool._all) + assert pool.committed_blocks == min(4096, expected) + + +# G5: publication is the scheduler's only source of blocks. + + +def test_publishing_beyond_the_backing_is_refused_before_the_pool_is_touched(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=8) + cache = make_cache(pool, pool.committed_blocks) + with pytest.raises(ValueError, match="committed"): + cache.publish_capacity(pool.max_blocks) + + +def test_publishing_is_monotone_and_idempotent(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=8) + cache = make_cache(pool, pool.committed_blocks) + first = pool.committed_blocks + grown = pool.commit(64) + assert cache.publish_capacity(grown) == grown + assert cache.publish_capacity(grown) == grown + with pytest.raises(ValueError, match="only grow"): + cache.publish_capacity(grown - 1) + assert cache.published_blocks == grown > first + + +def test_a_pool_that_under_commits_is_caught_at_the_plan_boundary(): + class Lazy(GranularPool): + def commit(self, blocks): + stale = self.committed_blocks + super().commit(blocks) + if not blocks: + return self.committed_blocks + self.committed_blocks = stale # a growth that reports the old count + return stale + + pool = Lazy([DATA, DATA], max_blocks=1024, initial_blocks=8) + with pytest.raises(RuntimeError, match="backed blocks"): + commit_measured_capacity( + pool, + report=report(free=60 * GIB, total=80 * GIB, blocks=pool.committed_blocks), + bytes_per_block=3 * MIB, + useful_blocks=1024, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=MIB, + ) + + +# G6: FP8 binds through the pool, and only through the pool. + + +def test_fp8_binds_the_scale_planes_the_pool_carries(): + data = ((LAYERS, BLOCK, KV_HEADS, HEAD_DIM), torch.float8_e4m3fn) + pool = fp8_pool([data, data, SCALE, SCALE], max_blocks=1024, initial_blocks=1) + pool.scale_tensors = (pool.tensors[2], pool.tensors[3]) + pool.tensors = pool.tensors[:2] + cache = make_cache(pool, pool.committed_blocks, kv_cache_dtype="fp8_e4m3") + assert cache.key_cache.dtype == torch.float8_e4m3fn + assert cache.key_scale is pool.scale_tensors[0] + assert cache.value_scale is pool.scale_tensors[1] + + +def test_fp8_without_exposed_scale_planes_is_refused_with_the_hook_named(): + data = ((LAYERS, BLOCK, KV_HEADS, HEAD_DIM), torch.float8_e4m3fn) + pool = fp8_pool([data, data, SCALE, SCALE], max_blocks=1024, initial_blocks=1) + # The bytes are reserved, but the pool does not expose them as scales. + pool.tensors = pool.tensors[:2] + with pytest.raises(ValueError, match="scale_tensors"): + make_cache(pool, pool.committed_blocks, kv_cache_dtype="fp8_e4m3") + + +def test_a_pool_without_the_scale_bytes_is_refused_before_the_hook(): + data = ((LAYERS, BLOCK, KV_HEADS, HEAD_DIM), torch.float8_e4m3fn) + pool = fp8_pool([data, data], max_blocks=1024, initial_blocks=1) + with pytest.raises(ValueError, match="committed bytes"): + make_cache(pool, pool.committed_blocks, kv_cache_dtype="fp8_e4m3") + + +def test_scale_planes_of_the_wrong_layout_are_refused(): + data = ((LAYERS, BLOCK, KV_HEADS, HEAD_DIM), torch.float8_e4m3fn) + pool = fp8_pool([data, data, SCALE, SCALE], max_blocks=1024, initial_blocks=1) + # Missing the head axis: a plausible mistake that would silently mis-index. + pool.scale_tensors = ( + torch.zeros((1024, LAYERS, BLOCK), dtype=torch.float32), + torch.zeros((1024, LAYERS, BLOCK), dtype=torch.float32), + ) + pool.tensors = pool.tensors[:2] + with pytest.raises(ValueError, match="scale layout"): + make_cache(pool, pool.committed_blocks, kv_cache_dtype="fp8_e4m3") + + +def test_a_pool_that_stores_a_different_format_is_refused(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=1) + with pytest.raises(ValueError, match="must declare the format"): + make_cache(pool, pool.committed_blocks, kv_cache_dtype="fp8_e4m3", fp8_scale=0.5) + + +# G7: unexercised paths keep the estimate. + + +def test_a_gap_keeps_the_estimate_even_when_the_measurement_is_zero(): + value, record = transient_allowance( + report(free=1, total=1, blocks=1, gaps=("long context",)), + estimate_bytes=512 * MIB, + ) + assert value == 512 * MIB + assert record["measured_transient_bytes"] == 0 + + +def test_a_gap_with_no_allowance_is_refused_rather_than_sized_as_measured(): + with pytest.raises(ValueError, match="coverage gaps require"): + measured_kv_capacity( + report=report(free=60 * GIB, total=80 * GIB, blocks=0, gaps=("long context",)), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=0.9, + transient_bytes=0, + safety_bytes=MIB, + ) + + +def test_a_phase_that_peaked_below_its_baseline_contributes_nothing(): + phases = [ + dict( + name="reset", + driver_free_bytes=1, + device_total_bytes=1, + allocated_bytes=100, + peak_allocated_bytes=40, # a stats reset inside the phase + ), + dict(name="cleaned", driver_free_bytes=1, device_total_bytes=1), + ] + value, record = transient_allowance(dict(phases=phases, coverage_gaps=()), estimate_bytes=MIB) + assert record["measured_transient_bytes"] == 0 + assert value == MIB + + +def test_the_concurrency_factor_scales_the_measurement_not_the_estimate(): + phases = [ + dict( + name="cleaned", + driver_free_bytes=1, + device_total_bytes=1, + allocated_bytes=GIB, + peak_allocated_bytes=2 * GIB, + ) + ] + value, _ = transient_allowance( + dict(phases=phases, coverage_gaps=()), estimate_bytes=MIB, overlap_factor=4 + ) + assert value == 4 * GIB + + +# G9: violations fail at startup, before anything is mapped. + + +@pytest.mark.parametrize( + "overrides, message", + [ + (dict(bytes_per_block=True), "bytes_per_block"), + (dict(useful_blocks=True), "useful_blocks"), + (dict(gpu_memory_utilization=0), "gpu_memory_utilization"), + (dict(gpu_memory_utilization=1.5), "gpu_memory_utilization"), + (dict(transient_bytes=-1), "transient_bytes"), + (dict(safety_bytes=-1), "safety_bytes"), + (dict(existing_blocks=True), "existing_blocks"), + (dict(reservation_blocks=0), "reservation_blocks"), + ], +) +def test_invalid_plan_inputs_are_rejected(overrides, message): + arguments = dict( + report=report(free=60 * GIB, total=80 * GIB, blocks=0), + bytes_per_block=3 * MIB, + useful_blocks=1 << 20, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=MIB, + ) + arguments.update(overrides) + with pytest.raises(ValueError, match=message): + measured_kv_capacity(**arguments) + + +def test_the_report_must_be_a_measurement_of_this_pool(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=8) + for bad in (None, {}, dict(num_blocks=True), dict(num_blocks=-1), dict(num_blocks=3)): + with pytest.raises(ValueError): + commit_measured_capacity( + pool, + report=dict(phases=[], coverage_gaps=()) if bad is None else bad, + bytes_per_block=3 * MIB, + useful_blocks=1024, + gpu_memory_utilization=0.9, + transient_bytes=GIB, + safety_bytes=MIB, + ) + + +def test_a_pool_that_claims_more_backing_than_it_reserves_is_refused(): + pool = GranularPool([DATA, DATA], max_blocks=64, initial_blocks=8) + pool.committed_blocks = 65 + with pytest.raises(ValueError, match="reserves only"): + make_cache(pool, 8) + + +def test_a_pool_must_back_the_blocks_the_cache_opens_with(): + pool = GranularPool([DATA, DATA], max_blocks=1024, initial_blocks=8) + with pytest.raises(ValueError, match="committed .* blocks"): + make_cache(pool, pool.committed_blocks + 1) + + +# Boundary: the smallest pool the scheme allows. + + +def test_a_single_block_pool_can_be_planned_published_and_used(): + pool = GranularPool([DATA, DATA], max_blocks=1, initial_blocks=1) + assert pool.committed_blocks == 1 + cache = make_cache(pool, 1) + assert cache.published_blocks == 1 + cache.key_cache[0].fill_(1.0) + assert float(cache.key_cache[0].mean()) == 1.0 + with pytest.raises(ValueError, match="reservation"): + cache.publish_capacity(2) + + +# The reference torch attention reserve, measured rather than assumed. + + +def model_config(**overrides): + values = dict( + max_position_embeddings=65536, + num_attention_heads=16, + num_key_value_heads=16, + head_dim=128, + total_ut_steps=4, + ) + values.update(overrides) + return SimpleNamespace(**values) + + +def test_the_reference_attention_reserve_is_the_measured_footprint(): + # Measured on an A100 with torch_paged_attention and a bf16 pool: 65536 + # tokens peak at 1612.2 MB, which is K and V gathered in the pool dtype and + # then in float32 (12 bytes per element) plus two score vectors. + reserve = torch_attention_scratch_bytes(model_config(), pool_element_size=2) + gathered = 2 * 65536 * 16 * 128 * (2 + 4) + scores = 2 * 65536 * 16 * 4 + assert reserve == gathered + scores + measured = 1_612_190_208 + assert measured <= reserve <= 1.01 * measured + # The estimate this replaces reserved 8 * head_dim + 8 floats per token and + # head, i.e. 4.03125 GiB for the same shape: 2.5 GiB out of the KV budget. + assert reserve < 4.03125 * GIB + + +def test_the_reserve_scales_with_the_context_instead_of_a_fixed_multiple(): + small = torch_attention_scratch_bytes( + model_config(max_position_embeddings=4096), pool_element_size=2 + ) + large = torch_attention_scratch_bytes( + model_config(max_position_embeddings=8192), pool_element_size=2 + ) + assert large == 2 * small + assert 100_766_208 <= small <= 1.05 * 100_766_208 + + +def test_an_fp8_pool_gathers_half_the_bytes_of_a_bf16_pool(): + bf16 = torch_attention_scratch_bytes(model_config(), pool_element_size=2) + fp8 = torch_attention_scratch_bytes(model_config(), pool_element_size=1) + gathered = 2 * 65536 * 16 * 128 + assert bf16 - fp8 == gathered + + +def test_a_grouped_query_configuration_counts_the_expanded_copy(): + plain = torch_attention_scratch_bytes(model_config(), pool_element_size=2) + grouped = torch_attention_scratch_bytes( + model_config(num_key_value_heads=4), pool_element_size=2 + ) + # Fewer key-value heads gather less history, but the float32 expansion is + # still paid for every attention head, so the reserve drops without + # collapsing to the key-value count. + assert grouped < plain + assert grouped > 2 * 65536 * 4 * 128 * 6 + + +# The trial pool is a computed number, not a guess: without it warmup cannot +# cover the shapes that decide the capacity. + + +def test_the_bootstrap_covers_the_largest_prefill_step_and_the_decode_tails(): + config = model_config(max_position_embeddings=65536) + cache = SimpleNamespace(block_size=16, layout="last_exited") + scheduler = SimpleNamespace(max_num_batched_tokens=1024, max_num_seqs=8) + # 1024 tokens over 16-token blocks is 64 blocks, times the four loop copies, + # plus one growing tail per concurrent sequence per copy. + assert bootstrap_blocks(config, cache, scheduler) == 64 * 4 + 8 * 4 + + +def test_the_bootstrap_is_capped_by_the_supported_context(): + config = model_config(max_position_embeddings=2048) + cache = SimpleNamespace(block_size=16, layout="last_exited") + scheduler = SimpleNamespace(max_num_batched_tokens=1 << 20, max_num_seqs=1) + # No single forward can exceed one sequence at the supported context. + assert bootstrap_blocks(config, cache, scheduler) == 128 * 4 + 4 + + +def test_a_flat_layout_needs_no_loop_copies(): + config = model_config() + cache = SimpleNamespace(block_size=16, layout="shared") + scheduler = SimpleNamespace(max_num_batched_tokens=1024, max_num_seqs=8) + assert bootstrap_blocks(config, cache, scheduler) == 64 + 8 diff --git a/tests/test_rfc192_joint_gpu.py b/tests/test_rfc192_joint_gpu.py new file mode 100644 index 00000000..0a17d0f5 --- /dev/null +++ b/tests/test_rfc192_joint_gpu.py @@ -0,0 +1,437 @@ +"""Joint-scheme behaviour on a real device: measured capacity over a VMM KV pool. + +Run with an explicitly selected device:: + + CUDA_VISIBLE_DEVICES=0 python -m pytest tests/test_rfc192_joint_gpu.py --run-gpu + +Every test states a design goal and then measures it against the composed scheme +(measured planner + mapped storage + published capacity): + +* G1 the growth is bounded by the device cap and the driver sees it; +* G4 addresses, strides and captured graph bounds never change when capacity + grows, and a graph captured on the trial pool replays on the new blocks; +* G5 only backed blocks are visible, and the reservation beyond them is not + mapped; +* G6 FP8 binds its scale planes and its byte accounting matches the pool; +* G9 a contract violation fails before anything is used, and a failed growth + leaves a pool the next call can still use. + +The driver is the instrument, not the torch allocator: the point of the scheme +is that this memory never appears in the allocator counters. +""" + +import gc +import os +import subprocess +import sys +from types import SimpleNamespace + +import pytest +import torch + +pytest.importorskip("vllm_rlt.core.kv_storage") + +from vllm_rlt.core.kv_storage import PoolSpec, StableKVStorage, cuda_driver # noqa: E402 + +from tests.helpers import tiny_ouro_model # noqa: E402 +from vllm_rlt.config import CacheConfig, ExecutionConfig, SchedulerConfig # noqa: E402 +from vllm_rlt.core.kv_cache_manager import KVCacheManager, kv_bytes_per_block # noqa: E402 +from vllm_rlt.core.memory import ( # noqa: E402 + commit_measured_capacity, + plan_cache, + torch_attention_scratch_bytes, +) +from vllm_rlt.kernels.paged_attention import torch_paged_attention # noqa: E402 + +MIB = 1 << 20 +LAYERS, HEADS, DIM, BLOCK = 2, 8, 128, 16 +PLANE_BYTES = LAYERS * BLOCK * HEADS * DIM * 2 # one plane, one block, bf16 +BLOCK_BYTES = 2 * PLANE_BYTES +DEVICE = torch.device("cuda:0") +USEFUL = 4096 +SAFETY = 256 * MIB +ESTIMATE = 512 * MIB + +pytestmark = pytest.mark.gpu + + +@pytest.fixture(autouse=True) +def tidy(): + yield + gc.collect() + torch.cuda.synchronize(DEVICE) + torch.cuda.empty_cache() + + +def sample(name="cleaned"): + free, total = torch.cuda.mem_get_info(DEVICE) + return dict( + name=name, + elapsed_seconds=0.0, + driver_free_bytes=free, + device_total_bytes=total, + allocated_bytes=torch.cuda.memory_allocated(DEVICE), + peak_allocated_bytes=torch.cuda.max_memory_allocated(DEVICE), + ) + + +def report(pool): + return dict( + status="prepared", + phases=[sample("initialized"), sample("cleaned")], + coverage_gaps=(), + num_blocks=pool.committed_blocks, + ) + + +def data_spec(dtype=torch.bfloat16): + return PoolSpec((LAYERS, BLOCK, HEADS, DIM), dtype) + + +def make_cache(pool, num_blocks, **kwargs): + parameters = dict( + num_layers=LAYERS, + num_kv_heads=HEADS, + head_dim=DIM, + num_blocks=num_blocks, + block_size=BLOCK, + max_loops=1, + device=DEVICE, + dtype=torch.bfloat16, + storage=pool, + ) + parameters.update(kwargs) + return KVCacheManager(**parameters) + + +def plan_and_grow(pool, *, useful=USEFUL, bytes_per_block=BLOCK_BYTES, transient=ESTIMATE): + free_before, _ = torch.cuda.mem_get_info(DEVICE) + allocated_before = torch.cuda.memory_allocated(DEVICE) + layout = [(t.data_ptr(), tuple(t.shape), tuple(t.stride())) for t in pool.tensors] + backed, record = commit_measured_capacity( + pool, + report=report(pool), + bytes_per_block=bytes_per_block, + useful_blocks=useful, + gpu_memory_utilization=0.9, + transient_bytes=transient, + safety_bytes=SAFETY, + ) + free_after, _ = torch.cuda.mem_get_info(DEVICE) + return dict( + backed=backed, + record=record, + layout_stable=layout + == [(t.data_ptr(), tuple(t.shape), tuple(t.stride())) for t in pool.tensors], + driver_delta=free_before - free_after, + allocated_delta=torch.cuda.memory_allocated(DEVICE) - allocated_before, + ) + + +def touch_block(block, committed, max_blocks=USEFUL): + """Touch one block in a child process: an unmapped page poisons the context.""" + script = f""" +import torch +from vllm_rlt.core.kv_storage import PoolSpec, StableKVStorage +spec = PoolSpec(({LAYERS}, {BLOCK}, {HEADS}, {DIM}), torch.bfloat16) +pool = StableKVStorage( + [spec, spec], max_blocks={max_blocks}, initial_blocks=1, device=torch.device("cuda:0") +) +pool.commit({committed}) +pool.tensors[0][{block}].fill_(1.0) +torch.cuda.synchronize() +print("TOUCHED", pool.committed_blocks) +""" + return subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, env=os.environ + ) + + +# G1 + G4: the measurement becomes physical memory, and nothing moves. + + +def test_the_measured_plan_grows_the_pool_to_the_useful_cap_in_place(): + pool = StableKVStorage( + [data_spec(), data_spec()], max_blocks=USEFUL, initial_blocks=1, device=DEVICE + ) + trial = pool.committed_blocks + assert trial < USEFUL + growth = plan_and_grow(pool) + assert growth["backed"] == USEFUL + assert growth["record"]["limited_by"] == "useful_blocks" + assert growth["layout_stable"] + expected = (USEFUL - trial) * BLOCK_BYTES + assert abs(growth["driver_delta"] - expected) <= 32 * MIB + assert growth["allocated_delta"] == 0 + + +def test_the_grown_blocks_hold_data_and_the_rest_of_the_reservation_is_unmapped(): + usable = 512 + pool = StableKVStorage( + [data_spec(), data_spec()], max_blocks=USEFUL, initial_blocks=1, device=DEVICE + ) + growth = plan_and_grow(pool, useful=usable) + assert growth["backed"] == usable + cache = make_cache(pool, pool.committed_blocks) + cache.publish_capacity(growth["backed"]) + last = cache.published_blocks - 1 + cache.key_cache[last].fill_(1.0) + cache.value_cache[last].fill_(-1.0) + torch.cuda.synchronize(DEVICE) + assert float(cache.key_cache[last].float().mean()) == 1.0 + assert float(cache.value_cache[last].float().mean()) == -1.0 + # A block the plan never paid for is address space without memory. + fault = touch_block(USEFUL - 1, usable) + assert fault.returncode != 0, f"uncommitted block was writable: {fault.stdout}" + assert "CUDA" in fault.stderr + + +# G4: a graph captured on the trial pool still describes the grown pool. + + +def test_a_graph_captured_before_the_growth_writes_the_new_blocks(): + pool = StableKVStorage( + [data_spec(), data_spec()], max_blocks=USEFUL, initial_blocks=1, device=DEVICE + ) + keys = pool.tensors[0] + target = torch.tensor([USEFUL - 1], device=DEVICE) + payload = torch.ones((1, LAYERS, BLOCK, HEADS, DIM), dtype=torch.bfloat16, device=DEVICE) + graph = torch.cuda.CUDAGraph() + torch.cuda.synchronize(DEVICE) + with torch.cuda.graph(graph): + keys.index_put_((target,), payload) + plan_and_grow(pool) + graph.replay() + torch.cuda.synchronize(DEVICE) + assert bool((keys[USEFUL - 1] == 1).all()) + assert float(keys[0].float().abs().sum()) == 0.0 + + +def test_a_gathered_read_of_new_blocks_matches_the_eager_answer(): + pool = StableKVStorage( + [data_spec(), data_spec()], max_blocks=USEFUL, initial_blocks=1, device=DEVICE + ) + keys = pool.tensors[0] + table = torch.tensor([0, USEFUL - 1], device=DEVICE) + query = torch.randn(HEADS, DIM, dtype=torch.bfloat16, device=DEVICE) + + def gathered(): + flat = keys.index_select(0, table).reshape(2 * LAYERS * BLOCK, HEADS, DIM).float() + scores = (flat * query.float()).sum(-1) + weights = torch.softmax(scores, dim=0) + return (weights.unsqueeze(-1) * flat).sum(0) + + graph = torch.cuda.CUDAGraph() + torch.cuda.synchronize(DEVICE) + with torch.cuda.graph(graph): + captured = gathered() + plan_and_grow(pool) + keys[0] = 1.0 + keys[USEFUL - 1] = 2.0 + graph.replay() + torch.cuda.synchronize(DEVICE) + # The same read, run eagerly on the same data, must agree with the capture. + eager = gathered() + assert torch.allclose(captured, eager, atol=1e-3) + # And it reads live memory: changing the far block changes the answer, which + # a graph holding a copy of the trial pool could not do. + keys[USEFUL - 1] = 0.0 + graph.replay() + torch.cuda.synchronize(DEVICE) + assert torch.allclose(captured, gathered(), atol=1e-3) + assert not torch.allclose(captured, eager, atol=1e-3) + + +# G6: FP8 keeps its scales on the pool and its byte accounting matches. + + +class Fp8Source: + """The adapter an integration needs: the storage exposes only ``tensors``.""" + + kv_cache_dtype = "fp8_e4m3" + + def __init__(self, storage): + self._storage = storage + self.tensors = storage.tensors[:2] + self.scale_tensors = storage.tensors[2:] + + @property + def max_blocks(self): + return self._storage.max_blocks + + @property + def committed_blocks(self): + return self._storage.committed_blocks + + @property + def committed_bytes(self): + return self._storage.committed_bytes + + def commit(self, blocks): + return self._storage.commit(blocks) + + +def test_fp8_grows_with_scale_planes_and_matches_the_block_accounting(): + data = PoolSpec((LAYERS, BLOCK, HEADS, DIM), torch.float8_e4m3fn) + scale = PoolSpec((LAYERS, BLOCK, HEADS), torch.float32) + usable = 1024 + storage = StableKVStorage( + [data, data, scale, scale], max_blocks=usable, initial_blocks=1, device=DEVICE + ) + source = Fp8Source(storage) + per_block = kv_bytes_per_block(LAYERS, BLOCK, HEADS, DIM, 1, "fp8_e4m3") + growth = plan_and_grow(source, useful=usable, bytes_per_block=per_block, transient=MIB) + assert growth["backed"] == usable + mapped = storage.committed_bytes + assert mapped >= usable * per_block + assert mapped - usable * per_block <= 8 * MIB # four planes, one granule each + + cache = make_cache(source, source.committed_blocks, kv_cache_dtype="fp8_e4m3") + cache.publish_capacity(growth["backed"]) + assert cache.key_scale is storage.tensors[2] + assert cache.value_scale is storage.tensors[3] + last = cache.published_blocks - 1 + cache.key_cache[last].fill_(1.0) + cache.key_scale[last].fill_(0.5) + torch.cuda.synchronize(DEVICE) + assert float(cache.key_scale[last].mean()) == 0.5 + + +# G1 from the other side: the reservation is address space only. + + +def test_a_reservation_larger_than_the_card_is_address_space_not_memory(): + huge = 262144 # 16 GiB per plane, more than the card holds for KV here + free_before, _ = torch.cuda.mem_get_info(DEVICE) + storage = StableKVStorage( + [data_spec(), data_spec()], max_blocks=huge, initial_blocks=1, device=DEVICE + ) + free_after, _ = torch.cuda.mem_get_info(DEVICE) + assert storage.tensors[0].shape[0] == huge + assert free_before - free_after < 64 * MIB + committed = storage.commit(64) + assert committed >= 64 + assert storage.committed_bytes <= 64 * BLOCK_BYTES + 64 * MIB + + +# G9: violations fail before use, and a failed growth stays recoverable. + + +@pytest.mark.xfail(strict=True, reason="open in #194: commit() accepts a negative count") +def test_commit_rejects_counts_outside_the_reservation(): + pool = StableKVStorage( + [data_spec(), data_spec()], max_blocks=64, initial_blocks=1, device=DEVICE + ) + with pytest.raises(ValueError, match="max_blocks"): + pool.commit(65) + with pytest.raises(ValueError): + pool.commit(-1) + + +def test_a_failed_growth_keeps_the_pool_usable(monkeypatch): + pool = StableKVStorage( + [data_spec(), data_spec()], max_blocks=4096, initial_blocks=1, device=DEVICE + ) + before = pool.committed_blocks + driver = cuda_driver() + real_map = driver.map + calls = {"n": 0} + + def flaky(address, size, handle): + calls["n"] += 1 + if calls["n"] == 2: # the second plane fails after the first one grew + raise RuntimeError("CUDA driver error 2: out of memory") + return real_map(address, size, handle) + + monkeypatch.setattr(driver, "map", flaky) + with pytest.raises(RuntimeError, match="out of memory"): + pool.commit(2048) + monkeypatch.setattr(driver, "map", real_map) + assert pool.committed_blocks == before + assert pool.commit(before + 8) >= before + + +@pytest.mark.xfail(strict=True, reason="open in #194: a failed growth strands the partial mapping") +def test_a_failed_growth_does_not_hold_memory_its_capacity_cannot_use(monkeypatch): + pool = StableKVStorage( + [data_spec(), data_spec()], max_blocks=4096, initial_blocks=1, device=DEVICE + ) + driver = cuda_driver() + real_map = driver.map + calls = {"n": 0} + + def flaky(address, size, handle): + calls["n"] += 1 + if calls["n"] == 2: + raise RuntimeError("CUDA driver error 2: out of memory") + return real_map(address, size, handle) + + monkeypatch.setattr(driver, "map", flaky) + with pytest.raises(RuntimeError, match="out of memory"): + pool.commit(2048) + monkeypatch.setattr(driver, "map", real_map) + # Physical memory the reported block count cannot use is stranded: the pool + # cannot shrink, and the mapping only comes back when the pool is released. + stranded = pool.committed_bytes - pool.committed_blocks * BLOCK_BYTES + assert stranded <= 8 * MIB, f"{stranded / MIB:.1f} MiB are stranded after a failed growth" + + +def test_the_plan_refuses_a_report_that_does_not_describe_this_pool(): + pool = StableKVStorage( + [data_spec(), data_spec()], max_blocks=1024, initial_blocks=1, device=DEVICE + ) + with pytest.raises(ValueError, match="storage backs"): + commit_measured_capacity( + pool, + report=dict(num_blocks=1, phases=[sample()], coverage_gaps=()), + bytes_per_block=BLOCK_BYTES, + useful_blocks=1024, + gpu_memory_utilization=0.9, + transient_bytes=MIB, + safety_bytes=MIB, + ) + assert pool.committed_blocks > 1 + + +# The estimate that stays in force for uncovered paths has to be honest about +# what the kernel it stands for actually allocates. + + +def test_the_reference_attention_reserve_bounds_the_kernel_it_sizes(): + length = 4096 + blocks = length // BLOCK + key = torch.zeros((blocks, BLOCK, HEADS, DIM), dtype=torch.bfloat16, device=DEVICE) + value = torch.zeros_like(key) + query = torch.randn(1, HEADS, DIM, dtype=torch.bfloat16, device=DEVICE) + table = torch.arange(blocks, device=DEVICE).unsqueeze(0) + lengths = torch.tensor([length], device=DEVICE) + torch.cuda.synchronize(DEVICE) + torch.cuda.reset_peak_memory_stats(DEVICE) + baseline = torch.cuda.memory_allocated(DEVICE) + torch_paged_attention(query, key, value, table, lengths) + torch.cuda.synchronize(DEVICE) + measured = torch.cuda.max_memory_allocated(DEVICE) - baseline + config = SimpleNamespace( + max_position_embeddings=length, + num_attention_heads=HEADS, + num_key_value_heads=HEADS, + head_dim=DIM, + ) + reserve = torch_attention_scratch_bytes(config, pool_element_size=2) + # Cover the kernel, but not by a blanket multiple: the previous estimate was + # 2.7 times this measurement, and that excess came out of the KV budget. + assert measured <= reserve <= 1.1 * measured + + +def test_the_planner_does_not_charge_the_probe_pool_as_workspace(): + # RFC #192 section 5: temporary probe KV is not runtime workspace. The probe + # allocates a pool just large enough for its forward, so a peak that still + # contains those bytes takes KV capacity out of the KV budget twice. + model = tiny_ouro_model(device=DEVICE, dtype=torch.bfloat16) + cache = CacheConfig(block_size=2) + scheduler = SchedulerConfig(max_num_seqs=2, max_num_batched_tokens=8, prefill_chunk_size=4) + _, record = plan_cache(model, cache, scheduler, ExecutionConfig(), "torch") + assert record["probe_kv_bytes"] > 0 + assert record["profile_peak_bytes"] == max( + 0, record["raw_profile_peak_bytes"] - record["probe_kv_bytes"] + ) diff --git a/vllm_rlt/core/kv_cache_manager.py b/vllm_rlt/core/kv_cache_manager.py index c6187d77..6a8617b4 100644 --- a/vllm_rlt/core/kv_cache_manager.py +++ b/vllm_rlt/core/kv_cache_manager.py @@ -18,6 +18,7 @@ from copy import deepcopy from dataclasses import dataclass, field from numbers import Integral +from typing import Protocol import torch @@ -166,6 +167,23 @@ class KVSnapshot: fp8_scale: float | None = None +class KVCapacitySource(Protocol): + """Storage that maps physical memory behind one fixed address range. + + ``tensors`` holds the K and V planes in that order and spans ``max_blocks``; + only the first ``committed_blocks`` are backed. ``commit(blocks)`` maps more + and returns how many blocks are fully backed. Release is by reference, as + with ``torch.empty``: the storage owner decides, not this manager. + """ + + max_blocks: int + committed_blocks: int + committed_bytes: int + tensors: tuple[torch.Tensor, ...] + + def commit(self, blocks: int) -> int: ... + + class KVCacheManager: """Own a fixed physical page pool shared by request/depth allocations. @@ -194,6 +212,7 @@ def __init__( attention: AttentionBackend | None = None, kv_cache_dtype: str = "auto", fp8_scale: float | None = None, + storage: KVCapacitySource | None = None, ): for name, value in ( ("num_layers", num_layers), @@ -252,30 +271,23 @@ def __init__( ) self.attention_info = self.attention.info self.backend = self.attention_info["selected_backend"] - capability = "fp8_kv" if fp8_scale is None else "fp8_kv_static" - if kv_cache_dtype != "auto" and not getattr(self.attention.capabilities, capability): - raise ValueError( - f"the {self.attention_info['backend']} backend does not read FP8 KV " - f"with {'per-vector' if fp8_scale is None else 'fixed'} scales" + self._storage = storage + self._watermark_ratio = watermark_ratio + if storage is None: + self._open_torch_planes( + num_blocks=num_blocks, + block_size=block_size, + num_kv_heads=num_kv_heads, + head_dim=head_dim, + dtype=dtype, + kv_cache_dtype=kv_cache_dtype, + fp8_scale=fp8_scale, ) - shape = (num_blocks, num_layers, block_size, num_kv_heads, head_dim) - storage = torch.float8_e4m3fn if kv_cache_dtype == "fp8_e4m3" else dtype - self.key_cache = torch.empty(shape, device=self.device, dtype=storage) - self.value_cache = torch.empty_like(self.key_cache) - # One scale per stored vector; None for an unquantized pool. - self.key_scale = self.value_scale = None - if kv_cache_dtype == "fp8_e4m3": - # Imported fixed-scale pages use the same local scale as locally written pages. - scale = 1.0 if fp8_scale is None else fp8_scale - self.key_scale = torch.full(shape[:-1], scale, device=self.device, dtype=torch.float32) - self.value_scale = torch.full_like(self.key_scale, scale) - # Keep the existing per-vector storage/lifecycle for this prototype. FA - # borrows the immutable scalar; Torch/Triton continue reading the scale pool. - self._fixed_scale = ( - torch.tensor(fp8_scale, device=self.device, dtype=torch.float32) - if fp8_scale is not None - else None - ) + else: + self._open_mapped_planes(storage, num_blocks) + # Requests only ever receive published blocks, and publishing requires + # committed physical memory, so published <= committed <= max holds. + self.published_blocks = num_blocks # Resolve an implicit CUDA index to the actual storage device once. self.device = self.key_cache.device self._free_blocks = list(reversed(range(num_blocks))) @@ -291,7 +303,7 @@ def __init__( self.enable_prefix_caching = enable_prefix_caching self.incremental_allocation = incremental_allocation # Full allocation already reserves each request's maximum KV capacity. - self.watermark_blocks = int(watermark_ratio * num_blocks) if incremental_allocation else 0 + self.watermark_blocks = self._watermark(num_blocks) self._refs = [0] * num_blocks self._prefixes = OrderedDict() self._pending_prefixes = [] @@ -324,6 +336,177 @@ def bytes_per_block(self) -> int: self.kv_cache_dtype, ) + @property + def storage(self) -> KVCapacitySource | None: + return self._storage + + def _watermark(self, blocks: int) -> int: + return int(self._watermark_ratio * blocks) if self.incremental_allocation else 0 + + def _open_torch_planes( + self, + *, + num_blocks: int, + block_size: int, + num_kv_heads: int, + head_dim: int, + dtype: torch.dtype, + kv_cache_dtype: str, + fp8_scale: float | None, + ) -> None: + """Allocate the K/V planes with the PyTorch allocator, including FP8 scales.""" + capability = "fp8_kv" if fp8_scale is None else "fp8_kv_static" + if kv_cache_dtype != "auto" and not getattr(self.attention.capabilities, capability): + raise ValueError( + f"the {self.attention_info['backend']} backend does not read FP8 KV " + f"with {'per-vector' if fp8_scale is None else 'fixed'} scales" + ) + shape = (num_blocks, self.num_layers, block_size, num_kv_heads, head_dim) + storage_dtype = torch.float8_e4m3fn if kv_cache_dtype == "fp8_e4m3" else dtype + self.key_cache = torch.empty(shape, device=self.device, dtype=storage_dtype) + self.value_cache = torch.empty_like(self.key_cache) + # One scale per stored vector; None for an unquantized pool. + self.key_scale = self.value_scale = None + if kv_cache_dtype == "fp8_e4m3": + # Imported fixed-scale pages use the same local scale as locally written pages. + scale = 1.0 if fp8_scale is None else fp8_scale + self.key_scale = torch.full(shape[:-1], scale, device=self.device, dtype=torch.float32) + self.value_scale = torch.full_like(self.key_scale, scale) + # Keep the existing per-vector storage/lifecycle for this prototype. FA + # borrows the immutable scalar; Torch/Triton continue reading the scale pool. + self._fixed_scale = ( + torch.tensor(fp8_scale, device=self.device, dtype=torch.float32) + if fp8_scale is not None + else None + ) + self.max_blocks = num_blocks + self.committed_blocks = num_blocks + + def _open_mapped_planes(self, storage: KVCapacitySource, num_blocks: int) -> None: + """Bind the K/V planes to a pool that owns their physical mappings. + + The pool must declare the element format it carries. FP8 KV is supported + only through the hook below: a source that carries per-vector scales + exposes ``scale_tensors`` (K first), and one that relies on a fixed + ``fp8_scale`` needs no per-vector storage. Anything else is rejected here + rather than writing unquantized bytes into a quantized cache. Only the + pool's backed blocks are exposed; publishing them is the manager's + decision, not the storage's. + """ + pool_dtype = getattr(storage, "kv_cache_dtype", "auto") + if pool_dtype != self.kv_cache_dtype: + raise ValueError( + f"the pool stores {pool_dtype} KV but the cache was configured for " + f"{self.kv_cache_dtype}; a mapped pool must declare the format it carries" + ) + if storage.committed_blocks > storage.max_blocks: + raise ValueError( + f"storage reports {storage.committed_blocks} committed blocks but " + f"reserves only {storage.max_blocks}" + ) + expected = kv_bytes_per_block( + self.num_layers, + self.block_size, + self.num_kv_heads, + self.head_dim, + torch.empty((), dtype=self.dtype).element_size(), + self.kv_cache_dtype, + ) + if storage.max_blocks < num_blocks: + raise ValueError( + f"storage reserves {storage.max_blocks} blocks but {num_blocks} were requested" + ) + if storage.committed_blocks < num_blocks: + raise ValueError( + f"storage committed {storage.committed_blocks} blocks but {num_blocks} " + "were requested; commit the pool before building the cache" + ) + if storage.committed_bytes < num_blocks * expected: + raise ValueError( + f"storage reports {storage.committed_bytes} committed bytes but " + f"{num_blocks} blocks need {num_blocks * expected}" + ) + keys, values = storage.tensors + shape = ( + storage.max_blocks, + self.num_layers, + self.block_size, + self.num_kv_heads, + self.head_dim, + ) + element_dtype = torch.float8_e4m3fn if self.kv_cache_dtype == "fp8_e4m3" else self.dtype + for name, tensor in (("keys", keys), ("values", values)): + if tensor.dtype != element_dtype or tuple(tensor.shape) != shape: + raise ValueError(f"storage {name} do not match the KV layout") + self.key_cache, self.value_cache = keys, values + self.key_scale, self.value_scale = self._bind_scale_planes(storage) + self._fixed_scale = ( + torch.tensor(self.fp8_scale, device=self.device, dtype=torch.float32) + if self.fp8_scale is not None + else None + ) + self.max_blocks = storage.max_blocks + self.committed_blocks = storage.committed_blocks + + def _bind_scale_planes(self, storage): + """Return the pool's per-vector FP8 scales, or ``(None, None)``. + + This is the extension point for FP8 KV over a mapped pool. A source that + carries scales exposes ``scale_tensors`` with K first; a source used with + a fixed ``fp8_scale`` needs no per-vector storage. ``committed_bytes`` is + expected to cover the data and the scale pools together. + """ + if self.kv_cache_dtype == "auto" or self.fp8_scale is not None: + return None, None + scales = getattr(storage, "scale_tensors", None) + if scales is None: + raise ValueError( + "mapped FP8 KV needs per-vector scales: expose `scale_tensors` on the " + "capacity source, or configure a fixed fp8_scale" + ) + key_scale, value_scale = scales + scale_shape = ( + storage.max_blocks, + self.num_layers, + self.block_size, + self.num_kv_heads, + ) + for name, tensor in (("key_scale", key_scale), ("value_scale", value_scale)): + if tensor.dtype != torch.float32 or tuple(tensor.shape) != scale_shape: + raise ValueError(f"storage {name} do not match the FP8 scale layout") + return key_scale, value_scale + + def publish_capacity(self, blocks: int) -> int: + """Grow the allocatable pool after the storage mapped more blocks. + + The K/V tensors keep their address, shape and stride; only the free pool + and the published count grow. Uncommitted blocks are never published, so + no allocation can reference unmapped memory. + """ + if self._storage is None: + raise RuntimeError("capacity publishing requires mapped storage") + if type(blocks) is not int or blocks < self.published_blocks: + raise ValueError("published capacity can only grow") + if blocks > self.max_blocks: + raise ValueError( + f"cannot publish {blocks} blocks; the reservation holds {self.max_blocks}" + ) + # Re-read the pool: a commit may have happened since the last publish. + self.committed_blocks = self._storage.committed_blocks + if blocks > self.committed_blocks: + raise ValueError( + f"cannot publish {blocks} blocks; the storage committed {self.committed_blocks}" + ) + if blocks == self.published_blocks: + return blocks + self._refs.extend([0] * (blocks - self.published_blocks)) + # _claim pops from the tail, so later blocks follow in ascending order. + self._free_blocks.extend(reversed(range(self.published_blocks, blocks))) + self.published_blocks = blocks + self.num_blocks = blocks + self.watermark_blocks = self._watermark(blocks) + return blocks + def required_blocks(self, max_tokens: int) -> int: if not isinstance(max_tokens, Integral) or isinstance(max_tokens, bool) or max_tokens <= 0: raise ValueError("max_tokens must be a positive integer") diff --git a/vllm_rlt/core/memory.py b/vllm_rlt/core/memory.py index 1c52c16c..dbe7d635 100644 --- a/vllm_rlt/core/memory.py +++ b/vllm_rlt/core/memory.py @@ -19,6 +19,223 @@ def budget_blocks(available_bytes, bytes_per_block): return blocks +def measurement_budget(report): + """Driver free/total bytes and coverage gaps from a startup preparation report. + + ``report`` is step 1 of RFC #192 (``StageEngine.prepare_runtime``): boundary + samples taken after draining, with the allocator cache retained. Only the + last sample sizes capacity, because it is the state after warmup and capture. + """ + if not report: + raise ValueError("a measured KV plan requires a startup preparation report") + phases = report.get("phases") or () + if not phases: + raise ValueError("the startup report contains no phase samples") + final = phases[-1] + free, total = final.get("driver_free_bytes"), final.get("device_total_bytes") + if type(free) is not int or type(total) is not int or total <= 0 or free < 0: + raise ValueError("the final startup phase lacks valid driver free/total bytes") + return free, total, tuple(report.get("coverage_gaps") or ()) + + +def measured_kv_capacity( + *, + report, + bytes_per_block, + useful_blocks, + gpu_memory_utilization, + transient_bytes, + safety_bytes, + existing_blocks=0, + reservation_blocks=None, +): + """Total blocks the pool may hold after warmup and capture. + + ``free`` memory already excludes weights, execution buffers, captured graphs + and anything already mapped, including ``existing_blocks`` (the bootstrap + prefix). The measured capacity is therefore additional, and the cumulative + ``commit(total)`` of a storage maps only the new part. + + ``transient_bytes`` covers execution above that persistent baseline and + ``safety_bytes`` the fixed reserve. The result is clamped by the logical + ``useful_blocks`` and, when the pool cannot grow that far, by + ``reservation_blocks``; the binding limit and every margin are recorded. + + ``gpu_memory_utilization`` keeps its existing meaning: a fraction of the + whole device, not of what is free after the baseline. The KV budget is that + cap minus everything already resident, i.e. weights, execution buffers, + captured graphs and mapped blocks. + """ + for name, value in ( + ("bytes_per_block", bytes_per_block), + ("useful_blocks", useful_blocks), + ): + if type(value) is not int or value < 1: + raise ValueError(f"{name} must be a positive integer") + for name, value in ( + ("transient_bytes", transient_bytes), + ("safety_bytes", safety_bytes), + ("existing_blocks", existing_blocks), + ): + if type(value) is not int or value < 0: + raise ValueError(f"{name} must be a nonnegative integer") + if reservation_blocks is not None and ( + type(reservation_blocks) is not int or reservation_blocks < 1 + ): + raise ValueError("reservation_blocks must be a positive integer") + if not 0 < gpu_memory_utilization <= 1: + raise ValueError("gpu_memory_utilization must be in (0, 1]") + free, total, gaps = measurement_budget(report) + if gaps and not transient_bytes: + # The preparation reported paths it did not exercise. Sizing them as if + # measured would publish a pool that cannot serve them. + raise ValueError(f"coverage gaps require an explicit transient allowance: {gaps[0]}") + resident = total - free + # What the utilization cap still allows, bounded by measured free memory. + remaining = min(free, int(total * gpu_memory_utilization) - resident) + budget = remaining - transient_bytes - safety_bytes + additional = max(0, budget // bytes_per_block) + capacity = existing_blocks + additional + if capacity < 1: + raise ValueError( + "no KV capacity fits the measured budget: " + f"remaining={remaining} transient={transient_bytes} " + f"safety={safety_bytes} block={bytes_per_block}" + ) + limit = "budget" + if capacity > useful_blocks: + capacity, limit = useful_blocks, "useful_blocks" + if reservation_blocks is not None and capacity > reservation_blocks: + capacity, limit = reservation_blocks, "reservation" + gaps = ( + *gaps, + "measured capacity exceeds the reservation; committed capacity truncated", + ) + return capacity, dict( + source="measured_warmup", + bytes_per_block=bytes_per_block, + driver_free_bytes=free, + device_total_bytes=total, + resident_bytes=resident, + utilization_cap_bytes=int(total * gpu_memory_utilization), + remaining_instance_bytes=remaining, + transient_bytes=transient_bytes, + safety_bytes=safety_bytes, + kv_budget_bytes=budget, + existing_blocks=existing_blocks, + additional_blocks=additional, + max_useful_blocks=useful_blocks, + reservation_blocks=reservation_blocks, + limited_by=limit, + coverage_gaps=gaps, + ) + + +def transient_allowance(report, *, estimate_bytes, overlap_factor=1): + """Allowance for execution above the persistent baseline of a phase. + + A phase records its end state and its own peak, so ``peak - allocated`` is + what that phase needed on top of what it kept. The largest such delta is + measured; ``estimate_bytes`` covers paths the preparation did not exercise + and must stay in force. ``overlap_factor`` covers supported concurrency, + because a serial peak understates a concurrent envelope. The larger of the + two is returned, so an unmeasured path is never sized as if measured. + """ + if type(estimate_bytes) is not int or estimate_bytes < 0: + raise ValueError("estimate_bytes must be a nonnegative integer") + if type(overlap_factor) is not int or overlap_factor < 1: + raise ValueError("overlap_factor must be an integer of at least 1") + phases = (report or {}).get("phases") or () + measured = 0 + sampled = 0 + for phase in phases: + peak, allocated = phase.get("peak_allocated_bytes"), phase.get("allocated_bytes") + if type(peak) is not int or type(allocated) is not int: + continue + sampled += 1 + measured = max(measured, peak - allocated) + value = max(measured * overlap_factor, estimate_bytes) + return value, dict( + transient_bytes=value, + measured_transient_bytes=measured, + estimate_bytes=estimate_bytes, + overlap_factor=overlap_factor, + sampled_phases=sampled, + ) + + +def commit_measured_capacity( + storage, + *, + report, + bytes_per_block, + useful_blocks, + gpu_memory_utilization, + transient_bytes, + safety_bytes, + allow_reservation_truncation=False, +): + """Plan the measured capacity, map it, and return the publishable block count. + + Enforces the preconditions of the agreed ordering: the report describes the + pool the storage already backs, the plan never exceeds the reservation, and + the storage must report at least the planned blocks as backed. The caller + publishes exactly the returned count and nothing else. + + Two caller policies are checked here rather than assumed. The trial pool must + already back at least one block, because a mapped pool cannot be built with no + mapping at all. And its reservation must be sized from ``useful_blocks``, not + from the pre-warmup estimate: otherwise the measured capacity is clamped back + to the estimate and the pool can never grow. Pass + ``allow_reservation_truncation=True`` only when that clamp is intended. + """ + existing = (report or {}).get("num_blocks") + if type(existing) is not int or existing < 0: + raise ValueError("the startup report must record the current pool as num_blocks") + if existing < 1: + raise ValueError( + "the trial pool must back at least one block; size it from the warmup " + "coverage target before preparing the runtime" + ) + if existing > storage.max_blocks: + raise ValueError( + f"the report describes {existing} blocks but the storage reserves {storage.max_blocks}" + ) + if storage.committed_blocks != existing: + # The pool changed after the sample, so the measured free memory no + # longer describes this storage. + raise ValueError( + f"the report describes {existing} blocks but the storage backs " + f"{storage.committed_blocks}" + ) + capacity, record = measured_kv_capacity( + report=report, + bytes_per_block=bytes_per_block, + useful_blocks=useful_blocks, + gpu_memory_utilization=gpu_memory_utilization, + transient_bytes=transient_bytes, + safety_bytes=safety_bytes, + existing_blocks=existing, + reservation_blocks=storage.max_blocks, + ) + if record["limited_by"] == "reservation" and not allow_reservation_truncation: + raise RuntimeError( + f"the measured capacity ({capacity} blocks) exceeds the " + f"{storage.max_blocks}-block reservation, so it would be truncated to the " + "pre-warmup estimate; reserve the useful cap instead of the estimate" + ) + backed = storage.commit(capacity) + if type(backed) is not int or backed < capacity: + raise RuntimeError(f"storage reported {backed} backed blocks after committing {capacity}") + if backed > storage.max_blocks: + raise RuntimeError( + f"storage reported {backed} backed blocks beyond its " + f"{storage.max_blocks}-block reservation" + ) + record.update(committed_blocks=backed, storage="mapped") + return backed, record + + def graph_memory_reserve(model, scheduler, execution, speculative=None): """Headroom per pool plus retained speculative coda logits across all entries. @@ -124,6 +341,59 @@ def calibrate_fp8_scale(model, cache, attention) -> float: return 2.0 ** math.ceil(math.log2(scale)) +def torch_attention_scratch_bytes(config, *, pool_element_size): + """Transient the reference torch attention needs for one long-context row. + + ``torch_paged_attention`` resolves one row at a time: it gathers that row's + whole history for K and for V in the pool dtype, copies each of them into + float32, and keeps two score vectors of ``[heads, length]`` floats. Nothing + else scales with the context, and the tensors are released before the next + row, so the peak is linear in the length and does not depend on the layer + count. + + Measured with ``torch_paged_attention`` on an A100 (16 heads, head_dim 128, + bf16 pool, one row): 100.8 MB at 4096 tokens, 403.1 MB at 16384 and + 1612.2 MB at 65536 — 12 bytes per element of the gathered history, which is + exactly ``2 * (pool_element_size + 4)``, plus the two score vectors. The + estimate this replaces used ``8 * head_dim + 8`` floats per token and head, + which is 2.7 times the measurement, and that excess came straight out of the + KV budget: 2.5 GiB, or about 860 blocks, on a 65536-token checkpoint. + + The repeated head axis is not measured, because no grouped-query checkpoint + was available; it adds a float32 copy of the expanded history and is counted + whenever key-value heads are fewer than attention heads. + """ + length = config.max_position_embeddings + gathered = 2 * length * config.num_key_value_heads * config.head_dim * (pool_element_size + 4) + scores = 2 * length * config.num_attention_heads * 4 + repeat = 0 + if config.num_attention_heads > config.num_key_value_heads: + repeat = 2 * length * config.num_attention_heads * config.head_dim * 4 + return gathered + scores + repeat + + +def bootstrap_blocks(config, cache, scheduler): + """Blocks the trial pool must back before startup warmup can measure anything. + + Warmup runs one forward per shape, so the pool has to hold the largest + prefill step (``max_num_batched_tokens`` tokens, capped by + ``max_num_seqs * max_position_embeddings``) plus one growing tail block per + concurrent sequence for the decode cases that follow. The looped layout + keeps ``total_ut_steps`` copies of each. + + A pool smaller than this makes warmup skip shapes and report a coverage gap, + and a measurement with gaps cannot retire the estimate it was meant to + replace: the measured plan keeps the formula reserve and the extra startup + work buys nothing. Commit at least this many blocks before + ``prepare_runtime``. + """ + tokens = min( + scheduler.max_num_batched_tokens, scheduler.max_num_seqs * config.max_position_embeddings + ) + depth = config.total_ut_steps if cache.layout == "last_exited" else 1 + return math.ceil(tokens / cache.block_size) * depth + scheduler.max_num_seqs * depth + + @torch.inference_mode() def plan_cache( model, @@ -177,13 +447,15 @@ def plan_cache( min(config.max_position_embeddings, count - start) for start in range(0, count, config.max_position_embeddings) ] + probe_blocks = sum(math.ceil(length / cache.block_size) for length in lengths) * ( + config.total_ut_steps if cache.layout == "last_exited" else 1 + ) probe = KVCacheManager( num_layers=getattr(config, "num_kv_layers", config.num_hidden_layers), num_kv_heads=config.num_key_value_heads, head_dim=config.head_dim, max_loops=config.total_ut_steps, - num_blocks=sum(math.ceil(length / cache.block_size) for length in lengths) - * (config.total_ut_steps if cache.layout == "last_exited" else 1), + num_blocks=probe_blocks, block_size=cache.block_size, layout=cache.layout, device=device, @@ -201,19 +473,19 @@ def plan_cache( positions.extend(range(length)) tokens = torch.zeros(count, dtype=torch.long, device=device) logits = _probe_forward(model, probe, tokens, ids, positions) - torch.cuda.synchronize(device) - peak = max(0, torch.cuda.max_memory_allocated(device) - allocated) + raw_peak = max(0, torch.cuda.max_memory_allocated(device) - allocated) + # The probe's own KV pool is not runtime workspace: charging it here would + # take KV bytes out of the KV budget twice (RFC #192, section 5). + probe_kv_bytes = probe_blocks * per_block + peak = max(0, raw_peak - probe_kv_bytes) del logits, probe - # Profiling includes a conservative temporary KV allocation. Also budget for - # long-context reference attention (Triton's online softmax has bounded scratch). + # Fused attention keeps bounded scratch. The reference torch path gathers a + # whole history into float32 per row, so its transient scales with the + # context the deployment supports, not with the prefill batch. context_scratch = 0 if backend == "torch": - context_scratch = ( - config.max_position_embeddings - * config.num_attention_heads - * (8 * config.head_dim + 8) - * 4 - ) + pool_element = 1 if cache.kv_cache_dtype == "fp8_e4m3" else parameter.element_size() + context_scratch = torch_attention_scratch_bytes(config, pool_element_size=pool_element) buffers = execution_buffer_bytes( config, scheduler, @@ -253,10 +525,13 @@ def plan_cache( source="cuda_profile", bytes_per_block=per_block, profile_peak_bytes=peak, + raw_profile_peak_bytes=raw_peak, + probe_kv_bytes=probe_kv_bytes, concurrent_peak_bytes=concurrent_peak, max_useful_blocks=useful_blocks, cuda_graph_reserve_bytes=graph_reserve, static_buffer_bytes=buffers, context_scratch_bytes=context_scratch, + metadata_bytes=metadata, kv_budget_bytes=int(budget), )