Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion backends/cuda/passes/lower_offgraph_kv.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.

Expand All @@ -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]]
Expand All @@ -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)
Expand All @@ -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(
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
13 changes: 10 additions & 3 deletions backends/cuda/runtime/test/test_cuda_kv_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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);
Expand Down
1 change: 1 addition & 0 deletions backends/cuda/tests/targets.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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",
],
Expand Down
125 changes: 125 additions & 0 deletions backends/cuda/tests/test_offgraph_kv_batched_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 (
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"]
)
Expand All @@ -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):
Expand Down Expand Up @@ -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")
Expand Down
Loading
Loading