|
| 1 | +"""Compiled window snapshots preserve immutable history and accepted prefixes.""" |
| 2 | + |
| 3 | +import os |
| 4 | + |
| 5 | +import pytest |
| 6 | +import torch |
| 7 | +from b12x.preparation import PreparationSession |
| 8 | +from cuda.bindings import driver as cuda |
| 9 | + |
| 10 | +from ignition.components.compressed_mla import PreparedCompressedCacheWriter |
| 11 | +from ignition.components.paged_batch import Metadata |
| 12 | +from ignition.components.ring_commit import PreparedRingCommit |
| 13 | +from ignition.components.state import StateLayout, StateStorage, gather_rows |
| 14 | +from ignition.components.window_indices import PreparedWindowIndices |
| 15 | +from ignition.preparation.compilation import compile_forward |
| 16 | +from ignition.preparation.graphs import PreparedGraphBundle |
| 17 | + |
| 18 | +pytestmark = pytest.mark.skipif(os.environ.get("FLARE_RUN_CUDA_TESTS") != "1", |
| 19 | + reason="requires an explicitly assigned CUDA device") |
| 20 | + |
| 21 | + |
| 22 | +class SnapshotCase: |
| 23 | + def __init__(self, requests, width, mode, session, *, fused): |
| 24 | + device = torch.device("cuda:0") |
| 25 | + self.mode, self.fused = mode, fused |
| 26 | + layout = StateLayout.from_specs((("before", (256,), torch.uint8), |
| 27 | + ("window", (128 * 528,), torch.uint8), ("after", (256,), torch.uint8))) |
| 28 | + self.storage = StateStorage.allocate(layout, requests + 3, device) |
| 29 | + self.history = self.storage.region("window") |
| 30 | + self.metadata = Metadata.allocate(requests * width, requests, 1, device, |
| 31 | + max_query_tokens=width) |
| 32 | + self.indices = PreparedWindowIndices(self.metadata, mode=mode, |
| 33 | + tokens=requests * width, page_size=128 + width, |
| 34 | + width=128 + width if mode == "draft" else 128) |
| 35 | + self.values = torch.zeros((requests * width, 512), dtype=torch.bfloat16, device=device) |
| 36 | + self.counts = torch.zeros(requests, dtype=torch.int32, device=device) |
| 37 | + self.commit = PreparedRingCommit(self.storage.backing, |
| 38 | + (layout.region("window").offset,), self.metadata.state_rows, self.metadata.starts, |
| 39 | + token_capacity=width, window_tokens=128, record_bytes=528) |
| 40 | + self.cache = self.commit.staging[0] |
| 41 | + self.observed = torch.empty_like(self.cache) |
| 42 | + self.writer = PreparedCompressedCacheWriter(self.values, self.cache, self.indices.window_slots, |
| 43 | + page_size=128 + width, kind="swa", session=session, name=f"window.{fused}", |
| 44 | + history=self.history if fused else None, |
| 45 | + history_rows=self.metadata.state_rows if fused else None, |
| 46 | + snapshot_tokens=128 if fused else 0) |
| 47 | + |
| 48 | + def __call__(self): |
| 49 | + self.indices() |
| 50 | + if not self.fused: |
| 51 | + gather_rows(self.history, self.metadata.state_rows, self.cache[:, :128 * 528]) |
| 52 | + self.writer(self.values) |
| 53 | + self.observed.copy_(self.cache) |
| 54 | + if self.mode == "verify": |
| 55 | + self.commit(self.counts) |
| 56 | + # Consumers and accepted commits must finish before private inputs are reused. |
| 57 | + self.values.fill_(37) |
| 58 | + self.cache.fill_(129) |
| 59 | + |
| 60 | + |
| 61 | +@pytest.mark.parametrize("requests", [1, 3]) |
| 62 | +@pytest.mark.parametrize("mode,width", [("verify", 8), ("draft", 7)]) |
| 63 | +@torch.no_grad() |
| 64 | +def test_compiled_native_snapshot_writer_preserves_ragged_state_and_lifetimes(requests, mode, width): |
| 65 | + device = torch.device("cuda:0") |
| 66 | + with PreparationSession(device=device, autotune=False, compile_workers=2) as session: |
| 67 | + cases = [SnapshotCase(requests, width, mode, session, fused=fused) for fused in (False, True)] |
| 68 | + compiled = [compile_forward(case) for case in cases] |
| 69 | + graphs = {} |
| 70 | + counts = [] |
| 71 | + for name, forward in zip(("separate", "fused"), compiled, strict=True): |
| 72 | + graph = torch.cuda.CUDAGraph(keep_graph=True) |
| 73 | + with session.capture(), torch.cuda.graph(graph): |
| 74 | + forward() |
| 75 | + graph.instantiate() |
| 76 | + graphs[name] = graph |
| 77 | + status, _, count = cuda.cuGraphGetNodes(cuda.CUgraph(graph.raw_cuda_graph())) |
| 78 | + assert status == cuda.CUresult.CUDA_SUCCESS |
| 79 | + counts.append(count) |
| 80 | + assert counts[0] - counts[1] == 1 |
| 81 | + bundle = PreparedGraphBundle(device=0, graphs=graphs, buffers={}, resources=(cases, compiled)) |
| 82 | + worker = bundle.start_worker() |
| 83 | + try: |
| 84 | + for step in range(2 * (width + 1)): |
| 85 | + initial = torch.randint(0, 256, cases[0].storage.backing.shape, dtype=torch.uint8, device=device) |
| 86 | + values = torch.randn_like(cases[0].values) * .25 |
| 87 | + values[0].zero_() |
| 88 | + values[-1].fill_(2**-20) |
| 89 | + lengths = [width if r == 0 else (step + r) % (width + 1) for r in range(requests)] |
| 90 | + selected = [(step + r) % (requests + 2) + 1 for r in range(requests)] |
| 91 | + starts = torch.tensor([127 + (step // (width + 1)) + r * 128 |
| 92 | + for r in range(requests)], device=device) |
| 93 | + length_tensor = torch.tensor(lengths, dtype=torch.int32, device=device) |
| 94 | + accepted = [min(step % (width + 1), length) for length in lengths] |
| 95 | + tokens = torch.zeros((requests, width), dtype=torch.int64, device=device) |
| 96 | + pages = torch.zeros((requests, 1), dtype=torch.int32, device=device) |
| 97 | + for case in cases: |
| 98 | + case.storage.backing.copy_(initial) |
| 99 | + case.values.copy_(values) |
| 100 | + case.cache.fill_(173) |
| 101 | + case.counts.copy_(torch.tensor(accepted, dtype=torch.int32, device=device)) |
| 102 | + case.metadata.set(starts, length_tensor, torch.tensor(selected, device=device), |
| 103 | + pages, tokens, torch.tensor([requests], dtype=torch.int32, device=device)) |
| 104 | + torch.cuda.synchronize() |
| 105 | + before = torch.cuda.memory_stats() |
| 106 | + for name in ("separate", "fused") if step % 2 else ("fused", "separate"): |
| 107 | + ticket = worker.submit(bundle.graph_indices[name]) |
| 108 | + completion = worker.poll(timeout_ms=120000) |
| 109 | + assert completion is not None and completion.ticket == ticket and completion.error is None |
| 110 | + after = torch.cuda.memory_stats() |
| 111 | + for key in ("allocation.all.allocated", "allocation.all.freed", |
| 112 | + "segment.all.allocated", "segment.all.freed"): |
| 113 | + assert before[key] == after[key] |
| 114 | + control, candidate = cases |
| 115 | + assert torch.equal(control.observed, candidate.observed) |
| 116 | + assert torch.equal(control.storage.backing, candidate.storage.backing) |
| 117 | + expected = initial.clone() |
| 118 | + if mode == "verify": |
| 119 | + region = candidate.storage.layout.region("window") |
| 120 | + for request, count in enumerate(accepted): |
| 121 | + for token in range(count): |
| 122 | + destination = region.offset + ((int(starts[request]) + token) % 128) * 528 |
| 123 | + source = (128 + token) * 528 |
| 124 | + expected[selected[request], destination:destination + 528].copy_( |
| 125 | + candidate.observed[request, source:source + 528]) |
| 126 | + assert torch.equal(candidate.storage.backing, expected) |
| 127 | + assert candidate.cache.eq(129).all() and candidate.values.eq(37).all() |
| 128 | + finally: |
| 129 | + worker.close() |
| 130 | + for graph in graphs.values(): |
| 131 | + graph.reset() |
0 commit comments