Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def test_fused_recurrent_gated_delta_rule_310p_parity_precision():
torch.float16
)

initial_state = torch.randn(2, num_v_heads, kdim, vdim, dtype=torch.float16, device=device)
initial_state = torch.randn(2, num_v_heads, vdim, kdim, dtype=torch.float16, device=device)
cu_seqlens = torch.tensor([0, 4, 9], dtype=torch.long, device=device)
# For inplace_final_state=True, Ascend triton kernel expects explicit per-token state indices.
# seq0 (len=4) -> state 0, seq1 (len=5) -> state 1.
Expand Down
41 changes: 38 additions & 3 deletions tests/ut/_310p/ops/test_chunk_gated_delta_rule_310.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def test_chunk_gated_delta_rule_310_output_shape_and_dtype():
v = torch.randn(bsz, total_tokens, num_v_heads, vdim, dtype=torch.float16)
g = -0.2 * torch.rand(bsz, total_tokens, num_v_heads, dtype=torch.float32)
beta = (0.15 + 0.35 * torch.rand(bsz, total_tokens, num_v_heads, dtype=torch.float32)).to(torch.float16)
initial_state = torch.randn(bsz, num_v_heads, kdim, vdim, dtype=torch.float16)
initial_state = torch.randn(bsz, num_v_heads, vdim, kdim, dtype=torch.float16)

out, final_state = chunk_gated_delta_rule_pytorch(
q=q,
Expand Down Expand Up @@ -56,7 +56,7 @@ def test_chunk_gated_delta_rule_310_varlen_path():
g = -0.2 * torch.rand(bsz, total_tokens, num_v_heads, dtype=torch.float32)
beta = (0.15 + 0.35 * torch.rand(bsz, total_tokens, num_v_heads, dtype=torch.float32)).to(torch.float16)
cu_seqlens = torch.tensor([0, 4, 9], dtype=torch.long)
initial_state = torch.randn(2, num_v_heads, kdim, vdim, dtype=torch.float16)
initial_state = torch.randn(2, num_v_heads, vdim, kdim, dtype=torch.float16)

out, final_state = chunk_gated_delta_rule_pytorch(
q=q,
Expand Down Expand Up @@ -91,7 +91,7 @@ def test_chunk_gated_delta_rule_310_varlen_tnd_path():
g_tnd = -0.2 * torch.rand(total_tokens, num_v_heads, dtype=torch.float32)
beta_tnd = (0.15 + 0.35 * torch.rand(total_tokens, num_v_heads, dtype=torch.float32)).to(torch.float16)
cu_seqlens = torch.tensor([0, 4, 9], dtype=torch.long)
initial_state = torch.randn(2, num_v_heads, kdim, vdim, dtype=torch.float16)
initial_state = torch.randn(2, num_v_heads, vdim, kdim, dtype=torch.float16)

out_tnd, final_state_tnd = chunk_gated_delta_rule_pytorch(
q=q_tnd,
Expand Down Expand Up @@ -124,3 +124,38 @@ def test_chunk_gated_delta_rule_310_varlen_tnd_path():
assert final_state_tnd is not None
assert final_state_bthd is not None
torch.testing.assert_close(final_state_tnd, final_state_bthd, rtol=1e-4, atol=1e-4)


def test_chunk_gated_delta_rule_310_state_layout_matches_vllm():
q = torch.tensor([[[[1.0, 0.0]]]], dtype=torch.float32)
k = torch.tensor([[[[1.0, 0.0]]]], dtype=torch.float32)
v = torch.tensor([[[[10.0, 20.0, 30.0]]]], dtype=torch.float32)
g = torch.zeros(1, 1, 1, dtype=torch.float32)
beta = torch.ones(1, 1, 1, dtype=torch.float32)
initial_state = torch.tensor(
[[[[1.0, 2.0], [4.0, 8.0], [16.0, 32.0]]]],
dtype=torch.float32,
)

out, final_state = chunk_gated_delta_rule_pytorch(
q=q,
k=k,
v=v,
g=g,
beta=beta,
initial_state=initial_state,
output_final_state=True,
cu_seqlens=None,
head_first=False,
use_qk_l2norm_in_kernel=False,
)

expected_out = torch.tensor([[[[10.0, 20.0, 30.0]]]], dtype=torch.float32) / (2.0**0.5)
expected_state = torch.tensor(
[[[[10.0, 2.0], [20.0, 8.0], [30.0, 32.0]]]],
dtype=torch.float32,
)

torch.testing.assert_close(out, expected_out, rtol=1e-5, atol=1e-5)
assert final_state is not None
torch.testing.assert_close(final_state, expected_state, rtol=1e-5, atol=1e-5)
38 changes: 38 additions & 0 deletions tests/ut/_310p/ops/test_fused_recurrent_gated_delta_rule_310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import torch

from vllm_ascend._310p.ops.fla.fused_recurrent_gated_delta_rule import fused_recurrent_gated_delta_rule_pytorch


def test_fused_recurrent_gated_delta_rule_310_state_layout_matches_vllm():
q = torch.tensor([[[[1.0, 0.0]]]], dtype=torch.float32)
k = torch.tensor([[[[1.0, 0.0]]]], dtype=torch.float32)
v = torch.tensor([[[[10.0, 20.0, 30.0]]]], dtype=torch.float32)
g = torch.zeros(1, 1, 1, dtype=torch.float32)
beta = torch.ones(1, 1, 1, dtype=torch.float32)
initial_state = torch.tensor(
[[[[1.0, 2.0], [4.0, 8.0], [16.0, 32.0]]]],
dtype=torch.float32,
)

out, final_state = fused_recurrent_gated_delta_rule_pytorch(
q=q,
k=k,
v=v,
g=g,
beta=beta,
initial_state=initial_state,
inplace_final_state=False,
cu_seqlens=None,
ssm_state_indices=None,
num_accepted_tokens=None,
use_qk_l2norm_in_kernel=False,
)

expected_out = torch.tensor([[[[10.0, 20.0, 30.0]]]], dtype=torch.float32) / (2.0**0.5)
expected_state = torch.tensor(
[[[[10.0, 2.0], [20.0, 8.0], [30.0, 32.0]]]],
dtype=torch.float32,
)

torch.testing.assert_close(out, expected_out, rtol=1e-5, atol=1e-5)
torch.testing.assert_close(final_state, expected_state, rtol=1e-5, atol=1e-5)
20 changes: 8 additions & 12 deletions vllm_ascend/_310p/ops/fla/chunk_gated_delta_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@
CHUNK_SIZE = 64


def _l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6) -> torch.Tensor:
return x * torch.rsqrt(x.square().sum(dim=dim, keepdim=True) + eps)


def _expand_qk_to_v_heads(x: torch.Tensor, num_v_heads: int) -> torch.Tensor:
"""
Expand q/k heads to match v heads for grouped-value-attention semantics.
Expand Down Expand Up @@ -104,12 +100,12 @@ def _torch_chunk_gated_delta_rule_chunked(
query/key: [B, T, H, K]
value: [B, T, H, V]
g/beta: [B, T, H]
initial_state: [B, H, K, V]
initial_state: [B, H, V, K]
"""
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)
query = F.normalize(query, p=2, dim=-1).to(query.dtype)
key = F.normalize(key, p=2, dim=-1).to(key.dtype)
Comment thread
Tflowers-0129 marked this conversation as resolved.
Resolved

query, key, value, beta, g = [
x.transpose(1, 2).contiguous().to(torch.float32) for x in (query, key, value, beta, g)
Expand Down Expand Up @@ -155,7 +151,7 @@ def _torch_chunk_gated_delta_rule_chunked(
k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))

last_recurrent_state = (
torch.zeros(batch_size, num_heads, k_head_dim, v_head_dim, device=value.device, dtype=value.dtype)
torch.zeros(batch_size, num_heads, v_head_dim, k_head_dim, device=value.device, dtype=value.dtype)
if initial_state is None
else initial_state.to(value)
)
Expand All @@ -167,13 +163,13 @@ def _torch_chunk_gated_delta_rule_chunked(
for i in range(0, total_sequence_length // chunk_size):
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
attn_inter_chunk = (q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]).masked_fill_(mask_upper, 0)
v_prime = k_cumdecay[:, :, i] @ last_recurrent_state
v_prime = k_cumdecay[:, :, i] @ last_recurrent_state.transpose(-1, -2)
v_new = v_i - v_prime
inter_state = (q_i * g[:, :, i, :, None].exp()) @ last_recurrent_state
inter_state = (q_i * g[:, :, i, :, None].exp()) @ last_recurrent_state.transpose(-1, -2)
core_attn_out[:, :, i] = inter_state + attn_inter_chunk @ v_new
last_recurrent_state = (
last_recurrent_state * g[:, :, i, -1, None, None].exp()
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
+ v_new.transpose(-1, -2) @ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None])
)

if not output_final_state:
Expand Down Expand Up @@ -221,7 +217,7 @@ def chunk_gated_delta_rule_pytorch(
if initial_state is not None:
states = initial_state.to(torch.float32).clone()
else:
states = torch.zeros(num_states, h_v, k_dim, v_dim, dtype=torch.float32, device=q.device)
states = torch.zeros(num_states, h_v, v_dim, k_dim, dtype=torch.float32, device=q.device)

out = torch.zeros_like(v)
for seq_idx, start, end in seq_ranges:
Expand Down
11 changes: 6 additions & 5 deletions vllm_ascend/_310p/ops/fla/fused_recurrent_gated_delta_rule.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import torch
import torch.nn.functional as F
Comment thread
Tflowers-0129 marked this conversation as resolved.
Resolved


def _maybe_l2norm(x: torch.Tensor, enabled: bool) -> torch.Tensor:
if not enabled:
return x
return x / (torch.sqrt(torch.sum(x * x, dim=-1, keepdim=True)) + 1e-6)
return F.normalize(x, p=2, dim=-1).to(x.dtype)
Comment thread
Tflowers-0129 marked this conversation as resolved.
Resolved


def _expand_to_hv(x: torch.Tensor, hv: int) -> torch.Tensor:
Expand Down Expand Up @@ -65,7 +66,7 @@ def _run_recurrent_gated_delta_rule(
q,k: [B, T, H, K]
v: [B, T, HV, V]
g,beta: [B, T, HV] (beta may also be [B, T, HV, V])
states: [N_state, HV, K, V]
states: [N_state, HV, V, K]
"""
B, T, _, Kdim = k.shape
HV = v.shape[2]
Expand Down Expand Up @@ -112,7 +113,7 @@ def _run_recurrent_gated_delta_rule(
continue
if init_state_idx >= states.shape[0]:
raise IndexError(f"state_idx {init_state_idx} out of range for states size {states.shape[0]}")
h_t = states[init_state_idx].transpose(-1, -2).to(torch.float32)
h_t = states[init_state_idx].to(torch.float32)
else:
h_t = torch.zeros(HV, Vdim, Kdim, dtype=torch.float32, device=q.device)

Expand Down Expand Up @@ -176,7 +177,7 @@ def _run_recurrent_gated_delta_rule(
if state_idx >= 0:
if state_idx >= states.shape[0]:
raise IndexError(f"state_idx {state_idx} out of range for states size {states.shape[0]}")
states[state_idx] = h_t.transpose(-1, -2).to(states.dtype)
states[state_idx] = h_t.to(states.dtype)

return out, states

Expand Down Expand Up @@ -204,7 +205,7 @@ def fused_recurrent_gated_delta_rule_pytorch(
if initial_state is not None:
states = initial_state if inplace_final_state else initial_state.clone()
else:
states = torch.zeros(n_states, HV, Kdim, Vdim, dtype=q.dtype, device=q.device)
states = torch.zeros(n_states, HV, Vdim, Kdim, dtype=q.dtype, device=q.device)

scale = Kdim**-0.5
out, states = _run_recurrent_gated_delta_rule(
Expand Down
Loading