diff --git a/backends/cuda/passes/lower_offgraph_kv.py b/backends/cuda/passes/lower_offgraph_kv.py index 15c994a9708..b12f4ea5c34 100644 --- a/backends/cuda/passes/lower_offgraph_kv.py +++ b/backends/cuda/passes/lower_offgraph_kv.py @@ -112,6 +112,14 @@ def parse_offgraph_kv_manifest(value: bytes) -> dict[str, Any]: # noqa: C901 raise ValueError("off-graph context_window must be a bool") if manifest["context_window"] and manifest["causal"]: raise ValueError("off-graph context_window requires non-causal attention") + if not isinstance(manifest.setdefault("symmetric_window", False), bool): + raise ValueError("off-graph symmetric_window must be a bool") + if manifest["symmetric_window"] and ( + manifest["causal"] or manifest["context_window"] + ): + raise ValueError( + "off-graph symmetric_window requires non-causal per-query attention" + ) if layout == "cell": # A cell step packs tokens of several sequences into the shared pool, # so the pool bounds its width, not one sequence's capacity. @@ -297,6 +305,7 @@ def batched_sequence_step( causal: bool, out_dtype: torch.dtype | None = None, context_window: bool = False, + symmetric_window: bool = False, ) -> torch.Tensor: """Write this step's K/V into each sequence's column, then attend. @@ -310,7 +319,8 @@ def batched_sequence_step( ``seq_cols`` is declared at the widest step; writes use the first K/V-width entries. ``k``/``v`` are BHSD; the storage is BSHD. ``context_window`` gives every draft block query the same retained context - before the block; ordinary attention uses each query's own window. + before the block; ``symmetric_window`` uses strict per-query distance as in + DFlash. Ordinary attention uses each query's own past-window bound. """ position = position.reshape(-1) slots = (position % rows) * columns + seq_cols[: k.shape[2]] @@ -327,6 +337,7 @@ def batched_sequence_step( window, rows if ring else 0, context_window=context_window, + symmetric_window=symmetric_window, ) if out_dtype is not None and out.dtype != out_dtype: out = out.to(out_dtype) @@ -342,6 +353,7 @@ def _batched_sequence_step_fn( causal: bool, out_dtype, context_window: bool = False, + symmetric_window: bool = False, ): def fn(q, k, v, position, k_storage, v_storage, seq_cols, seq_info): return batched_sequence_step( @@ -361,6 +373,7 @@ def fn(q, k, v, position, k_storage, v_storage, seq_cols, seq_info): causal, out_dtype, context_window, + symmetric_window, ) return fn @@ -753,6 +766,7 @@ def _lower_batched_sequence( self._manifest["causal"], out_dtype, self._manifest.get("context_window", False), + self._manifest.get("symmetric_window", False), ) return fn, call_args, example_args diff --git a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp index 8d753579de0..5e4881224f7 100644 --- a/backends/cuda/runtime/test/test_cuda_kv_cache.cpp +++ b/backends/cuda/runtime/test/test_cuda_kv_cache.cpp @@ -1930,10 +1930,10 @@ TEST_F(CudaCellCacheTest, DFlashUploadsKVWideCellsAndQueryWideOwnerMasks) { EXPECT_EQ( read_mask(fake.bound["mask2"].data, 4, 8), Mask( - {{0, 1, 1, 1, 1, 0, 0, 0}, - {0, 1, 1, 1, 1, 0, 0, 0}, + {{0, 0, 1, 1, 1, 0, 0, 0}, + {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 1, 1}, - {0, 0, 0, 0, 0, 1, 1, 1}})); + {0, 0, 0, 0, 0, 0, 1, 1}})); EXPECT_EQ(control->pos(b), 3); EXPECT_EQ(control->pos(a), 1); // Block removal leaves holes; the next owner order is reversed. @@ -1950,6 +1950,13 @@ TEST_F(CudaCellCacheTest, DFlashUploadsKVWideCellsAndQueryWideOwnerMasks) { {0, 0, 0, 1, 1, 1, 0, 0}, {1, 1, 1, 0, 0, 0, 1, 1}, {1, 1, 1, 0, 0, 0, 1, 1}})); + EXPECT_EQ( + read_mask(fake.bound["mask2"].data, 4, 8), + Mask( + {{0, 0, 0, 1, 1, 1, 0, 0}, + {0, 0, 0, 1, 1, 0, 0, 0}, + {0, 0, 1, 0, 0, 0, 1, 1}, + {0, 0, 0, 0, 0, 0, 1, 1}})); EXPECT_EQ(handle.cuda_graph_state.phase, cu::CudaGraphPhase::Replay); EXPECT_EQ(fake.bound["cells"].data, cells); EXPECT_EQ(control->pos(b), 3); diff --git a/backends/cuda/tests/targets.bzl b/backends/cuda/tests/targets.bzl index 09daa0afd10..98a7cb1142c 100644 --- a/backends/cuda/tests/targets.bzl +++ b/backends/cuda/tests/targets.bzl @@ -550,6 +550,7 @@ def define_common_targets(is_fbcode = False): "//executorch/exir:lib", "//executorch/exir/backend:compile_spec_schema", "//executorch/exir/dialects:lib", + "//executorch/examples/models/muse-glimmer/model:dflash_model", # The oracle is the neutral op itself, not a reference rebuilt here. "//executorch/extension/llm/cache:cache", ], diff --git a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py index 257e81df5e7..f9e0cc65c7e 100644 --- a/backends/cuda/tests/test_offgraph_kv_batched_sequence.py +++ b/backends/cuda/tests/test_offgraph_kv_batched_sequence.py @@ -18,6 +18,7 @@ import unittest import torch +import torch.nn.functional as F from executorch.backends.cuda.passes.lower_offgraph_kv import ( batched_sequence_step, @@ -29,6 +30,10 @@ parse_offgraph_kv_manifest, ring_physical_capacity, ) + +from executorch.examples.models.muse_glimmer.model.dflash_model import ( + build_dflash_swa_mask, +) from executorch.exir import EdgeCompileConfig, to_edge from executorch.exir.dialects._ops import ops as exir_ops from executorch.extension.llm.cache.reference_cache import ( @@ -261,6 +266,37 @@ def forward(self, q, k, v, position): return flat + ring +class _DraftRing(torch.nn.Module): + def forward(self, q, k, v, position): + return torch.ops.kvcache.update_and_attend( + q, k, v, position, 0, SCALE, torch.bfloat16 + ) + + +def _draft_model_reference(q, storage, segments, window, rows): + out = torch.zeros_like(q, dtype=torch.float32) + for start, block, col, end in segments: + context = end - block + slots = torch.arange(window, device=q.device) + context_positions = slots + ((context - 1 - slots) // window) * window + positions = torch.cat( + (context_positions, torch.arange(context, end, device=q.device)) + ) + values = ( + storage[positions.clamp_min(0) % rows, col].transpose(0, 1)[None].float() + ) + mask = build_dflash_swa_mask(context, block, window, window).to(q.device) + out[:, :, start : start + block] = F.scaled_dot_product_attention( + q[:, :, start : start + block].float(), + torch.zeros_like(values), + values, + attn_mask=mask, + scale=SCALE, + enable_gqa=True, + ) + return out + + @unittest.skipUnless(torch.cuda.is_available(), "CUDA required") class LowerBatchedSequencePassTest(unittest.TestCase): CAPACITY = 32 @@ -307,6 +343,7 @@ def test_manifest_is_validated(self) -> None: self.assertEqual(parsed["layout"], "batched-sequence") self.assertTrue(parsed["causal"]) self.assertFalse(parsed["context_window"]) + self.assertFalse(parsed["symmetric_window"]) self.assertFalse( parse_offgraph_kv_manifest(self.manifest(causal=False))["causal"] ) @@ -317,6 +354,9 @@ def test_manifest_is_validated(self) -> None: {"causal": 1}, {"context_window": 1}, {"context_window": True}, + {"symmetric_window": 1}, + {"symmetric_window": True}, + {"causal": False, "context_window": True, "symmetric_window": True}, {"max_write": self.CAPACITY + 1}, ): with self.assertRaises(ValueError): @@ -400,6 +440,91 @@ def test_non_causal_context_window_reaches_sdpa_varlen(self) -> None: ) self.assertTrue(flag) + def _lowered_draft_ring(self, block, window): + writes = 3 + 2 * block + q, k, v, position = _inputs(0, writes) + q = q[:, :, : 2 * block].contiguous() + program = torch.export.export( + _DraftRing(), (q, k, v, position.reshape(-1, 1)), strict=False + ) + edge = to_edge( + program, compile_config=EdgeCompileConfig(_check_ir_validity=False) + ).exported_program() + manifest = self.manifest( + causal=False, + symmetric_window=True, + max_write=64, + maximum_capacity=128, + layers=[{"layer_id": 0, "policy": "ring", "window": window}], + ) + lowered = LowerOffGraphKVPass(parse_offgraph_kv_manifest(manifest))(edge) + runtime = {} + for name, value in list(lowered.constants.items()): + if name.startswith(OFFGRAPH_KV_FQN_PREFIX): + runtime[name] = torch.zeros_like(value, device="cuda") + lowered.constants[name] = runtime[name] + calls = [ + n + for n in lowered.graph_module.graph.nodes + if n.target == torch.ops.triton.sdpa_varlen.default + ] + self.assertEqual(len(calls), 1) + call = calls[0] + self.assertTrue( + call.kwargs.get( + "symmetric_window", call.args[10] if len(call.args) > 10 else False + ) + ) + return lowered.module(), runtime, q + + def _draft_runtime_inputs(self, q, runtime, values, starts, block): + rows = values.shape[0] + slots = torch.arange(rows, device="cuda") + positions, segments, columns = [], [], [] + for col, (start, fresh) in enumerate(zip(starts, (2, 1))): + context = start + fresh + retained = slots + rows * ((start - 1 - slots) // rows) + values[:, col] = retained[:, None, None] / 16 + positions.extend(range(start, context + block)) + columns.extend([col] * (fresh + block)) + segments.append((col * block, block, col, context + block)) + position = torch.tensor(positions, device="cuda") + k = torch.zeros( + 1, N_KV_HEADS, len(positions), HEAD_DIM, device="cuda", dtype=q.dtype + ) + v = (position[None, None, :, None] / 16).expand_as(k).to(q.dtype).contiguous() + runtime[OFFGRAPH_KV_SEQ_COLS_FQN][: len(columns)].copy_(torch.tensor(columns)) + runtime[OFFGRAPH_KV_SEQ_INFO_FQN].copy_( + torch.tensor( + segments + [(0, 0, 0, 0)] * (self.MAX_SEGMENTS - 2), dtype=torch.int32 + ) + ) + return k, v, position, segments + + def test_lowered_dflash_ring_matches_model_across_wrap(self): + window = 3 + for block in (2, 8): + module, runtime, q = self._lowered_draft_ring(block, window) + rows = ring_physical_capacity(window, 64) + values = runtime[f"{OFFGRAPH_KV_FQN_PREFIX}layer_0_v"].view( + rows, self.MAX_SEQS + 1, N_KV_HEADS, HEAD_DIM + ) + for starts in ((0, 0), (20, 13), (70, 90)): + k, v, position, segments = self._draft_runtime_inputs( + q, runtime, values, starts, block + ) + got = module(q, k, v, position.reshape(-1, 1)) + want = _draft_model_reference(q, values, segments, window, rows) + torch.testing.assert_close(got.float(), want, atol=2e-2, rtol=2e-2) + for col, (start, fresh) in enumerate(zip(starts, (2, 1))): + write_positions = torch.arange( + start, start + fresh + block, device="cuda" + ) + torch.testing.assert_close( + values[write_positions % rows, col, 0, 0], + (write_positions / 16).to(q.dtype), + ) + def test_step_width_pass_accepts_the_packed_layout(self) -> None: with self.assertRaises(ValueError): CheckOffGraphKVStepWidthPass(b"0:0", layout="paged") diff --git a/backends/cuda/tests/test_sdpa_varlen.py b/backends/cuda/tests/test_sdpa_varlen.py index 297f9dca809..365b74d109f 100644 --- a/backends/cuda/tests/test_sdpa_varlen.py +++ b/backends/cuda/tests/test_sdpa_varlen.py @@ -11,9 +11,14 @@ import torch.nn.functional as F from executorch.backends.cuda.triton.kernels.sdpa_varlen import sdpa_varlen +from executorch.examples.models.muse_glimmer.model.dflash_model import ( + build_dflash_swa_mask, +) -def _reference(q, k_store, v_store, segments, scale, causal, window, ring): +def _reference( + q, k_store, v_store, segments, scale, causal, window, ring, symmetric=False +): """Per-segment attention over logical positions, in float32.""" _, hq, t_total, d = q.shape hkv = k_store.shape[2] @@ -36,17 +41,15 @@ def _reference(q, k_store, v_store, segments, scale, causal, window, ring): visible &= positions[None, :] <= query_pos[:, None] if window: visible &= positions[None, :] > query_pos[:, None] - window + if symmetric: + visible &= positions[None, :] < query_pos[:, None] + window scores = scores.masked_fill(~visible, float("-inf")) out[0, :, q_start : q_start + q_len] = torch.softmax(scores, -1) @ v return out def _dflash_reference(q, k_store, v_store, segments, scale, window, ring): - """Use the original drafter's context-ring + whole-block mask.""" - from executorch.examples.models.muse_glimmer.model.dflash_model import ( - build_dflash_swa_mask, - ) - + """Use the drafter's per-query mask over retained context and draft K/V.""" out = torch.zeros_like(q, dtype=torch.float32) groups = q.shape[1] // k_store.shape[2] for start, block, col, end in segments: @@ -72,7 +75,9 @@ def _dflash_reference(q, k_store, v_store, segments, scale, window, ring): return out -def _dflash_inputs(contexts, block, window, ring, *, hq=8, hkv=2, d=64): +def _dflash_inputs( + contexts, block, window, ring, *, hq=8, hkv=2, d=64, visible_values=False +): rows = ring or max(contexts) + block q = torch.zeros( 1, hq, len(contexts) * block, d, device="cuda", dtype=torch.bfloat16 @@ -88,6 +93,22 @@ def _dflash_inputs(contexts, block, window, ring, *, hq=8, hkv=2, d=64): # per-query windows omit this key from every draft block query. k[row, col, :, 0] = 100 v[row, col] = 1 + if visible_values: + values = ( + 2 * (col + 1) + + context / window + + torch.arange(hkv, device=q.device)[:, None] + + torch.arange(d, device=q.device)[None, :] / d + ) + # The first key is visible only to query zero; the draft key stays + # visible to every query. Keep the excluded boundary sentinel above. + for position, contribution in ( + (context - window + 1, values + 8), + (context + block - 1, values), + ): + row = position % ring if ring else position + k[row, col, :, 0] = 96 + v[row, col] = contribution segments.append((col * block, block, col, context + block)) padded = segments + [(0, 0, 0, 0)] * (4 - len(segments)) info = torch.tensor(padded, device="cuda", dtype=torch.int32) @@ -96,6 +117,29 @@ def _dflash_inputs(contexts, block, window, ring, *, hq=8, hkv=2, d=64): @unittest.skipUnless(torch.cuda.is_available(), "CUDA required") class SdpaVarlenTest(unittest.TestCase): + def _nonzero_dflash_reference(self, q, k, v, segments, scale, window, ring): + want = _dflash_reference(q, k, v, segments, scale, window, ring) + positions = _reference( + q, k, v, segments, scale, False, window, ring, symmetric=True + ) + torch.testing.assert_close(want, positions, atol=1e-5, rtol=1e-5) + self.assertTrue(torch.isfinite(want).all()) + self.assertGreater(want.abs().min().item(), 0.5) + groups = q.shape[1] // k.shape[2] + for start, block, _, _ in segments: + self.assertGreater( + (want[:, :, start] - want[:, :, start + 1]).abs().min().item(), 1 + ) + first_group = want[:, 0, start : start + block] + next_group = want[:, groups, start : start + block] + self.assertGreater((first_group - next_group).abs().min().item(), 0.5) + for previous, current in zip(segments, segments[1:]): + self.assertGreater( + (want[:, :, previous[0]] - want[:, :, current[0]]).abs().min().item(), + 0.5, + ) + return want + def _run( self, segments, @@ -160,59 +204,89 @@ def test_non_causal_draft_block(self): def test_dflash_context_window_matches_original_mask(self): window = 2048 - for block, ring in itertools.product((2, 16), (0, 2175)): - q, k, v, info, segments = _dflash_inputs((3000, 7100), block, window, ring) + for block, ring, visible_values in itertools.product( + (2, 16), (0, 2175), (False, True) + ): + q, k, v, info, segments = _dflash_inputs( + (3000, 7100), block, window, ring, visible_values=visible_values + ) got = sdpa_varlen( - q, k, v, info, 0.125, False, window, ring, context_window=True + q, k, v, info, 0.125, False, window, ring, symmetric_window=True ) - want = _dflash_reference(q, k, v, segments, 0.125, window, ring) + if visible_values: + want = self._nonzero_dflash_reference( + q, k, v, segments, 0.125, window, ring + ) + else: + want = _dflash_reference(q, k, v, segments, 0.125, window, ring) + self.assertTrue((want == 0).all()) torch.testing.assert_close(got.float(), want, atol=2e-2, rtol=2e-2) ordinary = sdpa_varlen(q, k, v, info, 0.125, False, window, ring) ordinary_want = _reference(q, k, v, segments, 0.125, False, window, ring) torch.testing.assert_close( ordinary.float(), ordinary_want, atol=2e-2, rtol=2e-2 ) - self.assertGreater((got.float() - ordinary.float()).abs().max().item(), 0.9) + shared = sdpa_varlen( + q, k, v, info, 0.125, False, window, ring, context_window=True + ) + self.assertGreater((shared.float() - got.float()).abs().max().item(), 0.9) def test_dflash_context_window_muse_head_geometry(self): window = 2048 for block in (2, 16): ring = window + block q, k, v, info, segments = _dflash_inputs( - (3000, 7100), block, window, ring, hq=32, hkv=8, d=128 + (3000, 7100), + block, + window, + ring, + hq=32, + hkv=8, + d=128, + visible_values=True, ) scale = 128**-0.5 got = sdpa_varlen( - q, k, v, info, scale, False, window, ring, context_window=True + q, k, v, info, scale, False, window, ring, symmetric_window=True + ) + want = self._nonzero_dflash_reference( + q, k, v, segments, scale, window, ring ) - want = _dflash_reference(q, k, v, segments, scale, window, ring) torch.testing.assert_close(got.float(), want, atol=2e-2, rtol=2e-2) def test_dflash_context_window_graph_replay(self): window, ring, block = 2048, 2175, 16 - q, k, v, info, _ = _dflash_inputs((4096, 6000), block, window, ring) - sdpa_varlen(q, k, v, info, 0.125, False, window, ring, context_window=True) + q, k, v, info, _ = _dflash_inputs( + (4096, 6000), block, window, ring, visible_values=True + ) + sdpa_varlen(q, k, v, info, 0.125, False, window, ring, symmetric_window=True) graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): out = sdpa_varlen( - q, k, v, info, 0.125, False, window, ring, context_window=True + q, k, v, info, 0.125, False, window, ring, symmetric_window=True ) + previous_want = None for contexts in ((4096, 6000), (8192, 2500)): _, new_k, new_v, new_info, segments = _dflash_inputs( - contexts, block, window, ring + contexts, block, window, ring, visible_values=True ) k.copy_(new_k) v.copy_(new_v) info.copy_(new_info) graph.replay() - want = _dflash_reference(q, k, v, segments, 0.125, window, ring) + want = self._nonzero_dflash_reference( + q, k, v, segments, 0.125, window, ring + ) + if previous_want is not None: + self.assertGreater((want - previous_want).abs().min().item(), 0.5) torch.testing.assert_close(out.float(), want, atol=2e-2, rtol=2e-2) + previous_want = want.clone() def test_dynamic_dflash_context_window(self): window, ring, block = 2048, 2175, 16 compiled = torch.compile( lambda q, k, v, info: sdpa_varlen( - q, k, v, info, 0.125, False, window, ring, context_window=True + q, k, v, info, 0.125, False, window, ring, symmetric_window=True ), fullgraph=True, dynamic=True, @@ -222,13 +296,95 @@ def test_dynamic_dflash_context_window(self): before = frames["unique_graphs"] for owners in (2, 3, 4): q, k, v, info, segments = _dflash_inputs( - (3000, 5000, 7000, 9000)[:owners], block, window, ring + (3000, 5000, 7000, 9000)[:owners], + block, + window, + ring, + visible_values=True, ) got = compiled(q, k, v, info) - want = _dflash_reference(q, k, v, segments, 0.125, window, ring) + want = self._nonzero_dflash_reference( + q, k, v, segments, 0.125, window, ring + ) torch.testing.assert_close(got.float(), want, atol=2e-2, rtol=2e-2) self.assertEqual(frames["unique_graphs"] - before, 1) + def test_dflash_symmetric_windows_match_position_and_model_oracles(self): + for window, block in itertools.product((1, 3, 8), (1, 2, 4, 16)): + for ring in (0, window + block - 1, 512): + with self.subTest(window=window, block=block, ring=ring): + q, k, v, info, segments = _dflash_inputs( + (0, window - 1, window + 1, 3 * window), block, window, ring + ) + k.zero_() + slots = torch.arange(k.shape[0], device=q.device) + for _, _, col, end in segments: + positions = ( + slots + ring * ((end - 1 - slots) // ring) + if ring + else slots + ) + v[:, col] = positions[:, None, None] / 16 + got = sdpa_varlen( + q, k, v, info, 0.125, False, window, ring, symmetric_window=True + ) + want = _reference( + q, k, v, segments, 0.125, False, window, ring, symmetric=True + ) + model = _dflash_reference(q, k, v, segments, 0.125, window, ring) + torch.testing.assert_close(model, want, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(got.float(), want, atol=2e-2, rtol=2e-2) + + def test_dflash_strict_right_boundary(self): + window, block, context = 3, 8, 20 + for ring in (0, window + block - 1): + q, k, v, info, segments = _dflash_inputs((context,), block, window, ring) + k.zero_() + v.zero_() + row = (context + window) % ring if ring else context + window + k[row, 0, :, 0] = 100 + v[row, 0] = 1 + got = sdpa_varlen( + q, k, v, info, 0.125, False, window, ring, symmetric_window=True + ) + want = _dflash_reference(q, k, v, segments, 0.125, window, ring) + torch.testing.assert_close(got.float(), want, atol=2e-2, rtol=2e-2) + self.assertTrue((got[:, :, 0] == 0).all()) + self.assertTrue((got[:, :, 1:6] > 0.9).all()) + self.assertTrue((got[:, :, 6:] == 0).all()) + ordinary = sdpa_varlen(q, k, v, info, 0.125, False, window, ring) + self.assertTrue((ordinary[:, :, 0] > 0.9).all()) + + def test_dflash_zero_window_remains_full_attention(self): + self._run([(0, 2, 0, 80)], causal=False) + q, k, v, info, segments = _dflash_inputs((20,), 2, 8, 0) + got = sdpa_varlen(q, k, v, info, 0.125, False, symmetric_window=True) + want = _reference(q, k, v, segments, 0.125, False, 0, 0) + torch.testing.assert_close(got.float(), want, atol=2e-2, rtol=2e-2) + + def test_dflash_graph_replay_reads_new_query_lengths(self): + window, ring = 3, 512 + q, k, v, info, _ = _dflash_inputs((20,), 16, window, ring) + k.zero_() + v[:, 0] = torch.arange(ring, device=q.device)[:, None, None] / 32 + sdpa_varlen(q, k, v, info, 0.125, False, window, ring, symmetric_window=True) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + out = sdpa_varlen( + q, k, v, info, 0.125, False, window, ring, symmetric_window=True + ) + for length, end in ((1, 1), (2, 513), (8, 1030), (16, 900)): + segments = [(0, length, 0, end)] + info.copy_(torch.tensor(segments + [(0, 0, 0, 0)] * 3, dtype=torch.int32)) + graph.replay() + want = _reference( + q, k, v, segments, 0.125, False, window, ring, symmetric=True + ) + model = _dflash_reference(q, k, v, segments, 0.125, window, ring) + torch.testing.assert_close(model, want, atol=1e-6, rtol=1e-6) + torch.testing.assert_close(out.float(), want, atol=2e-2, rtol=2e-2) + self.assertTrue((out[:, :, length:] == 0).all()) + def test_head_layouts(self): for hq, hkv, d in itertools.product((4, 16), (1, 4), (64, 128)): if hq % hkv: @@ -423,6 +579,19 @@ def test_rejects_unsupported_layouts(self): v = torch.randn_like(k) with self.assertRaisesRegex(ValueError, "context_window requires non-causal"): sdpa_varlen(q, k, v, info, 0.125, context_window=True) + with self.assertRaisesRegex(ValueError, "symmetric_window requires"): + sdpa_varlen(q, k, v, info, 0.125, symmetric_window=True) + with self.assertRaisesRegex(ValueError, "symmetric_window requires"): + sdpa_varlen( + q, + k, + v, + info, + 0.125, + False, + context_window=True, + symmetric_window=True, + ) if __name__ == "__main__": diff --git a/backends/cuda/triton/kernels/sdpa_varlen.py b/backends/cuda/triton/kernels/sdpa_varlen.py index bc3ecea5698..40bc1c2ab2d 100644 --- a/backends/cuda/triton/kernels/sdpa_varlen.py +++ b/backends/cuda/triton/kernels/sdpa_varlen.py @@ -68,6 +68,7 @@ def _sdpa_varlen_kernel( # noqa: C901 NUM_SPLITS: tl.constexpr, IS_CAUSAL: tl.constexpr, CONTEXT_WINDOW: tl.constexpr, + SYMMETRIC_WINDOW: tl.constexpr, WINDOW: tl.constexpr, RING: tl.constexpr, BLOCK_M: tl.constexpr, @@ -113,6 +114,8 @@ def _sdpa_varlen_kernel( # noqa: C901 hi = kv_end if IS_CAUSAL: hi = kv_end - q_len + r_last + 1 + elif SYMMETRIC_WINDOW and WINDOW > 0: + hi = tl.minimum(hi, kv_end - q_len + r_last + WINDOW) lo = 0 if WINDOW > 0: if CONTEXT_WINDOW: @@ -155,6 +158,8 @@ def _sdpa_varlen_kernel( # noqa: C901 visible = visible & (kv_pos[None, :] >= kv_end - q_len - WINDOW) else: visible = visible & (kv_pos[None, :] > pos[:, None] - WINDOW) + if SYMMETRIC_WINDOW: + visible = visible & (kv_pos[None, :] < pos[:, None] + WINDOW) qk = tl.where(visible, qk, -float("inf")) m_ij = tl.maximum(m_i, tl.max(qk, axis=1)) @@ -188,7 +193,7 @@ def _sdpa_varlen_kernel( # noqa: C901 @triton.jit -def _sdpa_varlen_decode_kernel( +def _sdpa_varlen_decode_kernel( # noqa: C901 Q_ptr, K_ptr, V_ptr, @@ -215,6 +220,7 @@ def _sdpa_varlen_decode_kernel( NUM_SPLITS: tl.constexpr, IS_CAUSAL: tl.constexpr, CONTEXT_WINDOW: tl.constexpr, + SYMMETRIC_WINDOW: tl.constexpr, WINDOW: tl.constexpr, RING: tl.constexpr, BLOCK_N: tl.constexpr, @@ -259,6 +265,8 @@ def _sdpa_varlen_decode_kernel( hi = tl.minimum(kv_end, RING) else: hi = pos + 1 if IS_CAUSAL else kv_end + if SYMMETRIC_WINDOW and WINDOW > 0: + hi = tl.minimum(hi, pos + WINDOW) lo = 0 if WINDOW > 0: if CONTEXT_WINDOW: @@ -299,6 +307,8 @@ def _sdpa_varlen_decode_kernel( visible &= kv_pos[None, :] >= kv_end - q_len - WINDOW else: visible &= kv_pos[None, :] > pos - WINDOW + if SYMMETRIC_WINDOW: + visible &= kv_pos[None, :] < pos + WINDOW qk = tl.where(visible, qk, -float("inf")) m_ij = tl.maximum(m_i, tl.max(qk, axis=1)) @@ -386,6 +396,7 @@ def sdpa_varlen( # noqa: C901 ring: int = 0, rows_available: int = -1, context_window: bool = False, + symmetric_window: bool = False, ) -> torch.Tensor: """Attend each segment of ``query`` to its own sequence's K/V. @@ -407,6 +418,10 @@ def sdpa_varlen( # noqa: C901 context_window: non-causal draft queries share the last ``window`` context positions before ``kv_end - q_len`` and see the entire query block. Ordinary attention keeps its per-query window. + symmetric_window: non-causal per-query visibility with + ``abs(query_position - key_position) < window``, as in DFlash. + Mutually exclusive with ``context_window``; zero window is full + attention in either mode. Returns: ``[1, H_q, T, D]``; rows no segment covers are zero. """ @@ -444,6 +459,8 @@ def sdpa_varlen( # noqa: C901 raise ValueError("seq_info must be contiguous on the query device") if context_window and is_causal: raise ValueError("context_window requires non-causal attention") + if symmetric_window and (is_causal or context_window): + raise ValueError("symmetric_window requires non-causal per-query attention") groups = Hq // Hkv available = rows if rows_available < 0 else min(rows_available, rows) # Branching on a symbolic T would guard (and AOTI then pin) the exported @@ -493,6 +510,7 @@ def sdpa_varlen( # noqa: C901 NUM_SPLITS=splits, IS_CAUSAL=is_causal, CONTEXT_WINDOW=context_window, + SYMMETRIC_WINDOW=symmetric_window, WINDOW=window, RING=ring, BLOCK_N=128, @@ -531,6 +549,7 @@ def sdpa_varlen( # noqa: C901 NUM_SPLITS=splits, IS_CAUSAL=is_causal, CONTEXT_WINDOW=context_window, + SYMMETRIC_WINDOW=symmetric_window, WINDOW=window, RING=ring, BLOCK_M=block_m, @@ -569,5 +588,6 @@ def _sdpa_varlen_fake( ring=0, rows_available=-1, context_window=False, + symmetric_window=False, ): return torch.empty_like(query) diff --git a/examples/models/muse-glimmer/export/export_dflash.py b/examples/models/muse-glimmer/export/export_dflash.py index 4b136775e11..6ac5d8decef 100644 --- a/examples/models/muse-glimmer/export/export_dflash.py +++ b/examples/models/muse-glimmer/export/export_dflash.py @@ -339,7 +339,8 @@ def prepare_cuda_packed_draft( """Trace the packed draft and publish its independent cache geometry. On the sequence layout the draft keeps one private history per resident - session, and each owner's block attends all of it and the whole block. + session. Sliding layers use a symmetric per-query window; flat layers see + all of the context and draft block. """ validate_dflash_export_options("cuda", True, draft_model.config) @@ -393,7 +394,7 @@ def prepare_cuda_packed_draft( single_manifest = enable_dflash_offgraph_kv_cache(draft_model, max_write) manifest = ( batched_sequence_manifest( - single_manifest, max_kv_seqs, causal=False, context_window=True + single_manifest, max_kv_seqs, causal=False, symmetric_window=True ) if sequence_layout else cell_manifest(single_manifest, max_cells) diff --git a/examples/models/muse-glimmer/export/export_solo.py b/examples/models/muse-glimmer/export/export_solo.py index 064292d8ea1..ea248c48148 100644 --- a/examples/models/muse-glimmer/export/export_solo.py +++ b/examples/models/muse-glimmer/export/export_solo.py @@ -338,6 +338,7 @@ def batched_sequence_manifest( max_seqs: int, causal: bool = True, context_window: bool = False, + symmetric_window: bool = False, ) -> str: """The batched-sequence lowering manifest: one column per sequence.""" from executorch.backends.cuda.passes.lower_offgraph_kv import ( @@ -351,6 +352,8 @@ def batched_sequence_manifest( manifest["causal"] = causal if context_window: manifest["context_window"] = True + if symmetric_window: + manifest["symmetric_window"] = True return json.dumps(manifest, sort_keys=True, separators=(",", ":")) diff --git a/extension/llm/cache/cell_cache.cpp b/extension/llm/cache/cell_cache.cpp index 5190e2ac224..2148718e637 100644 --- a/extension/llm/cache/cell_cache.cpp +++ b/extension/llm/cache/cell_cache.cpp @@ -343,19 +343,15 @@ std::vector CellCache::build_mask(int window) const { for (int i = 0; i < length; ++i) { const uint64_t tok_bit = bit(step_seq_ids_[i]); const int32_t tok_pos = step_pos_[i]; - // Draft history is anchored at context end, shared by all block queries. - const int32_t context_end = - info_[step_seq_ids_[i]].max_pos + 1 - dflash_block_size_.value_or(0); - const int32_t oldest = window > 0 - ? (dflash_block_size_ ? context_end - window : tok_pos - window + 1) - : 0; + const int32_t oldest = window > 0 ? tok_pos - window + 1 : 0; uint8_t* row = bits.data() + static_cast(i) * used_end_; for (int j = 0; j < used_end_; ++j) { row[j] = static_cast( pos_[j] >= 0 && // occupied: a freed cell holds nothing (owners_[j] & tok_bit) && // one of this query's sequences - (dflash_block_size_ || pos_[j] <= tok_pos) && // full draft block - pos_[j] >= oldest); // within the window + (dflash_block_size_ || pos_[j] <= tok_pos) && pos_[j] >= oldest && + (!dflash_block_size_ || window <= 0 || + static_cast(pos_[j]) - tok_pos < window)); } } return bits; diff --git a/extension/llm/cache/test/BUCK b/extension/llm/cache/test/BUCK new file mode 100644 index 00000000000..a63bddbcecd --- /dev/null +++ b/extension/llm/cache/test/BUCK @@ -0,0 +1,6 @@ +load("@fbsource//tools/build_defs:fbsource_utils.bzl", "is_fbcode") +load(":targets.bzl", "define_common_targets") + +oncall("executorch") + +define_common_targets(is_fbcode = is_fbcode()) diff --git a/extension/llm/cache/test/cache_test.cpp b/extension/llm/cache/test/cache_test.cpp index 8d51c4f9359..489a2f18777 100644 --- a/extension/llm/cache/test/cache_test.cpp +++ b/extension/llm/cache/test/cache_test.cpp @@ -874,7 +874,7 @@ TEST_F(CacheTest, KvSharedLayerReservesIdempotently) { EXPECT_EQ(c.place(0, {7, 8, 9}), nullptr); // different tokens, never declared } -TEST_F(CacheTest, DFlashCellRowsUseOwnerOrderAndContextAnchoredWindow) { +TEST_F(CacheTest, DFlashCellRowsUseOwnerOrderAndPerQueryWindow) { CacheGeometry geometry{{flat_layer(), ring_layer(2), ring_layer(2)}}; geometry.dflash_block_size = 2; CellCache cache(geometry, config(32)); @@ -892,14 +892,52 @@ TEST_F(CacheTest, DFlashCellRowsUseOwnerOrderAndContextAnchoredWindow) { EXPECT_EQ(row(*flat, 3), "11111..."); EXPECT_EQ(row(*flat, 4), "11111..."); EXPECT_EQ(row(*flat, 6), ".....111"); - // b's context ends at 3: retain positions 1,2 and the full block 3,4. - EXPECT_EQ(row(*windowed, 3), ".1111..."); - EXPECT_EQ(row(*windowed, 4), ".1111..."); + // Strict distance < 2: the oldest context key is outside every query window. + EXPECT_EQ(row(*windowed, 3), "..111..."); + EXPECT_EQ(row(*windowed, 4), "...11..."); EXPECT_EQ(row(*windowed, 6), ".....111"); + EXPECT_EQ(row(*windowed, 7), "......11"); EXPECT_EQ(cache.place_step(2, args.positions.data(), 8), windowed); EXPECT_EQ(cache.free_cells(), 24); } +// This test exercises the experimental cell-cache API by design. +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif +TEST_F(CacheTest, DFlashCellStrictWindowMatchesAbsolutePositions) { + for (const int window : {1, 3, 8}) { + for (const int block : {1, 4, 16}) { + CacheGeometry geometry{{ring_layer(window)}}; + geometry.dflash_block_size = block; + CellCache cache(geometry, config(128)); + const int32_t a = *cache.seq_new(), b = *cache.seq_new(); + const auto args = + flatten_step({{b, 0, 3 * window + block}, {a, 0, block}}); + ASSERT_TRUE(cache.declare_step(args.seq_ids)); + const auto* step = cache.place_step( + 0, args.positions.data(), static_cast(args.positions.size())); + ASSERT_NE(step, nullptr); + for (const int query : step->query_rows) { + std::string expected(step->read_len, '.'); + for (size_t key = 0; key < args.positions.size(); ++key) { + const int delta = args.positions[query] - args.positions[key]; + if (args.seq_ids[query] == args.seq_ids[key] && delta > -window && + delta < window) { + expected[step->cells[key]] = '1'; + } + } + EXPECT_EQ(row(*step, query), expected) + << "window=" << window << " block=" << block << " query=" << query; + } + } + } +} +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + TEST_F(CacheTest, DFlashCellRejectsMalformedGroupingWithoutPlacement) { CacheGeometry geometry{{flat_layer()}}; geometry.dflash_block_size = 2; diff --git a/extension/llm/cache/test/targets.bzl b/extension/llm/cache/test/targets.bzl new file mode 100644 index 00000000000..7aabe8a52e5 --- /dev/null +++ b/extension/llm/cache/test/targets.bzl @@ -0,0 +1,14 @@ +load("@fbsource//xplat/executorch/build:runtime_wrapper.bzl", "runtime") + +def define_common_targets(is_fbcode = False): + if not is_fbcode: + return + + runtime.cxx_test( + name = "cache_test", + srcs = ["cache_test.cpp"], + deps = [ + "//executorch/extension/llm/cache:kv_cache", + "//executorch/test/utils:utils", + ], + )