Repository navigation
fix(rocke): honour the block-table stride in the scalar attention fallback #13889
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
dlangbe
merged 25 commits into
develop
from
users/dlangbe/rocke-drop-shape-from-cache-key
Oct 29, 2026
+679
−313
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
892ef5c
fix(rocke/attention): key every resolved selector in the tiled cache …
dlangbe 8352908
perf(rocke/attention): drop raw num_seqs from the tiled cache keys
dlangbe dc2a8f3
feat(rocke/attention): add an A/B harness for the tiled cache keys
dlangbe 46d97d7
Merge remote-tracking branch 'origin/develop' into users/dlangbe/rock…
dlangbe 9544316
fix(rocke/attention): keep garbage collection out of the tiled cache-…
dlangbe 09297f9
docs(rocke/attention): require new attention selectors in the tiled c…
dlangbe 4d98028
refactor(rocke/attention): modernize typing and imports in the tiled …
dlangbe 8c66efc
perf(rocke/attention): reuse resolved geometry in the tiled cache key
dlangbe 4f75b57
perf(rocke/attention): check shape before env knobs in single-batch p…
dlangbe 24becc4
Merge remote-tracking branch 'origin/develop' into users/dlangbe/rock…
dlangbe 08a4a27
test(rocke/attention): pin the single-batch tail of the tiled cache key
dlangbe fde9689
Merge remote-tracking branch 'origin/develop' into users/dlangbe/rock…
dlangbe 615dc7e
Merge remote-tracking branch 'origin/develop' into users/dlangbe/rock…
dlangbe 0009508
fix(rocke/attention): pass the scalar block-table stride as a kernarg
dlangbe 6b4a95d
test(rocke): add a scalar family to the cache-key A/B harness
dlangbe d6a84a0
Merge remote-tracking branch 'origin/develop' into users/dlangbe/rock…
dlangbe ec41895
test(rocke): re-bless scalar attention IR goldens for the stride kernarg
dlangbe 6a6ca5a
refactor(rocke): share the scalar block-table lookup between 2D and 3D
dlangbe 405e46c
test(rocke): run the scalar attention stride tests in CI
dlangbe 4420023
Merge remote-tracking branch 'origin/develop' into users/dlangbe/rock…
dlangbe 7189edc
test(rocke): cover the remaining scalar key fields and drop stale max…
dlangbe 562eafd
Merge remote-tracking branch 'origin/develop' into users/dlangbe/rock…
dlangbe 5a78d34
Merge branch 'develop' into users/dlangbe/rocke-drop-shape-from-cache…
dlangbe f9c4ad6
Merge remote-tracking branch 'origin/develop' into users/dlangbe/rock…
dlangbe 56ae952
test(rocke): re-bless the scalar attention differential golden
dlangbe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
185 changes: 185 additions & 0 deletions
185
...ders/hip-kernel-provider/rocke/library/tests/test_attention_scalar_block_table_numeric.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| # Copyright (c) Advanced Micro Devices, Inc., or its affiliates. | ||
| # SPDX-License-Identifier: MIT | ||
|
|
||
| """Scalar fallback launches with block-table rows wider than the batch needs. | ||
|
|
||
| Callers usually size block-table rows for the longest sequence they admit, not | ||
| the longest one in the current batch. The scalar kernels index rows by the | ||
| table's real row stride (the ``block_table_stride`` kernarg), so every sequence | ||
| after the first must still find its own blocks. Unused table slots point at a | ||
| poison block, so a wrong row stride corrupts the output instead of passing by | ||
| luck. | ||
|
|
||
| The launch goes through ``run_unified_attention_torch(backend="scalar")`` with | ||
| ``rocke.runtime`` device buffers instead of torch tensors, so the test runs in | ||
| GPU lanes without torch. Reference attention is computed independently in FP32 | ||
| with numpy from the logical K/V, after rounding inputs to fp16. Skips without a | ||
| GPU, and on devices whose target id the attention builders do not know. | ||
| """ | ||
|
|
||
| import ctypes | ||
| import itertools | ||
| import math | ||
|
|
||
| import numpy as np | ||
| import pytest | ||
|
|
||
| from kernels.common import attention_unified as au | ||
| from rocke.core.arch.target import known_arches | ||
| from rocke.runtime.hip_module import get_device_arch | ||
|
|
||
| _HQ, _HKV, _D, _BS = 8, 2, 64, 16 | ||
| _ATOL = 1e-2 | ||
|
|
||
| # The launch compiles for the device's own target id, which the builders must | ||
| # know (gfx11 devices are only known through their generic target). | ||
| _ARCH = get_device_arch() | ||
| pytestmark = [ | ||
| pytest.mark.gpu, | ||
| pytest.mark.skipif( | ||
| _ARCH not in known_arches(), | ||
| reason=f"needs a GPU with a known attention target, found {_ARCH}", | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def rt(): | ||
| from rocke.runtime.hip_module import Runtime | ||
|
|
||
| return Runtime() | ||
|
|
||
|
|
||
| def _u8(array): | ||
| return (ctypes.c_uint8 * array.nbytes).from_buffer(array) | ||
|
|
||
|
|
||
| class _DeviceArray: | ||
| """A device copy of a numpy array, exposing the tensor attributes | ||
| ``run_unified_attention_torch`` reads. ``shape`` may be narrower than the | ||
| host array along the last axis, which models a column view of it.""" | ||
|
|
||
| device = None | ||
|
|
||
| def __init__(self, rt, host, *, shape=None): | ||
| from rocke.runtime.launcher import DeviceMem | ||
|
|
||
| self._rt = rt | ||
| self._host = np.ascontiguousarray(host) | ||
| self._mem = DeviceMem(self._host.nbytes) | ||
| rt.memcpy_h2d(self._mem.ptr(), _u8(self._host), self._host.nbytes) | ||
| self.shape = self._host.shape if shape is None else shape | ||
|
|
||
| def stride(self, dim): | ||
| return self._host.strides[dim] // self._host.itemsize | ||
|
|
||
| def data_ptr(self): | ||
| return self._mem.ptr() | ||
|
|
||
| def read(self): | ||
| out = np.empty_like(self._host) | ||
| self._rt.memcpy_d2h(_u8(out), self._mem.ptr(), out.nbytes) | ||
| return out | ||
|
|
||
|
|
||
| def _case(q_lens, kv_lens, row_width, *, seed): | ||
| """A paged case whose block-table rows hold ``row_width`` slots.""" | ||
| rng = np.random.default_rng(seed) | ||
| needed = [math.ceil(n / _BS) for n in kv_lens] | ||
| num_blocks = sum(needed) + 1 | ||
| poison = num_blocks - 1 | ||
| order = iter(rng.permutation(num_blocks - 1)) | ||
| table = np.full((len(kv_lens), row_width), poison, dtype=np.int32) | ||
| for s, n in enumerate(needed): | ||
| table[s, :n] = [next(order) for _ in range(n)] | ||
|
|
||
| def randn(*shape): | ||
| return rng.standard_normal(shape).astype(np.float16) | ||
|
|
||
| q = randn(sum(q_lens), _HQ, _D) | ||
| k = randn(num_blocks, _BS, _HKV, _D) | ||
| v = randn(num_blocks, _BS, _HKV, _D) | ||
| k[poison] = 64.0 | ||
| v[poison] = 64.0 | ||
| cu = np.array([0, *itertools.accumulate(q_lens)], dtype=np.int32) | ||
| problem = au.UnifiedAttentionProblem( | ||
| total_q=sum(q_lens), | ||
| num_seqs=len(q_lens), | ||
| num_query_heads=_HQ, | ||
| num_kv_heads=_HKV, | ||
| head_size=_D, | ||
| block_size=_BS, | ||
| max_seqlen_q=max(q_lens), | ||
| max_seqlen_k=max(kv_lens), | ||
| dtype="fp16", | ||
| ) | ||
| return problem, q, k, v, cu, table | ||
|
|
||
|
|
||
| def _reference(q, k, v, cu, table, q_lens, kv_lens): | ||
| out = np.zeros(q.shape, dtype=np.float32) | ||
| ratio = _HQ // _HKV | ||
| for s, (q_len, kv_len) in enumerate(zip(q_lens, kv_lens)): | ||
| blocks = table[s, : math.ceil(kv_len / _BS)] | ||
| keys = k[blocks].reshape(-1, _HKV, _D)[:kv_len].astype(np.float32) | ||
| values = v[blocks].reshape(-1, _HKV, _D)[:kv_len].astype(np.float32) | ||
| context = kv_len - q_len | ||
| for i in range(q_len): | ||
| tok = int(cu[s]) + i | ||
| visible = context + i + 1 | ||
| for h in range(_HQ): | ||
| scores = keys[:visible, h // ratio] @ q[tok, h].astype(np.float32) | ||
| scores /= math.sqrt(_D) | ||
| probs = np.exp(scores - scores.max()) | ||
| out[tok, h] = (probs / probs.sum()) @ values[:visible, h // ratio] | ||
| return out | ||
|
|
||
|
|
||
| def _launch(rt, problem, q, k, v, cu, kv_lens, block_table): | ||
| out = _DeviceArray(rt, np.zeros_like(q)) | ||
| au.run_unified_attention_torch( | ||
| problem=problem, | ||
| q=_DeviceArray(rt, q), | ||
| k=_DeviceArray(rt, k), | ||
| v=_DeviceArray(rt, v), | ||
| out=out, | ||
| cu_seqlens_q=_DeviceArray(rt, cu), | ||
| seqused_k=_DeviceArray(rt, np.array(kv_lens, dtype=np.int32)), | ||
| softmax_scale=1.0 / math.sqrt(_D), | ||
| block_table=block_table, | ||
| softcap=0.0, | ||
| backend="scalar", | ||
| ) | ||
| return out.read().astype(np.float32) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("view_of_wider", (False, True), ids=("wide", "view")) | ||
| def test_wide_block_table_rows(rt, view_of_wider): | ||
| q_lens, kv_lens = [5, 1, 9], [37, 20, 61] | ||
| row_width = math.ceil(max(kv_lens) / _BS) + 6 | ||
| alloc_width = row_width + 5 if view_of_wider else row_width | ||
| problem, q, k, v, cu, table = _case(q_lens, kv_lens, alloc_width, seed=0) | ||
| dev = _DeviceArray(rt, table, shape=(len(q_lens), row_width)) | ||
| assert dev.stride(0) > math.ceil(problem.max_seqlen_k / _BS) | ||
| got = _launch(rt, problem, q, k, v, cu, kv_lens, dev) | ||
| want = _reference(q, k, v, cu, table, q_lens, kv_lens) | ||
| max_abs = float(np.abs(got - want).max()) | ||
| assert max_abs <= _ATOL, f"max_abs {max_abs:.3e} vs fp32 reference" | ||
|
|
||
|
|
||
| def test_one_binary_serves_different_batches(rt): | ||
| """Shapes that differ only in batch geometry share a key; the second | ||
| launch must reuse the first binary and still match the reference.""" | ||
| first = ([4, 2], [30, 17], 4) | ||
| second = ([1, 7, 3, 2], [90, 64, 15, 33], 12) | ||
| launchers = None | ||
| for i, (q_lens, kv_lens, width) in enumerate((first, second)): | ||
| problem, q, k, v, cu, table = _case(q_lens, kv_lens, width, seed=i) | ||
| got = _launch(rt, problem, q, k, v, cu, kv_lens, _DeviceArray(rt, table)) | ||
| if launchers is None: | ||
| launchers = len(au._SCALAR_LAUNCHERS) | ||
| else: | ||
| assert len(au._SCALAR_LAUNCHERS) == launchers | ||
| want = _reference(q, k, v, cu, table, q_lens, kv_lens) | ||
| max_abs = float(np.abs(got - want).max()) | ||
| assert max_abs <= _ATOL, f"case {i}: max_abs {max_abs:.3e}" | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.