"""Fixed PAT cached attention kernels, preserving published arithmetic.""" import torch import triton import triton.language as tl from .attention import KernelConfig, _cached_pat_attention_phases @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: # d68a14e3: retain the existing phase values and interface dtype. 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_rotate_vector( x, cosine, sine, 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_D // 2, 2)) even, odd = tl.split(pairs) quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_D,)) return tl.fma(quarter_turn, sine, source * cosine).to(x.dtype) else: pairs = tl.reshape(x, (BLOCK_D // 2, 2)) even, odd = tl.split(pairs) quarter_turn = tl.reshape(tl.join(-odd, even), (BLOCK_D,)) return x * cosine + quarter_turn * sine @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_active_q1_online_step( q, k, v, valid, has_key, m, denominator, output, qk_scale, ): """Scalar-query online softmax using vector reductions, never MMA.""" scores = ( tl.sum( q[None, :].to(tl.float32) * k.to(tl.float32), axis=1, ) * qk_scale ) scores = tl.where(valid, scores, -float("inf")) tile_max = tl.max(scores, axis=0) 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), 0.0) output = output * alpha + tl.sum( probability[:, None] * v.to(tl.float32), axis=0, ) denominator = denominator * alpha + tl.sum(probability, axis=0) return next_m, denominator, output @triton.jit def _pat_active_q1_last_cta_combine( partial_ptr, completion_counter_ptr, out_ptr, row, head, completion_index, heads, head_dim, BLOCK_D: tl.constexpr, MEMORY_SPLITS: tl.constexpr, ): """Reduce published split states and reset the replay counter.""" offs_d = tl.arange(0, BLOCK_D) d_mask = offs_d < head_dim state_base = (row * heads + head) * MEMORY_SPLITS * (BLOCK_D + 2) global_m = -float("inf") any_partial = False for split in tl.static_range(0, MEMORY_SPLITS): split_base = state_base + split * (BLOCK_D + 2) split_denominator = tl.load(partial_ptr + split_base + 1) split_present = split_denominator > 0.0 split_m = tl.load(partial_ptr + split_base) global_m = tl.maximum( global_m, tl.where(split_present, split_m, -float("inf")), ) any_partial = any_partial | split_present safe_global_m = tl.where(any_partial, global_m, 0.0) combined_denominator = 0.0 combined_output = tl.zeros((BLOCK_D,), tl.float32) for split in tl.static_range(0, MEMORY_SPLITS): split_base = state_base + split * (BLOCK_D + 2) split_denominator = tl.load(partial_ptr + split_base + 1) split_present = split_denominator > 0.0 split_m = tl.load(partial_ptr + split_base) split_alpha = tl.where( split_present, tl.exp2(split_m - safe_global_m), 0.0, ) split_output = tl.load( partial_ptr + split_base + 2 + offs_d, mask=d_mask, other=0.0, ) combined_denominator += split_denominator * split_alpha combined_output += split_output * split_alpha safe_denominator = tl.where( combined_denominator > 0.0, combined_denominator, 1.0, ) tl.store( out_ptr + row * heads * head_dim + head * head_dim + offs_d, combined_output / safe_denominator, mask=d_mask, ) tl.atomic_xchg( completion_counter_ptr + completion_index, 0, sem="release", scope="gpu", ) @triton.jit( do_not_specialize=("memory_slots", "exact_slots", "local_slots"), do_not_specialize_on_alignment=( "memory_slots", "exact_slots", "local_slots", ), ) def _pat_active_forward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, k_exact_ptr, v_exact_ptr, k_local_ptr, v_local_ptr, out_ptr, row_lengths_ptr, memory_query_start_ptr, row_memory_start_ptr, row_memory_length_ptr, row_token_memory_length_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, row_local_start_ptr, phase_cos_ptr, phase_sin_ptr, q_tile_rows_ptr, q_tile_starts_ptr, q_row_offsets_ptr, q_row_starts_ptr, scale, memory_slots, exact_slots, local_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_Q: tl.constexpr, BLOCK_K_MEMORY: tl.constexpr, BLOCK_K_TOKEN: tl.constexpr, BLOCK_D: tl.constexpr, QUERY_IS_EOC: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): """Cached PAT decode over caller-owned persistent K/V arenas.""" 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_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) 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, ) q_row_offset = tl.load(q_row_offsets_ptr + row) q_row_start = tl.load(q_row_starts_ptr + row) q_flat = q_row_offset + q_pos - q_row_start d_mask = offs_d < head_dim q = tl.load( q_ptr + q_flat[:, 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 local_row_start = tl.load(row_local_start_ptr + row) local_stop = tl.where( QUERY_IS_EOC, row_length, tl.minimum(lexical_length, q_start + BLOCK_Q), ) offs_k = tl.arange(0, BLOCK_K_TOKEN) local_start = 0 while local_start < local_stop: local_pos = local_start + offs_k local_abs = local_row_start + local_pos local_mask = (local_pos < local_stop) & (local_abs < local_slots) k = tl.load( k_local_ptr + local_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & local_mask[None, :], other=0.0, ) v = tl.load( v_local_ptr + local_abs[:, 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 if not QUERY_IS_EOC: exact_start = tl.load(row_exact_start_ptr + row) exact_length = 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 = 0 while exact_offset_start < exact_length: exact_offset = exact_offset_start + offs_k exact_abs = exact_start + exact_offset exact_mask = (exact_offset < exact_length) & (exact_abs < exact_slots) k = tl.load( k_exact_ptr + exact_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & exact_mask[None, :], other=0.0, ) v = tl.load( v_exact_ptr + exact_abs[:, 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 memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.where( QUERY_IS_EOC, tl.load(row_memory_length_ptr + row), tl.load(row_token_memory_length_ptr + row), ) memory_offsets = tl.arange(0, BLOCK_K_MEMORY) if QUERY_IS_EOC: newest_length = 0 # Keep the multi-query owner free of the same zero-iteration dot body. if GLOBAL_SLOTS > 0 and not QUERY_IS_EOC: newest_length = tl.where( memory_length >= GLOBAL_SLOTS, GLOBAL_SLOTS, 0, ) newest_start = memory_start + memory_length - newest_length 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, ) 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 < newest_length: newest_offset = newest_offset_start + memory_offsets newest_abs = newest_start + newest_offset newest_mask = (newest_offset < newest_length) & (newest_abs < memory_slots) 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, ) 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, ) valid = q_mask[:, None] & newest_mask[None, :] m, denominator, output = _pat_online_step( q_newest, k, v, valid, q_mask & (newest_length > 0), m, denominator, output, qk_scale, ) newest_offset_start += BLOCK_K_MEMORY 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, ) remote_memory_length = memory_length if not QUERY_IS_EOC: remote_memory_length = tl.maximum(memory_length - GLOBAL_SLOTS, 0) memory_offset_start = 0 while memory_offset_start < remote_memory_length: memory_offset = memory_offset_start + memory_offsets memory_abs = memory_start + memory_offset memory_mask = (memory_offset < remote_memory_length) & (memory_abs < memory_slots) k = tl.load( k_memory_ptr + memory_abs[None, :] * heads * head_dim + head * head_dim + offs_d[:, None], mask=d_mask[:, None] & memory_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) valid = q_mask[:, None] & memory_mask[None, :] m, denominator, output = _pat_online_step( q_memory, k, v, valid, q_mask, m, denominator, output, qk_scale, ) memory_offset_start += BLOCK_K_MEMORY safe_denominator = tl.where(q_mask, denominator, 1.0) normalized = output / safe_denominator[:, None] tl.store( out_ptr + q_flat[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], normalized, mask=q_mask[:, None] & d_mask[None, :], ) @triton.jit( do_not_specialize=("memory_slots", "exact_slots", "local_slots"), do_not_specialize_on_alignment=( "memory_slots", "exact_slots", "local_slots", ), ) def _pat_active_q1_forward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, k_exact_ptr, v_exact_ptr, k_local_ptr, v_local_ptr, out_ptr, row_lengths_ptr, memory_query_start_ptr, row_memory_start_ptr, row_memory_length_ptr, row_token_memory_length_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, row_local_start_ptr, phase_cos_ptr, phase_sin_ptr, q_row_starts_ptr, scale, memory_slots, exact_slots, local_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_K_MEMORY: tl.constexpr, BLOCK_K_TOKEN: tl.constexpr, BLOCK_D: tl.constexpr, QUERY_IS_EOC: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): """One scalar query per row/head, with no padded query or dot tile.""" row = tl.program_id(0) head = tl.program_id(1) q_pos = tl.load(q_row_starts_ptr + row) row_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) query_valid = (q_pos < row_length) & tl.where( QUERY_IS_EOC, q_pos >= lexical_length, q_pos < lexical_length, ) offs_d = tl.arange(0, BLOCK_D) d_mask = offs_d < head_dim q_flat = row q = tl.load( q_ptr + q_flat * heads * head_dim + head * head_dim + offs_d, mask=query_valid & d_mask, other=0.0, ) m = -float("inf") denominator = 0.0 output = tl.zeros((BLOCK_D,), tl.float32) qk_scale = scale * 1.4426950408889634 offs_token = tl.arange(0, BLOCK_K_TOKEN) local_row_start = tl.load(row_local_start_ptr + row) local_stop = tl.where( QUERY_IS_EOC, row_length, tl.minimum(lexical_length, q_pos + 1), ) local_start = 0 while local_start < local_stop: local_pos = local_start + offs_token local_abs = local_row_start + local_pos local_mask = query_valid & (local_pos < local_stop) & (local_abs < local_slots) k = tl.load( k_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) m, denominator, output = _pat_active_q1_online_step( q, k, v, local_mask, query_valid, m, denominator, output, qk_scale, ) local_start += BLOCK_K_TOKEN if not QUERY_IS_EOC: exact_start = tl.load(row_exact_start_ptr + row) exact_length = 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=query_valid & d_mask, other=1.0, ) table_sine = tl.load( phase_sin_ptr + exact_phase_offset, mask=query_valid & 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_vector( q, exact_cosine.to(q.dtype), exact_sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) exact_offset_start = 0 while exact_offset_start < exact_length: exact_offset = exact_offset_start + offs_token exact_abs = exact_start + exact_offset exact_mask = ( query_valid & (exact_offset < exact_length) & (exact_abs < exact_slots) & (exact_offset > q_pos) ) k = tl.load( k_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) has_exact = query_valid & (q_pos + 1 < exact_length) m, denominator, output = _pat_active_q1_online_step( q_exact, k, v, exact_mask, has_exact, m, denominator, output, qk_scale, ) exact_offset_start += BLOCK_K_TOKEN memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.where( QUERY_IS_EOC, tl.load(row_memory_length_ptr + row), tl.load(row_token_memory_length_ptr + row), ) offs_memory = tl.arange(0, BLOCK_K_MEMORY) if QUERY_IS_EOC: newest_length = 0 # Both predicates are constexpr. Elide a provably empty newest loop # instead of asking the compiler to lower a zero-iteration dot body. if GLOBAL_SLOTS > 0 and not QUERY_IS_EOC: newest_length = tl.where( memory_length >= GLOBAL_SLOTS, GLOBAL_SLOTS, 0, ) newest_start = memory_start + memory_length - newest_length newest_phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d newest_cosine = tl.load( phase_cos_ptr + newest_phase_offset, mask=query_valid & d_mask, other=1.0, ) newest_sine = tl.load( phase_sin_ptr + newest_phase_offset, mask=query_valid & d_mask, other=0.0, ) q_newest = _pat_rotate_vector( q, newest_cosine.to(q.dtype), newest_sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) newest_offset_start = 0 while newest_offset_start < newest_length: newest_offset = newest_offset_start + offs_memory newest_abs = newest_start + newest_offset newest_mask = ( query_valid & (newest_offset < newest_length) & (newest_abs < memory_slots) ) k = tl.load( k_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) 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, ) m, denominator, output = _pat_active_q1_online_step( q_newest, k, v, newest_mask, query_valid & (newest_length > 0), m, denominator, output, qk_scale, ) newest_offset_start += BLOCK_K_MEMORY phase_row = tl.where( QUERY_IS_EOC, CHUNK_SIZE - 1, tl.minimum(q_pos, CHUNK_SIZE - 1), ) phase_offset = phase_row * BLOCK_D + offs_d cosine = tl.load( phase_cos_ptr + phase_offset, mask=query_valid & d_mask, other=1.0, ) sine = tl.load( phase_sin_ptr + phase_offset, mask=query_valid & d_mask, other=0.0, ) q_memory = _pat_rotate_vector( q, cosine.to(q.dtype), sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) remote_memory_length = memory_length if not QUERY_IS_EOC: remote_memory_length = tl.maximum(memory_length - GLOBAL_SLOTS, 0) memory_offset_start = 0 while memory_offset_start < remote_memory_length: memory_offset = memory_offset_start + offs_memory memory_abs = memory_start + memory_offset memory_mask = ( query_valid & (memory_offset < remote_memory_length) & (memory_abs < memory_slots) ) k = tl.load( k_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) has_memory = query_valid & (remote_memory_length > 0) m, denominator, output = _pat_active_q1_online_step( q_memory, k, v, memory_mask, has_memory, m, denominator, output, qk_scale, ) memory_offset_start += BLOCK_K_MEMORY safe_denominator = tl.where(query_valid, denominator, 1.0) normalized = output / safe_denominator tl.store( out_ptr + q_flat * heads * head_dim + head * head_dim + offs_d, normalized, mask=query_valid & d_mask, ) @triton.jit( do_not_specialize=("memory_slots", "exact_slots", "local_slots"), do_not_specialize_on_alignment=( "memory_slots", "exact_slots", "local_slots", ), ) def _pat_active_q1_splitk_forward_kernel( q_ptr, k_memory_ptr, v_memory_ptr, k_exact_ptr, v_exact_ptr, k_local_ptr, v_local_ptr, partial_ptr, completion_counter_ptr, out_ptr, row_lengths_ptr, memory_query_start_ptr, row_memory_start_ptr, row_token_memory_length_ptr, row_exact_start_ptr, row_exact_length_ptr, row_exact_delta_ptr, row_local_start_ptr, phase_cos_ptr, phase_sin_ptr, q_row_starts_ptr, scale, memory_slots, exact_slots, local_slots, heads, head_dim, GLOBAL_SLOTS: tl.constexpr, CHUNK_SIZE: tl.constexpr, BLOCK_K_MEMORY: tl.constexpr, BLOCK_K_TOKEN: tl.constexpr, BLOCK_D: tl.constexpr, MEMORY_SPLITS: tl.constexpr, FP32_ROTARY_PRODUCTS: tl.constexpr = False, ): """Eight disjoint Q1 owners; the last CTA combines in this launch.""" row = tl.program_id(0) head = tl.program_id(1) memory_split = tl.program_id(2) q_pos = tl.load(q_row_starts_ptr + row) row_length = tl.load(row_lengths_ptr + row) lexical_length = tl.load(memory_query_start_ptr + row) query_valid = (q_pos < row_length) & (q_pos < lexical_length) offs_d = tl.arange(0, BLOCK_D) d_mask = offs_d < head_dim q = tl.load( q_ptr + row * heads * head_dim + head * head_dim + offs_d, mask=query_valid & d_mask, other=0.0, ) m = -float("inf") denominator = 0.0 output = tl.zeros((BLOCK_D,), tl.float32) qk_scale = scale * 1.4426950408889634 # Split zero owns the short local, previous-exact, and newest-global # lanes. Those lanes are intentionally not replicated across the # seven remote-only owners. if memory_split == 0: offs_token = tl.arange(0, BLOCK_K_TOKEN) local_row_start = tl.load(row_local_start_ptr + row) local_stop = tl.minimum(lexical_length, q_pos + 1) local_start = 0 while local_start < local_stop: local_pos = local_start + offs_token local_abs = local_row_start + local_pos local_mask = query_valid & (local_pos < local_stop) & (local_abs < local_slots) k = tl.load( k_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_local_ptr + local_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=local_mask[:, None] & d_mask[None, :], other=0.0, ) m, denominator, output = _pat_active_q1_online_step( q, k, v, local_mask, query_valid, m, denominator, output, qk_scale, ) local_start += BLOCK_K_TOKEN exact_start = tl.load(row_exact_start_ptr + row) exact_length = 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=query_valid & d_mask, other=1.0, ) table_sine = tl.load( phase_sin_ptr + exact_phase_offset, mask=query_valid & 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_vector( q, exact_cosine.to(q.dtype), exact_sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) exact_offset_start = 0 while exact_offset_start < exact_length: exact_offset = exact_offset_start + offs_token exact_abs = exact_start + exact_offset exact_mask = ( query_valid & (exact_offset < exact_length) & (exact_abs < exact_slots) & (exact_offset > q_pos) ) k = tl.load( k_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_exact_ptr + exact_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=exact_mask[:, None] & d_mask[None, :], other=0.0, ) has_exact = query_valid & (q_pos + 1 < exact_length) m, denominator, output = _pat_active_q1_online_step( q_exact, k, v, exact_mask, has_exact, m, denominator, output, qk_scale, ) exact_offset_start += BLOCK_K_TOKEN memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.load(row_token_memory_length_ptr + row) offs_memory = tl.arange(0, BLOCK_K_MEMORY) if GLOBAL_SLOTS > 0: newest_length = tl.where( memory_length >= GLOBAL_SLOTS, GLOBAL_SLOTS, 0, ) newest_start = memory_start + memory_length - newest_length newest_phase_offset = (CHUNK_SIZE - 1) * BLOCK_D + offs_d newest_cosine = tl.load( phase_cos_ptr + newest_phase_offset, mask=query_valid & d_mask, other=1.0, ) newest_sine = tl.load( phase_sin_ptr + newest_phase_offset, mask=query_valid & d_mask, other=0.0, ) q_newest = _pat_rotate_vector( q, newest_cosine.to(q.dtype), newest_sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) newest_offset_start = 0 while newest_offset_start < newest_length: newest_offset = newest_offset_start + offs_memory newest_abs = newest_start + newest_offset newest_mask = ( query_valid & (newest_offset < newest_length) & (newest_abs < memory_slots) ) k = tl.load( k_memory_ptr + newest_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=newest_mask[:, None] & d_mask[None, :], other=0.0, ) 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, ) m, denominator, output = _pat_active_q1_online_step( q_newest, k, v, newest_mask, query_valid & (newest_length > 0), m, denominator, output, qk_scale, ) newest_offset_start += BLOCK_K_MEMORY memory_start = tl.load(row_memory_start_ptr + row) memory_length = tl.load(row_token_memory_length_ptr + row) remote_memory_length = tl.maximum(memory_length - GLOBAL_SLOTS, 0) offs_memory = tl.arange(0, BLOCK_K_MEMORY) phase_offset = tl.minimum(q_pos, CHUNK_SIZE - 1) * BLOCK_D + offs_d cosine = tl.load( phase_cos_ptr + phase_offset, mask=query_valid & d_mask, other=1.0, ) sine = tl.load( phase_sin_ptr + phase_offset, mask=query_valid & d_mask, other=0.0, ) q_memory = _pat_rotate_vector( q, cosine.to(q.dtype), sine.to(q.dtype), BLOCK_D=BLOCK_D, FP32_PRODUCTS=FP32_ROTARY_PRODUCTS, ) memory_offset_start = memory_split * BLOCK_K_MEMORY while memory_offset_start < remote_memory_length: memory_offset = memory_offset_start + offs_memory memory_abs = memory_start + memory_offset memory_mask = ( query_valid & (memory_offset < remote_memory_length) & (memory_abs < memory_slots) ) k = tl.load( k_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) v = tl.load( v_memory_ptr + memory_abs[:, None] * heads * head_dim + head * head_dim + offs_d[None, :], mask=memory_mask[:, None] & d_mask[None, :], other=0.0, ) m, denominator, output = _pat_active_q1_online_step( q_memory, k, v, memory_mask, query_valid & (remote_memory_length > 0), m, denominator, output, qk_scale, ) memory_offset_start += MEMORY_SPLITS * BLOCK_K_MEMORY partial_base = ((row * heads + head) * MEMORY_SPLITS + memory_split) * (BLOCK_D + 2) tl.store(partial_ptr + partial_base, m) tl.store(partial_ptr + partial_base + 1, denominator) tl.store( partial_ptr + partial_base + 2 + offs_d, output, mask=d_mask, ) # Every split publishes its state before entering one GPU-scope # acq_rel release sequence. The CTA observing MEMORY_SPLITS - 1 is # therefore the last arrival and has acquired every partial store. # It performs the stable reduction in this same kernel launch, then # resets the persistent counter so the buffer is CUDA-graph replayable. completion_index = row * heads + head completed_before = tl.atomic_add( completion_counter_ptr + completion_index, 1, sem="acq_rel", scope="gpu", ) is_last = completed_before == MEMORY_SPLITS - 1 if is_last: _pat_active_q1_last_cta_combine( partial_ptr, completion_counter_ptr, out_ptr, row, head, completion_index, heads, head_dim, BLOCK_D=BLOCK_D, MEMORY_SPLITS=MEMORY_SPLITS, ) @triton.jit def _active_q1_post_projection_kernel( packed_qkv_ptr, query_cos_ptr, query_sin_ptr, key_cos_ptr, key_sin_ptr, qk_log_scale_ptr, flat_storage_indices_ptr, query_out_ptr, key_out_ptr, key_storage_ptr, value_storage_ptr, n_heads: tl.constexpr, head_dim: tl.constexpr, block_d: tl.constexpr, qk_norm_enabled: tl.constexpr, qk_norm_eps: tl.constexpr, q_scale_multiplier: tl.constexpr, ): token = tl.program_id(0) head = tl.program_id(1) offsets = tl.arange(0, block_d) mask = offsets < head_dim pair_offsets = offsets ^ 1 projected_base = (token * n_heads + head) * head_dim packed_token_base = token * 3 * n_heads * head_dim query_base = packed_token_base + head * head_dim key_base = query_base + n_heads * head_dim value_base = key_base + n_heads * head_dim rope_base = token * head_dim element_type = packed_qkv_ptr.dtype.element_ty query_raw = tl.load( packed_qkv_ptr + query_base + offsets, mask=mask, other=0.0, ) query_pair = tl.load( packed_qkv_ptr + query_base + pair_offsets, mask=mask, other=0.0, ) key_raw = tl.load( packed_qkv_ptr + key_base + offsets, mask=mask, other=0.0, ) key_pair = tl.load( packed_qkv_ptr + key_base + pair_offsets, mask=mask, other=0.0, ) query_cos = tl.load( query_cos_ptr + rope_base + offsets, mask=mask, other=0.0, ) query_sin = tl.load( query_sin_ptr + rope_base + offsets, mask=mask, other=0.0, ) key_cos = tl.load( key_cos_ptr + rope_base + offsets, mask=mask, other=0.0, ) key_sin = tl.load( key_sin_ptr + rope_base + offsets, mask=mask, other=0.0, ) pair_sign = tl.where((offsets & 1) == 0, -1.0, 1.0) # Preserve the eager low-precision operation boundaries. GPU # qualification still owns final bitwise/tolerance adjudication because # the fused reduction tree is necessarily kernel-local. query_cos_term = (query_raw * query_cos).to(element_type) query_sin_term = (query_pair * pair_sign * query_sin).to(element_type) query = (query_cos_term + query_sin_term).to(element_type) key_cos_term = (key_raw * key_cos).to(element_type) key_sin_term = (key_pair * pair_sign * key_sin).to(element_type) key = (key_cos_term + key_sin_term).to(element_type) if qk_norm_enabled: query_fp32 = query.to(tl.float32) key_fp32 = key.to(tl.float32) query_denom = tl.maximum( tl.sqrt(tl.sum(query_fp32 * query_fp32, axis=0)), qk_norm_eps, ) key_denom = tl.maximum( tl.sqrt(tl.sum(key_fp32 * key_fp32, axis=0)), qk_norm_eps, ) query_unit = (query_fp32 / query_denom).to(element_type) key = (key_fp32 / key_denom).to(element_type) scale = tl.exp(tl.load(qk_log_scale_ptr + head).to(tl.float32)).to(element_type) query = (query_unit * scale).to(element_type) query = (query * q_scale_multiplier).to(element_type) tl.store(query_out_ptr + projected_base + offsets, query, mask=mask) tl.store(key_out_ptr + projected_base + offsets, key, mask=mask) flat_index = tl.load(flat_storage_indices_ptr + token) storage_base = (flat_index * n_heads + head) * head_dim tl.store(key_storage_ptr + storage_base + offsets, key, mask=mask) projected_value = tl.load( packed_qkv_ptr + value_base + offsets, mask=mask, other=0.0, ) tl.store( value_storage_ptr + storage_base + offsets, projected_value, mask=mask, ) def prepare_one(packed, layer, positions, key_storage, value_storage, offset): """Fuse rotary/QK normalization and publish a single lexical token's KV.""" heads, dimension = layer.n_heads, layer.head_dim cosine, sine = layer.rope.cache(positions, dtype=packed.dtype, device=packed.device) query = packed.new_empty((1, heads, dimension)) key = torch.empty_like(query) index = torch.tensor([offset], device=packed.device, dtype=torch.long) _active_q1_post_projection_kernel[(1, heads)]( packed, cosine, sine, cosine, sine, layer.qk_log_scale, index, query, key, key_storage, value_storage, n_heads=heads, head_dim=dimension, block_d=triton.next_power_of_2(dimension), qk_norm_enabled=True, qk_norm_eps=layer.qk_norm_eps, q_scale_multiplier=dimension**0.5, num_warps=1, ) return query def attend( query, memory, exact, local, *, offset, lexical_count, global_slots, chunk_size, max_memory_size, tail, ): """One active document row; lexical Q1 uses the fixed eight-way reduction.""" km, vm = memory ke, ve = exact kl, vl = local config = KernelConfig(chunk_size, max_memory_size, warps=2) heads, dimension = query.shape[1:] block_d = triton.next_power_of_2(dimension) pc, ps = _cached_pat_attention_phases( config=config, device=query.device, dtype=query.dtype, head_dim=dimension ) def integer(value): return torch.tensor([value], dtype=torch.int32, device=query.device) zero = integer(0) length = integer(offset + query.size(0)) lexical = integer(lexical_count) memory_length, exact_length = integer(km.size(0)), integer(ke.size(0)) start = integer(offset) output = torch.empty_like(query) args = ( query, km, vm, ke, ve, kl, vl, output, length, lexical, zero, memory_length, memory_length, zero, exact_length, zero, zero, pc, ps, ) scalars = (dimension**-0.5, km.size(0), ke.size(0), kl.size(0), heads, dimension) launch = { "GLOBAL_SLOTS": global_slots, "CHUNK_SIZE": chunk_size, "BLOCK_K_MEMORY": 64, "BLOCK_K_TOKEN": 16, "BLOCK_D": block_d, "QUERY_IS_EOC": tail, "num_warps": 2, "num_stages": 3, "FP32_ROTARY_PRODUCTS": True, } if not tail: workspace = torch.empty( (1, heads, 8, block_d + 2), device=query.device, dtype=torch.float32 ) counters = torch.zeros((1, heads), device=query.device, dtype=torch.int32) _pat_active_q1_splitk_forward_kernel[(1, heads, 8)]( query, km, vm, ke, ve, kl, vl, workspace, counters, output, length, lexical, zero, memory_length, zero, exact_length, zero, zero, pc, ps, start, *scalars, GLOBAL_SLOTS=global_slots, CHUNK_SIZE=chunk_size, BLOCK_K_MEMORY=64, BLOCK_K_TOKEN=16, BLOCK_D=block_d, MEMORY_SPLITS=8, num_warps=2, num_stages=3, FP32_ROTARY_PRODUCTS=True, ) elif query.size(0) == 1: _pat_active_q1_forward_kernel[(1, heads)](*args, start, *scalars, **launch) else: tiles = triton.cdiv(query.size(0), 16) tile_rows = torch.zeros(tiles, dtype=torch.int32, device=query.device) tile_starts = torch.arange(tiles, dtype=torch.int32, device=query.device) * 16 + offset _pat_active_forward_kernel[(tiles, heads)]( *args, tile_rows, tile_starts, zero, start, *scalars, BLOCK_Q=16, **launch, ) return output