"""Choose the sparse implementation during warmup, without consulting the live block list.""" import statistics import torch _plans = {} def _plan_inputs(args): q, k, v, counts, indices, block_size, causal = args batch, rows, capacity = indices.shape blocks = (k.size(2) + block_size - 1) // block_size # Use a reproducible mix of occupancy and scattered blocks. Construct outside captured calls. row = torch.arange(batch * rows, device=q.device).view(batch, rows) slots = torch.arange(capacity, device=q.device) lengths = (row * 7 + capacity // 2) % capacity + 1 lengths = torch.where(row == 0, capacity, lengths) if rows > 1: lengths[:, -1] = 0 ids = (row[..., None] * 17 + slots * max(1, blocks // capacity)) % blocks plan_counts = torch.empty_like(counts).copy_(lengths) plan_indices = torch.empty_like(indices).copy_(torch.where(slots < lengths[..., None], ids, -1)) return q, k, v, plan_counts, plan_indices, block_size, causal def pick_backend(direct, flex, args): q, k, v, counts, indices, block_size, causal = args key = (q.device, q.dtype, block_size, causal, tuple((tuple(t.shape), t.stride()) for t in (q, k, v, counts, indices))) if key in _plans: return _plans[key] if torch.cuda.is_current_stream_capturing(): return False plan_inputs = _plan_inputs(args) graphs = [] for fn in (direct, flex): fn(*plan_inputs) graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): for _ in range(12): out = fn(*plan_inputs) graphs.append((graph, out)) samples = [[], []] for round_id in range(8): for i in (range(2) if round_id % 2 == 0 else (1, 0)): start, end = (torch.cuda.Event(enable_timing=True) for _ in range(2)) start.record() graphs[i][0].replay() end.record() end.synchronize() if round_id >= 2: samples[i].append(start.elapsed_time(end)) # Retain FlexAttention on a timing tie. _plans[key] = statistics.median(samples[0]) < 0.98 * statistics.median(samples[1]) return _plans[key]