fla-core 0.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fla/__init__.py +4 -0
- fla/modules/__init__.py +33 -0
- fla/modules/activations.py +548 -0
- fla/modules/convolution.py +1143 -0
- fla/modules/feature_map.py +300 -0
- fla/modules/fused_bitlinear.py +632 -0
- fla/modules/fused_cross_entropy.py +419 -0
- fla/modules/fused_kl_div.py +324 -0
- fla/modules/fused_linear_cross_entropy.py +620 -0
- fla/modules/fused_norm_gate.py +1253 -0
- fla/modules/grpo.py +411 -0
- fla/modules/l2norm.py +285 -0
- fla/modules/l2warp.py +38 -0
- fla/modules/layernorm.py +1433 -0
- fla/modules/layernorm_gated.py +528 -0
- fla/modules/mlp.py +132 -0
- fla/modules/parallel.py +42 -0
- fla/modules/rotary.py +500 -0
- fla/modules/token_shift.py +543 -0
- fla/ops/__init__.py +53 -0
- fla/ops/abc/__init__.py +7 -0
- fla/ops/abc/chunk.py +1117 -0
- fla/ops/abc/naive.py +96 -0
- fla/ops/attn/__init__.py +7 -0
- fla/ops/attn/decoding.py +182 -0
- fla/ops/attn/parallel.py +730 -0
- fla/ops/based/__init__.py +9 -0
- fla/ops/based/fused_chunk.py +373 -0
- fla/ops/based/naive.py +72 -0
- fla/ops/based/parallel.py +408 -0
- fla/ops/comba/__init__.py +7 -0
- fla/ops/comba/chunk.py +342 -0
- fla/ops/comba/fused_recurrent.py +332 -0
- fla/ops/comba/utils.py +172 -0
- fla/ops/comba/wy_fast.py +423 -0
- fla/ops/common/__init__.py +1 -0
- fla/ops/common/chunk_delta_h.py +527 -0
- fla/ops/common/chunk_h.py +384 -0
- fla/ops/common/chunk_h_parallel.py +551 -0
- fla/ops/common/chunk_h_split.py +596 -0
- fla/ops/common/chunk_o.py +681 -0
- fla/ops/common/chunk_scaled_dot_kkt.py +305 -0
- fla/ops/common/fused_chunk.py +629 -0
- fla/ops/common/fused_recurrent.py +567 -0
- fla/ops/delta_rule/__init__.py +11 -0
- fla/ops/delta_rule/chunk.py +311 -0
- fla/ops/delta_rule/fused_chunk.py +6 -0
- fla/ops/delta_rule/fused_recurrent.py +535 -0
- fla/ops/delta_rule/naive.py +120 -0
- fla/ops/delta_rule/parallel.py +403 -0
- fla/ops/delta_rule/wy_fast.py +294 -0
- fla/ops/forgetting_attn/__init__.py +7 -0
- fla/ops/forgetting_attn/parallel.py +64 -0
- fla/ops/gated_delta_product/__init__.py +5 -0
- fla/ops/gated_delta_product/chunk.py +305 -0
- fla/ops/gated_delta_product/chunk_deltaproduct_h.py +502 -0
- fla/ops/gated_delta_product/chunk_deltaproduct_o.py +154 -0
- fla/ops/gated_delta_product/chunk_ref.py +68 -0
- fla/ops/gated_delta_product/naive.py +36 -0
- fla/ops/gated_delta_rule/__init__.py +7 -0
- fla/ops/gated_delta_rule/chunk.py +340 -0
- fla/ops/gated_delta_rule/fused_recurrent.py +351 -0
- fla/ops/gated_delta_rule/wy_fast.py +296 -0
- fla/ops/generalized_delta_rule/__init__.py +9 -0
- fla/ops/generalized_delta_rule/dplr/__init__.py +7 -0
- fla/ops/generalized_delta_rule/dplr/chunk.py +362 -0
- fla/ops/generalized_delta_rule/dplr/chunk_A_bwd.py +367 -0
- fla/ops/generalized_delta_rule/dplr/chunk_A_fwd.py +198 -0
- fla/ops/generalized_delta_rule/dplr/chunk_h_bwd.py +175 -0
- fla/ops/generalized_delta_rule/dplr/chunk_h_fwd.py +175 -0
- fla/ops/generalized_delta_rule/dplr/chunk_o_bwd.py +430 -0
- fla/ops/generalized_delta_rule/dplr/chunk_o_fwd.py +125 -0
- fla/ops/generalized_delta_rule/dplr/fused_recurrent.py +268 -0
- fla/ops/generalized_delta_rule/dplr/naive.py +96 -0
- fla/ops/generalized_delta_rule/dplr/wy_fast_bwd.py +164 -0
- fla/ops/generalized_delta_rule/dplr/wy_fast_fwd.py +284 -0
- fla/ops/generalized_delta_rule/iplr/__init__.py +7 -0
- fla/ops/generalized_delta_rule/iplr/chunk.py +492 -0
- fla/ops/generalized_delta_rule/iplr/fused_recurrent.py +452 -0
- fla/ops/generalized_delta_rule/iplr/naive.py +69 -0
- fla/ops/generalized_delta_rule/iplr/wy_fast.py +300 -0
- fla/ops/gla/__init__.py +11 -0
- fla/ops/gla/chunk.py +1298 -0
- fla/ops/gla/fused_chunk.py +642 -0
- fla/ops/gla/fused_recurrent.py +111 -0
- fla/ops/gla/naive.py +41 -0
- fla/ops/gsa/__init__.py +9 -0
- fla/ops/gsa/chunk.py +1133 -0
- fla/ops/gsa/fused_recurrent.py +536 -0
- fla/ops/gsa/naive.py +69 -0
- fla/ops/hgrn/__init__.py +9 -0
- fla/ops/hgrn/chunk.py +282 -0
- fla/ops/hgrn/fused_recurrent.py +308 -0
- fla/ops/hgrn/naive.py +63 -0
- fla/ops/lightning_attn/__init__.py +9 -0
- fla/ops/lightning_attn/chunk.py +84 -0
- fla/ops/lightning_attn/fused_recurrent.py +84 -0
- fla/ops/linear_attn/__init__.py +11 -0
- fla/ops/linear_attn/chunk.py +76 -0
- fla/ops/linear_attn/fused_chunk.py +61 -0
- fla/ops/linear_attn/fused_recurrent.py +35 -0
- fla/ops/linear_attn/naive.py +64 -0
- fla/ops/linear_attn/utils.py +10 -0
- fla/ops/log_linear_attn/__init__.py +7 -0
- fla/ops/log_linear_attn/chunk.py +1904 -0
- fla/ops/log_linear_attn/naive.py +50 -0
- fla/ops/mesa_net/__init__.py +5 -0
- fla/ops/mesa_net/chunk.py +371 -0
- fla/ops/mesa_net/chunk_cg_solver_bwd.py +162 -0
- fla/ops/mesa_net/chunk_cg_solver_fwd.py +186 -0
- fla/ops/mesa_net/chunk_h_fwd.py +170 -0
- fla/ops/mesa_net/chunk_h_kk_intra_bwd.py +191 -0
- fla/ops/mesa_net/chunk_h_kv_intra_bwd.py +209 -0
- fla/ops/mesa_net/chunk_h_kv_intra_bwd_separate.py +300 -0
- fla/ops/mesa_net/decoding_one_step.py +175 -0
- fla/ops/mesa_net/naive.py +131 -0
- fla/ops/nsa/__init__.py +9 -0
- fla/ops/nsa/compression.py +536 -0
- fla/ops/nsa/naive.py +103 -0
- fla/ops/nsa/parallel.py +879 -0
- fla/ops/nsa/utils.py +92 -0
- fla/ops/path_attn/__init__.py +7 -0
- fla/ops/path_attn/cumprod_householder_bwd.py +140 -0
- fla/ops/path_attn/cumprod_householder_fwd.py +119 -0
- fla/ops/path_attn/intra_chunk_preprocess_bwd.py +140 -0
- fla/ops/path_attn/intra_chunk_preprocess_bwd_prepare.py +208 -0
- fla/ops/path_attn/intra_chunk_preprocess_fwd.py +168 -0
- fla/ops/path_attn/parallel.py +270 -0
- fla/ops/path_attn/parallel_path_bwd_inter_dkv.py +189 -0
- fla/ops/path_attn/parallel_path_bwd_inter_dqh.py +200 -0
- fla/ops/path_attn/parallel_path_bwd_intra.py +172 -0
- fla/ops/path_attn/parallel_path_fwd.py +195 -0
- fla/ops/path_attn/prepare_k_cache.py +74 -0
- fla/ops/path_attn/transform_q.py +108 -0
- fla/ops/rebased/__init__.py +7 -0
- fla/ops/rebased/naive.py +27 -0
- fla/ops/rebased/parallel.py +464 -0
- fla/ops/retention/__init__.py +13 -0
- fla/ops/retention/chunk.py +77 -0
- fla/ops/retention/fused_chunk.py +78 -0
- fla/ops/retention/fused_recurrent.py +33 -0
- fla/ops/retention/naive.py +15 -0
- fla/ops/retention/parallel.py +71 -0
- fla/ops/rwkv4/__init__.py +7 -0
- fla/ops/rwkv4/fused_recurrent.py +472 -0
- fla/ops/rwkv6/__init__.py +9 -0
- fla/ops/rwkv6/chunk.py +1300 -0
- fla/ops/rwkv6/chunk_naive.py +43 -0
- fla/ops/rwkv6/fused_recurrent.py +673 -0
- fla/ops/rwkv6/recurrent_naive.py +103 -0
- fla/ops/rwkv7/__init__.py +10 -0
- fla/ops/rwkv7/channel_mixing.py +323 -0
- fla/ops/rwkv7/chunk.py +78 -0
- fla/ops/rwkv7/fused_addcmul.py +293 -0
- fla/ops/rwkv7/fused_k_update.py +346 -0
- fla/ops/rwkv7/fused_recurrent.py +334 -0
- fla/ops/rwkv7/gate_output_correction.py +244 -0
- fla/ops/simple_gla/__init__.py +13 -0
- fla/ops/simple_gla/chunk.py +303 -0
- fla/ops/simple_gla/fused_chunk.py +108 -0
- fla/ops/simple_gla/fused_recurrent.py +112 -0
- fla/ops/simple_gla/naive.py +114 -0
- fla/ops/simple_gla/parallel.py +722 -0
- fla/ops/titans/__init__.py +7 -0
- fla/ops/titans/log_impl.py +153 -0
- fla/ops/titans/naive.py +375 -0
- fla/ops/ttt/__init__.py +9 -0
- fla/ops/ttt/chunk.py +1441 -0
- fla/ops/ttt/fused_chunk.py +831 -0
- fla/ops/ttt/naive.py +126 -0
- fla/ops/utils/__init__.py +58 -0
- fla/ops/utils/constant.py +6 -0
- fla/ops/utils/cumsum.py +465 -0
- fla/ops/utils/index.py +133 -0
- fla/ops/utils/logcumsumexp.py +52 -0
- fla/ops/utils/logsumexp.py +80 -0
- fla/ops/utils/matmul.py +245 -0
- fla/ops/utils/op.py +62 -0
- fla/ops/utils/pack.py +208 -0
- fla/ops/utils/pooling.py +207 -0
- fla/ops/utils/softmax.py +106 -0
- fla/ops/utils/solve_tril.py +381 -0
- fla/utils.py +462 -0
- fla_core-0.3.2.dist-info/METADATA +575 -0
- fla_core-0.3.2.dist-info/RECORD +188 -0
- fla_core-0.3.2.dist-info/WHEEL +5 -0
- fla_core-0.3.2.dist-info/licenses/LICENSE +21 -0
- fla_core-0.3.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
import torch
|
|
4
|
+
from einops import rearrange
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def naive_chunk_rwkv6(
|
|
8
|
+
q: torch.Tensor,
|
|
9
|
+
k: torch.Tensor,
|
|
10
|
+
v: torch.Tensor,
|
|
11
|
+
w: torch.Tensor,
|
|
12
|
+
u: torch.Tensor,
|
|
13
|
+
chunk_size: int = 32
|
|
14
|
+
):
|
|
15
|
+
assert q.shape[-2] % chunk_size == 0
|
|
16
|
+
orig_dtype = q.dtype
|
|
17
|
+
num_chunk = q.shape[-2] // chunk_size
|
|
18
|
+
u = u.unsqueeze(0)
|
|
19
|
+
|
|
20
|
+
q, k, v, w = map(lambda x: rearrange(x, 'b h (n c) d -> b h n c d', c=chunk_size).float(), (q, k, v, w))
|
|
21
|
+
|
|
22
|
+
w_cumsum = w.cumsum(-2)
|
|
23
|
+
|
|
24
|
+
kw = k * (w_cumsum[..., -1, None, :] - w_cumsum).exp()
|
|
25
|
+
wkv = kw.transpose(-1, -2) @ v
|
|
26
|
+
|
|
27
|
+
wkv_new = torch.zeros_like(wkv)
|
|
28
|
+
|
|
29
|
+
for i in range(num_chunk - 1):
|
|
30
|
+
wkv_new[:, :, i+1] = (wkv_new[:, :, i] * w_cumsum[:, :, i, -1, :, None].exp()) + wkv[:, :, i]
|
|
31
|
+
|
|
32
|
+
o_inter = torch.einsum('b h n d p, b h n c d -> b h n c p', wkv_new, (q * (w_cumsum - w).exp()))
|
|
33
|
+
|
|
34
|
+
o_intra = torch.zeros_like(o_inter)
|
|
35
|
+
for i in range(chunk_size):
|
|
36
|
+
attn = (q[:, :, :, i, None] * k * (w_cumsum[:, :, :, i, None] - w[:, :, :, i, None] - w_cumsum).exp()).sum(-1)
|
|
37
|
+
mask = (torch.arange(0, chunk_size) < i).to(attn.device)
|
|
38
|
+
attn.masked_fill_(~mask, 0)
|
|
39
|
+
intra_inter_o = (attn.unsqueeze(-1) * v).sum(-2)
|
|
40
|
+
intra_intra_o = (q[:, :, :, i] * u.unsqueeze(2) * k[:, :, :, i]).sum(-1).unsqueeze(-1) * v[:, :, :, i]
|
|
41
|
+
o_intra[:, :, :, i] = intra_inter_o + intra_intra_o
|
|
42
|
+
o = o_inter + o_intra
|
|
43
|
+
return rearrange(o, 'b h n c d -> b h (n c) d').to(orig_dtype)
|
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
import warnings
|
|
5
|
+
from typing import Optional, Tuple
|
|
6
|
+
|
|
7
|
+
import torch
|
|
8
|
+
import triton
|
|
9
|
+
import triton.language as tl
|
|
10
|
+
|
|
11
|
+
from fla.ops.utils.op import exp
|
|
12
|
+
from fla.utils import autocast_custom_bwd, autocast_custom_fwd, input_guard
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@triton.heuristics({
|
|
16
|
+
'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
|
|
17
|
+
'STORE_FINAL_STATE': lambda args: args['ht'] is not None,
|
|
18
|
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
|
|
19
|
+
})
|
|
20
|
+
@triton.autotune(
|
|
21
|
+
configs=[
|
|
22
|
+
triton.Config({}, num_warps=num_warps)
|
|
23
|
+
for num_warps in [1, 2, 4, 8, 16]
|
|
24
|
+
],
|
|
25
|
+
key=['BK', 'BV']
|
|
26
|
+
)
|
|
27
|
+
@triton.jit(do_not_specialize=['T'])
|
|
28
|
+
def fused_recurrent_rwkv6_fwd_kernel(
|
|
29
|
+
q, # query [B, H, T, K]/[B, T, H, K]
|
|
30
|
+
k, # key [B, H, T, K]/[B, T, H, K]
|
|
31
|
+
v, # value [B, H, T, V]/[B, T, H, V]
|
|
32
|
+
w, # log gate [B, H, T]/[B, T, H] or None
|
|
33
|
+
u, # bonus [B, H, K]
|
|
34
|
+
o, # output [NK, B, H, T, V]/[NK, B, T, H, V]
|
|
35
|
+
h0, # initial hidden state [B, H, K, V]
|
|
36
|
+
ht, # final hidden state [B, H, K, V]
|
|
37
|
+
cu_seqlens,
|
|
38
|
+
scale,
|
|
39
|
+
T,
|
|
40
|
+
B: tl.constexpr,
|
|
41
|
+
H: tl.constexpr,
|
|
42
|
+
K: tl.constexpr,
|
|
43
|
+
V: tl.constexpr,
|
|
44
|
+
BK: tl.constexpr,
|
|
45
|
+
BV: tl.constexpr,
|
|
46
|
+
REVERSE: tl.constexpr, # whether to reverse the recurrence
|
|
47
|
+
USE_INITIAL_STATE: tl.constexpr, # whether to use initial state
|
|
48
|
+
STORE_FINAL_STATE: tl.constexpr, # whether to store final state
|
|
49
|
+
IS_VARLEN: tl.constexpr,
|
|
50
|
+
):
|
|
51
|
+
i_v, i_k, i_nh = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64), tl.program_id(2).to(tl.int64)
|
|
52
|
+
i_n, i_h = i_nh // H, i_nh % H
|
|
53
|
+
if IS_VARLEN:
|
|
54
|
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
|
|
55
|
+
all = T
|
|
56
|
+
T = eos - bos
|
|
57
|
+
else:
|
|
58
|
+
bos, eos = i_n * T, i_n * T + T
|
|
59
|
+
all = B * T
|
|
60
|
+
|
|
61
|
+
o_k = i_k * BK + tl.arange(0, BK)
|
|
62
|
+
o_v = i_v * BV + tl.arange(0, BV)
|
|
63
|
+
p_q = q + (bos + ((T-1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
|
64
|
+
p_k = k + (bos + ((T-1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
|
65
|
+
p_v = v + (bos + ((T-1) if REVERSE else 0)) * H*V + i_h * V + o_v
|
|
66
|
+
p_w = w + (bos + ((T-1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
|
67
|
+
p_o = o + ((i_k * all + bos) + ((T-1) if REVERSE else 0)) * H*V + i_h * V + o_v
|
|
68
|
+
p_u = u + i_h * K + o_k
|
|
69
|
+
|
|
70
|
+
mask_k = o_k < K
|
|
71
|
+
mask_v = o_v < V
|
|
72
|
+
mask_h = mask_k[:, None] & mask_v[None, :]
|
|
73
|
+
|
|
74
|
+
b_u = tl.load(p_u, mask=mask_k, other=0).to(tl.float32)
|
|
75
|
+
|
|
76
|
+
b_h = tl.zeros([BK, BV], dtype=tl.float32)
|
|
77
|
+
if USE_INITIAL_STATE:
|
|
78
|
+
p_h0 = h0 + i_nh * K*V + o_k[:, None] * V + o_v[None, :]
|
|
79
|
+
b_h += tl.load(p_h0, mask=mask_h, other=0).to(tl.float32)
|
|
80
|
+
|
|
81
|
+
for _ in range(0, T):
|
|
82
|
+
b_q = tl.load(p_q, mask=mask_k, other=0).to(tl.float32) * scale
|
|
83
|
+
b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
|
|
84
|
+
b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
|
|
85
|
+
b_w = tl.load(p_w, mask=mask_k, other=0).to(tl.float32)
|
|
86
|
+
b_kv = b_k[:, None] * b_v[None, :]
|
|
87
|
+
b_o = tl.sum((b_h + b_kv * b_u[:, None]) * b_q[:, None], 0)
|
|
88
|
+
b_h = b_h * exp(b_w)[:, None] + b_kv
|
|
89
|
+
tl.store(p_o, b_o.to(p_o.dtype.element_ty), mask=mask_v)
|
|
90
|
+
p_q += (-1 if REVERSE else 1) * H*K
|
|
91
|
+
p_k += (-1 if REVERSE else 1) * H*K
|
|
92
|
+
p_v += (-1 if REVERSE else 1) * H*V
|
|
93
|
+
p_w += (-1 if REVERSE else 1) * H*K
|
|
94
|
+
p_o += (-1 if REVERSE else 1) * H*V
|
|
95
|
+
|
|
96
|
+
if STORE_FINAL_STATE:
|
|
97
|
+
p_ht = ht + i_nh * K*V + o_k[:, None] * V + o_v[None, :]
|
|
98
|
+
tl.store(p_ht, b_h.to(p_ht.dtype.element_ty), mask=mask_h)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@triton.heuristics({
|
|
102
|
+
'USE_INITIAL_STATE': lambda args: args['h0'] is not None,
|
|
103
|
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
|
|
104
|
+
})
|
|
105
|
+
@triton.autotune(
|
|
106
|
+
configs=[
|
|
107
|
+
triton.Config({}, num_warps=1),
|
|
108
|
+
triton.Config({}, num_warps=2),
|
|
109
|
+
triton.Config({}, num_warps=4),
|
|
110
|
+
],
|
|
111
|
+
key=['BK', 'BV']
|
|
112
|
+
)
|
|
113
|
+
@triton.jit(do_not_specialize=['T'])
|
|
114
|
+
def fused_recurrent_rwkv6_bwd_kernel_dq(
|
|
115
|
+
k, # key [B, H, T, V]/[B, T, H, V]
|
|
116
|
+
v, # value [B, H, T, V]/[B, T, H, V]
|
|
117
|
+
w, # log gate [B, H, T]/[B, T, H]
|
|
118
|
+
u, # bonus [B, H, K]
|
|
119
|
+
do, # gradient of output [B, H, T, V]/[B, T, H, V]
|
|
120
|
+
dq, # gradient of query [NV, B, H, T, K]/[NV, B, T, H, K]
|
|
121
|
+
dq1, # gradient of query_aux [NV, B, H, T, K]/[NV, B, T, H, K]
|
|
122
|
+
h0,
|
|
123
|
+
cu_seqlens,
|
|
124
|
+
scale,
|
|
125
|
+
T,
|
|
126
|
+
B: tl.constexpr,
|
|
127
|
+
H: tl.constexpr,
|
|
128
|
+
K: tl.constexpr,
|
|
129
|
+
V: tl.constexpr,
|
|
130
|
+
BK: tl.constexpr,
|
|
131
|
+
BV: tl.constexpr,
|
|
132
|
+
REVERSE: tl.constexpr,
|
|
133
|
+
USE_INITIAL_STATE: tl.constexpr,
|
|
134
|
+
IS_VARLEN: tl.constexpr,
|
|
135
|
+
):
|
|
136
|
+
i_v, i_k, i_nh = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64), tl.program_id(2).to(tl.int64)
|
|
137
|
+
i_n, i_h = i_nh // H, i_nh % H
|
|
138
|
+
if IS_VARLEN:
|
|
139
|
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
|
|
140
|
+
all = T
|
|
141
|
+
T = eos - bos
|
|
142
|
+
else:
|
|
143
|
+
bos, eos = i_n * T, i_n * T + T
|
|
144
|
+
all = B * T
|
|
145
|
+
|
|
146
|
+
o_k = i_k * BK + tl.arange(0, BK)
|
|
147
|
+
o_v = i_v * BV + tl.arange(0, BV)
|
|
148
|
+
p_k = k + (bos + ((T-1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
|
149
|
+
p_v = v + (bos + ((T-1) if REVERSE else 0)) * H*V + i_h * V + o_v
|
|
150
|
+
p_w = w + (bos + ((T-1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
|
151
|
+
p_do = do + (bos + ((T-1) if REVERSE else 0)) * H*V + i_h * V + o_v
|
|
152
|
+
p_dq = dq + ((i_v * all + bos) + ((T-1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
|
153
|
+
p_dq1 = dq1 + ((i_v * all + bos) + ((T-1) if REVERSE else 0)) * H*K + i_h * K + o_k
|
|
154
|
+
p_u = u + i_h * K + o_k
|
|
155
|
+
|
|
156
|
+
mask_k = o_k < K
|
|
157
|
+
mask_v = o_v < V
|
|
158
|
+
mask_h = mask_k[:, None] & mask_v[None, :]
|
|
159
|
+
|
|
160
|
+
b_u = tl.load(p_u, mask=mask_k, other=0).to(tl.float32)
|
|
161
|
+
|
|
162
|
+
b_h = tl.zeros([BK, BV], dtype=tl.float32)
|
|
163
|
+
if USE_INITIAL_STATE:
|
|
164
|
+
p_h0 = h0 + i_nh * K*V + o_k[:, None] * V + o_v[None, :]
|
|
165
|
+
b_h += tl.load(p_h0, mask=mask_h, other=0).to(tl.float32)
|
|
166
|
+
|
|
167
|
+
for _ in range(0, T):
|
|
168
|
+
b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
|
|
169
|
+
b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
|
|
170
|
+
b_w = tl.load(p_w, mask=mask_k, other=0).to(tl.float32)
|
|
171
|
+
b_do = tl.load(p_do, mask=mask_v, other=0).to(tl.float32)
|
|
172
|
+
b_kv = b_k[:, None] * b_v[None, :]
|
|
173
|
+
|
|
174
|
+
b_hq = b_h * b_do[None, :]
|
|
175
|
+
b_dq = tl.sum(b_hq + b_kv * b_u[:, None] * b_do[None, :], 1) * scale
|
|
176
|
+
b_dq1 = tl.sum(b_hq, 1)
|
|
177
|
+
b_h = b_h * exp(b_w)[:, None]
|
|
178
|
+
b_h += b_kv
|
|
179
|
+
tl.store(p_dq, b_dq.to(p_dq.dtype.element_ty), mask=mask_k)
|
|
180
|
+
tl.store(p_dq1, b_dq1.to(p_dq1.dtype.element_ty), mask=mask_k)
|
|
181
|
+
|
|
182
|
+
p_k += (-1 if REVERSE else 1) * H*K
|
|
183
|
+
p_v += (-1 if REVERSE else 1) * H*V
|
|
184
|
+
p_w += (-1 if REVERSE else 1) * H*K
|
|
185
|
+
p_do += (-1 if REVERSE else 1) * H*V
|
|
186
|
+
p_dq += (-1 if REVERSE else 1) * H*K
|
|
187
|
+
p_dq1 += (-1 if REVERSE else 1) * H*K
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
@triton.heuristics({
|
|
191
|
+
'USE_INITIAL_STATE': lambda args: args['dh0'] is not None,
|
|
192
|
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
|
|
193
|
+
})
|
|
194
|
+
@triton.autotune(
|
|
195
|
+
configs=[
|
|
196
|
+
triton.Config({}, num_warps=1),
|
|
197
|
+
triton.Config({}, num_warps=2),
|
|
198
|
+
triton.Config({}, num_warps=4),
|
|
199
|
+
],
|
|
200
|
+
key=['BK', 'BV']
|
|
201
|
+
)
|
|
202
|
+
@triton.jit(do_not_specialize=['T'])
|
|
203
|
+
def fused_recurrent_rwkv6_bwd_kernel_dkv(
|
|
204
|
+
q, # query [B, H, T, K]/[B, T, H, K]
|
|
205
|
+
k, # key [B, H, T, V]/[B, T, H, V]
|
|
206
|
+
v, # value [B, H, T, V]/[B, T, H, V]
|
|
207
|
+
w, # log gate [B, H, T]/[B, T, H]
|
|
208
|
+
u, # bonus [B, H, K]
|
|
209
|
+
do, # gradient of output [B, H, T, V]/[B, T, H, V]
|
|
210
|
+
dk, # gradient of key [NV, B, H, T, K]/[NK, B, T, H, K]
|
|
211
|
+
dk1, # gradient of key_aux [NV, B, H, T, K]/[NK, B, T, H, K]
|
|
212
|
+
dv, # gradient of value [NK, B, H, T, V]/[NV, B, T, H, V]
|
|
213
|
+
dh0, # gradient of initial hidden state [N, H, K, V]
|
|
214
|
+
cu_seqlens,
|
|
215
|
+
scale,
|
|
216
|
+
T,
|
|
217
|
+
B: tl.constexpr,
|
|
218
|
+
H: tl.constexpr,
|
|
219
|
+
K: tl.constexpr,
|
|
220
|
+
V: tl.constexpr,
|
|
221
|
+
BK: tl.constexpr,
|
|
222
|
+
BV: tl.constexpr,
|
|
223
|
+
REVERSE: tl.constexpr,
|
|
224
|
+
USE_INITIAL_STATE: tl.constexpr,
|
|
225
|
+
IS_VARLEN: tl.constexpr,
|
|
226
|
+
):
|
|
227
|
+
i_v, i_k, i_nh = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64), tl.program_id(2).to(tl.int64)
|
|
228
|
+
i_n, i_h = i_nh // H, i_nh % H
|
|
229
|
+
if IS_VARLEN:
|
|
230
|
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int64), tl.load(cu_seqlens + i_n + 1).to(tl.int64)
|
|
231
|
+
all = T
|
|
232
|
+
T = eos - bos
|
|
233
|
+
else:
|
|
234
|
+
bos, eos = i_n * T, i_n * T + T
|
|
235
|
+
all = B * T
|
|
236
|
+
|
|
237
|
+
o_k = i_k * BK + tl.arange(0, BK)
|
|
238
|
+
o_v = i_v * BV + tl.arange(0, BV)
|
|
239
|
+
p_q = q + (bos + ((T-1) if not REVERSE else 0)) * H*K + i_h * K + o_k
|
|
240
|
+
p_k = k + (bos + ((T-1) if not REVERSE else 0)) * H*K + i_h * K + o_k
|
|
241
|
+
p_v = v + (bos + ((T-1) if not REVERSE else 0)) * H*V + i_h * V + o_v
|
|
242
|
+
p_w = w + (bos + ((T-1) if not REVERSE else 0)) * H*K + i_h * K + o_k
|
|
243
|
+
p_do = do + (bos + ((T-1) if not REVERSE else 0)) * H*V + i_h * V + o_v
|
|
244
|
+
p_dk = dk + ((i_v * all + bos) + ((T-1) if not REVERSE else 0)) * H*K + i_h * K + o_k
|
|
245
|
+
p_dk1 = dk1 + ((i_v * all + bos) + ((T-1) if not REVERSE else 0)) * H*K + i_h * K + o_k
|
|
246
|
+
p_dv = dv + ((i_k * all + bos) + ((T-1) if not REVERSE else 0)) * H*V + i_h * V + o_v
|
|
247
|
+
p_u = u + i_h * K + o_k
|
|
248
|
+
|
|
249
|
+
mask_k = o_k < K
|
|
250
|
+
mask_v = o_v < V
|
|
251
|
+
mask_h = mask_k[:, None] & mask_v[None, :]
|
|
252
|
+
|
|
253
|
+
b_u = tl.load(p_u, mask=mask_k, other=0).to(tl.float32)
|
|
254
|
+
|
|
255
|
+
b_dh = tl.zeros([BK, BV], dtype=tl.float32)
|
|
256
|
+
for _ in range(T - 1, -1, -1):
|
|
257
|
+
b_q = tl.load(p_q, mask=mask_k, other=0).to(tl.float32) * scale
|
|
258
|
+
b_k = tl.load(p_k, mask=mask_k, other=0).to(tl.float32)
|
|
259
|
+
b_v = tl.load(p_v, mask=mask_v, other=0).to(tl.float32)
|
|
260
|
+
b_w = tl.load(p_w, mask=mask_k, other=0).to(tl.float32)
|
|
261
|
+
b_do = tl.load(p_do, mask=mask_v, other=0).to(tl.float32)
|
|
262
|
+
b_dkv = b_q[:, None] * b_do[None, :]
|
|
263
|
+
b_dk = tl.sum(b_dh * b_v[None, :], 1)
|
|
264
|
+
tl.store(p_dk1, b_dk.to(p_dk1.dtype.element_ty), mask=mask_k)
|
|
265
|
+
b_dk += tl.sum(b_dkv * b_u[:, None] * b_v[None, :], 1)
|
|
266
|
+
b_dv = tl.sum((b_dh + (b_dkv * b_u[:, None])) * b_k[:, None], 0)
|
|
267
|
+
|
|
268
|
+
tl.store(p_dk, b_dk.to(p_dk.dtype.element_ty), mask=mask_k)
|
|
269
|
+
tl.store(p_dv, b_dv.to(p_dv.dtype.element_ty), mask=mask_v)
|
|
270
|
+
b_dh *= exp(b_w)[:, None]
|
|
271
|
+
b_dh += b_dkv
|
|
272
|
+
|
|
273
|
+
p_q += (-1 if not REVERSE else 1) * H*K
|
|
274
|
+
p_k += (-1 if not REVERSE else 1) * H*K
|
|
275
|
+
p_v += (-1 if not REVERSE else 1) * H*V
|
|
276
|
+
p_w += (-1 if not REVERSE else 1) * H*K
|
|
277
|
+
p_do += (-1 if not REVERSE else 1) * H*V
|
|
278
|
+
p_dk += (-1 if not REVERSE else 1) * H*K
|
|
279
|
+
p_dk1 += (-1 if not REVERSE else 1) * H*K
|
|
280
|
+
p_dv += (-1 if not REVERSE else 1) * H*V
|
|
281
|
+
|
|
282
|
+
if USE_INITIAL_STATE:
|
|
283
|
+
p_dh0 = dh0 + i_nh * K*V + o_k[:, None] * V + o_v[None, :]
|
|
284
|
+
tl.store(p_dh0, b_dh.to(p_dh0.dtype.element_ty), mask=mask_h)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@triton.heuristics({
|
|
288
|
+
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None
|
|
289
|
+
})
|
|
290
|
+
@triton.autotune(
|
|
291
|
+
configs=[
|
|
292
|
+
triton.Config({'BT': BT, 'BK': BK}, num_warps=num_warps)
|
|
293
|
+
for BT in [16, 32, 64]
|
|
294
|
+
for BK in [32, 64]
|
|
295
|
+
for num_warps in [1, 2, 4, 8]
|
|
296
|
+
],
|
|
297
|
+
key=['K']
|
|
298
|
+
)
|
|
299
|
+
@triton.jit(do_not_specialize=['T'])
|
|
300
|
+
def fused_recurrent_rwkv6_bwd_kernel_dw(
|
|
301
|
+
q,
|
|
302
|
+
k,
|
|
303
|
+
dq,
|
|
304
|
+
dk,
|
|
305
|
+
dw,
|
|
306
|
+
cu_seqlens,
|
|
307
|
+
scale,
|
|
308
|
+
T,
|
|
309
|
+
H: tl.constexpr,
|
|
310
|
+
K: tl.constexpr,
|
|
311
|
+
BT: tl.constexpr,
|
|
312
|
+
BK: tl.constexpr,
|
|
313
|
+
REVERSE: tl.constexpr,
|
|
314
|
+
IS_VARLEN: tl.constexpr
|
|
315
|
+
):
|
|
316
|
+
i_k, i_nh = tl.program_id(0), tl.program_id(1)
|
|
317
|
+
i_n, i_h = i_nh // H, i_nh % H
|
|
318
|
+
if IS_VARLEN:
|
|
319
|
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
|
320
|
+
else:
|
|
321
|
+
bos, eos = i_n * T, i_n * T + T
|
|
322
|
+
T = eos - bos
|
|
323
|
+
NT = tl.cdiv(T, BT)
|
|
324
|
+
|
|
325
|
+
o_i = tl.arange(0, BT)
|
|
326
|
+
m_i = tl.where(o_i[:, None] >= o_i[None, :], 1., 0.) if not REVERSE else tl.where(o_i[:, None] <= o_i[None, :], 1., 0.)
|
|
327
|
+
|
|
328
|
+
b_z = tl.zeros([BK], dtype=tl.float32)
|
|
329
|
+
|
|
330
|
+
i_t = 0 if not REVERSE else NT - 1
|
|
331
|
+
for _ in range(NT):
|
|
332
|
+
p_q = tl.make_block_ptr(q + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + 1, i_k * BK), (BT, BK), (1, 0))
|
|
333
|
+
p_k = tl.make_block_ptr(k + (bos*H + i_h) * K, (T-1, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
|
334
|
+
p_dq = tl.make_block_ptr(dq + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT + 1, i_k * BK), (BT, BK), (1, 0))
|
|
335
|
+
p_dk = tl.make_block_ptr(dk + (bos*H + i_h) * K, (T-1, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
|
336
|
+
p_dw = tl.make_block_ptr(dw + (bos*H + i_h) * K, (T, K), (H*K, 1), (i_t * BT, i_k * BK), (BT, BK), (1, 0))
|
|
337
|
+
# [BT, BK]
|
|
338
|
+
b_q = tl.load(p_q, boundary_check=(0, 1)).to(tl.float32)
|
|
339
|
+
b_dq = tl.load(p_dq, boundary_check=(0, 1)).to(tl.float32)
|
|
340
|
+
b_k = tl.load(p_k, boundary_check=(0, 1)).to(tl.float32)
|
|
341
|
+
b_dk = tl.load(p_dk, boundary_check=(0, 1)).to(tl.float32)
|
|
342
|
+
b_dw = (b_q * b_dq * scale) - b_k * b_dk
|
|
343
|
+
b_c = b_z[None, :] + tl.dot(m_i, b_dw, allow_tf32=False)
|
|
344
|
+
tl.store(p_dw, b_c.to(p_dw.dtype.element_ty), boundary_check=(0, 1))
|
|
345
|
+
if i_t >= 0:
|
|
346
|
+
b_z += tl.sum(b_dw, 0)
|
|
347
|
+
|
|
348
|
+
i_t += (1 if not REVERSE else -1)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def fused_recurrent_rwkv6_fwd(
|
|
352
|
+
q: torch.Tensor,
|
|
353
|
+
k: torch.Tensor,
|
|
354
|
+
v: torch.Tensor,
|
|
355
|
+
w: torch.Tensor,
|
|
356
|
+
u: torch.Tensor,
|
|
357
|
+
scale: Optional[float] = None,
|
|
358
|
+
initial_state: Optional[torch.Tensor] = None,
|
|
359
|
+
output_final_state: bool = False,
|
|
360
|
+
reverse: bool = False,
|
|
361
|
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
|
362
|
+
):
|
|
363
|
+
B, T, H, K, V = *k.shape, v.shape[-1]
|
|
364
|
+
N = B if cu_seqlens is None else len(cu_seqlens) - 1
|
|
365
|
+
BK, BV = min(triton.next_power_of_2(K), 32), min(triton.next_power_of_2(V), 32)
|
|
366
|
+
NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
|
|
367
|
+
|
|
368
|
+
h0 = initial_state
|
|
369
|
+
ht = q.new_empty(N, H, K, V, dtype=torch.float) if output_final_state else None
|
|
370
|
+
o = q.new_empty(NK, *v.shape, dtype=torch.float)
|
|
371
|
+
|
|
372
|
+
grid = (NV, NK, N * H)
|
|
373
|
+
fused_recurrent_rwkv6_fwd_kernel[grid](
|
|
374
|
+
q,
|
|
375
|
+
k,
|
|
376
|
+
v,
|
|
377
|
+
w,
|
|
378
|
+
u,
|
|
379
|
+
o,
|
|
380
|
+
h0,
|
|
381
|
+
ht,
|
|
382
|
+
cu_seqlens,
|
|
383
|
+
scale,
|
|
384
|
+
T=T,
|
|
385
|
+
B=B,
|
|
386
|
+
H=H,
|
|
387
|
+
K=K,
|
|
388
|
+
V=V,
|
|
389
|
+
BK=BK,
|
|
390
|
+
BV=BV,
|
|
391
|
+
REVERSE=reverse,
|
|
392
|
+
)
|
|
393
|
+
o = o.sum(0)
|
|
394
|
+
return o, ht
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def fused_recurrent_rwkv6_bwd(
|
|
398
|
+
q: torch.Tensor,
|
|
399
|
+
k: torch.Tensor,
|
|
400
|
+
v: torch.Tensor,
|
|
401
|
+
w: torch.Tensor,
|
|
402
|
+
u: torch.Tensor,
|
|
403
|
+
do: torch.Tensor,
|
|
404
|
+
scale: Optional[float] = None,
|
|
405
|
+
initial_state: Optional[torch.Tensor] = None,
|
|
406
|
+
reverse: bool = False,
|
|
407
|
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
|
408
|
+
):
|
|
409
|
+
B, T, H, K, V = *k.shape, v.shape[-1]
|
|
410
|
+
N = B if cu_seqlens is None else len(cu_seqlens) - 1
|
|
411
|
+
|
|
412
|
+
BK, BV = min(triton.next_power_of_2(K), 16), min(triton.next_power_of_2(V), 64)
|
|
413
|
+
NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
|
|
414
|
+
|
|
415
|
+
dq = q.new_empty(NV, *q.shape, dtype=torch.float)
|
|
416
|
+
dq1 = torch.empty_like(dq)
|
|
417
|
+
|
|
418
|
+
grid = (NV, NK, N * H)
|
|
419
|
+
fused_recurrent_rwkv6_bwd_kernel_dq[grid](
|
|
420
|
+
k,
|
|
421
|
+
v,
|
|
422
|
+
w,
|
|
423
|
+
u,
|
|
424
|
+
do,
|
|
425
|
+
dq,
|
|
426
|
+
dq1,
|
|
427
|
+
initial_state,
|
|
428
|
+
cu_seqlens,
|
|
429
|
+
scale,
|
|
430
|
+
T=T,
|
|
431
|
+
B=B,
|
|
432
|
+
H=H,
|
|
433
|
+
K=K,
|
|
434
|
+
V=V,
|
|
435
|
+
BK=BK,
|
|
436
|
+
BV=BV,
|
|
437
|
+
REVERSE=reverse,
|
|
438
|
+
)
|
|
439
|
+
dq = dq.sum(0)
|
|
440
|
+
dq1 = dq1.sum(0)
|
|
441
|
+
|
|
442
|
+
BK, BV = min(triton.next_power_of_2(K), 32), min(triton.next_power_of_2(V), 32)
|
|
443
|
+
NK, NV = triton.cdiv(K, BK), triton.cdiv(V, BV)
|
|
444
|
+
|
|
445
|
+
dk = q.new_empty(NV, *k.shape, dtype=torch.float)
|
|
446
|
+
dk1 = q.new_empty(NV, *k.shape, dtype=torch.float)
|
|
447
|
+
dv = q.new_empty(NK, *v.shape, dtype=torch.float)
|
|
448
|
+
|
|
449
|
+
dh0 = torch.empty_like(initial_state) if initial_state is not None else None
|
|
450
|
+
grid = (NV, NK, N * H)
|
|
451
|
+
fused_recurrent_rwkv6_bwd_kernel_dkv[grid](
|
|
452
|
+
q,
|
|
453
|
+
k,
|
|
454
|
+
v,
|
|
455
|
+
w,
|
|
456
|
+
u,
|
|
457
|
+
do,
|
|
458
|
+
dk,
|
|
459
|
+
dk1,
|
|
460
|
+
dv,
|
|
461
|
+
dh0,
|
|
462
|
+
cu_seqlens,
|
|
463
|
+
scale,
|
|
464
|
+
T=T,
|
|
465
|
+
B=B,
|
|
466
|
+
H=H,
|
|
467
|
+
K=K,
|
|
468
|
+
V=V,
|
|
469
|
+
BK=BK,
|
|
470
|
+
BV=BV,
|
|
471
|
+
REVERSE=reverse,
|
|
472
|
+
)
|
|
473
|
+
dk = dk.sum(0)
|
|
474
|
+
dk1 = dk1.sum(0)
|
|
475
|
+
dv = dv.sum(0)
|
|
476
|
+
|
|
477
|
+
dw = torch.empty_like(w)
|
|
478
|
+
def grid(meta): return (triton.cdiv(meta['K'], meta['BK']), N * H)
|
|
479
|
+
fused_recurrent_rwkv6_bwd_kernel_dw[grid](
|
|
480
|
+
q,
|
|
481
|
+
k,
|
|
482
|
+
dq1,
|
|
483
|
+
dk1,
|
|
484
|
+
dw,
|
|
485
|
+
cu_seqlens,
|
|
486
|
+
scale,
|
|
487
|
+
T=T,
|
|
488
|
+
H=H,
|
|
489
|
+
K=K,
|
|
490
|
+
REVERSE=not reverse,
|
|
491
|
+
)
|
|
492
|
+
du = (do.float() * v).sum(-1, True, dtype=torch.float) * q * k * scale
|
|
493
|
+
du = du.sum((0, 1))
|
|
494
|
+
return dq, dk, dv, dw, du, dh0
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
class FusedRecurrentRWKV6Function(torch.autograd.Function):
|
|
498
|
+
|
|
499
|
+
@staticmethod
|
|
500
|
+
@input_guard
|
|
501
|
+
@autocast_custom_fwd
|
|
502
|
+
def forward(
|
|
503
|
+
ctx,
|
|
504
|
+
q: torch.Tensor,
|
|
505
|
+
k: torch.Tensor,
|
|
506
|
+
v: torch.Tensor,
|
|
507
|
+
w: torch.Tensor,
|
|
508
|
+
u: torch.Tensor,
|
|
509
|
+
scale: Optional[float] = None,
|
|
510
|
+
initial_state: Optional[torch.Tensor] = None,
|
|
511
|
+
output_final_state: bool = False,
|
|
512
|
+
reverse: bool = False,
|
|
513
|
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
|
514
|
+
):
|
|
515
|
+
o, ht = fused_recurrent_rwkv6_fwd(
|
|
516
|
+
q=q,
|
|
517
|
+
k=k,
|
|
518
|
+
v=v,
|
|
519
|
+
w=w,
|
|
520
|
+
u=u,
|
|
521
|
+
scale=scale,
|
|
522
|
+
initial_state=initial_state,
|
|
523
|
+
output_final_state=output_final_state,
|
|
524
|
+
reverse=reverse,
|
|
525
|
+
cu_seqlens=cu_seqlens,
|
|
526
|
+
)
|
|
527
|
+
ctx.save_for_backward(q, k, v, w, u, initial_state)
|
|
528
|
+
ctx.scale = scale
|
|
529
|
+
ctx.reverse = reverse
|
|
530
|
+
ctx.cu_seqlens = cu_seqlens
|
|
531
|
+
return o.to(v), ht
|
|
532
|
+
|
|
533
|
+
@staticmethod
|
|
534
|
+
@input_guard
|
|
535
|
+
@autocast_custom_bwd
|
|
536
|
+
def backward(ctx, do, dht):
|
|
537
|
+
q, k, v, w, u, initial_state = ctx.saved_tensors
|
|
538
|
+
|
|
539
|
+
dq, dk, dv, dw, du, dh0 = fused_recurrent_rwkv6_bwd(
|
|
540
|
+
q=q,
|
|
541
|
+
k=k,
|
|
542
|
+
v=v,
|
|
543
|
+
w=w,
|
|
544
|
+
u=u,
|
|
545
|
+
do=do,
|
|
546
|
+
scale=ctx.scale,
|
|
547
|
+
initial_state=initial_state,
|
|
548
|
+
reverse=ctx.reverse,
|
|
549
|
+
cu_seqlens=ctx.cu_seqlens,
|
|
550
|
+
)
|
|
551
|
+
dh0 = dh0.to(initial_state) if dh0 is not None else dh0
|
|
552
|
+
return dq.to(q), dk.to(k), dv.to(v), dw.to(w), du.to(u), None, dh0, None, None, None
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def fused_recurrent_rwkv6(
|
|
556
|
+
r: torch.Tensor,
|
|
557
|
+
k: torch.Tensor,
|
|
558
|
+
v: torch.Tensor,
|
|
559
|
+
w: torch.Tensor,
|
|
560
|
+
u: torch.Tensor,
|
|
561
|
+
scale: Optional[int] = None,
|
|
562
|
+
initial_state: Optional[torch.Tensor] = None,
|
|
563
|
+
output_final_state: bool = False,
|
|
564
|
+
reverse: bool = False,
|
|
565
|
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
|
566
|
+
head_first: bool = False
|
|
567
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
568
|
+
r"""
|
|
569
|
+
Args:
|
|
570
|
+
r (torch.Tensor):
|
|
571
|
+
reception of shape `[B, T, H, K]`.
|
|
572
|
+
Alias: q, query in linear attention.
|
|
573
|
+
k (torch.Tensor):
|
|
574
|
+
keys of shape `[B, T, H, K]`.
|
|
575
|
+
v (torch.Tensor):
|
|
576
|
+
values of shape `[B, T, H, V]`.
|
|
577
|
+
w (torch.Tensor):
|
|
578
|
+
data-dependent decays of shape `[B, T, H, K]`. in log space! Alias: g.
|
|
579
|
+
u (torch.Tensor):
|
|
580
|
+
bonus of shape `[H, K]`
|
|
581
|
+
scale (Optional[float]):
|
|
582
|
+
Scale factor for the attention scores.
|
|
583
|
+
If not provided, it will default to `1 / sqrt(K)`. Default: `None`.
|
|
584
|
+
initial_state (Optional[torch.Tensor]):
|
|
585
|
+
Initial state of shape `[N, H, K, V]` for `N` input sequences.
|
|
586
|
+
For equal-length input sequences, `N` equals the batch size `B`.
|
|
587
|
+
Default: `None`.
|
|
588
|
+
output_final_state (Optional[bool]):
|
|
589
|
+
Whether to output the final state of shape `[N, H, K, V]`. Default: `False`.
|
|
590
|
+
reverse (Optional[bool]):
|
|
591
|
+
If `True`, process the state passing in reverse order. Default: `False`.
|
|
592
|
+
cu_seqlens (torch.LongTensor):
|
|
593
|
+
Cumulative sequence lengths of shape `[N+1]` used for variable-length training,
|
|
594
|
+
consistent with the FlashAttention API.
|
|
595
|
+
head_first (Optional[bool]):
|
|
596
|
+
Whether the inputs are in the head-first format. Default: `False`.
|
|
597
|
+
This argument has been deprecated.
|
|
598
|
+
|
|
599
|
+
Returns:
|
|
600
|
+
o (torch.Tensor):
|
|
601
|
+
Outputs of shape `[B, T, H, V]`.
|
|
602
|
+
final_state (Optional[torch.Tensor]):
|
|
603
|
+
Final state of shape `[N, H, K, V]` if `output_final_state=True` else `None`.
|
|
604
|
+
|
|
605
|
+
Examples::
|
|
606
|
+
>>> import torch
|
|
607
|
+
>>> import torch.nn.functional as F
|
|
608
|
+
>>> from einops import rearrange
|
|
609
|
+
>>> from fla.ops.rwkv6 import fused_recurrent_rwkv6
|
|
610
|
+
# inputs with equal lengths
|
|
611
|
+
>>> B, T, H, K, V = 4, 2048, 4, 512, 512
|
|
612
|
+
>>> q = torch.randn(B, T, H, K, device='cuda')
|
|
613
|
+
>>> k = torch.randn(B, T, H, K, device='cuda')
|
|
614
|
+
>>> v = torch.randn(B, T, H, V, device='cuda')
|
|
615
|
+
>>> g = F.logsigmoid(torch.randn(B, T, H, K, device='cuda'))
|
|
616
|
+
>>> u = torch.randn(H, K, device='cuda')
|
|
617
|
+
>>> h0 = torch.randn(B, H, K, V, device='cuda')
|
|
618
|
+
>>> o, ht = fused_recurrent_rwkv6(
|
|
619
|
+
q, k, v, g, u,
|
|
620
|
+
initial_state=h0,
|
|
621
|
+
output_final_state=True
|
|
622
|
+
)
|
|
623
|
+
# for variable-length inputs, the batch size `B` is expected to be 1 and `cu_seqlens` is required
|
|
624
|
+
>>> q, k, v, g = map(lambda x: rearrange(x, 'b t h d -> 1 (b t) h d'), (q, k, v, g))
|
|
625
|
+
# for a batch with 4 sequences, `cu_seqlens` with 5 start/end positions are expected
|
|
626
|
+
>>> cu_seqlens = q.new_tensor([0, 2048, 4096, 6144, 8192], dtype=torch.long)
|
|
627
|
+
>>> o_var, ht_var = fused_recurrent_rwkv6(
|
|
628
|
+
q, k, v, g, u,
|
|
629
|
+
initial_state=h0,
|
|
630
|
+
output_final_state=True,
|
|
631
|
+
cu_seqlens=cu_seqlens
|
|
632
|
+
)
|
|
633
|
+
>>> assert o.allclose(o_var.view(o.shape))
|
|
634
|
+
>>> assert ht.allclose(ht_var)
|
|
635
|
+
"""
|
|
636
|
+
if head_first:
|
|
637
|
+
raise DeprecationWarning(
|
|
638
|
+
"head_first is deprecated and will be removed in a future version. "
|
|
639
|
+
"Please use head_first=False for now instead."
|
|
640
|
+
)
|
|
641
|
+
if not head_first and r.shape[1] < r.shape[2]:
|
|
642
|
+
warnings.warn(
|
|
643
|
+
f"Input tensor shape suggests potential format mismatch: seq_len ({r.shape[1]}) < num_heads ({r.shape[2]}). "
|
|
644
|
+
"This may indicate the inputs were passed in head-first format [B, H, T, ...] "
|
|
645
|
+
"when head_first=False was specified. "
|
|
646
|
+
"Please verify your input tensor format matches the expected shape [B, T, H, ...]."
|
|
647
|
+
)
|
|
648
|
+
if cu_seqlens is not None:
|
|
649
|
+
if r.shape[0] != 1:
|
|
650
|
+
raise ValueError(
|
|
651
|
+
f"The batch size is expected to be 1 rather than {r.shape[0]} when using `cu_seqlens`."
|
|
652
|
+
f"Please flatten variable-length inputs before processing."
|
|
653
|
+
)
|
|
654
|
+
if initial_state is not None and initial_state.shape[0] != len(cu_seqlens) - 1:
|
|
655
|
+
raise ValueError(
|
|
656
|
+
f"The number of initial states is expected to be equal to the number of input sequences, "
|
|
657
|
+
f"i.e., {len(cu_seqlens) - 1} rather than {initial_state.shape[0]}."
|
|
658
|
+
)
|
|
659
|
+
if scale is None:
|
|
660
|
+
scale = k.shape[-1] ** -0.5
|
|
661
|
+
o, final_state = FusedRecurrentRWKV6Function.apply(
|
|
662
|
+
r,
|
|
663
|
+
k,
|
|
664
|
+
v,
|
|
665
|
+
w,
|
|
666
|
+
u,
|
|
667
|
+
scale,
|
|
668
|
+
initial_state,
|
|
669
|
+
output_final_state,
|
|
670
|
+
reverse,
|
|
671
|
+
cu_seqlens,
|
|
672
|
+
)
|
|
673
|
+
return o, final_state
|