PAT-code / src /pat /kernels /attention.py
ICLRPAT27's picture
Publish reviewed PAT training and inference supplement
643267a verified
Raw History Blame Contribute Delete
120 kB
"""PAT fused attention. Only the publication training/prefill path is retained. FP32 relative rotary products, query-owned backward, and Hopper ragged TMA accumulation preserve the checkpoint producer's arithmetic. """ from __future__ import annotations from .layout import PackedLayout ROPE_BASE = 10_000.0 import math from collections import OrderedDict from collections.abc import Sequence from dataclasses import dataclass from threading import Lock from typing import Any import torch try: import triton import triton.language as tl from triton.tools.ragged_tma import atomic_add_ragged, create_ragged_descriptor _HAS_TRITON = True except ImportError: triton = None tl = None _HAS_TRITON = False _SUPPORTED_CHUNK_SIZES = frozenset({16, 32}) _SUPPORTED_DTYPES = frozenset({torch.float16, torch.bfloat16, torch.float32}) _PAT_MEMORY_BLOCK_Q = 64 _PAT_MEMORY_BACKWARD_BLOCK_K = 64 _PAT_MEMORY_FORWARD_WARPS = 4 _PAT_MEMORY_BACKWARD_WARPS = 4 _PAT_TOKEN_BACKWARD_WARPS = 4 _PAT_PLAN_CACHE_MAX_ENTRIES = 32 _PAT_PHASE_CACHE_MAX_ENTRIES = _PAT_PLAN_CACHE_MAX_ENTRIES _PAT_PHASE_CACHE: OrderedDict[ tuple[KernelConfig, torch.device, torch.dtype, int, int], tuple[torch.Tensor, torch.Tensor] ] = OrderedDict() _PAT_PHASE_CACHE_LOCK = Lock() _PAT_FIXED_ROW_CACHE_MAX_ENTRIES = _PAT_PLAN_CACHE_MAX_ENTRIES _PAT_FIXED_ROW_CACHE: OrderedDict[tuple[tuple[Any, ...], torch.device, int], torch.Tensor] = ( OrderedDict() ) _PAT_FIXED_ROW_CACHE_LOCK = Lock() _PAT_TRUSTED_MATERIALIZER = object() def _memory_query_block_k(configured_block_k: int) -> int: """Bound the five-product query owner while respecting smaller K tiles.""" return min(_PAT_MEMORY_BACKWARD_BLOCK_K, int(configured_block_k)) def _power_of_two(name: str, value: int) -> int: value_i = int(value) if value_i <= 0 or value_i & value_i - 1: raise ValueError(f"{name} must be a positive power of two; got {value!r}") return value_i def _block_d(head_dim: int) -> int: return max(16, 1 << max(0, int(head_dim) - 1).bit_length()) def _validate_pat_head_dim(head_dim: int) -> int: """Validate the one ragged-TMA backward geometry before any launch.""" value = int(head_dim) block_dimension = _block_d(value) if value < 20 or value % 4 or block_dimension > 128: raise ValueError( f"PAT ragged-TMA backward requires head_dim divisible by 4 in [20, 128]; got {value}" ) return block_dimension def _require_pat_hopper(device: torch.device) -> None: """Require the descriptor atomics used by the publication kernel.""" capability = torch.cuda.get_device_capability(device) if int(capability[0]) < 9: raise RuntimeError( f"production attention PAT requires an SM90-or-newer CUDA GPU for ragged TMA descriptor atomics; got compute capability {capability[0]}.{capability[1]}" ) @dataclass(frozen=True) class KernelConfig: """Fixed publication tile geometry and runtime context capacity.""" chunk_size: int max_memory_size: int block_q: int = 16 block_k_memory: int = 64 block_k_token: int = 16 warps: int = 4 stages: int = 3 def __post_init__(self) -> None: if int(self.chunk_size) not in _SUPPORTED_CHUNK_SIZES: raise ValueError( f"production attention PAT supports chunk_size 16 or 32; got {self.chunk_size!r}" ) if isinstance(self.max_memory_size, bool) or int(self.max_memory_size) < 4: raise ValueError( f"production attention PAT requires max_memory_size >= 4; got {self.max_memory_size!r}" ) _power_of_two("block_q", self.block_q) _power_of_two("block_k_memory", self.block_k_memory) _power_of_two("block_k_token", self.block_k_token) for name, value in ( ("block_q", self.block_q), ("block_k_memory", self.block_k_memory), ("block_k_token", self.block_k_token), ): if int(value) < 16 or int(value) > 128: raise ValueError( f"{name} must be a tensor-core tile size in [16, 128]; got {value!r}" ) if int(self.warps) not in {2, 4, 8}: raise ValueError(f"warps must be 2, 4, or 8; got {self.warps!r}") if int(self.stages) not in {1, 2, 3, 4, 5}: raise ValueError(f"stages must be in [1, 5]; got {self.stages!r}") @dataclass(frozen=True) class _PATMaterializedLayout: """One per-batch PAT layout and its canonical token-storage maps.""" layout: PackedLayout canonical_order: torch.Tensor logical_order: torch.Tensor canonical_positions: torch.Tensor canonical_key_positions: torch.Tensor q_tile_rows: torch.Tensor q_tile_starts: torch.Tensor token_row_ids: torch.Tensor memory_tile_union_start: torch.Tensor memory_tile_union_end: torch.Tensor memory_tile_interior_start: torch.Tensor memory_tile_interior_end: torch.Tensor token_owner_rows: torch.Tensor token_owner_starts: torch.Tensor block_q: int block_k_memory: int block_k_token: int total_lexical_tokens: int global_slots: int storage: torch.Tensor provenance: _PATMaterializationProvenance | None @dataclass(frozen=True) class _PATMaterializationProvenance: """Unforgeable batch-lifetime marker for the internal fused materializer.""" storage_identity: int device: torch.device stream: int @dataclass(frozen=True) class FixedGeometry: """Authoritative fixed-packer inputs consumed by the private materializer.""" row_offsets: torch.Tensor row_lengths: torch.Tensor row_content_lengths: torch.Tensor chunk_piece_id: torch.Tensor piece_chunk_base: torch.Tensor eoc_abs_idx: torch.Tensor token_count: int max_row_length: int max_chunk_index: int planner_cache_key: tuple[Any, ...] @property def row_count(self) -> int: return int(self.row_lengths.numel()) @property def memory_tail_slots(self) -> int: return int(self.eoc_abs_idx.size(1)) @dataclass(frozen=True) class PATPlan: """O(tile) immutable launch metadata built once with the packed layout.""" config: KernelConfig row_count: int token_slots: int total_lexical_tokens: int local_tail_slots: int memory_slots: int global_slots: int heads: int head_dim: int dtype: torch.dtype row_offsets: torch.Tensor row_pos_to_flat: torch.Tensor row_lengths: torch.Tensor row_chunk_indices: torch.Tensor memory_query_start: torch.Tensor row_memory_start_abs: torch.Tensor row_memory_length: torch.Tensor row_token_memory_length: torch.Tensor row_exact_start_abs: torch.Tensor row_exact_length: torch.Tensor row_exact_query_phase_delta: torch.Tensor row_compressed_eoc_local_key_phase_delta: torch.Tensor q_tile_rows: torch.Tensor q_tile_starts: torch.Tensor token_row_ids: torch.Tensor canonical_order: torch.Tensor logical_order: torch.Tensor memory_tile_union_start: torch.Tensor memory_tile_union_end: torch.Tensor memory_tile_interior_start: torch.Tensor memory_tile_interior_end: torch.Tensor token_owner_rows: torch.Tensor token_owner_starts: torch.Tensor memory_phase_cos: torch.Tensor memory_phase_sin: torch.Tensor metadata_signature: tuple[tuple[Any, ...], ...] canonical_metadata: torch.Tensor metadata_validation_result: torch.Tensor metadata_validation_stream: int | None _trusted_materialization: _PATMaterializationProvenance | None = None @property def query_tiles(self) -> int: return int(self.q_tile_rows.numel()) @property def token_tiles(self) -> int: return int(self.token_owner_rows.numel()) @property def memory_query_tiles(self) -> int: return int(self.memory_tile_union_start.numel()) @property def metadata(self) -> tuple[torch.Tensor, ...]: return ( self.row_offsets, self.row_pos_to_flat, self.row_lengths, self.row_chunk_indices, self.memory_query_start, self.row_memory_start_abs, self.row_memory_length, self.row_token_memory_length, self.row_exact_start_abs, self.row_exact_length, self.row_exact_query_phase_delta, self.row_compressed_eoc_local_key_phase_delta, ) @property def bound_metadata(self) -> tuple[torch.Tensor, ...]: """All mutable tensors whose exact identity/version binds this plan.""" return (*self.metadata, self.canonical_order, self.logical_order) if _HAS_TRITON: @triton.jit( do_not_specialize=( "rows", "physical_tokens", "target_tokens", "total_lexical_tokens", "q_tile_capacity", "token_tile_capacity", "memory_tile_count", "pieces", ), do_not_specialize_on_alignment=( "rows", "physical_tokens", "target_tokens", "total_lexical_tokens", "q_tile_capacity", "token_tile_capacity", "memory_tile_count", "pieces", ), ) def _pat_materialize_layout_kernel( physical_row_offsets_ptr, physical_row_pos_to_flat_ptr, physical_row_lengths_ptr, physical_memory_query_start_ptr, physical_memory_start_ptr, physical_memory_length_ptr, physical_eoc_ptr, row_chunk_indices_ptr, piece_chunk_base_ptr, expected_row_geometry_ptr, storage_ptr, rows, physical_tokens, target_tokens, total_lexical_tokens, q_tile_capacity, token_tile_capacity, memory_tile_count, pieces, PHYSICAL_SLOTS: tl.constexpr, LOCAL_SLOTS: tl.constexpr, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, MAX_MEMORY_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K_MEMORY: tl.constexpr, BLOCK_K_TOKEN: tl.constexpr, BLOCK_MEMORY_QUERY: tl.constexpr, BLOCK_ROW: tl.constexpr, TRUSTED_FIXED: tl.constexpr, ): """Materialize one exact PAT signature without scans or gathers.""" row = tl.program_id(0) position = tl.arange(0, BLOCK_ROW) row_mask = row < rows physical_offset = tl.load(physical_row_offsets_ptr + row, mask=row_mask, other=0).to( tl.int64 ) physical_length = tl.load(physical_row_lengths_ptr + row, mask=row_mask, other=0).to( tl.int64 ) lexical_length = physical_length - PHYSICAL_SLOTS target_offset = physical_offset + row * (LOCAL_SLOTS - PHYSICAL_SLOTS) target_length = lexical_length + LOCAL_SLOTS if TRUSTED_FIXED: piece_id = tl.load(row_chunk_indices_ptr + row, mask=row_mask, other=-1).to(tl.int64) piece_valid = row_mask & (piece_id >= 0) & (piece_id < pieces) safe_piece_id = tl.maximum(0, tl.minimum(piece_id, pieces - 1)) piece_base = tl.load( piece_chunk_base_ptr + safe_piece_id, mask=piece_valid, other=rows + 1 ).to(tl.int64) chunk_index = row - piece_base else: piece_valid = row_mask chunk_index = tl.load(row_chunk_indices_ptr + row, mask=row_mask, other=-1).to(tl.int64) expected_lexical_length = tl.load( expected_row_geometry_ptr + row, mask=row_mask, other=-1 ).to(tl.int64) expected_chunk_index = tl.load( expected_row_geometry_ptr + rows + row, mask=row_mask, other=-1 ).to(tl.int64) memory_query_start = tl.load( physical_memory_query_start_ptr + row, mask=row_mask, other=-1 ).to(tl.int64) if TRUSTED_FIXED: physical_memory_start = 0 physical_memory_length = 0 else: physical_memory_start = tl.load( physical_memory_start_ptr + row, mask=row_mask, other=-1 ).to(tl.int64) physical_memory_length = tl.load( physical_memory_length_ptr + row, mask=row_mask, other=-1 ).to(tl.int64) previous_row = tl.maximum(row - 1, 0) previous_offset = tl.load( physical_row_offsets_ptr + previous_row, mask=row_mask, other=0 ).to(tl.int64) previous_length = tl.load( physical_row_lengths_ptr + previous_row, mask=row_mask, other=0 ).to(tl.int64) if TRUSTED_FIXED: previous_chunk = tl.load( expected_row_geometry_ptr + rows + previous_row, mask=row_mask, other=0 ).to(tl.int64) else: previous_chunk = tl.load( row_chunk_indices_ptr + previous_row, mask=row_mask, other=0 ).to(tl.int64) expected_physical_offset = tl.where(row == 0, 0, previous_offset + previous_length) previous_target_offset = tl.where( row == 0, 0, previous_offset + previous_row * (LOCAL_SLOTS - PHYSICAL_SLOTS) ) visible_memory_chunks = tl.minimum(chunk_index, MAX_MEMORY_SIZE - 1) expected_memory_start = (row - visible_memory_chunks) * PHYSICAL_SLOTS expected_memory_length = visible_memory_chunks * PHYSICAL_SLOTS if TRUSTED_FIXED: physical_memory_start = expected_memory_start physical_memory_length = expected_memory_length row_valid = ( row_mask & piece_valid & (physical_offset == expected_physical_offset) & (physical_offset >= 0) & (physical_offset + physical_length <= physical_tokens) & (lexical_length > 0) & (lexical_length <= CHUNK_SIZE) & (lexical_length == expected_lexical_length) & (memory_query_start == lexical_length) & (chunk_index >= 0) & (chunk_index == expected_chunk_index) & ((row == 0) | (chunk_index == 0) | (chunk_index == previous_chunk + 1)) & (physical_memory_start >= 0) & (physical_memory_length >= 0) & (physical_memory_start % PHYSICAL_SLOTS == 0) & (physical_memory_length % PHYSICAL_SLOTS == 0) & (physical_memory_start + physical_memory_length <= rows * PHYSICAL_SLOTS) & (physical_memory_start == expected_memory_start) & (physical_memory_length == expected_memory_length) & (target_offset >= 0) & (target_offset + target_length <= target_tokens) ) if TRUSTED_FIXED: identity_invalid = position < 0 else: physical_position_mask = row_mask & (position < physical_length) physical_flat = physical_offset + position physical_flat_in_bounds = ( physical_position_mask & (physical_flat >= 0) & (physical_flat < physical_tokens) ) identity_value = tl.load( physical_row_pos_to_flat_ptr + physical_flat, mask=physical_flat_in_bounds, other=-1 ).to(tl.int64) identity_invalid = physical_position_mask & ( ~physical_flat_in_bounds | (identity_value != physical_flat) ) physical_tail_mask = row_mask & (position < PHYSICAL_SLOTS) physical_eoc = tl.load( physical_eoc_ptr + row * PHYSICAL_SLOTS + position, mask=physical_tail_mask, other=-1 ).to(tl.int64) eoc_invalid = physical_tail_mask & ( physical_eoc != physical_offset + lexical_length + position ) row_valid &= (tl.sum(identity_invalid.to(tl.int32), axis=0) == 0) & ( tl.sum(eoc_invalid.to(tl.int32), axis=0) == 0 ) row_offsets_base = 0 row_pos_to_flat_base = row_offsets_base + rows row_lengths_base = row_pos_to_flat_base + target_tokens row_chunk_indices_base = row_lengths_base + rows memory_query_start_base = row_chunk_indices_base + rows row_memory_start_base = memory_query_start_base + rows row_memory_length_base = row_memory_start_base + rows local_positions_base = row_memory_length_base + rows query_positions_base = local_positions_base + target_tokens eoc_base = query_positions_base + target_tokens memory_positions_base = eoc_base + rows * LOCAL_SLOTS row_token_memory_length_base = memory_positions_base + rows * GLOBAL_SLOTS row_exact_start_base = row_token_memory_length_base + rows row_exact_length_base = row_exact_start_base + rows row_exact_delta_base = row_exact_length_base + rows row_compressed_delta_base = row_exact_delta_base + rows canonical_order_base = row_compressed_delta_base + rows logical_order_base = canonical_order_base + target_tokens canonical_positions_base = logical_order_base + target_tokens canonical_key_positions_base = canonical_positions_base + target_tokens token_row_ids_base = canonical_key_positions_base + target_tokens q_tile_rows_base = token_row_ids_base + target_tokens q_tile_starts_base = q_tile_rows_base + q_tile_capacity token_owner_rows_base = q_tile_starts_base + q_tile_capacity token_owner_starts_base = token_owner_rows_base + token_tile_capacity memory_union_start_base = token_owner_starts_base + token_tile_capacity memory_union_end_base = memory_union_start_base + memory_tile_count memory_interior_start_base = memory_union_end_base + memory_tile_count memory_interior_end_base = memory_interior_start_base + memory_tile_count q_tile_counter_base = memory_interior_end_base + memory_tile_count token_owner_counter_base = q_tile_counter_base + 1 validation_result_base = token_owner_counter_base + 1 invalid_value = -1 tl.store( storage_ptr + row_offsets_base + row, tl.where(row_valid, target_offset, invalid_value), mask=row_mask, ) tl.store( storage_ptr + row_lengths_base + row, tl.where(row_valid, target_length, invalid_value), mask=row_mask, ) tl.store( storage_ptr + row_chunk_indices_base + row, tl.where(row_valid, chunk_index, invalid_value), mask=row_mask, ) tl.store( storage_ptr + memory_query_start_base + row, tl.where(row_valid, lexical_length, invalid_value), mask=row_mask, ) scaled_memory_start = physical_memory_start // PHYSICAL_SLOTS * GLOBAL_SLOTS scaled_memory_length = physical_memory_length // PHYSICAL_SLOTS * GLOBAL_SLOTS tl.store( storage_ptr + row_memory_start_base + row, tl.where(row_valid, scaled_memory_start, invalid_value), mask=row_mask, ) tl.store( storage_ptr + row_memory_length_base + row, tl.where(row_valid, scaled_memory_length, invalid_value), mask=row_mask, ) tl.store( storage_ptr + row_token_memory_length_base + row, tl.where(row_valid, scaled_memory_length, invalid_value), mask=row_mask, ) tl.store( storage_ptr + row_exact_start_base + row, tl.where(row_valid, previous_target_offset, invalid_value), mask=row_mask, ) previous_exact_chunks = tl.minimum(chunk_index, 1) exact_length = previous_exact_chunks * CHUNK_SIZE exact_delta = tl.where(chunk_index == 0, 0, tl.where(chunk_index == 1, 1, CHUNK_SIZE)) tl.store( storage_ptr + row_exact_length_base + row, tl.where(row_valid, exact_length, invalid_value), mask=row_mask, ) tl.store( storage_ptr + row_exact_delta_base + row, tl.where(row_valid, exact_delta, invalid_value), mask=row_mask, ) tl.store( storage_ptr + row_compressed_delta_base + row, tl.where(row_valid, 0, invalid_value), mask=row_mask, ) target_position_mask = row_valid & (position < target_length) logical_index = target_offset + position local_base = chunk_index - previous_exact_chunks + previous_exact_chunks * CHUNK_SIZE query_position = local_base + position local_position = tl.where( position >= lexical_length, local_base + lexical_length, query_position ) lexical_index = physical_offset - row * PHYSICAL_SLOTS + position canonical_index = tl.where( position < lexical_length, lexical_index, total_lexical_tokens + row * LOCAL_SLOTS + position - lexical_length, ) tl.store( storage_ptr + row_pos_to_flat_base + logical_index, logical_index, mask=target_position_mask, ) tl.store( storage_ptr + local_positions_base + logical_index, local_position, mask=target_position_mask, ) tl.store( storage_ptr + query_positions_base + logical_index, query_position, mask=target_position_mask, ) tl.store( storage_ptr + canonical_order_base + canonical_index, logical_index, mask=target_position_mask, ) tl.store( storage_ptr + logical_order_base + logical_index, canonical_index, mask=target_position_mask, ) tl.store( storage_ptr + canonical_positions_base + canonical_index, query_position, mask=target_position_mask, ) tl.store( storage_ptr + canonical_key_positions_base + canonical_index, local_position, mask=target_position_mask, ) tl.store(storage_ptr + token_row_ids_base + canonical_index, row, mask=target_position_mask) lexical_q_tiles = (lexical_length + BLOCK_Q - 1) // BLOCK_Q tail_q_tiles = (LOCAL_SLOTS + BLOCK_Q - 1) // BLOCK_Q row_q_tiles = lexical_q_tiles + tail_q_tiles q_tile_offset = ( tl.atomic_add(storage_ptr + q_tile_counter_base, row_q_tiles, mask=row_valid) - 1 ) q_tile_mask = row_valid & (position < row_q_tiles) q_start = tl.where( position < lexical_q_tiles, position * BLOCK_Q, lexical_length + (position - lexical_q_tiles) * BLOCK_Q, ) tl.store(storage_ptr + q_tile_rows_base + q_tile_offset + position, row, mask=q_tile_mask) tl.store( storage_ptr + q_tile_starts_base + q_tile_offset + position, q_start, mask=q_tile_mask ) row_token_tiles = (target_length + BLOCK_K_TOKEN - 1) // BLOCK_K_TOKEN token_tile_offset = ( tl.atomic_add(storage_ptr + token_owner_counter_base, row_token_tiles, mask=row_valid) - 1 ) token_tile_mask = row_valid & (position < row_token_tiles) tl.store( storage_ptr + token_owner_rows_base + token_tile_offset + position, row, mask=token_tile_mask, ) tl.store( storage_ptr + token_owner_starts_base + token_tile_offset + position, position * BLOCK_K_TOKEN, mask=token_tile_mask, ) local_tail_mask = row_valid & (position < LOCAL_SLOTS) tail_index = row * LOCAL_SLOTS + position tl.store( storage_ptr + eoc_base + tail_index, target_offset + lexical_length + position, mask=local_tail_mask, ) global_tail_mask = row_valid & (position < GLOBAL_SLOTS) global_index = row * GLOBAL_SLOTS + position tl.store( storage_ptr + memory_positions_base + global_index, chunk_index, mask=global_tail_mask ) memory_tile = tl.program_id(0) q_lane = tl.arange(0, BLOCK_MEMORY_QUERY) q_token = memory_tile * BLOCK_MEMORY_QUERY + q_lane q_valid = (memory_tile < memory_tile_count) & (q_token < target_tokens) search_low = tl.zeros((BLOCK_MEMORY_QUERY,), tl.int64) search_high = search_low + rows for _ in tl.static_range(0, 32): candidate = (search_low + search_high) // 2 candidate_valid = (search_low < search_high) & (candidate < rows) candidate_physical_offset = tl.load( physical_row_offsets_ptr + candidate, mask=q_valid & candidate_valid, other=0 ).to(tl.int64) candidate_lexical_offset = candidate_physical_offset - candidate * PHYSICAL_SLOTS search_right = q_valid & candidate_valid & (q_token >= candidate_lexical_offset) search_low = tl.where(search_right, candidate + 1, search_low) search_high = tl.where(candidate_valid & ~search_right, candidate, search_high) lexical_row = tl.maximum(search_low - 1, 0) tail_row = (q_token - total_lexical_tokens) // LOCAL_SLOTS query_row = tl.where(q_token < total_lexical_tokens, lexical_row, tail_row) query_row_valid = q_valid & (query_row >= 0) & (query_row < rows) if TRUSTED_FIXED: query_chunk = tl.load( expected_row_geometry_ptr + rows + query_row, mask=query_row_valid, other=0 ).to(tl.int64) query_memory_chunks = tl.minimum(query_chunk, MAX_MEMORY_SIZE - 1) query_memory_start = (query_row - query_memory_chunks) * GLOBAL_SLOTS query_memory_length = query_memory_chunks * GLOBAL_SLOTS else: query_physical_memory_start = tl.load( physical_memory_start_ptr + query_row, mask=query_row_valid, other=0 ).to(tl.int64) query_physical_memory_length = tl.load( physical_memory_length_ptr + query_row, mask=query_row_valid, other=0 ).to(tl.int64) query_memory_start = query_physical_memory_start // PHYSICAL_SLOTS * GLOBAL_SLOTS query_memory_length = query_physical_memory_length // PHYSICAL_SLOTS * GLOBAL_SLOTS query_memory_length = tl.where( q_token < total_lexical_tokens, tl.maximum(query_memory_length - GLOBAL_SLOTS, 0), query_memory_length, ) has_query_memory = query_row_valid & (query_memory_length > 0) any_query_memory = tl.sum(has_query_memory.to(tl.int32), axis=0) > 0 union_start = tl.min(tl.where(has_query_memory, query_memory_start, 2147483647), axis=0) union_end = tl.max( tl.where(has_query_memory, query_memory_start + query_memory_length, 0), axis=0 ) common_start = tl.max(tl.where(has_query_memory, query_memory_start, 0), axis=0) common_end = tl.min( tl.where(has_query_memory, query_memory_start + query_memory_length, 2147483647), axis=0 ) union_start = tl.where(any_query_memory, union_start, 0) union_end = tl.where(any_query_memory, union_end, 0) common_start = tl.where(any_query_memory, common_start, 0) common_end = tl.where(any_query_memory, common_end, 0) start_delta = tl.maximum(common_start - union_start, 0) end_delta = tl.maximum(common_end - union_start, 0) aligned_start = ( union_start + (start_delta + BLOCK_K_MEMORY - 1) // BLOCK_K_MEMORY * BLOCK_K_MEMORY ) aligned_end = union_start + end_delta // BLOCK_K_MEMORY * BLOCK_K_MEMORY has_interior = aligned_start < aligned_end interior_start = tl.where(has_interior, aligned_start, union_end) interior_end = tl.where(has_interior, aligned_end, union_end) memory_tile_mask = memory_tile < memory_tile_count tl.store( storage_ptr + memory_union_start_base + memory_tile, union_start, mask=memory_tile_mask ) tl.store( storage_ptr + memory_union_end_base + memory_tile, union_end, mask=memory_tile_mask ) tl.store( storage_ptr + memory_interior_start_base + memory_tile, interior_start, mask=memory_tile_mask, ) tl.store( storage_ptr + memory_interior_end_base + memory_tile, interior_end, mask=memory_tile_mask, ) tl.atomic_xchg(storage_ptr + validation_result_base, 0, mask=row_mask & ~row_valid) @triton.jit def _pat_rotate_rows( x, cosine, sine, BLOCK_M: tl.constexpr, BLOCK_D: tl.constexpr, FP32_PRODUCTS: tl.constexpr = False, ): if FP32_PRODUCTS: source = x.to(tl.float32) cosine, sine = (cosine.to(tl.float32), sine.to(tl.float32)) pairs = tl.reshape(source, (BLOCK_M, BLOCK_D // 2, 2)) even, odd = tl.split(pairs) quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_M, BLOCK_D)) return tl.fma(quarter_turn, sine, source * cosine).to(x.dtype) else: pairs = tl.reshape(x, (BLOCK_M, BLOCK_D // 2, 2)) even, odd = tl.split(pairs) quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_M, BLOCK_D)) return x * cosine + quarter_turn * sine @triton.jit def _pat_canonical_token_index( row, row_offset, row_position, lexical_length, total_lexical_tokens, local_tail_slots ): """Map one logical row position into [all lexical][all local tails].""" lexical_index = row_offset - row * local_tail_slots + row_position tail_index = total_lexical_tokens + row * local_tail_slots + row_position - lexical_length return tl.where(row_position < lexical_length, lexical_index, tail_index) @triton.jit def _pat_logical_query_from_canonical( q_token, row, row_offset, lexical_length, total_lexical_tokens, local_tail_slots ): """Recover logical packed-row coordinates from a physical query index.""" lexical_start = row_offset - row * local_tail_slots lexical_position = q_token - lexical_start tail_position = q_token - total_lexical_tokens - row * local_tail_slots q_pos = tl.where( q_token < total_lexical_tokens, lexical_position, lexical_length + tail_position ) return (row_offset + q_pos, q_pos) @triton.jit def _pat_online_step(q, k, v, valid, has_key, m, denominator, output, qk_scale): scores = tl.dot(q, k, input_precision="ieee") * qk_scale scores = tl.where(valid, scores, -float("inf")) tile_max = tl.max(scores, axis=1) next_m = tl.where(has_key, tl.maximum(m, tile_max), m) alpha = tl.where(has_key, tl.exp2(m - next_m), 1.0) probability = tl.where(valid, tl.exp2(scores - next_m[:, None]), 0.0) output = output * alpha[:, None] + tl.dot( probability.to(v.dtype), v, input_precision="ieee" ) denominator = denominator * alpha + tl.sum(probability, axis=1) return (next_m, denominator, output) @triton.jit def _pat_memory_forward_tile( q_memory, k_memory_ptr, v_memory_ptr, memory_tile_start, memory_start, memory_length, has_memory, union_end, m, denominator, output, qk_scale, memory_slots, head, heads, head_dim, offs_k, offs_d, d_mask, FULL_INTERIOR: tl.constexpr, ): """Process one original K tile, specializing its shared interior.""" k_abs = memory_tile_start + offs_k if FULL_INTERIOR: k = tl.load( k_memory_ptr + k_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None], other=0.0, ) v = tl.load( v_memory_ptr + k_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=d_mask[None, :], other=0.0, ) valid = has_memory[:, None] has_key = has_memory else: k_mask = (k_abs < union_end) & (k_abs < memory_slots) k = tl.load( k_memory_ptr + k_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & k_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + k_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=k_mask[:, None] & d_mask[None, :], other=0.0, ) memory_end = memory_start + memory_length valid = ( has_memory[:, None] & k_mask[None, :] & (k_abs[None, :] >= memory_start[:, None]) & (k_abs[None, :] < memory_end[:, None]) ) tile_end = tl.minimum(memory_tile_start + offs_k.shape[0], union_end) has_key = has_memory & (memory_start < tile_end) & (memory_end > memory_tile_start) return _pat_online_step(q_memory, k, v, valid, has_key, m, denominator, output, qk_scale) @triton.jit( do_not_specialize=("total_lexical_tokens",), do_not_specialize_on_alignment=("total_lexical_tokens",), ) def _pat_token_forward_kernel( q_ptr, k_token_ptr, v_token_ptr, out_ptr, lse_ptr, row_offsets_ptr, row_lengths_ptr, memory_query_start_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, phase_cos_ptr, phase_sin_ptr, q_tile_rows_ptr, q_tile_starts_ptr, total_lexical_tokens, local_tail_slots, scale, heads, head_dim, BLOCK_Q: tl.constexpr, BLOCK_K_TOKEN: tl.constexpr, BLOCK_D: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): tile = tl.program_id(0) head = tl.program_id(1) row = tl.load(q_tile_rows_ptr + tile) q_start = tl.load(q_tile_starts_ptr + tile) row_offset = tl.load(row_offsets_ptr + row) row_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) query_is_eoc = q_start >= lexical_length offs_q = tl.arange(0, BLOCK_Q) offs_d = tl.arange(0, BLOCK_D) q_pos = q_start + offs_q q_mask = (q_pos < row_length) & tl.where( query_is_eoc, q_pos >= lexical_length, q_pos < lexical_length ) d_mask = offs_d < head_dim q_flat = row_offset + q_pos q_token = _pat_canonical_token_index( row, row_offset, q_pos, lexical_length, total_lexical_tokens, local_tail_slots ) q = tl.load( q_ptr + q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=q_mask[:, None] & d_mask[None, :], other=0.0, ) m = tl.full((BLOCK_Q,), -float("inf"), tl.float32) denominator = tl.zeros((BLOCK_Q,), tl.float32) output = tl.zeros((BLOCK_Q, BLOCK_D), tl.float32) qk_scale = scale * 1.4426950408889634 offs_kt = tl.arange(0, BLOCK_K_TOKEN) local_stop = tl.where( query_is_eoc, row_length, tl.minimum(lexical_length, q_start + BLOCK_Q) ) local_start = 0 while local_start < local_stop: local_pos = local_start + offs_kt local_token = _pat_canonical_token_index( row, row_offset, local_pos, lexical_length, total_lexical_tokens, local_tail_slots ) local_mask = local_pos < local_stop k = tl.load( k_token_ptr + local_token[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & local_mask[None, :], other=0.0, ) v = tl.load( v_token_ptr + local_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) visible = query_is_eoc | (local_pos[None, :] <= q_pos[:, None]) valid = q_mask[:, None] & local_mask[None, :] & visible m, denominator, output = _pat_online_step( q, k, v, valid, q_mask, m, denominator, output, qk_scale ) local_start += BLOCK_K_TOKEN exact_start = tl.load(row_exact_start_ptr + row) exact_length = tl.where(query_is_eoc, 0, tl.load(row_exact_length_ptr + row)) exact_delta = tl.load(row_exact_delta_ptr + row) exact_phase_offset = exact_delta * BLOCK_D + offs_d table_cosine = tl.load(phase_cos_ptr + exact_phase_offset, mask=d_mask, other=1.0) table_sine = tl.load(phase_sin_ptr + exact_phase_offset, mask=d_mask, other=0.0) has_exact_phase = exact_delta != 0 exact_cosine = tl.where(has_exact_phase, table_cosine, 1.0) exact_sine = tl.where(has_exact_phase, -table_sine, 0.0) q_exact = _pat_rotate_rows( q, exact_cosine[None, :].to(q.dtype), exact_sine[None, :].to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) exact_offset_start = (q_start + 1) // BLOCK_K_TOKEN * BLOCK_K_TOKEN exact_source_row = tl.maximum(row - 1, 0) while exact_offset_start < exact_length: exact_offset = exact_offset_start + offs_kt exact_token = exact_start - exact_source_row * local_tail_slots + exact_offset exact_mask = exact_offset < exact_length k = tl.load( k_token_ptr + exact_token[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & exact_mask[None, :], other=0.0, ) v = tl.load( v_token_ptr + exact_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) valid = q_mask[:, None] & exact_mask[None, :] & (exact_offset[None, :] > q_pos[:, None]) exact_tile_stop = tl.minimum(exact_offset_start + BLOCK_K_TOKEN, exact_length) has_exact_key = q_mask & (q_pos + 1 < exact_tile_stop) m, denominator, output = _pat_online_step( q_exact, k, v, valid, has_exact_key, m, denominator, output, qk_scale ) exact_offset_start += BLOCK_K_TOKEN safe_denominator = tl.where(q_mask, denominator, 1.0) normalized = output / safe_denominator[:, None] lse = tl.where(q_mask, m + tl.log2(safe_denominator), 0.0) tl.store( out_ptr + q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], normalized, mask=q_mask[:, None] & d_mask[None, :], ) tl.store(lse_ptr + q_flat * heads + head, lse, mask=q_mask) @triton.jit( do_not_specialize=("total_lexical_tokens", "memory_slots"), do_not_specialize_on_alignment=("total_lexical_tokens", "memory_slots"), ) def _pat_newest_forward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, token_out_ptr, lse_ptr, row_offsets_ptr, memory_query_start_ptr, row_memory_start_ptr, row_memory_length_ptr, phase_cos_ptr, phase_sin_ptr, total_lexical_tokens, local_tail_slots, scale, memory_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_D: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): """Merge newest memory into lexical seed tiles owned by one row/head.""" row = tl.program_id(0) head = tl.program_id(1) row_offset = tl.load(row_offsets_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) offs_k = tl.arange(0, BLOCK_K) offs_d = tl.arange(0, BLOCK_D) d_mask = offs_d < head_dim memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.load(row_memory_length_ptr + row) has_newest_memory = memory_length >= GLOBAL_SLOTS newest_start = memory_start + memory_length - GLOBAL_SLOTS newest_phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d newest_cosine = tl.load(phase_cos_ptr + newest_phase_offset, mask=d_mask, other=1.0) newest_sine = tl.load(phase_sin_ptr + newest_phase_offset, mask=d_mask, other=0.0) qk_scale = scale * 1.4426950408889634 q_start = 0 while q_start < lexical_length: offs_q = tl.arange(0, BLOCK_Q) q_pos = q_start + offs_q q_mask = (q_pos < lexical_length) & has_newest_memory q_flat = row_offset + q_pos q_token = _pat_canonical_token_index( row, row_offset, q_pos, lexical_length, total_lexical_tokens, local_tail_slots ) token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :] q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0) output = tl.load( token_out_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0 ).to(tl.float32) seed_lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to( tl.float32 ) m = tl.where(q_mask, seed_lse, -float("inf")) denominator = tl.where(q_mask, 1.0, 0.0).to(tl.float32) q_newest = _pat_rotate_rows( q, newest_cosine[None, :].to(q.dtype), newest_sine[None, :].to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) newest_offset_start = 0 while newest_offset_start < GLOBAL_SLOTS: newest_offset = newest_offset_start + offs_k newest_abs = newest_start + newest_offset newest_mask = ( has_newest_memory & (newest_offset < GLOBAL_SLOTS) & (newest_abs < memory_slots) ) newest_k = tl.load( k_memory_ptr + newest_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & newest_mask[None, :], other=0.0, ) newest_v = tl.load( v_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) newest_valid = q_mask[:, None] & newest_mask[None, :] m, denominator, output = _pat_online_step( q_newest, newest_k, newest_v, newest_valid, q_mask, m, denominator, output, qk_scale, ) newest_offset_start += BLOCK_K safe_denominator = tl.where(q_mask, denominator, 1.0) normalized = output / safe_denominator[:, None] final_lse = tl.where(q_mask, m + tl.log2(safe_denominator), 0.0) tl.store( token_out_ptr + token_offsets, normalized, mask=q_mask[:, None] & d_mask[None, :] ) tl.store(lse_ptr + q_flat * heads + head, final_lse, mask=q_mask) q_start += BLOCK_Q @triton.jit( do_not_specialize=("total_lexical_tokens", "tokens", "memory_slots"), do_not_specialize_on_alignment=("total_lexical_tokens", "tokens", "memory_slots"), ) def _pat_memory_forward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, token_out_ptr, out_ptr, lse_ptr, row_offsets_ptr, memory_query_start_ptr, row_memory_start_ptr, row_memory_length_ptr, phase_cos_ptr, phase_sin_ptr, token_row_ids_ptr, memory_tile_union_start_ptr, memory_tile_union_end_ptr, memory_tile_interior_start_ptr, memory_tile_interior_end_ptr, total_lexical_tokens, local_tail_slots, scale, tokens, memory_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_D: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): """Merge exact per-query compressed memory into token-only seed state.""" tile = tl.program_id(0) head = tl.program_id(1) offs_q = tl.arange(0, BLOCK_Q) offs_k = tl.arange(0, BLOCK_K) offs_d = tl.arange(0, BLOCK_D) q_token = tile * BLOCK_Q + offs_q q_mask = q_token < tokens row = tl.load(token_row_ids_ptr + q_token, mask=q_mask, other=0) row_offset = tl.load(row_offsets_ptr + row, mask=q_mask, other=0) lexical_length = tl.load(memory_query_start_ptr + row, mask=q_mask, other=0) q_flat, q_pos = _pat_logical_query_from_canonical( q_token, row, row_offset, lexical_length, total_lexical_tokens, local_tail_slots ) query_is_eoc = q_pos >= lexical_length d_mask = offs_d < head_dim token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :] q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0) phase_row = tl.where(query_is_eoc, CHUNK_SIZE - 1, tl.minimum(q_pos, CHUNK_SIZE - 1)) phase_offset = phase_row[:, None] * BLOCK_D + offs_d[None, :] cosine = tl.load( phase_cos_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=1.0 ) sine = tl.load( phase_sin_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=0.0 ) q_memory = _pat_rotate_rows( q, cosine.to(q.dtype), sine.to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) output = tl.load( token_out_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0 ).to(tl.float32) seed_lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(tl.float32) m = tl.where(q_mask, seed_lse, -float("inf")) denominator = tl.where(q_mask, 1.0, 0.0).to(tl.float32) qk_scale = scale * 1.4426950408889634 memory_start = tl.load(row_memory_start_ptr + row, mask=q_mask, other=0) memory_length = tl.load(row_memory_length_ptr + row, mask=q_mask, other=0) if GLOBAL_SLOTS > 0: memory_length = tl.where( query_is_eoc, memory_length, tl.maximum(memory_length - GLOBAL_SLOTS, 0) ) has_memory = q_mask & (memory_length > 0) union_start = tl.load(memory_tile_union_start_ptr + tile) union_end = tl.load(memory_tile_union_end_ptr + tile) interior_start = tl.load(memory_tile_interior_start_ptr + tile) interior_end = tl.load(memory_tile_interior_end_ptr + tile) memory_tile_start = union_start while memory_tile_start < interior_start: m, denominator, output = _pat_memory_forward_tile( q_memory, k_memory_ptr, v_memory_ptr, memory_tile_start, memory_start, memory_length, has_memory, union_end, m, denominator, output, qk_scale, memory_slots, head, heads, head_dim, offs_k, offs_d, d_mask, FULL_INTERIOR=False, ) memory_tile_start += BLOCK_K memory_tile_start = interior_start while memory_tile_start < interior_end: m, denominator, output = _pat_memory_forward_tile( q_memory, k_memory_ptr, v_memory_ptr, memory_tile_start, memory_start, memory_length, has_memory, union_end, m, denominator, output, qk_scale, memory_slots, head, heads, head_dim, offs_k, offs_d, d_mask, FULL_INTERIOR=True, ) memory_tile_start += BLOCK_K memory_tile_start = interior_end while memory_tile_start < union_end: m, denominator, output = _pat_memory_forward_tile( q_memory, k_memory_ptr, v_memory_ptr, memory_tile_start, memory_start, memory_length, has_memory, union_end, m, denominator, output, qk_scale, memory_slots, head, heads, head_dim, offs_k, offs_d, d_mask, FULL_INTERIOR=False, ) memory_tile_start += BLOCK_K safe_denominator = tl.where(q_mask, denominator, 1.0) normalized = output / safe_denominator[:, None] final_lse = tl.where(q_mask, m + tl.log2(safe_denominator), 0.0) tl.store(out_ptr + token_offsets, normalized, mask=q_mask[:, None] & d_mask[None, :]) tl.store(lse_ptr + q_flat * heads + head, final_lse, mask=q_mask) @triton.jit( do_not_specialize=("total_lexical_tokens", "tokens"), do_not_specialize_on_alignment=("total_lexical_tokens", "tokens"), ) def _pat_delta_kernel( out_ptr, do_ptr, delta_ptr, row_offsets_ptr, memory_query_start_ptr, token_row_ids_ptr, total_lexical_tokens, local_tail_slots, tokens, heads, head_dim, BLOCK_Q: tl.constexpr, BLOCK_D: tl.constexpr, ): tile = tl.program_id(0) head = tl.program_id(1) q_token = tile * BLOCK_Q + tl.arange(0, BLOCK_Q) offs_d = tl.arange(0, BLOCK_D) q_mask = q_token < tokens row = tl.load(token_row_ids_ptr + q_token, mask=q_mask, other=0) row_offset = tl.load(row_offsets_ptr + row, mask=q_mask, other=0) lexical_length = tl.load(memory_query_start_ptr + row, mask=q_mask, other=0) q_flat, _ = _pat_logical_query_from_canonical( q_token, row, row_offset, lexical_length, total_lexical_tokens, local_tail_slots ) mask = q_mask[:, None] & (offs_d[None, :] < head_dim) offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :] output = tl.load(out_ptr + offsets, mask=mask, other=0.0).to(tl.float32) gradient = tl.load(do_ptr + offsets, mask=mask, other=0.0).to(tl.float32) value = tl.sum(output * gradient, axis=1) tl.store(delta_ptr + q_flat * heads + head, value, mask=q_mask) @triton.jit def _pat_five_dot_edge(q, k, v, do, lse, delta, valid, scale): """All five backward matrix products for one visible Q/K tile edge.""" scores = tl.dot(q, k, input_precision="ieee") * (scale * 1.4426950408889634) probability = tl.where(valid, tl.exp2(scores - lse[:, None]), 0.0) probability_gradient = tl.dot(do, tl.trans(v), input_precision="ieee") score_gradient = tl.where(valid, probability * (probability_gradient - delta[:, None]), 0.0) dq = tl.dot(score_gradient.to(k.dtype), tl.trans(k), input_precision="ieee") * scale dk = tl.dot(tl.trans(score_gradient.to(q.dtype)), q, input_precision="ieee") * scale dv = tl.dot(tl.trans(probability.to(do.dtype)), do, input_precision="ieee") return (dq, dk, dv) @triton.jit def _pat_atomic_dq(dq_accum_ptr, dq, q_token, q_mask, offs_d, d_mask, head, heads, head_dim): offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :] tl.atomic_add(dq_accum_ptr + offsets, dq, mask=q_mask[:, None] & d_mask[None, :]) @triton.jit( do_not_specialize=("total_lexical_tokens", "tokens", "memory_slots"), do_not_specialize_on_alignment=("total_lexical_tokens", "tokens", "memory_slots"), ) def _pat_memory_query_owner_backward_kernel( dk_descriptor, dv_descriptor, q_ptr, k_memory_ptr, v_memory_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, row_offsets_ptr, memory_query_start_ptr, phase_cos_ptr, phase_sin_ptr, token_row_ids_ptr, memory_tile_union_start_ptr, memory_tile_union_end_ptr, total_lexical_tokens, local_tail_slots, row_memory_start_ptr, row_memory_length_ptr, scale, tokens, memory_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_D: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): tile = tl.program_id(0) head = tl.program_id(1) offs_q = tl.arange(0, BLOCK_Q) offs_k = tl.arange(0, BLOCK_K) offs_d = tl.arange(0, BLOCK_D) q_token = tile * BLOCK_Q + offs_q q_mask = q_token < tokens row = tl.load(token_row_ids_ptr + q_token, mask=q_mask, other=0) row_offset = tl.load(row_offsets_ptr + row, mask=q_mask, other=0) lexical_length = tl.load(memory_query_start_ptr + row, mask=q_mask, other=0) q_flat, q_pos = _pat_logical_query_from_canonical( q_token, row, row_offset, lexical_length, total_lexical_tokens, local_tail_slots ) query_is_eoc = q_pos >= lexical_length d_mask = offs_d < head_dim token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :] q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0) do = tl.load(do_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0) lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(tl.float32) saved_delta = tl.load(delta_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to( tl.float32 ) memory_start = tl.load(row_memory_start_ptr + row, mask=q_mask, other=0) memory_length = tl.load(row_memory_length_ptr + row, mask=q_mask, other=0) if GLOBAL_SLOTS > 0: memory_length = tl.where( query_is_eoc, memory_length, tl.maximum(memory_length - GLOBAL_SLOTS, 0) ) phase_row = tl.where(query_is_eoc, CHUNK_SIZE - 1, tl.minimum(q_pos, CHUNK_SIZE - 1)) phase_offset = phase_row[:, None] * BLOCK_D + offs_d[None, :] cosine = tl.load( phase_cos_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=1.0 ) sine = tl.load( phase_sin_ptr + phase_offset, mask=q_mask[:, None] & d_mask[None, :], other=0.0 ) transformed_q = _pat_rotate_rows( q, cosine.to(q.dtype), sine.to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) has_memory = q_mask & (memory_length > 0) union_start = tl.load(memory_tile_union_start_ptr + tile) union_end = tl.load(memory_tile_union_end_ptr + tile) union_count = union_end - union_start descriptor_start = union_start.to(tl.int32) descriptor_count = union_count.to(tl.int32) transformed_dq = tl.zeros((BLOCK_Q, BLOCK_D), tl.float32) memory_tile_start = union_start while memory_tile_start < union_end: k_abs = memory_tile_start + offs_k k_mask = (k_abs < union_end) & (k_abs < memory_slots) k = tl.load( k_memory_ptr + k_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & k_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + k_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=k_mask[:, None] & d_mask[None, :], other=0.0, ) valid = ( has_memory[:, None] & k_mask[None, :] & (k_abs[None, :] >= memory_start[:, None]) & (k_abs[None, :] < memory_start[:, None] + memory_length[:, None]) ) scores = tl.dot(transformed_q, k, input_precision="ieee") * (scale * 1.4426950408889634) probability = tl.where(valid, tl.exp2(scores - lse[:, None]), 0.0) probability_gradient = tl.dot(do, tl.trans(v), input_precision="ieee") score_gradient = tl.where( valid, probability * (probability_gradient - saved_delta[:, None]), 0.0 ) transformed_dq += ( tl.dot(score_gradient.to(k.dtype), tl.trans(k), input_precision="ieee") * scale ) dk = ( tl.dot( tl.trans(score_gradient.to(transformed_q.dtype)), transformed_q, input_precision="ieee", ) * scale ) atomic_add_ragged( dk_descriptor, descriptor_start, descriptor_count, [(memory_tile_start - union_start).to(tl.int32), head, 0], tl.reshape(dk, (BLOCK_K, 1, BLOCK_D)), ) dv = tl.dot(tl.trans(probability.to(do.dtype)), do, input_precision="ieee") atomic_add_ragged( dv_descriptor, descriptor_start, descriptor_count, [(memory_tile_start - union_start).to(tl.int32), head, 0], tl.reshape(dv, (BLOCK_K, 1, BLOCK_D)), ) memory_tile_start += BLOCK_K original_dq = _pat_rotate_rows( transformed_dq, cosine.to(transformed_dq.dtype), -sine.to(transformed_dq.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) tl.store(dq_accum_ptr + token_offsets, original_dq, mask=q_mask[:, None] & d_mask[None, :]) @triton.jit def _pat_token_query_edge( q_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, k, v, k_abs, owner_local_pos, owner_k_mask, row, q_start, row_offsets_ptr, row_lengths_ptr, memory_query_start_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, phase_cos_ptr, phase_sin_ptr, total_lexical_tokens, local_tail_slots, scale, head, heads, head_dim, EXACT_LANE: tl.constexpr, EOC_QUERY: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_D: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): offs_q = tl.arange(0, BLOCK_Q) offs_d = tl.arange(0, BLOCK_D) q_pos = q_start + offs_q row_offset = tl.load(row_offsets_ptr + row) row_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) q_mask = (q_pos < row_length) & tl.where( EOC_QUERY, q_pos >= lexical_length, q_pos < lexical_length ) d_mask = offs_d < head_dim q_flat = row_offset + q_pos q_token = _pat_canonical_token_index( row, row_offset, q_pos, lexical_length, total_lexical_tokens, local_tail_slots ) token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :] q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0) do = tl.load(do_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0) lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(tl.float32) saved_delta = tl.load(delta_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to( tl.float32 ) if EXACT_LANE: exact_start = tl.load(row_exact_start_ptr + row) exact_length = tl.load(row_exact_length_ptr + row) exact_offset = k_abs - exact_start k_mask = owner_k_mask & (exact_offset >= 0) & (exact_offset < exact_length) valid = q_mask[:, None] & k_mask[None, :] & (exact_offset[None, :] > q_pos[:, None]) exact_delta = tl.load(row_exact_delta_ptr + row) exact_phase_offset = exact_delta * BLOCK_D + offs_d table_cosine = tl.load(phase_cos_ptr + exact_phase_offset, mask=d_mask, other=1.0) table_sine = tl.load(phase_sin_ptr + exact_phase_offset, mask=d_mask, other=0.0) has_exact_phase = exact_delta != 0 cosine = tl.where(has_exact_phase, table_cosine, 1.0) sine = tl.where(has_exact_phase, -table_sine, 0.0) transformed_q = _pat_rotate_rows( q, cosine[None, :].to(q.dtype), sine[None, :].to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) else: k_mask = owner_k_mask visible = EOC_QUERY | (owner_local_pos[None, :] <= q_pos[:, None]) valid = q_mask[:, None] & k_mask[None, :] & visible transformed_q = q dq, dk, dv = _pat_five_dot_edge(transformed_q, k, v, do, lse, saved_delta, valid, scale) if EXACT_LANE: original_dq = _pat_rotate_rows( dq, cosine[None, :].to(dq.dtype), -sine[None, :].to(dq.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) else: original_dq = dq _pat_atomic_dq( dq_accum_ptr, original_dq, q_token, q_mask, offs_d, d_mask, head, heads, head_dim ) return (dk, dv) @triton.jit def _pat_newest_memory_query_edge( q_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, k, v, memory_k_mask, row, q_start, row_offsets_ptr, lexical_length, phase_cos_ptr, phase_sin_ptr, total_lexical_tokens, local_tail_slots, scale, head, heads, head_dim, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_D: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): """Backward edge for the newest, locally positioned memory group.""" offs_q = tl.arange(0, BLOCK_Q) offs_d = tl.arange(0, BLOCK_D) q_pos = q_start + offs_q row_offset = tl.load(row_offsets_ptr + row) q_mask = q_pos < lexical_length d_mask = offs_d < head_dim q_flat = row_offset + q_pos q_token = _pat_canonical_token_index( row, row_offset, q_pos, lexical_length, total_lexical_tokens, local_tail_slots ) token_offsets = q_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :] q = tl.load(q_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0) do = tl.load(do_ptr + token_offsets, mask=q_mask[:, None] & d_mask[None, :], other=0.0) lse = tl.load(lse_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to(tl.float32) saved_delta = tl.load(delta_ptr + q_flat * heads + head, mask=q_mask, other=0.0).to( tl.float32 ) phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d cosine = tl.load(phase_cos_ptr + phase_offset, mask=d_mask, other=1.0) sine = tl.load(phase_sin_ptr + phase_offset, mask=d_mask, other=0.0) transformed_q = _pat_rotate_rows( q, cosine[None, :].to(q.dtype), sine[None, :].to(q.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) valid = q_mask[:, None] & memory_k_mask[None, :] transformed_dq, dk, dv = _pat_five_dot_edge( transformed_q, k, v, do, lse, saved_delta, valid, scale ) original_dq = _pat_rotate_rows( transformed_dq, cosine[None, :].to(transformed_dq.dtype), -sine[None, :].to(transformed_dq.dtype), BLOCK_M=BLOCK_Q, BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) _pat_atomic_dq( dq_accum_ptr, original_dq, q_token, q_mask, offs_d, d_mask, head, heads, head_dim ) return (dk, dv) @triton.jit( do_not_specialize=("total_lexical_tokens", "memory_slots"), do_not_specialize_on_alignment=("total_lexical_tokens", "memory_slots"), ) def _pat_newest_memory_owner_backward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, dk_memory_accum_ptr, dv_memory_accum_ptr, row_offsets_ptr, memory_query_start_ptr, row_memory_start_ptr, row_memory_length_ptr, phase_cos_ptr, phase_sin_ptr, total_lexical_tokens, local_tail_slots, scale, memory_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_D: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): """One row/head owner for the newest collapsed memory-group edge.""" row = tl.program_id(0) head = tl.program_id(1) lexical_length = tl.load(memory_query_start_ptr + row) memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.load(row_memory_length_ptr + row) owns_newest = memory_length >= GLOBAL_SLOTS newest_start = memory_start + memory_length - GLOBAL_SLOTS offs_k = tl.arange(0, BLOCK_K) offs_d = tl.arange(0, BLOCK_D) d_mask = offs_d < head_dim newest_offset_start = 0 while newest_offset_start < GLOBAL_SLOTS: newest_offset = newest_offset_start + offs_k newest_abs = newest_start + newest_offset newest_mask = owns_newest & (newest_offset < GLOBAL_SLOTS) & (newest_abs < memory_slots) newest_k = tl.load( k_memory_ptr + newest_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & newest_mask[None, :], other=0.0, ) newest_v = tl.load( v_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) newest_dk = tl.zeros((BLOCK_K, BLOCK_D), tl.float32) newest_dv = tl.zeros((BLOCK_K, BLOCK_D), tl.float32) newest_q_start = 0 newest_q_stop = tl.where(owns_newest, lexical_length, 0) while newest_q_start < newest_q_stop: edge_dk, edge_dv = _pat_newest_memory_query_edge( q_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, newest_k, newest_v, newest_mask, row, newest_q_start, row_offsets_ptr, lexical_length, phase_cos_ptr, phase_sin_ptr, total_lexical_tokens, local_tail_slots, scale, head, heads, head_dim, CHUNK_SIZE=CHUNK_SIZE, BLOCK_Q=BLOCK_Q, BLOCK_K=BLOCK_K, BLOCK_D=BLOCK_D, FP32_ROTARY_PRODUCTS=FP32_ROTARY_PRODUCTS, ) newest_dk += edge_dk newest_dv += edge_dv newest_q_start += BLOCK_Q newest_offsets = ( newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :] ) newest_store_mask = newest_mask[:, None] & d_mask[None, :] tl.atomic_add(dk_memory_accum_ptr + newest_offsets, newest_dk, mask=newest_store_mask) tl.atomic_add(dv_memory_accum_ptr + newest_offsets, newest_dv, mask=newest_store_mask) newest_offset_start += BLOCK_K @triton.jit( do_not_specialize=("total_lexical_tokens", "row_count"), do_not_specialize_on_alignment=("total_lexical_tokens", "row_count"), ) def _pat_token_owner_backward_kernel( q_ptr, k_token_ptr, v_token_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, dk_token_ptr, dv_token_ptr, row_offsets_ptr, row_lengths_ptr, memory_query_start_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, phase_cos_ptr, phase_sin_ptr, owner_rows_ptr, owner_starts_ptr, total_lexical_tokens, local_tail_slots, scale, row_count, heads, head_dim, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K: tl.constexpr, BLOCK_D: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): owner = tl.program_id(0) head = tl.program_id(1) row = tl.load(owner_rows_ptr + owner) k_start = tl.load(owner_starts_ptr + owner) row_offset = tl.load(row_offsets_ptr + row) row_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) offs_k = tl.arange(0, BLOCK_K) offs_d = tl.arange(0, BLOCK_D) local_pos = k_start + offs_k k_abs = row_offset + local_pos k_token = _pat_canonical_token_index( row, row_offset, local_pos, lexical_length, total_lexical_tokens, local_tail_slots ) k_mask = local_pos < row_length d_mask = offs_d < head_dim k = tl.load( k_token_ptr + k_token[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & k_mask[None, :], other=0.0, ) v = tl.load( v_token_ptr + k_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=k_mask[:, None] & d_mask[None, :], other=0.0, ) dk = tl.zeros((BLOCK_K, BLOCK_D), tl.float32) dv = tl.zeros((BLOCK_K, BLOCK_D), tl.float32) q_start = k_start // BLOCK_Q * BLOCK_Q while q_start < lexical_length: edge_dk, edge_dv = _pat_token_query_edge( q_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, k, v, k_abs, local_pos, k_mask, row, q_start, row_offsets_ptr, row_lengths_ptr, memory_query_start_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, phase_cos_ptr, phase_sin_ptr, total_lexical_tokens, local_tail_slots, scale, head, heads, head_dim, EXACT_LANE=False, EOC_QUERY=False, CHUNK_SIZE=CHUNK_SIZE, BLOCK_Q=BLOCK_Q, BLOCK_K=BLOCK_K, BLOCK_D=BLOCK_D, FP32_ROTARY_PRODUCTS=FP32_ROTARY_PRODUCTS, ) dk += edge_dk dv += edge_dv q_start += BLOCK_Q q_start = lexical_length while q_start < row_length: edge_dk, edge_dv = _pat_token_query_edge( q_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, k, v, k_abs, local_pos, k_mask, row, q_start, row_offsets_ptr, row_lengths_ptr, memory_query_start_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, phase_cos_ptr, phase_sin_ptr, total_lexical_tokens, local_tail_slots, scale, head, heads, head_dim, EXACT_LANE=False, EOC_QUERY=True, CHUNK_SIZE=CHUNK_SIZE, BLOCK_Q=BLOCK_Q, BLOCK_K=BLOCK_K, BLOCK_D=BLOCK_D, FP32_ROTARY_PRODUCTS=FP32_ROTARY_PRODUCTS, ) dk += edge_dk dv += edge_dv q_start += BLOCK_Q consumer = row + 1 has_consumer = consumer < row_count consumer_exact_start = tl.load(row_exact_start_ptr + consumer, mask=has_consumer, other=-1) consumer_exact_length = tl.load(row_exact_length_ptr + consumer, mask=has_consumer, other=0) owns_exact = ( has_consumer & (consumer_exact_start == row_offset) & (consumer_exact_length > k_start) ) consumer_lexical_length = tl.load( memory_query_start_ptr + consumer, mask=owns_exact, other=0 ) exact_q_stop = tl.minimum(consumer_lexical_length, k_start + BLOCK_K) q_start = 0 while owns_exact & (q_start < exact_q_stop): edge_dk, edge_dv = _pat_token_query_edge( q_ptr, lse_ptr, do_ptr, delta_ptr, dq_accum_ptr, k, v, k_abs, local_pos, k_mask, consumer, q_start, row_offsets_ptr, row_lengths_ptr, memory_query_start_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, phase_cos_ptr, phase_sin_ptr, total_lexical_tokens, local_tail_slots, scale, head, heads, head_dim, EXACT_LANE=True, EOC_QUERY=False, CHUNK_SIZE=CHUNK_SIZE, BLOCK_Q=BLOCK_Q, BLOCK_K=BLOCK_K, BLOCK_D=BLOCK_D, FP32_ROTARY_PRODUCTS=FP32_ROTARY_PRODUCTS, ) dk += edge_dk dv += edge_dv q_start += BLOCK_Q tl.store( dk_token_ptr + k_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], dk, mask=k_mask[:, None] & d_mask[None, :], ) tl.store( dv_token_ptr + k_token[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], dv, mask=k_mask[:, None] & d_mask[None, :], ) @triton.jit(do_not_specialize=("elements",), do_not_specialize_on_alignment=("elements",)) def _pat_cast_linear_kernel(accum_ptr, output_ptr, elements, BLOCK: tl.constexpr): offsets = tl.program_id(0) * BLOCK + tl.arange(0, BLOCK) valid = offsets < elements values = tl.load(accum_ptr + offsets, mask=valid, other=0.0) tl.store(output_ptr + offsets, values, mask=valid) class _PATFn(torch.autograd.Function): @staticmethod def forward( ctx: Any, q: torch.Tensor, k_memory: torch.Tensor, v_memory: torch.Tensor, k_token: torch.Tensor, v_token: torch.Tensor, row_offsets: torch.Tensor, row_lengths: torch.Tensor, memory_query_start: torch.Tensor, row_memory_start_abs: torch.Tensor, row_memory_length: torch.Tensor, row_token_memory_length: torch.Tensor, row_exact_start_abs: torch.Tensor, row_exact_length: torch.Tensor, row_exact_query_phase_delta: torch.Tensor, scale: float, plan: PATPlan, ) -> torch.Tensor: output = torch.empty_like(q) lse = torch.empty((int(q.size(0)), int(q.size(1))), device=q.device, dtype=torch.float32) config = plan.config block_dimension = _block_d(plan.head_dim) token_output = ( torch.empty(q.shape, device=q.device, dtype=torch.float32) if plan.memory_slots else output ) _pat_token_forward_kernel[plan.query_tiles, plan.heads]( q, k_token, v_token, token_output, lse, row_offsets, row_lengths, memory_query_start, row_exact_start_abs, row_exact_length, row_exact_query_phase_delta, plan.memory_phase_cos, plan.memory_phase_sin, plan.q_tile_rows, plan.q_tile_starts, plan.total_lexical_tokens, plan.local_tail_slots, float(scale), plan.heads, plan.head_dim, BLOCK_Q=int(config.block_q), BLOCK_K_TOKEN=int(config.block_k_token), BLOCK_D=block_dimension, num_warps=int(config.warps), num_stages=int(config.stages), FP32_ROTARY_PRODUCTS=True, ) if plan.memory_slots: _pat_newest_forward_kernel[plan.row_count, plan.heads]( q, k_memory, v_memory, token_output, lse, row_offsets, memory_query_start, row_memory_start_abs, row_memory_length, plan.memory_phase_cos, plan.memory_phase_sin, plan.total_lexical_tokens, plan.local_tail_slots, float(scale), plan.memory_slots, plan.heads, plan.head_dim, GLOBAL_SLOTS=int(plan.global_slots), CHUNK_SIZE=int(config.chunk_size), BLOCK_Q=int(config.block_q), BLOCK_K=int(config.block_k_token), BLOCK_D=block_dimension, num_warps=int(config.warps), num_stages=int(config.stages), FP32_ROTARY_PRODUCTS=True, ) memory_query_tiles = plan.memory_query_tiles _pat_memory_forward_kernel[memory_query_tiles, plan.heads]( q, k_memory, v_memory, token_output, output, lse, row_offsets, memory_query_start, row_memory_start_abs, row_memory_length, plan.memory_phase_cos, plan.memory_phase_sin, plan.token_row_ids, plan.memory_tile_union_start, plan.memory_tile_union_end, plan.memory_tile_interior_start, plan.memory_tile_interior_end, plan.total_lexical_tokens, plan.local_tail_slots, float(scale), plan.token_slots, plan.memory_slots, plan.heads, plan.head_dim, GLOBAL_SLOTS=int(plan.global_slots), CHUNK_SIZE=int(config.chunk_size), BLOCK_Q=_PAT_MEMORY_BLOCK_Q, BLOCK_K=int(config.block_k_memory), BLOCK_D=block_dimension, num_warps=_PAT_MEMORY_FORWARD_WARPS, num_stages=int(config.stages), FP32_ROTARY_PRODUCTS=True, ) ctx.save_for_backward( q, k_memory, v_memory, k_token, v_token, output, lse, row_offsets, row_lengths, memory_query_start, row_memory_start_abs, row_memory_length, row_token_memory_length, row_exact_start_abs, row_exact_length, row_exact_query_phase_delta, ) ctx.scale = float(scale) ctx.plan = plan return output @staticmethod def backward(ctx: Any, grad_output: torch.Tensor) -> tuple[Any, ...]: ( q, k_memory, v_memory, k_token, v_token, output, lse, row_offsets, row_lengths, memory_query_start, row_memory_start_abs, row_memory_length, _row_token_memory_length, row_exact_start_abs, row_exact_length, row_exact_query_phase_delta, ) = ctx.saved_tensors[:16] plan: PATPlan = ctx.plan config = plan.config block_dimension = _block_d(plan.head_dim) do = grad_output.contiguous() delta = torch.empty((plan.token_slots, plan.heads), device=q.device, dtype=torch.float32) delta_tiles = triton.cdiv(plan.token_slots, int(config.block_q)) _pat_delta_kernel[delta_tiles, plan.heads]( output, do, delta, row_offsets, memory_query_start, plan.token_row_ids, plan.total_lexical_tokens, plan.local_tail_slots, plan.token_slots, plan.heads, plan.head_dim, BLOCK_Q=int(config.block_q), BLOCK_D=block_dimension, num_warps=int(config.warps), num_stages=int(config.stages), ) dq_accum = ( torch.empty(q.shape, device=q.device, dtype=torch.float32) if plan.memory_slots else torch.zeros(q.shape, device=q.device, dtype=torch.float32) ) dk_memory = torch.empty_like(k_memory) dv_memory = torch.empty_like(v_memory) dk_token = torch.empty_like(k_token, dtype=k_token.dtype) dv_token = torch.empty_like(v_token) dk_memory_accum = torch.zeros(k_memory.shape, device=k_memory.device, dtype=torch.float32) dv_memory_accum = torch.zeros(v_memory.shape, device=v_memory.device, dtype=torch.float32) if plan.memory_slots: memory_query_tiles = plan.memory_query_tiles if memory_query_tiles: query_block_k = _memory_query_block_k(int(config.block_k_memory)) dk_descriptor = create_ragged_descriptor( dk_memory_accum, [query_block_k, 1, block_dimension] ) dv_descriptor = create_ragged_descriptor( dv_memory_accum, [query_block_k, 1, block_dimension] ) _pat_memory_query_owner_backward_kernel[memory_query_tiles, plan.heads]( dk_descriptor, dv_descriptor, q, k_memory, v_memory, lse, do, delta, dq_accum, row_offsets, memory_query_start, plan.memory_phase_cos, plan.memory_phase_sin, plan.token_row_ids, plan.memory_tile_union_start, plan.memory_tile_union_end, plan.total_lexical_tokens, plan.local_tail_slots, row_memory_start_abs, row_memory_length, float(ctx.scale), plan.token_slots, plan.memory_slots, plan.heads, plan.head_dim, GLOBAL_SLOTS=int(plan.global_slots), CHUNK_SIZE=int(config.chunk_size), BLOCK_Q=_PAT_MEMORY_BLOCK_Q, BLOCK_K=query_block_k, BLOCK_D=block_dimension, num_warps=_PAT_MEMORY_BACKWARD_WARPS, num_stages=int(config.stages), FP32_ROTARY_PRODUCTS=True, ) _pat_newest_memory_owner_backward_kernel[plan.row_count, plan.heads]( q, k_memory, v_memory, lse, do, delta, dq_accum, dk_memory_accum, dv_memory_accum, row_offsets, memory_query_start, row_memory_start_abs, row_memory_length, plan.memory_phase_cos, plan.memory_phase_sin, plan.total_lexical_tokens, plan.local_tail_slots, float(ctx.scale), plan.memory_slots, plan.heads, plan.head_dim, GLOBAL_SLOTS=int(plan.global_slots), CHUNK_SIZE=int(config.chunk_size), BLOCK_Q=int(config.block_q), BLOCK_K=int(config.block_k_token), BLOCK_D=block_dimension, num_warps=_PAT_TOKEN_BACKWARD_WARPS, num_stages=int(config.stages), FP32_ROTARY_PRODUCTS=True, ) if plan.token_tiles: _pat_token_owner_backward_kernel[plan.token_tiles, plan.heads]( q, k_token, v_token, lse, do, delta, dq_accum, dk_token, dv_token, row_offsets, row_lengths, memory_query_start, row_exact_start_abs, row_exact_length, row_exact_query_phase_delta, plan.memory_phase_cos, plan.memory_phase_sin, plan.token_owner_rows, plan.token_owner_starts, plan.total_lexical_tokens, plan.local_tail_slots, float(ctx.scale), plan.row_count, plan.heads, plan.head_dim, CHUNK_SIZE=int(config.chunk_size), BLOCK_Q=int(config.block_q), BLOCK_K=int(config.block_k_token), BLOCK_D=block_dimension, num_warps=_PAT_TOKEN_BACKWARD_WARPS, num_stages=int(config.stages), FP32_ROTARY_PRODUCTS=True, ) if plan.memory_slots: memory_elements = int(k_memory.numel()) cast_grid = (triton.cdiv(memory_elements, 256),) _pat_cast_linear_kernel[cast_grid]( dk_memory_accum, dk_memory, memory_elements, BLOCK=256, num_warps=4 ) _pat_cast_linear_kernel[cast_grid]( dv_memory_accum, dv_memory, memory_elements, BLOCK=256, num_warps=4 ) dq = torch.empty_like(q) elements = int(q.numel()) _pat_cast_linear_kernel[triton.cdiv(elements, 256),]( dq_accum, dq, elements, BLOCK=256, num_warps=4 ) return ( dq, dk_memory, dv_memory, dk_token, dv_token, None, None, None, None, None, None, None, None, None, None, None, ) def attention( *, q_canonical: torch.Tensor, k_memory: torch.Tensor, v_memory: torch.Tensor, k_token_canonical: torch.Tensor, v_token_canonical: torch.Tensor, scale: float, plan: PATPlan, ) -> torch.Tensor: """Launch the one canonical lexical-prefix/tail-suffix kernel core.""" return _PATFn.apply( q_canonical, k_memory, v_memory, k_token_canonical, v_token_canonical, plan.row_offsets, plan.row_lengths, plan.memory_query_start, plan.row_memory_start_abs, plan.row_memory_length, plan.row_token_memory_length, plan.row_exact_start_abs, plan.row_exact_length, plan.row_exact_query_phase_delta, float(scale), plan, ) @dataclass(frozen=True) class _PATLayoutKey: full: tuple[Any, ...] fixed: tuple[Any, ...] context: tuple[Any, ...] layer_zero: bool dynamic_local_slots: int | None dynamic_global_slots: int | None def _parse_pat_attention_layout_key(value: Any) -> _PATLayoutKey: """Parse the one exact key grammar emitted by packed production training.""" try: hash(value) except TypeError as exc: raise ValueError("PAT production planner key must be immutable and hashable") from exc if not isinstance(value, tuple): raise TypeError("PAT production planner key must be a tuple") full = value layer_zero = False root = value if len(root) == 2 and root[1] == "layer0_local_attention": layer_zero = True root = root[0] if not isinstance(root, tuple) or len(root) != 11 or root[1] != "token_level_context": raise ValueError( "PAT planner key must be exactly token_level_context, optionally wrapped once by layer0_local_attention" ) context = root base = context[0] dynamic_local_slots: int | None = None dynamic_global_slots: int | None = None if isinstance(base, tuple) and len(base) == 4 and (base[1] == "dynamic_memory"): dynamic_local_slots = _required_plain_int("dynamic local slots", base[2], minimum=1) dynamic_global_slots = _required_plain_int("dynamic global slots", base[3], minimum=1) base = base[0] if not isinstance(base, tuple) or len(base) != 10 or base[0] != "packed_training": raise ValueError("PAT planner key must terminate in exactly one packed_training key") return _PATLayoutKey( full=full, fixed=base, context=context, layer_zero=layer_zero, dynamic_local_slots=dynamic_local_slots, dynamic_global_slots=dynamic_global_slots, ) def _required_plain_int(name: str, value: Any, *, minimum: int = 0) -> int: if isinstance(value, bool) or not isinstance(value, int) or int(value) < minimum: raise ValueError(f"PAT trusted planner key requires {name} >= {minimum}; got {value!r}") return int(value) def _cached_fixed_row_geometry( *, fixed_key: tuple[Any, ...], lexical_lengths: Sequence[int], chunk_indices: Sequence[int], device: torch.device, ) -> torch.Tensor: """Cache the planner key's immutable per-row validator on its CUDA stream.""" stream = int(torch.cuda.current_stream(device).cuda_stream) key = (fixed_key, device, stream) with _PAT_FIXED_ROW_CACHE_LOCK: cached = _PAT_FIXED_ROW_CACHE.get(key) if cached is not None: _PAT_FIXED_ROW_CACHE.move_to_end(key) return cached with torch.inference_mode(False): cached = torch.tensor( [*lexical_lengths, *chunk_indices], device=device, dtype=torch.int64 ).contiguous() _PAT_FIXED_ROW_CACHE[key] = cached while len(_PAT_FIXED_ROW_CACHE) > _PAT_FIXED_ROW_CACHE_MAX_ENTRIES: _PAT_FIXED_ROW_CACHE.popitem(last=False) return cached def _materialize_pat_attention_layout( physical_layout: PackedLayout | FixedGeometry, *, local_slots: int, global_slots: int, chunk_size: int, max_memory_size: int, block_q: int = 16, block_k_memory: int = 64, block_k_token: int = 16, _trusted_internal: object | None = None, ) -> _PATMaterializedLayout: """Build one live PAT signature in one slab and one Triton launch.""" trusted_fixed = _trusted_internal is _PAT_TRUSTED_MATERIALIZER if trusted_fixed: if not isinstance(physical_layout, FixedGeometry): raise TypeError("trusted PAT materialization requires fixed geometry") elif not isinstance(physical_layout, PackedLayout): raise TypeError("physical_layout must be PackedLayout") if not _HAS_TRITON: raise RuntimeError("PAT layout materialization requires Triton") local_width = _required_plain_int("local_slots", local_slots, minimum=1) global_width = _required_plain_int("global_slots", global_slots, minimum=1) chunk = _required_plain_int("chunk_size", chunk_size, minimum=1) max_memory = _required_plain_int("max_memory_size", max_memory_size, minimum=4) query_block = _power_of_two("block_q", block_q) memory_block = _power_of_two("block_k_memory", block_k_memory) token_block = _power_of_two("block_k_token", block_k_token) if query_block < 16 or query_block > 128: raise ValueError("block_q must be in [16, 128]") if token_block < 16 or token_block > 128: raise ValueError("block_k_token must be in [16, 128]") if memory_block < 16 or memory_block > 128: raise ValueError("block_k_memory must be in [16, 128]") if _trusted_internal not in {None, _PAT_TRUSTED_MATERIALIZER}: raise ValueError("invalid PAT materializer provenance request") if chunk not in _SUPPORTED_CHUNK_SIZES: raise ValueError(f"PAT layout materialization supports chunk_size 16 or 32; got {chunk}") device = physical_layout.row_lengths.device if device.type != "cuda": raise RuntimeError("PAT fused layout materialization supports CUDA execution only") _require_pat_hopper(device) rows = int(physical_layout.row_count) physical_tokens = int(physical_layout.token_count) physical_slots = int(physical_layout.memory_tail_slots) if rows <= 0 or physical_tokens <= 0 or physical_slots <= 0: raise ValueError( "PAT fused layout materialization requires nonempty rows and a positive physical EOC width" ) if not trusted_fixed and physical_layout.row_pos_to_flat_is_identity is not True: raise ValueError("PAT fused layout materialization requires identity-packed rows") max_lexical_length = int(physical_layout.max_row_length) - physical_slots if max_lexical_length <= 0 or max_lexical_length > chunk: raise ValueError("PAT physical max lexical row length must be in [1, chunk_size]") if int(physical_layout.max_chunk_index) < 0: raise ValueError("PAT physical max_chunk_index must be non-negative") physical_row_offsets = physical_layout.row_offsets physical_row_lengths = physical_layout.row_lengths physical_memory_query_start = ( physical_layout.row_content_lengths if trusted_fixed else physical_layout.memory_query_start ) physical_eoc = physical_layout.eoc_abs_idx physical_row_chunk_or_piece = ( physical_layout.chunk_piece_id if trusted_fixed else physical_layout.row_chunk_indices ) physical_piece_chunk_base = ( physical_layout.piece_chunk_base if trusted_fixed else physical_row_offsets ) physical_row_pos_to_flat = ( physical_row_offsets if trusted_fixed else physical_layout.row_pos_to_flat ) physical_memory_start = ( physical_row_offsets if trusted_fixed else physical_layout.row_memory_start_abs ) physical_memory_length = ( physical_row_offsets if trusted_fixed else physical_layout.row_memory_length ) expected_tensors = [ ("row_offsets", physical_row_offsets, (rows,)), ("row_lengths", physical_row_lengths, (rows,)), ("memory_query_start", physical_memory_query_start, (rows,)), ("eoc_abs_idx", physical_eoc, (rows, physical_slots)), ("row_chunk_indices", physical_row_chunk_or_piece, (rows,)), ] if trusted_fixed: expected_tensors.append( ( "piece_chunk_base", physical_piece_chunk_base, (int(physical_piece_chunk_base.numel()),), ) ) else: expected_tensors.extend( ( ("row_pos_to_flat", physical_row_pos_to_flat, (physical_tokens,)), ("row_memory_start_abs", physical_memory_start, (rows,)), ("row_memory_length", physical_memory_length, (rows,)), ) ) for name, tensor, shape in expected_tensors: if ( not torch.is_tensor(tensor) or tuple(tensor.shape) != shape or tensor.dtype != torch.int64 or (tensor.device != device) or (not tensor.is_contiguous()) ): raise ValueError( f"PAT physical {name} must be a contiguous int64 {list(shape)} tensor on {device}" ) fixed_key = physical_layout.planner_cache_key if ( not isinstance(fixed_key, tuple) or len(fixed_key) != 10 or fixed_key[0] != "packed_training" or (type(fixed_key[1]) is not bool) ): raise ValueError( "PAT physical planner key must be packed_training with an explicit include_piece_start_bos flag" ) key_rows = _required_plain_int("row_count", fixed_key[2], minimum=1) key_max_row = _required_plain_int("physical max row length", fixed_key[3], minimum=1) key_tokens = _required_plain_int("physical token count", fixed_key[4], minimum=1) key_chunk = _required_plain_int("chunk_size", fixed_key[5], minimum=1) key_eoc = _required_plain_int("physical EOC width", fixed_key[6], minimum=1) key_max_memory = _required_plain_int("max_memory_size", fixed_key[7], minimum=4) if ( key_rows != rows or key_max_row != int(physical_layout.max_row_length) or key_tokens != physical_tokens or (key_chunk != chunk) or (key_eoc != physical_slots) or (key_max_memory != max_memory) ): raise ValueError("PAT physical layout disagrees with its fixed-training planner key") chunks_per_piece = fixed_key[8] short_rows_raw = fixed_key[9] if not isinstance(chunks_per_piece, tuple) or not chunks_per_piece: raise ValueError("PAT fixed-training key requires chunks_per_piece") piece_counts = tuple( _required_plain_int("chunks_per_piece entry", value, minimum=1) for value in chunks_per_piece ) if sum(piece_counts) != rows or not isinstance(short_rows_raw, tuple): raise ValueError("PAT fixed-training key has malformed piece geometry") piece_ends: set[int] = set() piece_cursor = 0 for count in piece_counts: piece_cursor += count piece_ends.add(piece_cursor) short_rows: dict[int, int] = {} previous_short_row = -1 for entry in short_rows_raw: if not isinstance(entry, tuple) or len(entry) != 2: raise ValueError("PAT short-row entries must be pairs") row = _required_plain_int("short row index", entry[0]) length = _required_plain_int("short row length", entry[1], minimum=1) if ( row >= rows or row <= previous_short_row or length >= chunk or (row + 1 not in piece_ends) ): raise ValueError("PAT fixed-training key contains an invalid short row") short_rows[row] = length previous_short_row = row expected_lexical_lengths = [short_rows.get(row, chunk) for row in range(rows)] expected_chunk_indices = [ chunk_index for piece_count in piece_counts for chunk_index in range(piece_count) ] expected_row_geometry = _cached_fixed_row_geometry( fixed_key=fixed_key, lexical_lengths=expected_lexical_lengths, chunk_indices=expected_chunk_indices, device=device, ) total_lexical_tokens = physical_tokens - rows * physical_slots expected_lexical_tokens = rows * chunk - sum(chunk - length for length in short_rows.values()) if total_lexical_tokens <= 0 or total_lexical_tokens != expected_lexical_tokens: raise ValueError("PAT physical token count disagrees with fixed-training row lengths") target_tokens = total_lexical_tokens + rows * local_width target_max_row = max_lexical_length + local_width full_lexical_q_tiles = (chunk + query_block - 1) // query_block tail_q_tiles = (local_width + query_block - 1) // query_block query_tile_capacity = rows * (full_lexical_q_tiles + tail_q_tiles) query_tiles = rows * (full_lexical_q_tiles + tail_q_tiles) - sum( full_lexical_q_tiles - (length + query_block - 1) // query_block for length in short_rows.values() ) full_token_tiles = (chunk + local_width + token_block - 1) // token_block token_tile_capacity = rows * full_token_tiles token_tiles = rows * full_token_tiles - sum( full_token_tiles - (length + local_width + token_block - 1) // token_block for length in short_rows.values() ) if query_tiles <= 0 or token_tiles <= 0: raise RuntimeError("PAT materializer derived empty launch geometry") memory_query_tiles = math.ceil(target_tokens / _PAT_MEMORY_BLOCK_Q) if memory_query_tiles <= 0: raise RuntimeError("PAT materializer derived empty memory launch geometry") planner_cache_key = ( (fixed_key, "dynamic_memory", local_width, global_width), "token_level_context", 2, max_memory, chunk, 1, global_width, "packed_local", "fixed_token_window", False, True, ) _parse_pat_attention_layout_key(planner_cache_key) section_counts = ( ("row_offsets", rows), ("row_pos_to_flat", target_tokens), ("row_lengths", rows), ("row_chunk_indices", rows), ("memory_query_start", rows), ("row_memory_start_abs", rows), ("row_memory_length", rows), ("local_positions", target_tokens), ("query_positions", target_tokens), ("eoc_abs_idx", rows * local_width), ("memory_positions", rows * global_width), ("row_token_memory_length", rows), ("row_exact_start_abs", rows), ("row_exact_length", rows), ("row_exact_query_phase_delta", rows), ("row_compressed_eoc_local_key_phase_delta", rows), ("canonical_order", target_tokens), ("logical_order", target_tokens), ("canonical_positions", target_tokens), ("canonical_key_positions", target_tokens), ("token_row_ids", target_tokens), ("q_tile_rows", query_tile_capacity), ("q_tile_starts", query_tile_capacity), ("token_owner_rows", token_tile_capacity), ("token_owner_starts", token_tile_capacity), ("memory_tile_union_start", memory_query_tiles), ("memory_tile_union_end", memory_query_tiles), ("memory_tile_interior_start", memory_query_tiles), ("memory_tile_interior_end", memory_query_tiles), ("q_tile_counter", 1), ("token_owner_counter", 1), ("validation_result", 1), ) section_offsets: dict[str, tuple[int, int]] = {} storage_elements = 0 for name, count in section_counts: section_offsets[name] = (storage_elements, storage_elements + count) storage_elements += count storage = torch.ones((storage_elements,), device=device, dtype=torch.int64) block_row = 1 << (chunk + max(physical_slots, local_width) - 1).bit_length() _pat_materialize_layout_kernel[max(rows, memory_query_tiles),]( physical_row_offsets, physical_row_pos_to_flat, physical_row_lengths, physical_memory_query_start, physical_memory_start, physical_memory_length, physical_eoc, physical_row_chunk_or_piece, physical_piece_chunk_base, expected_row_geometry, storage, rows, physical_tokens, target_tokens, total_lexical_tokens, query_tile_capacity, token_tile_capacity, memory_query_tiles, int(physical_piece_chunk_base.numel()), PHYSICAL_SLOTS=physical_slots, LOCAL_SLOTS=local_width, GLOBAL_SLOTS=global_width, CHUNK_SIZE=chunk, MAX_MEMORY_SIZE=max_memory, BLOCK_Q=query_block, BLOCK_K_MEMORY=memory_block, BLOCK_K_TOKEN=token_block, BLOCK_MEMORY_QUERY=_PAT_MEMORY_BLOCK_Q, BLOCK_ROW=block_row, TRUSTED_FIXED=_trusted_internal is _PAT_TRUSTED_MATERIALIZER, num_warps=2 if block_row <= 64 else 4, num_stages=1, ) def section(name: str) -> torch.Tensor: start, stop = section_offsets[name] return storage.narrow(0, start, stop - start) def exact_section(name: str, count: int) -> torch.Tensor: return section(name).narrow(0, 0, int(count)) validation_result = section("validation_result") if _trusted_internal is None: if int(validation_result.item()) != 1: raise ValueError("PAT physical layout values are malformed") else: torch._assert_async( validation_result, "PAT fixed-training layout disagrees with its exhaustive planner key" ) layout = PackedLayout( row_offsets=section("row_offsets"), row_pos_to_flat=section("row_pos_to_flat"), row_lengths=section("row_lengths"), row_chunk_indices=section("row_chunk_indices"), memory_query_start=section("memory_query_start"), row_memory_start_abs=section("row_memory_start_abs"), row_memory_length=section("row_memory_length"), local_positions=section("local_positions"), eoc_abs_idx=section("eoc_abs_idx").view(rows, local_width), memory_positions=section("memory_positions"), row_pos_to_flat_is_identity=True, max_row_length=target_max_row, max_chunk_index=int(physical_layout.max_chunk_index), query_positions=section("query_positions"), row_token_memory_length=section("row_token_memory_length"), row_exact_start_abs=section("row_exact_start_abs"), row_exact_length=section("row_exact_length"), row_exact_query_phase_delta=section("row_exact_query_phase_delta"), row_compressed_eoc_local_key_phase_delta=section( "row_compressed_eoc_local_key_phase_delta" ), planner_cache=None if trusted_fixed else physical_layout.planner_cache, planner_cache_key=planner_cache_key, token_context_schedule="fixed_token_window", fixed_window_contiguous_position_width=1, chronological_fixed_window=True, global_memory_slots_per_chunk=global_width, ) return _PATMaterializedLayout( layout=layout, canonical_order=section("canonical_order"), logical_order=section("logical_order"), canonical_positions=section("canonical_positions"), canonical_key_positions=section("canonical_key_positions"), q_tile_rows=exact_section("q_tile_rows", query_tiles), q_tile_starts=exact_section("q_tile_starts", query_tiles), token_row_ids=section("token_row_ids"), memory_tile_union_start=section("memory_tile_union_start"), memory_tile_union_end=section("memory_tile_union_end"), memory_tile_interior_start=section("memory_tile_interior_start"), memory_tile_interior_end=section("memory_tile_interior_end"), token_owner_rows=exact_section("token_owner_rows", token_tiles), token_owner_starts=exact_section("token_owner_starts", token_tiles), block_q=query_block, block_k_memory=memory_block, block_k_token=token_block, total_lexical_tokens=total_lexical_tokens, global_slots=global_width, storage=storage, provenance=_PATMaterializationProvenance( storage_identity=id(storage), device=device, stream=int(torch.cuda.current_stream(device).cuda_stream), ), ) def materialize_layout( fixed_geometry: FixedGeometry, *, local_slots: int, global_slots: int, config: KernelConfig ) -> _PATMaterializedLayout: """Internal one-launch materializer whose output may bind without revalidation.""" if not isinstance(config, KernelConfig): raise TypeError("config must be KernelConfig") return _materialize_pat_attention_layout( fixed_geometry, local_slots=local_slots, global_slots=global_slots, chunk_size=int(config.chunk_size), max_memory_size=int(config.max_memory_size), block_q=int(config.block_q), block_k_memory=int(config.block_k_memory), block_k_token=int(config.block_k_token), _trusted_internal=_PAT_TRUSTED_MATERIALIZER, ) def _cached_pat_attention_phases( *, config: KernelConfig, device: torch.device, dtype: torch.dtype, head_dim: int ) -> tuple[torch.Tensor, torch.Tensor]: """Return the only geometry-independent live tensors retained across batches.""" stream = int(torch.cuda.current_stream(device).cuda_stream) if device.type == "cuda" else 0 key = (config, device, dtype, int(head_dim), stream) with _PAT_PHASE_CACHE_LOCK: cached = _PAT_PHASE_CACHE.get(key) if cached is not None: _PAT_PHASE_CACHE.move_to_end(key) return cached block_dimension = _validate_pat_head_dim(int(head_dim)) dimensions = torch.arange(block_dimension, device=device, dtype=torch.float32) even_dimensions = torch.div(dimensions, 2, rounding_mode="floor") * 2 inverse_frequency = torch.exp(-math.log(ROPE_BASE) * even_dimensions / int(head_dim)) deltas = -torch.arange(int(config.chunk_size) + 1, device=device, dtype=torch.float32) angles = deltas[:, None] * inverse_frequency[None, :] cached = ( torch.cos(angles).to(dtype=dtype).contiguous(), torch.sin(angles).to(dtype=dtype).contiguous(), ) _PAT_PHASE_CACHE[key] = cached while len(_PAT_PHASE_CACHE) > _PAT_PHASE_CACHE_MAX_ENTRIES: _PAT_PHASE_CACHE.popitem(last=False) return cached def bind_plan( materialized: _PATMaterializedLayout, *, heads: int, head_dim: int, dtype: torch.dtype, config: KernelConfig, layer_zero: bool = False, ) -> PATPlan: """Bind one internal materialization without O(rows) work or GPU validation.""" if not isinstance(materialized, _PATMaterializedLayout): raise TypeError("materialized must be a PAT fused materialization") provenance = materialized.provenance if ( provenance is None or provenance.storage_identity != id(materialized.storage) or provenance.device != materialized.storage.device ): raise ValueError("PAT plan binding requires trusted materializer provenance") device = materialized.storage.device current_stream = int(torch.cuda.current_stream(device).cuda_stream) if provenance.stream != current_stream: raise ValueError("PAT trusted materialization must be bound on its producing CUDA stream") if not isinstance(config, KernelConfig): raise TypeError("config must be KernelConfig") if ( int(config.block_q) != materialized.block_q or int(config.block_k_memory) != materialized.block_k_memory or int(config.block_k_token) != materialized.block_k_token or (int(config.chunk_size) != int(materialized.layout.planner_cache_key[4])) or (int(config.max_memory_size) != int(materialized.layout.planner_cache_key[3])) ): raise ValueError("PAT config disagrees with trusted materialized geometry") head_count = _required_plain_int("heads", heads, minimum=1) dimension = _required_plain_int("head_dim", head_dim, minimum=1) _validate_pat_head_dim(dimension) if dtype not in _SUPPORTED_DTYPES: raise ValueError(f"unsupported PAT dtype: {dtype}") layout = materialized.layout rows = int(layout.row_count) token_slots = int(layout.token_count) expected_storage_pointer = materialized.storage.untyped_storage().data_ptr() bound_tensors = ( layout.row_offsets, layout.row_pos_to_flat, layout.row_lengths, layout.memory_query_start, layout.row_memory_start_abs, layout.row_memory_length, layout.row_token_memory_length, layout.row_exact_start_abs, layout.row_exact_length, layout.row_exact_query_phase_delta, layout.row_compressed_eoc_local_key_phase_delta, materialized.q_tile_rows, materialized.q_tile_starts, materialized.token_row_ids, materialized.canonical_order, materialized.logical_order, materialized.memory_tile_union_start, materialized.memory_tile_union_end, materialized.memory_tile_interior_start, materialized.memory_tile_interior_end, materialized.token_owner_rows, materialized.token_owner_starts, materialized.canonical_key_positions, layout.query_positions, ) if any(value is None for value in bound_tensors): raise ValueError("PAT trusted materialization is missing plan metadata") if any( tensor.untyped_storage().data_ptr() != expected_storage_pointer for tensor in bound_tensors if torch.is_tensor(tensor) ): raise ValueError("PAT trusted plan metadata escaped its materializer slab") assert layout.row_token_memory_length is not None assert layout.row_exact_start_abs is not None assert layout.row_exact_length is not None assert layout.row_exact_query_phase_delta is not None assert layout.row_compressed_eoc_local_key_phase_delta is not None zero_rows = layout.row_compressed_eoc_local_key_phase_delta memory_start = zero_rows if layer_zero else layout.row_memory_start_abs memory_length = zero_rows if layer_zero else layout.row_memory_length token_memory_length = zero_rows if layer_zero else layout.row_token_memory_length metadata = ( layout.row_offsets, layout.row_pos_to_flat, layout.row_lengths, layout.row_chunk_indices, layout.memory_query_start, memory_start, memory_length, token_memory_length, layout.row_exact_start_abs, layout.row_exact_length, layout.row_exact_query_phase_delta, layout.row_compressed_eoc_local_key_phase_delta, ) phase_cos, phase_sin = _cached_pat_attention_phases( config=config, device=device, dtype=dtype, head_dim=dimension ) memory_slots = 0 if layer_zero else rows * materialized.global_slots if layer_zero: empty_memory_tiles = materialized.storage.narrow(0, 0, 0) memory_tile_union_start = empty_memory_tiles memory_tile_union_end = empty_memory_tiles memory_tile_interior_start = empty_memory_tiles memory_tile_interior_end = empty_memory_tiles else: memory_tile_union_start = materialized.memory_tile_union_start memory_tile_union_end = materialized.memory_tile_union_end memory_tile_interior_start = materialized.memory_tile_interior_start memory_tile_interior_end = materialized.memory_tile_interior_end return PATPlan( config=config, row_count=rows, token_slots=token_slots, total_lexical_tokens=materialized.total_lexical_tokens, local_tail_slots=int(layout.memory_tail_slots), memory_slots=memory_slots, global_slots=0 if layer_zero else int(materialized.global_slots), heads=head_count, head_dim=dimension, dtype=dtype, row_offsets=metadata[0], row_pos_to_flat=metadata[1], row_lengths=metadata[2], row_chunk_indices=metadata[3], memory_query_start=metadata[4], row_memory_start_abs=metadata[5], row_memory_length=metadata[6], row_token_memory_length=metadata[7], row_exact_start_abs=metadata[8], row_exact_length=metadata[9], row_exact_query_phase_delta=metadata[10], row_compressed_eoc_local_key_phase_delta=metadata[11], q_tile_rows=materialized.q_tile_rows, q_tile_starts=materialized.q_tile_starts, token_row_ids=materialized.token_row_ids, canonical_order=materialized.canonical_order, logical_order=materialized.logical_order, memory_tile_union_start=memory_tile_union_start, memory_tile_union_end=memory_tile_union_end, memory_tile_interior_start=memory_tile_interior_start, memory_tile_interior_end=memory_tile_interior_end, token_owner_rows=materialized.token_owner_rows, token_owner_starts=materialized.token_owner_starts, memory_phase_cos=phase_cos, memory_phase_sin=phase_sin, metadata_signature=(), canonical_metadata=materialized.storage.narrow(0, 0, 0), metadata_validation_result=materialized.storage.narrow( 0, int(materialized.storage.numel()) - 1, 1 ), metadata_validation_stream=provenance.stream, _trusted_materialization=provenance, )
"""PAT fused attention. Only the publication training/prefill path is retained.
FP32 relative rotary products, query-owned backward, and Hopper ragged TMA
accumulation preserve the checkpoint producer's arithmetic.
"""
from __future__ import annotations
from .layout import PackedLayout
ROPE_BASE = 10_000.0
import math
from collections import OrderedDict
from collections.abc import Sequence
from dataclasses import dataclass
from threading import Lock
from typing import Any
import torch
try:
import triton
import triton.language as tl
from triton.tools.ragged_tma import atomic_add_ragged, create_ragged_descriptor
_HAS_TRITON = True
except ImportError:
triton = None
tl = None
_HAS_TRITON = False
_SUPPORTED_CHUNK_SIZES = frozenset({16, 32})
_SUPPORTED_DTYPES = frozenset({torch.float16, torch.bfloat16, torch.float32})
_PAT_MEMORY_BLOCK_Q = 64
_PAT_MEMORY_BACKWARD_BLOCK_K = 64
_PAT_MEMORY_FORWARD_WARPS = 4
_PAT_MEMORY_BACKWARD_WARPS = 4
_PAT_TOKEN_BACKWARD_WARPS = 4
_PAT_PLAN_CACHE_MAX_ENTRIES = 32
_PAT_PHASE_CACHE_MAX_ENTRIES = _PAT_PLAN_CACHE_MAX_ENTRIES
_PAT_PHASE_CACHE: OrderedDict[
tuple[KernelConfig, torch.device, torch.dtype, int, int], tuple[torch.Tensor, torch.Tensor]
] = OrderedDict()
_PAT_PHASE_CACHE_LOCK = Lock()
_PAT_FIXED_ROW_CACHE_MAX_ENTRIES = _PAT_PLAN_CACHE_MAX_ENTRIES
_PAT_FIXED_ROW_CACHE: OrderedDict[tuple[tuple[Any, ...], torch.device, int], torch.Tensor] = (
OrderedDict()
)
_PAT_FIXED_ROW_CACHE_LOCK = Lock()
_PAT_TRUSTED_MATERIALIZER = object()
def _memory_query_block_k(configured_block_k: int) -> int:
"""Bound the five-product query owner while respecting smaller K tiles."""
return min(_PAT_MEMORY_BACKWARD_BLOCK_K, int(configured_block_k))
def _power_of_two(name: str, value: int) -> int:
value_i = int(value)
if value_i <= 0 or value_i & value_i - 1:
raise ValueError(f"{name} must be a positive power of two; got {value!r}")
return value_i
def _block_d(head_dim: int) -> int:
return max(16, 1 << max(0, int(head_dim) - 1).bit_length())
def _validate_pat_head_dim(head_dim: int) -> int:
"""Validate the one ragged-TMA backward geometry before any launch."""
value = int(head_dim)
block_dimension = _block_d(value)
if value < 20 or value % 4 or block_dimension > 128:
raise ValueError(
f"PAT ragged-TMA backward requires head_dim divisible by 4 in [20, 128]; got {value}"
)
return block_dimension
def _require_pat_hopper(device: torch.device) -> None:
"""Require the descriptor atomics used by the publication kernel."""
capability = torch.cuda.get_device_capability(device)
if int(capability[0]) < 9:
raise RuntimeError(
f"production attention PAT requires an SM90-or-newer CUDA GPU for ragged TMA descriptor atomics; got compute capability {capability[0]}.{capability[1]}"
)
@dataclass(frozen=True)
class KernelConfig:
"""Fixed publication tile geometry and runtime context capacity."""
chunk_size: int
max_memory_size: int
block_q: int = 16
block_k_memory: int = 64
block_k_token: int = 16
warps: int = 4
stages: int = 3
def __post_init__(self) -> None: