[CPU][Perf] Enable fused kernels for GDN's gated delta rules (#43534)
Signed-off-by: Fadi Arafeh <fadi.arafeh@arm.com> Co-authored-by: Li, Jiang <jiang1.li@intel.com>
This commit is contained in:
co-authored by
Li, Jiang <jiang1.li@intel.com>
parent
dcdfe66bfa
commit
0b25cf4419
@@ -12,11 +12,6 @@ from vllm.model_executor.layers.mamba.ops.cpu.causal_conv1d import (
|
||||
causal_conv1d_torch,
|
||||
causal_conv1d_update_torch,
|
||||
)
|
||||
from vllm.model_executor.layers.mamba.ops.cpu.recurrent_gated_delta_rule import (
|
||||
chunk_gated_delta_rule,
|
||||
gdn_gating,
|
||||
recurrent_gated_delta_rule,
|
||||
)
|
||||
from vllm.utils.torch_utils import (
|
||||
LayerNameType,
|
||||
_resolve_layer_name,
|
||||
@@ -55,88 +50,91 @@ def cpu_gdn_attention_core(
|
||||
attn_metadata_i.spec_sequence_masks is None
|
||||
and attn_metadata_i.num_accepted_tokens is None
|
||||
), "speculative decode not supported in CPU GDN attention."
|
||||
|
||||
if torch.cpu._is_amx_tile_supported():
|
||||
return cpu_gdn_attention_core_amx(
|
||||
mixed_qkv,
|
||||
b,
|
||||
a,
|
||||
core_attn_out,
|
||||
attn_metadata_i,
|
||||
layer,
|
||||
)
|
||||
assert mixed_qkv.dtype == torch.bfloat16, "CPU GDN attention requires BF16."
|
||||
|
||||
state_indices_tensor = attn_metadata_i.non_spec_state_indices_tensor
|
||||
query_start_loc = attn_metadata_i.non_spec_query_start_loc
|
||||
assert state_indices_tensor is not None
|
||||
assert query_start_loc is not None
|
||||
|
||||
# [num_allocated_slots, conv_dim, kernel - 1]
|
||||
is_amx = torch.cpu._is_amx_tile_supported()
|
||||
|
||||
conv_state = layer.kv_cache[0]
|
||||
if not is_conv_state_dim_first():
|
||||
conv_state = conv_state.transpose(-1, -2)
|
||||
if is_amx:
|
||||
# AMX causal conv requires [num_allocated_slots, kernel - 1, conv_dim].
|
||||
if is_conv_state_dim_first():
|
||||
raise RuntimeError("AMX GDN attention requires `SD` conv_state layout.")
|
||||
conv_state = conv_state.transpose(1, 2)
|
||||
else:
|
||||
if not is_conv_state_dim_first():
|
||||
conv_state = conv_state.transpose(-1, -2)
|
||||
conv_weights = layer.conv1d.weight.view(
|
||||
layer.conv1d.weight.size(0), layer.conv1d.weight.size(2)
|
||||
)
|
||||
|
||||
# [num_allocated_slots, num_v_heads / tp_size, v_dim, k_dim]
|
||||
ssm_state = layer.kv_cache[1]
|
||||
mixed_qkv = mixed_qkv.contiguous()
|
||||
a = a.contiguous()
|
||||
b = b.contiguous()
|
||||
|
||||
num_allocated_slots, head_num, v_dim, k_dim = ssm_state.size()
|
||||
ssm_state = ssm_state.view(
|
||||
num_allocated_slots,
|
||||
head_num,
|
||||
k_dim,
|
||||
v_dim,
|
||||
)
|
||||
|
||||
num_decodes = attn_metadata_i.num_decodes
|
||||
num_decode_tokens = attn_metadata_i.num_decode_tokens
|
||||
num_prefills = attn_metadata_i.num_prefills
|
||||
num_prefill_tokens = attn_metadata_i.num_prefill_tokens
|
||||
|
||||
conv_weights = layer.conv1d.weight.view(
|
||||
layer.conv1d.weight.size(0), layer.conv1d.weight.size(2)
|
||||
)
|
||||
|
||||
# all decode requests (batched)
|
||||
if num_decodes > 0:
|
||||
decode_mixed_qkv = mixed_qkv[:num_decode_tokens]
|
||||
decode_b = b[:num_decode_tokens]
|
||||
decode_a = a[:num_decode_tokens]
|
||||
decode_state_indices = state_indices_tensor[:num_decodes]
|
||||
decode_conv_state = conv_state[decode_state_indices].contiguous()
|
||||
if is_amx:
|
||||
decode_mixed_qkv = ops.causal_conv1d_update_cpu(
|
||||
x=decode_mixed_qkv,
|
||||
conv_states=conv_state,
|
||||
weight=layer.conv1d.weight,
|
||||
bias=layer.conv1d.bias,
|
||||
silu_activation=layer.activation == "silu",
|
||||
conv_state_indices=decode_state_indices,
|
||||
is_vnni=True,
|
||||
)
|
||||
else:
|
||||
decode_conv_state = conv_state[decode_state_indices].contiguous()
|
||||
|
||||
decode_mixed_qkv = causal_conv1d_update_torch(
|
||||
# [B, dim] -> [B, dim, 1]
|
||||
x=decode_mixed_qkv.unsqueeze(-1),
|
||||
conv_state=decode_conv_state,
|
||||
weight=conv_weights,
|
||||
bias=layer.conv1d.bias,
|
||||
activation=layer.activation,
|
||||
).squeeze(-1)
|
||||
conv_state[decode_state_indices] = decode_conv_state
|
||||
decode_mixed_qkv = causal_conv1d_update_torch(
|
||||
# [B, dim] -> [B, dim, 1]
|
||||
x=decode_mixed_qkv.unsqueeze(-1),
|
||||
conv_state=decode_conv_state,
|
||||
weight=conv_weights,
|
||||
bias=layer.conv1d.bias,
|
||||
activation=layer.activation,
|
||||
).squeeze(-1)
|
||||
conv_state[decode_state_indices] = decode_conv_state
|
||||
|
||||
query, key, value = layer.rearrange_mixed_qkv(decode_mixed_qkv)
|
||||
|
||||
# [1, L, H, D] -> [B, 1, H, D] for batched decode
|
||||
query = query.transpose(0, 1).contiguous()
|
||||
key = key.transpose(0, 1).contiguous()
|
||||
value = value.transpose(0, 1).contiguous()
|
||||
|
||||
g, beta_output = gdn_gating(
|
||||
attn_out = ops.fused_sigmoid_gating_delta_rule_update_cpu(
|
||||
A_log=layer.A_log,
|
||||
dt_bias=layer.dt_bias,
|
||||
q=query,
|
||||
k=key,
|
||||
v=value,
|
||||
a=decode_a,
|
||||
b=decode_b,
|
||||
dt_bias=layer.dt_bias,
|
||||
)
|
||||
if g.ndim == 2:
|
||||
g = g.unsqueeze(1)
|
||||
beta_output = beta_output.unsqueeze(1)
|
||||
|
||||
initial_state = ssm_state[decode_state_indices].contiguous()
|
||||
attn_out, last_recurrent_state = recurrent_gated_delta_rule(
|
||||
query=query,
|
||||
key=key,
|
||||
value=value,
|
||||
g=g,
|
||||
beta=beta_output,
|
||||
initial_state=initial_state,
|
||||
scale=None,
|
||||
initial_state_source=ssm_state,
|
||||
initial_state_indices=decode_state_indices,
|
||||
cu_seqlens=query_start_loc[: num_decodes + 1],
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
)
|
||||
ssm_state[decode_state_indices] = last_recurrent_state.to(
|
||||
ssm_state.dtype
|
||||
).contiguous()
|
||||
core_attn_out[:num_decode_tokens] = attn_out.squeeze(1)
|
||||
|
||||
# all prefill requests: (varlen) currently naively loops over sequences
|
||||
@@ -160,154 +158,29 @@ def cpu_gdn_attention_core(
|
||||
num_decodes : num_decodes + num_prefills
|
||||
]
|
||||
|
||||
prefill_mixed_qkv = causal_conv1d_torch(
|
||||
x=prefill_mixed_qkv.transpose(0, 1),
|
||||
weight=conv_weights,
|
||||
bias=layer.conv1d.bias,
|
||||
conv_states=conv_state,
|
||||
query_start_loc=prefill_query_start_loc,
|
||||
cache_indices=prefill_state_indices,
|
||||
has_initial_state=prefill_has_initial_state,
|
||||
activation=layer.activation,
|
||||
).transpose(0, 1)
|
||||
|
||||
query, key, value = layer.rearrange_mixed_qkv(prefill_mixed_qkv)
|
||||
g, beta = gdn_gating(layer.A_log, prefill_a, prefill_b, layer.dt_bias)
|
||||
if g.ndim == 2:
|
||||
g = g.unsqueeze(0)
|
||||
beta = beta.unsqueeze(0)
|
||||
|
||||
initial_state = ssm_state[prefill_state_indices].contiguous()
|
||||
initial_state[~prefill_has_initial_state, ...] = 0
|
||||
attn_out, last_recurrent_state = chunk_gated_delta_rule(
|
||||
q=query,
|
||||
k=key,
|
||||
v=value,
|
||||
g=g,
|
||||
beta=beta,
|
||||
scale=None,
|
||||
initial_state=initial_state,
|
||||
cu_seqlens=prefill_query_start_loc,
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
)
|
||||
ssm_state[prefill_state_indices] = last_recurrent_state.to(ssm_state.dtype)
|
||||
core_attn_out[prefill_token_start:prefill_token_end] = attn_out.squeeze(0)
|
||||
|
||||
|
||||
def cpu_gdn_attention_core_fake(
|
||||
mixed_qkv: torch.Tensor,
|
||||
b: torch.Tensor,
|
||||
a: torch.Tensor,
|
||||
core_attn_out: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
"""Fake implementation for torch.compile."""
|
||||
return
|
||||
|
||||
|
||||
def cpu_gdn_attention_core_amx(
|
||||
mixed_qkv: torch.Tensor,
|
||||
b: torch.Tensor,
|
||||
a: torch.Tensor,
|
||||
core_attn_out: torch.Tensor,
|
||||
attn_metadata_i: GDNAttentionMetadata,
|
||||
layer: torch.nn.Module,
|
||||
):
|
||||
state_indices_tensor = attn_metadata_i.non_spec_state_indices_tensor
|
||||
query_start_loc = attn_metadata_i.non_spec_query_start_loc
|
||||
assert state_indices_tensor is not None
|
||||
assert query_start_loc is not None
|
||||
|
||||
# [num_allocated_slots, kernel - 1, conv_dim]
|
||||
conv_state = layer.kv_cache[0]
|
||||
if is_conv_state_dim_first():
|
||||
raise RuntimeError("AMX GDN attention requires `SD` conv_state layout.")
|
||||
# reshape to [num_allocated_slots, conv_dim, kernel - 1]
|
||||
conv_state_t = conv_state.transpose(1, 2)
|
||||
|
||||
# [num_allocated_slots, num_v_heads / tp_size, v_dim, k_dim]
|
||||
ssm_state = layer.kv_cache[1]
|
||||
# rehape to [num_allocated_slots, num_v_heads / tp_size, k_dim, v_dim]
|
||||
num_allocated_slots, head_num, v_dim, k_dim = ssm_state.size()
|
||||
ssm_state = ssm_state.view(
|
||||
num_allocated_slots,
|
||||
head_num,
|
||||
k_dim,
|
||||
v_dim,
|
||||
)
|
||||
|
||||
mixed_qkv = mixed_qkv.contiguous()
|
||||
a = a.contiguous()
|
||||
b = b.contiguous()
|
||||
|
||||
num_decodes = attn_metadata_i.num_decodes
|
||||
num_decode_tokens = attn_metadata_i.num_decode_tokens
|
||||
num_prefills = attn_metadata_i.num_prefills
|
||||
num_prefill_tokens = attn_metadata_i.num_prefill_tokens
|
||||
|
||||
if num_decodes > 0:
|
||||
decode_mixed_qkv = mixed_qkv[:num_decode_tokens]
|
||||
decode_b = b[:num_decode_tokens]
|
||||
decode_a = a[:num_decode_tokens]
|
||||
decode_state_indices = state_indices_tensor[:num_decodes]
|
||||
|
||||
decode_mixed_qkv = ops.causal_conv1d_update_cpu(
|
||||
x=decode_mixed_qkv,
|
||||
conv_states=conv_state_t,
|
||||
weight=layer.conv1d.weight,
|
||||
bias=layer.conv1d.bias,
|
||||
silu_activation=layer.activation == "silu",
|
||||
conv_state_indices=decode_state_indices,
|
||||
is_vnni=True,
|
||||
)
|
||||
|
||||
query, key, value = layer.rearrange_mixed_qkv(decode_mixed_qkv)
|
||||
attn_out = ops.fused_sigmoid_gating_delta_rule_update_cpu(
|
||||
A_log=layer.A_log,
|
||||
dt_bias=layer.dt_bias,
|
||||
q=query,
|
||||
k=key,
|
||||
v=value,
|
||||
a=decode_a,
|
||||
b=decode_b,
|
||||
initial_state_source=ssm_state,
|
||||
initial_state_indices=decode_state_indices,
|
||||
cu_seqlens=query_start_loc[: num_decodes + 1],
|
||||
use_qk_l2norm_in_kernel=True,
|
||||
)
|
||||
core_attn_out[:num_decode_tokens] = attn_out.squeeze(1)
|
||||
|
||||
if num_prefills > 0:
|
||||
has_initial_state = attn_metadata_i.has_initial_state
|
||||
assert has_initial_state is not None
|
||||
|
||||
prefill_token_start = num_decode_tokens
|
||||
prefill_token_end = prefill_token_start + num_prefill_tokens
|
||||
prefill_mixed_qkv = mixed_qkv[prefill_token_start:prefill_token_end]
|
||||
prefill_b = b[prefill_token_start:prefill_token_end]
|
||||
prefill_a = a[prefill_token_start:prefill_token_end]
|
||||
prefill_state_indices = state_indices_tensor[
|
||||
num_decodes : num_decodes + num_prefills
|
||||
]
|
||||
prefill_query_start_loc = (
|
||||
query_start_loc[num_decodes : num_decodes + num_prefills + 1]
|
||||
- num_decode_tokens
|
||||
)
|
||||
prefill_has_initial_state = has_initial_state[
|
||||
num_decodes : num_decodes + num_prefills
|
||||
]
|
||||
|
||||
prefill_mixed_qkv = ops.causal_conv1d_fwd_cpu(
|
||||
x=prefill_mixed_qkv.transpose(0, 1),
|
||||
weight=layer.conv1d.weight,
|
||||
bias=layer.conv1d.bias,
|
||||
conv_states=conv_state_t,
|
||||
query_start_loc=prefill_query_start_loc,
|
||||
cache_indices=prefill_state_indices,
|
||||
has_initial_state=prefill_has_initial_state,
|
||||
silu_activation=layer.activation == "silu",
|
||||
is_vnni=True,
|
||||
).transpose(0, 1)
|
||||
if is_amx:
|
||||
prefill_mixed_qkv = ops.causal_conv1d_fwd_cpu(
|
||||
x=prefill_mixed_qkv.transpose(0, 1),
|
||||
weight=layer.conv1d.weight,
|
||||
bias=layer.conv1d.bias,
|
||||
conv_states=conv_state,
|
||||
query_start_loc=prefill_query_start_loc,
|
||||
cache_indices=prefill_state_indices,
|
||||
has_initial_state=prefill_has_initial_state,
|
||||
silu_activation=layer.activation == "silu",
|
||||
is_vnni=True,
|
||||
).transpose(0, 1)
|
||||
else:
|
||||
prefill_mixed_qkv = causal_conv1d_torch(
|
||||
x=prefill_mixed_qkv.transpose(0, 1),
|
||||
weight=conv_weights,
|
||||
bias=layer.conv1d.bias,
|
||||
conv_states=conv_state,
|
||||
query_start_loc=prefill_query_start_loc,
|
||||
cache_indices=prefill_state_indices,
|
||||
has_initial_state=prefill_has_initial_state,
|
||||
activation=layer.activation,
|
||||
).transpose(0, 1)
|
||||
|
||||
query, key, value = layer.rearrange_mixed_qkv(prefill_mixed_qkv)
|
||||
g, beta = ops.fused_gdn_gating_cpu(
|
||||
@@ -334,6 +207,17 @@ def cpu_gdn_attention_core_amx(
|
||||
core_attn_out[prefill_token_start:prefill_token_end] = attn_out.squeeze(0)
|
||||
|
||||
|
||||
def cpu_gdn_attention_core_fake(
|
||||
mixed_qkv: torch.Tensor,
|
||||
b: torch.Tensor,
|
||||
a: torch.Tensor,
|
||||
core_attn_out: torch.Tensor,
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
"""Fake implementation for torch.compile."""
|
||||
return
|
||||
|
||||
|
||||
def register_cpu_gdn_attention_ops() -> None:
|
||||
global _CPU_GDN_ATTENTION_OPS_REGISTERED
|
||||
if _CPU_GDN_ATTENTION_OPS_REGISTERED:
|
||||
|
||||
@@ -1,223 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
def l2norm(
|
||||
x: torch.Tensor,
|
||||
dim: int = -1,
|
||||
eps: float = 1e-6,
|
||||
) -> torch.Tensor:
|
||||
inv_norm = torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
|
||||
return x * inv_norm
|
||||
|
||||
|
||||
def recurrent_gated_delta_rule(
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
beta: torch.Tensor,
|
||||
initial_state: torch.Tensor,
|
||||
scale: float | None = None,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
initial_dtype = query.dtype
|
||||
if use_qk_l2norm_in_kernel:
|
||||
query = l2norm(query, dim=-1, eps=1e-6)
|
||||
key = l2norm(key, dim=-1, eps=1e-6)
|
||||
|
||||
if query.shape[2] != value.shape[2]:
|
||||
repeat_factor = value.shape[2] // query.shape[2]
|
||||
query = query.repeat_interleave(repeat_factor, dim=2)
|
||||
key = key.repeat_interleave(repeat_factor, dim=2)
|
||||
|
||||
query, key, value, beta, g = [
|
||||
x.transpose(1, 2).contiguous().to(torch.float32)
|
||||
for x in (query, key, value, beta, g)
|
||||
]
|
||||
|
||||
batch_size, num_heads, sequence_length, _ = key.shape
|
||||
v_head_dim = value.shape[-1]
|
||||
if scale is None:
|
||||
scale = 1 / (query.shape[-1] ** 0.5)
|
||||
query = query * scale
|
||||
|
||||
core_attn_out = torch.empty(
|
||||
batch_size,
|
||||
num_heads,
|
||||
sequence_length,
|
||||
v_head_dim,
|
||||
dtype=value.dtype,
|
||||
)
|
||||
last_recurrent_state = initial_state.to(value)
|
||||
|
||||
for token_idx in range(sequence_length):
|
||||
q_t = query[:, :, token_idx]
|
||||
k_t = key[:, :, token_idx]
|
||||
v_t = value[:, :, token_idx]
|
||||
g_t = g[:, :, token_idx].exp().unsqueeze(-1).unsqueeze(-1)
|
||||
beta_t = beta[:, :, token_idx].unsqueeze(-1)
|
||||
|
||||
last_recurrent_state = last_recurrent_state * g_t
|
||||
kv_mem = (last_recurrent_state * k_t.unsqueeze(-2)).sum(dim=-1)
|
||||
delta = (v_t - kv_mem) * beta_t
|
||||
last_recurrent_state = last_recurrent_state + delta.unsqueeze(
|
||||
-1
|
||||
) * k_t.unsqueeze(-2)
|
||||
core_attn_out[:, :, token_idx] = (last_recurrent_state * q_t.unsqueeze(-2)).sum(
|
||||
dim=-1
|
||||
)
|
||||
|
||||
core_attn_out = core_attn_out.transpose(1, 2).contiguous().to(initial_dtype)
|
||||
return core_attn_out, last_recurrent_state
|
||||
|
||||
|
||||
def gdn_gating(
|
||||
A_log: torch.Tensor,
|
||||
a: torch.Tensor,
|
||||
b: torch.Tensor,
|
||||
dt_bias: torch.Tensor,
|
||||
beta: float = 1.0,
|
||||
threshold: float = 20.0,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
softplus_x = F.softplus(a.float() + dt_bias.float(), beta=beta, threshold=threshold)
|
||||
g = -torch.exp(A_log.float()) * softplus_x
|
||||
beta_output = torch.sigmoid(b.float()).to(dtype=b.dtype)
|
||||
return g, beta_output
|
||||
|
||||
|
||||
def chunk_gated_delta_rule(
|
||||
q: torch.Tensor,
|
||||
k: torch.Tensor,
|
||||
v: torch.Tensor,
|
||||
g: torch.Tensor,
|
||||
beta: torch.Tensor,
|
||||
*,
|
||||
initial_state: torch.Tensor,
|
||||
scale: float | None = None,
|
||||
cu_seqlens: torch.Tensor,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
output = torch.empty_like(v)
|
||||
state_dtype = initial_state.dtype
|
||||
chunk_size = 128
|
||||
sequence_bounds = [
|
||||
(
|
||||
seq_idx,
|
||||
int(cu_seqlens[seq_idx].item()),
|
||||
int(cu_seqlens[seq_idx + 1].item()),
|
||||
)
|
||||
for seq_idx in range(len(cu_seqlens) - 1)
|
||||
]
|
||||
chunk_eye = torch.eye(chunk_size, dtype=torch.float32)
|
||||
num_sequences = len(sequence_bounds)
|
||||
num_value_heads = v.shape[2]
|
||||
value_head_dim = v.shape[3]
|
||||
key_head_dim = k.shape[3]
|
||||
final_state = torch.empty(
|
||||
(num_sequences, num_value_heads, value_head_dim, key_head_dim),
|
||||
dtype=state_dtype,
|
||||
)
|
||||
|
||||
for seq_idx, begin, end in sequence_bounds:
|
||||
q_seq = q[:, begin:end]
|
||||
k_seq = k[:, begin:end]
|
||||
v_seq = v[:, begin:end]
|
||||
g_seq = g[:, begin:end]
|
||||
beta_seq = beta[:, begin:end]
|
||||
|
||||
initial_dtype = q_seq.dtype
|
||||
if use_qk_l2norm_in_kernel:
|
||||
q_seq = l2norm(q_seq, dim=-1, eps=1e-6)
|
||||
k_seq = l2norm(k_seq, dim=-1, eps=1e-6)
|
||||
|
||||
num_qk_heads = q_seq.shape[2]
|
||||
num_value_heads = v_seq.shape[2]
|
||||
if num_qk_heads != num_value_heads:
|
||||
repeat_factor = num_value_heads // num_qk_heads
|
||||
q_seq = q_seq.repeat_interleave(repeat_factor, dim=2)
|
||||
k_seq = k_seq.repeat_interleave(repeat_factor, dim=2)
|
||||
|
||||
q_seq, k_seq, v_seq, beta_seq, g_seq = [
|
||||
x.transpose(1, 2).contiguous().to(torch.float32)
|
||||
for x in (q_seq, k_seq, v_seq, beta_seq, g_seq)
|
||||
]
|
||||
seq_batch_size, num_heads, seq_len, qk_head_dim = q_seq.shape
|
||||
value_head_dim = v_seq.shape[-1]
|
||||
|
||||
if scale is None:
|
||||
scale = 1 / (qk_head_dim**0.5)
|
||||
|
||||
q_seq = q_seq * scale
|
||||
|
||||
seq_state = initial_state[seq_idx : seq_idx + 1].to(v_seq)
|
||||
seq_output = torch.empty(
|
||||
seq_batch_size,
|
||||
num_heads,
|
||||
seq_len,
|
||||
value_head_dim,
|
||||
dtype=v_seq.dtype,
|
||||
)
|
||||
|
||||
for chunk_start in range(0, seq_len, chunk_size):
|
||||
chunk_end = min(chunk_start + chunk_size, seq_len)
|
||||
q_chunk = q_seq[:, :, chunk_start:chunk_end]
|
||||
k_chunk = k_seq[:, :, chunk_start:chunk_end]
|
||||
v_chunk = v_seq[:, :, chunk_start:chunk_end]
|
||||
beta_chunk = beta_seq[:, :, chunk_start:chunk_end]
|
||||
g_chunk = g_seq[:, :, chunk_start:chunk_end]
|
||||
chunk_len = chunk_end - chunk_start
|
||||
|
||||
cum_g = g_chunk.cumsum(dim=-1)
|
||||
exp_cum_g = cum_g.exp()
|
||||
decay = (cum_g.unsqueeze(-1) - cum_g.unsqueeze(-2)).exp()
|
||||
|
||||
interaction = (k_chunk * beta_chunk.unsqueeze(-1)) @ k_chunk.transpose(
|
||||
-1, -2
|
||||
)
|
||||
interaction = torch.tril(interaction * decay, diagonal=-1)
|
||||
system = interaction + chunk_eye[:chunk_len, :chunk_len]
|
||||
|
||||
solved_values = torch.linalg.solve_triangular(
|
||||
system,
|
||||
v_chunk * beta_chunk.unsqueeze(-1),
|
||||
upper=False,
|
||||
)
|
||||
solved_keys = torch.linalg.solve_triangular(
|
||||
system,
|
||||
(k_chunk * beta_chunk.unsqueeze(-1)) * exp_cum_g.unsqueeze(-1),
|
||||
upper=False,
|
||||
)
|
||||
|
||||
incoming_memory = torch.einsum("bhvk,bhck->bhcv", seq_state, solved_keys)
|
||||
transformed_values = solved_values - incoming_memory
|
||||
|
||||
# Each chunk contributes both from the incoming recurrent state and
|
||||
# from its own in-chunk interactions.
|
||||
inter_chunk = torch.einsum(
|
||||
"bhvk,bhck->bhcv",
|
||||
seq_state,
|
||||
q_chunk * exp_cum_g.unsqueeze(-1),
|
||||
)
|
||||
intra_chunk = torch.tril((q_chunk @ k_chunk.transpose(-1, -2)) * decay)
|
||||
seq_output[:, :, chunk_start:chunk_end] = (
|
||||
inter_chunk + intra_chunk @ transformed_values
|
||||
)
|
||||
|
||||
# Carry the recurrent state forward to the next chunk boundary.
|
||||
end_decay = (cum_g[:, :, -1:] - cum_g).exp().unsqueeze(-1)
|
||||
decayed_keys = k_chunk * end_decay
|
||||
seq_state = seq_state * exp_cum_g[:, :, -1, None, None] + torch.einsum(
|
||||
"bhcv,bhck->bhvk", transformed_values, decayed_keys
|
||||
)
|
||||
|
||||
output[0, begin:end].copy_(
|
||||
seq_output.transpose(1, 2).contiguous().to(initial_dtype).squeeze(0)
|
||||
)
|
||||
final_state[seq_idx].copy_(seq_state.squeeze(0).to(state_dtype).contiguous())
|
||||
|
||||
return output, final_state
|
||||
Reference in New Issue
Block a user