Skip to content
Open
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
2 changes: 2 additions & 0 deletions amd_kernels/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,3 +383,5 @@ each category's `__init__.py` re-exports its families' `__all__` and holds no lo
- [`compile_watch.py`](compile_watch.py): reports a compile after the warm-ups.
- [`common/`](common/): buffer ops, launch helpers, the AITER GEMM's XCD swizzle, the HIP runtime binding, the
eight-rank flag helpers (`rank8_signal.py`, `rank8_comm.py`) and the persistent-kernel building blocks (`mono/`).

- `attention.dcp8_context_gather_mla_idx`: eight-rank direct peer gather for MLA and indexer context rows.
39 changes: 39 additions & 0 deletions amd_kernels/attention/dcp8_context_gather_mla_idx/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# DCP8 context gather

## Contract

Eight gfx950 ranks push byte-preserving MLA and indexer context rows into peer workspaces. All ranks must participate in the same collective order. Indexer values and scales retain their packed page layout. Workspace allocation and teardown are collective; callers must keep buffers alive until all GPU work completes.

Caches are three-dimensional tensors with packed rows and non-overlapping page strides; padding between pages is supported. Index blocks have 64 rows and MLA blocks a multiple of 64 rows. Tables and length vectors are int32 on the communicator device. MLA/value rows are 16-byte aligned, with four scale bytes per index row; tiled FP4 uses 64 value bytes. The workspace must be smaller than 4 GiB because buffer offsets are 32-bit. The current HIP device must match the communicator for construction, use and close.

The caller supplies valid block IDs, monotone query offsets and sufficient page/workspace capacity. Destination pages for each request are consecutive from its first table entry and must not overlap other requests. Metadata checks do not read GPU contents. All ranks must agree on valid inputs and empty calls before launch.

Gather and barrier calls must use one ordered stream per workspace. Warm each used row layout with valid inputs and call the barrier before capture. Close collectively before destroying the group, after dropping captured graphs; repeated close is a no-op. Borrowed workspace views become invalid on close.

## Entry points

- `DcpContextGather`: owns the IPC workspace, gathers context and synchronizes peer exchanges.
- `compile_context_push`: builds the FlyDSL gather variant selected by row layout.

## Tests

`pytest -q tests/attention/dcp8_context_gather_mla_idx/test_gather.py` checks eight ranks against a byte-exact reference, padded page strides, page boundaries, packed scales, changing inputs across graph replays, a delayed rank, immediate GPU consumption without an extra barrier, invalid metadata and teardown. CI assigns this target eight GPUs.

`AKR_COMPILE_ONLY=1 pytest -q tests/attention/dcp8_context_gather_mla_idx/test_compile.py` compiles the three supported production layouts without launching peer writes.

## Performance

`python -m benchmarks.attention.dcp8_context_gather_mla_idx.benchmark_gather` times the installed gather against byte-exact eager and graph checks. Use the same fixture and runtime with each pinned source checkout for A/B. It does not construct a replacement gather implementation. Twenty samples each replay ten calls; buffers and metadata are hot and fixed. These are primitive timings, not model throughput gains.

`--lengths 18432 --query-lengths 4096 --layout 576-fp4` specifies total sequence and new-token lengths separately. `656-fp4` selects the larger MLA record. Explicit lengths default to up to eight query tokens each.

8x MI355X, max-rank p50 microseconds, sequential same-node A/B against the frozen production gather:

| Shape / layout | Production baseline | This kernel |
|---|---:|---:|
| 18432 / 4096 query, 576B FP4 | 52.51 | 51.83 |
| Eight mixed requests, 576B FP4 | 21.35 | 20.48 |
| 4 x 32768, 576B FP4 | 306.23 | 305.63 |
| 1 x 131072, 576B FP4 | 305.98 | 305.76 |

These sequential measurements show comparable primitive performance; they do not establish a model-level speedup.
8 changes: 8 additions & 0 deletions amd_kernels/attention/dcp8_context_gather_mla_idx/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the amd-kernels project
"""DCP8 direct peer gather of MLA and indexer context rows."""

from .comm import DcpContextGather
from .kernel import DATA_OFF, compile_context_push

__all__ = ["DATA_OFF", "DcpContextGather", "compile_context_push"]
198 changes: 198 additions & 0 deletions amd_kernels/attention/dcp8_context_gather_mla_idx/comm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the amd-kernels project
"""Host communicator for the DCP8 direct context gather."""

import functools

import torch
import torch.distributed as dist

from amd_kernels.common.mono.peer import PeerBuffer
from amd_kernels.common.tensor_shim import _run_compiled

from .kernel import DATA_OFF, WORLD, compile_context_push, compile_exchange_barrier

_exchange_barrier = functools.cache(compile_exchange_barrier)


@functools.cache
def _push_kernel(mla_row_bytes, index_row_bytes, index_scale_bytes, tiled_fp4):
# These are specialization constants. Validate at the existing compile
# boundary, rather than repeating the same format checks on every layer.
if (mla_row_bytes <= 0 or mla_row_bytes % 16 or
index_row_bytes <= 0 or index_row_bytes % 16 or index_scale_bytes != 4 or
(tiled_fp4 and index_row_bytes != 64)):
raise ValueError("unsupported MLA/index row layout")
return compile_context_push(
mla_row_bytes,
index_row_bytes,
index_scale_bytes,
synchronize=True,
tiled_fp4=tiled_fp4,
)


class DcpContextGather:
"""One uncached workspace per rank, directly writable by every peer."""

def __init__(self, nbytes: int, group, rank: int, device: torch.device):
if dist.get_world_size(group) != WORLD or rank != dist.get_rank(group):
raise ValueError("context gather requires eight ranks and the group-local rank")
if nbytes <= 0 or nbytes % 16 or nbytes >= 2**32:
raise ValueError("workspace size must be positive, 16-byte aligned and below 4 GiB")
self.rank = rank
self.group = group
self.device = torch.device(device)
if self.device.type != "cuda":
raise ValueError("context gather requires a CUDA/ROCm device")
if self.device.index is None:
self.device = torch.device("cuda", torch.cuda.current_device())
if self.device.index != torch.cuda.current_device():
raise ValueError("communicator device must match the current HIP device")
self._closed = False
self.nbytes = nbytes
self.peer = PeerBuffer(DATA_OFF + nbytes, group, rank, WORLD, self.device)
self.data = self.peer.bytes[DATA_OFF:]
self.data_ptrs = self.peer.addresses + DATA_OFF
self.exchange_epoch = torch.zeros(1, dtype=torch.int32, device=self.device)
self.state = torch.zeros(2, dtype=torch.int32, device=self.device)
# PeerBuffer memory is not guaranteed zeroed. Only flags require an
# initial value; data rows are fully populated before consumption.
self.peer.bytes[:DATA_OFF].zero_()
torch.cuda.synchronize(self.device)
dist.barrier(group=group)

def gather(
self,
*,
mla_cache: torch.Tensor,
mla_block_table: torch.Tensor,
index_cache: torch.Tensor,
index_block_table: torch.Tensor,
seq_lens: torch.Tensor,
query_start_loc: torch.Tensor,
dst_block_table: torch.Tensor,
max_local_pages: int,
dst_index_offset: int,
index_row_bytes: int,
tiled_fp4: bool = False,
validate: bool = True,
) -> None:
"""Gather one layer; trusted callers may validate at allocation/batch boundaries.

With ``validate=False``, the caller must guarantee the same device,
packed cache rows, int32 tables/vectors and sufficient table/workspace
capacity for this batch. This does not memoize tensor identities.
"""
if self._closed:
raise RuntimeError("context gather communicator closed")
if validate:
if self.device.index != torch.cuda.current_device():
raise ValueError("communicator device must match the current HIP device")
tensors = (mla_cache, index_cache, mla_block_table, index_block_table,
seq_lens, query_start_loc, dst_block_table)
if any(t.device != self.device for t in tensors):
raise ValueError("all gather tensors must be on the communicator device")
num_requests = seq_lens.numel()
table_shapes = []
table_strides = []
for table in (mla_block_table, index_block_table, dst_block_table):
shape, strides = table.shape, table.stride()
if table.dtype != torch.int32 or len(shape) != 2 or strides[1] != 1:
raise ValueError("block tables must be int32 matrices with contiguous rows")
if shape[0] < num_requests:
raise ValueError("block table has fewer rows than requests")
table_shapes.append(shape)
table_strides.append(strides[0])
for vector in (seq_lens, query_start_loc):
if vector.dtype != torch.int32 or vector.ndim != 1 or not vector.is_contiguous():
raise ValueError("lengths and query offsets must be contiguous int32 vectors")
if query_start_loc.numel() != num_requests + 1:
raise ValueError("query offsets must have one more entry than sequence lengths")
if max_local_pages < 0 or not 0 < dst_index_offset < self.nbytes or dst_index_offset % 16:
raise ValueError("invalid page bound or workspace split")
# Block-major pools interleave layers between pages; kernels consume
# stride(0) explicitly, but each page's rows must remain packed.
cache_layouts = []
for cache in (mla_cache, index_cache):
shape, strides = cache.shape, cache.stride()
if (len(shape) != 3 or strides[2] != 1 or strides[1] != shape[2]
or strides[0] < shape[1] * shape[2]):
raise ValueError("caches must have packed rows and non-overlapping page strides")
itemsize = cache.element_size()
cache_layouts.append((shape[1], shape[2] * itemsize, strides[0] * itemsize))
if not max_local_pages or not num_requests:
return
# Kernel addresses and strides are bytes; no dtype view is needed.
mla_rows, mla_row_bytes, mla_page_stride = cache_layouts[0]
index_rows, index_bytes, index_page_stride = cache_layouts[1]
if mla_rows == 0 or mla_rows % 64 or index_rows != 64:
raise ValueError("MLA blocks must contain whole 64-row pages; index blocks have 64 rows")
index_scale_bytes = index_bytes - index_row_bytes
if (table_shapes[0][1] * (mla_rows // 64) < max_local_pages or
table_shapes[1][1] < max_local_pages or table_shapes[2][1] < 1):
raise ValueError("block tables do not cover the requested page bound")
else:
num_requests = seq_lens.numel()
if not max_local_pages or not num_requests:
return
mla_size, index_size = mla_cache.element_size(), index_cache.element_size()
mla_rows = mla_cache.shape[1]
mla_row_bytes = mla_cache.shape[2] * mla_size
mla_page_stride = mla_cache.stride(0) * mla_size
index_page_stride = index_cache.stride(0) * index_size
index_scale_bytes = index_cache.shape[2] * index_size - index_row_bytes
table_strides = (mla_block_table.stride(0), index_block_table.stride(0),
dst_block_table.stride(0))
kernel = _push_kernel(
mla_row_bytes, index_row_bytes, index_scale_bytes, tiled_fp4
)
_run_compiled(
kernel,
mla_cache.data_ptr(),
mla_page_stride,
mla_rows // 64,
mla_block_table.data_ptr(),
table_strides[0],
index_cache.data_ptr(),
index_page_stride,
index_block_table.data_ptr(),
table_strides[1],
seq_lens.data_ptr(),
query_start_loc.data_ptr(),
dst_block_table.data_ptr(),
table_strides[2],
*self.peer.host_addresses,
self.nbytes,
dst_index_offset,
self.rank,
max_local_pages,
num_requests,
self.state.data_ptr(),
torch.cuda.current_stream(self.device),
)

def barrier(self) -> None:
if self._closed:
raise RuntimeError("context gather communicator closed")
if self.device.index != torch.cuda.current_device():
raise ValueError("communicator device must match the current HIP device")
_run_compiled(
_exchange_barrier(),
*self.peer.host_addresses,
self.rank,
self.exchange_epoch.data_ptr(),
torch.cuda.current_stream(self.device),
)

def close(self) -> None:
if self._closed:
return
if self.device.index != torch.cuda.current_device():
raise ValueError("communicator device must match the current HIP device")
torch.cuda.synchronize(self.device)
dist.barrier(group=self.group)
self.peer.close()
self.data = None
self.data_ptrs = None
self._closed = True
Loading
Loading