areneau's picture
Update Clairic Transformers runtime
24191a8 verified
Raw History Blame Contribute Delete
5.78 kB
"""Pack native inputs and preserve native cache axes around selected kernels."""
from __future__ import annotations
from typing import Any
import torch
from .. import recurrent_metadata
def _packed_indices(mixed: torch.Tensor, mask: torch.Tensor | None) -> tuple[torch.Tensor, torch.Tensor]:
"""Return valid-token indices and one boundary per native row."""
batch, length = mixed.shape[:2]
if mask is None:
indices = torch.arange(batch * length, device=mixed.device)
boundaries = torch.arange(batch + 1, device=mixed.device, dtype=torch.int32) * length
return indices, boundaries
if mask.ndim != 2 or mask.shape[0] != batch or mask.shape[1] < length:
raise ValueError("Expected a two-dimensional mask covering current tokens")
valid = mask[:, -length:].to(device=mixed.device, dtype=torch.bool)
lengths = valid.sum(dim=1, dtype=torch.int32)
if bool((lengths == 0).any()):
raise ValueError("Each recurrent sequence must contain a current token")
boundaries = torch.cat((lengths.new_zeros(1), lengths.cumsum(0, dtype=torch.int32)))
return valid.reshape(-1).nonzero().flatten(), boundaries
def packed_indices(mixed: torch.Tensor, mask: torch.Tensor | None) -> tuple[torch.Tensor, torch.Tensor]:
"""Reuse exact packing metadata within an owned inference forward."""
return recurrent_metadata.packed_indices(mixed, mask, _packed_indices)
def source_state(native: torch.Tensor | None, batch: int, heads: int, key_dim: int,
value_dim: int, reference: torch.Tensor) -> torch.Tensor:
"""Map native K,V cache dimensions to the selected kernel's V,K layout."""
if native is None:
return torch.zeros(batch, heads, value_dim, key_dim,
device=reference.device, dtype=torch.float32)
if tuple(native.shape) != (batch, heads, key_dim, value_dim):
raise ValueError("Unexpected native recurrent cache shape")
if native.dtype != torch.float32:
raise ValueError("Recurrent states must retain float32 precision")
return native.transpose(-1, -2).contiguous()
def native_state(source: torch.Tensor) -> torch.Tensor:
"""Expose K,V cache axes without narrowing or copying source state."""
return source.transpose(-1, -2)
def store_state(cache: Any, layer_idx: int, state: torch.Tensor) -> torch.Tensor:
"""Initialize FP32 recurrent storage while retaining native cache lifecycle."""
if state.dtype != torch.float32:
raise ValueError("Expected float32 recurrent state")
layer = cache.layers[layer_idx]
if not layer.is_recurrent_states_initialized:
layer.recurrent_states = torch.empty_like(state)
if not torch.compiler.is_compiling():
torch._dynamo.mark_static_address(layer.recurrent_states)
layer.is_recurrent_states_initialized = True
elif layer.recurrent_states.dtype != torch.float32:
raise ValueError("Cannot resume a narrowed recurrent cache")
return cache.update_recurrent_state(state, layer_idx)
def prefill(mixed: torch.Tensor, a: torch.Tensor, b: torch.Tensor, A_log: torch.Tensor,
dt_bias: torch.Tensor, key_heads: int, value_heads: int, key_dim: int,
value_dim: int, initial_state: torch.Tensor | None,
attention_mask: torch.Tensor | None) -> tuple[torch.Tensor, torch.Tensor]:
"""Run packed prefill and scatter valid outputs to native padded shape."""
from .gating import fused_gdn_gating
from .index import prepare_chunk_indices
from .l2norm import l2norm_fwd
from .prefill import chunk_gated_delta_rule_fwd
batch, length, _ = mixed.shape
indices, boundaries = packed_indices(mixed, attention_mask)
packed = mixed.flatten(0, 1).index_select(0, indices)
pa = a.flatten(0, 1).index_select(0, indices)
pb = b.flatten(0, 1).index_select(0, indices)
query, key, value = torch.split(packed,
(key_heads * key_dim, key_heads * key_dim, value_heads * value_dim), dim=-1)
query = l2norm_fwd(query.reshape(1, -1, key_heads, key_dim).contiguous())
key = l2norm_fwd(key.reshape(1, -1, key_heads, key_dim).contiguous())
value = value.reshape(1, -1, value_heads, value_dim).contiguous()
gate, beta = fused_gdn_gating(A_log, pa, pb, dt_bias)
state = source_state(initial_state, batch, value_heads, key_dim, value_dim, mixed)
slots = recurrent_metadata.sequence_slots(mixed)
_, output, *_ = chunk_gated_delta_rule_fwd(query, key, value, gate, beta,
key_dim ** -0.5, state, slots, boundaries, prepare_chunk_indices(boundaries, 64))
padded = mixed.new_zeros(batch * length, value_heads, value_dim)
padded.index_copy_(0, indices, output.squeeze(0))
return padded.reshape(batch, length, value_heads, value_dim), native_state(state)
def decode(mixed: torch.Tensor, a: torch.Tensor, b: torch.Tensor, A_log: torch.Tensor,
dt_bias: torch.Tensor, initial_state: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Use the selected packed single-token recurrent operation."""
from .recurrent import fused_recurrent_gated_delta_rule_packed_decode
batch, length, _ = mixed.shape
if length != 1:
raise ValueError("Packed recurrent decode requires one token per row")
_, heads, key_dim, value_dim = initial_state.shape
state = source_state(initial_state, batch, heads, key_dim, value_dim, mixed)
output = mixed.new_empty(batch, 1, heads, value_dim)
slots = recurrent_metadata.sequence_slots(mixed)
fused_recurrent_gated_delta_rule_packed_decode(mixed[:, 0].contiguous(),
a[:, 0].contiguous(), b[:, 0].contiguous(), A_log, dt_bias, key_dim ** -0.5,
state, output, slots, use_qk_l2norm_in_kernel=True)
return output, native_state(state)