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
fla/ops/utils/index.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
import torch.nn.functional as F
|
|
8
|
+
import triton
|
|
9
|
+
import triton.language as tl
|
|
10
|
+
|
|
11
|
+
from fla.utils import tensor_cache
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@triton.autotune(
|
|
15
|
+
configs=[
|
|
16
|
+
triton.Config({}, num_warps=num_warps)
|
|
17
|
+
for num_warps in [4, 8, 16, 32]
|
|
18
|
+
],
|
|
19
|
+
key=['B'],
|
|
20
|
+
)
|
|
21
|
+
@triton.jit
|
|
22
|
+
def prepare_position_ids_kernel(
|
|
23
|
+
y,
|
|
24
|
+
cu_seqlens,
|
|
25
|
+
B: tl.constexpr
|
|
26
|
+
):
|
|
27
|
+
i_n = tl.program_id(0)
|
|
28
|
+
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
|
29
|
+
T = eos - bos
|
|
30
|
+
|
|
31
|
+
o = tl.arange(0, B)
|
|
32
|
+
for i in range(0, tl.cdiv(T, B) * B, B):
|
|
33
|
+
o_i = o + i
|
|
34
|
+
tl.store(y + bos + o_i, o_i, o_i < T)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@tensor_cache
|
|
38
|
+
def prepare_lens(cu_seqlens: torch.LongTensor) -> torch.LongTensor:
|
|
39
|
+
return cu_seqlens[1:] - cu_seqlens[:-1]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@tensor_cache
|
|
43
|
+
def prepare_lens_from_mask(mask: torch.BoolTensor) -> torch.LongTensor:
|
|
44
|
+
return mask.sum(dim=-1, dtype=torch.int32)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@tensor_cache
|
|
48
|
+
def prepare_cu_seqlens_from_lens(
|
|
49
|
+
lens: torch.LongTensor,
|
|
50
|
+
dtype: Optional[torch.dtype] = torch.int32
|
|
51
|
+
) -> torch.LongTensor:
|
|
52
|
+
return F.pad(lens.cumsum(dim=0, dtype=dtype), (1, 0))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@tensor_cache
|
|
56
|
+
def prepare_cu_seqlens_from_mask(
|
|
57
|
+
mask: torch.BoolTensor,
|
|
58
|
+
dtype: Optional[torch.dtype] = torch.int32
|
|
59
|
+
) -> torch.LongTensor:
|
|
60
|
+
return prepare_cu_seqlens_from_lens(prepare_lens_from_mask(mask), dtype)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@tensor_cache
|
|
64
|
+
def prepare_lens_from_cu_seqlens(
|
|
65
|
+
cu_seqlens: torch.LongTensor,
|
|
66
|
+
) -> torch.LongTensor:
|
|
67
|
+
return cu_seqlens[1:] - cu_seqlens[:-1]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@tensor_cache
|
|
71
|
+
def prepare_split_cu_seqlens(
|
|
72
|
+
batch_size: int,
|
|
73
|
+
seq_len: int,
|
|
74
|
+
split_size: int,
|
|
75
|
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
|
76
|
+
dtype: Optional[torch.dtype] = torch.int32,
|
|
77
|
+
device: Optional[torch.device] = torch.device('cpu')
|
|
78
|
+
) -> torch.LongTensor:
|
|
79
|
+
if cu_seqlens is None:
|
|
80
|
+
total_tokens = batch_size * seq_len
|
|
81
|
+
cu_seqlens = list(range(0, total_tokens, seq_len)) + [total_tokens]
|
|
82
|
+
else:
|
|
83
|
+
cu_seqlens = cu_seqlens.tolist()
|
|
84
|
+
return torch.tensor(
|
|
85
|
+
[
|
|
86
|
+
i
|
|
87
|
+
for bos, eos in zip(cu_seqlens[:-1], cu_seqlens[1:])
|
|
88
|
+
for i in range(bos, eos, split_size)
|
|
89
|
+
] + [cu_seqlens[-1]],
|
|
90
|
+
dtype=dtype,
|
|
91
|
+
device=device
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@tensor_cache
|
|
96
|
+
def prepare_position_ids(cu_seqlens: torch.LongTensor) -> torch.LongTensor:
|
|
97
|
+
return torch.cat([
|
|
98
|
+
torch.arange(n, dtype=cu_seqlens.dtype, device=cu_seqlens.device)
|
|
99
|
+
for n in prepare_lens(cu_seqlens).unbind()
|
|
100
|
+
])
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@tensor_cache
|
|
104
|
+
def prepare_sequence_ids(cu_seqlens: torch.LongTensor) -> torch.LongTensor:
|
|
105
|
+
return prepare_position_ids(cu_seqlens).eq(0).cumsum(0) - 1
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@tensor_cache
|
|
109
|
+
def prepare_token_indices(cu_seqlens: torch.LongTensor) -> torch.LongTensor:
|
|
110
|
+
position_ids = prepare_position_ids(cu_seqlens)
|
|
111
|
+
return torch.stack([prepare_sequence_ids(cu_seqlens), position_ids], 1).to(cu_seqlens)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@tensor_cache
|
|
115
|
+
def prepare_chunk_indices(
|
|
116
|
+
cu_seqlens: torch.LongTensor,
|
|
117
|
+
chunk_size: int
|
|
118
|
+
) -> torch.LongTensor:
|
|
119
|
+
indices = torch.cat([torch.arange(n) for n in triton.cdiv(prepare_lens(cu_seqlens), chunk_size).tolist()])
|
|
120
|
+
return torch.stack([indices.eq(0).cumsum(0) - 1, indices], 1).to(cu_seqlens)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@tensor_cache
|
|
124
|
+
def prepare_chunk_offsets(
|
|
125
|
+
cu_seqlens: torch.LongTensor,
|
|
126
|
+
chunk_size: int
|
|
127
|
+
) -> torch.LongTensor:
|
|
128
|
+
return torch.cat([cu_seqlens.new_tensor([0]), triton.cdiv(prepare_lens(cu_seqlens), chunk_size)]).cumsum(-1)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@tensor_cache
|
|
132
|
+
def get_max_num_splits(cu_seqlens: torch.LongTensor, chunk_size: int) -> int:
|
|
133
|
+
return triton.cdiv(int(max(prepare_lens(cu_seqlens))), chunk_size)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
import triton
|
|
5
|
+
import triton.language as tl
|
|
6
|
+
|
|
7
|
+
from fla.ops.utils.op import exp, log
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@triton.autotune(
|
|
11
|
+
configs=[
|
|
12
|
+
triton.Config({'BT': BT}, num_warps=num_warps)
|
|
13
|
+
for BT in [16, 32, 64]
|
|
14
|
+
for num_warps in [2, 4, 8]
|
|
15
|
+
],
|
|
16
|
+
key=['S']
|
|
17
|
+
)
|
|
18
|
+
@triton.jit(do_not_specialize=['T'])
|
|
19
|
+
def logcumsumexp_fwd_kernel(
|
|
20
|
+
s,
|
|
21
|
+
z,
|
|
22
|
+
T,
|
|
23
|
+
S: tl.constexpr,
|
|
24
|
+
BT: tl.constexpr
|
|
25
|
+
):
|
|
26
|
+
i_bh = tl.program_id(0)
|
|
27
|
+
o_i = tl.arange(0, BT)
|
|
28
|
+
m_s = tl.where(o_i[:, None] >= o_i[None, :], 1., 0.)
|
|
29
|
+
|
|
30
|
+
b_mp = tl.full([S,], float('-inf'), dtype=tl.float32)
|
|
31
|
+
b_zp = tl.zeros([S,], dtype=tl.float32)
|
|
32
|
+
for i_t in range(tl.cdiv(T, BT)):
|
|
33
|
+
p_s = tl.make_block_ptr(s + i_bh * T*S, (T, S), (S, 1), (i_t * BT, 0), (BT, S), (1, 0))
|
|
34
|
+
p_z = tl.make_block_ptr(z + i_bh * T*S, (T, S), (S, 1), (i_t * BT, 0), (BT, S), (1, 0))
|
|
35
|
+
|
|
36
|
+
# [BT, S]
|
|
37
|
+
b_s = tl.load(p_s, boundary_check=(0, 1)).to(tl.float32)
|
|
38
|
+
# [S,]
|
|
39
|
+
b_mc = tl.max(b_s, 0)
|
|
40
|
+
b_mc = tl.maximum(b_mp, b_mc)
|
|
41
|
+
b_zp = b_zp * exp(b_mp - b_mc)
|
|
42
|
+
# [BT, S]
|
|
43
|
+
b_s = exp(b_s - b_mc)
|
|
44
|
+
b_z = tl.dot(m_s, b_s, allow_tf32=False) + b_zp
|
|
45
|
+
# [S,]
|
|
46
|
+
b_zc = tl.max(b_z, 0)
|
|
47
|
+
b_mp = b_mc
|
|
48
|
+
b_zp = b_zc
|
|
49
|
+
# [BT, BS]
|
|
50
|
+
# small eps to prevent underflows
|
|
51
|
+
b_z = log(tl.where(b_z != 0, b_z, 1e-20)) + b_mc
|
|
52
|
+
tl.store(p_z, b_z.to(p_z.dtype.element_ty), boundary_check=(0, 1))
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2024, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
import triton
|
|
8
|
+
import triton.language as tl
|
|
9
|
+
|
|
10
|
+
from fla.ops.utils.op import exp, log
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@triton.heuristics({
|
|
14
|
+
'HAS_SCALE': lambda args: args['scale'] is not None
|
|
15
|
+
})
|
|
16
|
+
@triton.autotune(
|
|
17
|
+
configs=[
|
|
18
|
+
triton.Config({}, num_warps=num_warps)
|
|
19
|
+
for num_warps in [1, 2, 4, 8, 16, 32]
|
|
20
|
+
],
|
|
21
|
+
key=['D']
|
|
22
|
+
)
|
|
23
|
+
@triton.jit
|
|
24
|
+
def logsumexp_fwd_kernel(
|
|
25
|
+
x,
|
|
26
|
+
z,
|
|
27
|
+
scale,
|
|
28
|
+
D: tl.constexpr,
|
|
29
|
+
B: tl.constexpr,
|
|
30
|
+
HAS_SCALE: tl.constexpr
|
|
31
|
+
):
|
|
32
|
+
i_n, i_d = tl.program_id(0).to(tl.int64), tl.program_id(1).to(tl.int64)
|
|
33
|
+
o_d = i_d * B + tl.arange(0, B)
|
|
34
|
+
m_d = o_d < D
|
|
35
|
+
|
|
36
|
+
b_x = tl.load(x + i_n * D + o_d, mask=m_d, other=-float('inf'))
|
|
37
|
+
if HAS_SCALE:
|
|
38
|
+
b_x = b_x * scale
|
|
39
|
+
b_m = tl.max(b_x, 0)
|
|
40
|
+
b_z = log(tl.sum(exp(b_x - b_m), 0)) + b_m
|
|
41
|
+
tl.store(z + i_n * tl.cdiv(D, B) + i_d, b_z)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def logsumexp_fwd(
|
|
45
|
+
x,
|
|
46
|
+
scale: Optional[float] = None,
|
|
47
|
+
dtype: Optional[torch.dtype] = None
|
|
48
|
+
):
|
|
49
|
+
r"""
|
|
50
|
+
Compute the logsumexp of the input tensor over the last dimension.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
x (Tensor):
|
|
54
|
+
The input tensor of any shape.
|
|
55
|
+
scale (Optional[float]):
|
|
56
|
+
The scale applied to the input tensor. Default: `None`.
|
|
57
|
+
dtype (Optional[torch.dtype]):
|
|
58
|
+
The data type of the output tensor. Default: `None`.
|
|
59
|
+
Returns:
|
|
60
|
+
Tensor: The logsumexp of the input tensor.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
shape = x.shape
|
|
64
|
+
x = x.view(-1, shape[-1])
|
|
65
|
+
N, D = x.shape
|
|
66
|
+
B = min(triton.next_power_of_2(D), 64 * 1024)
|
|
67
|
+
ND = triton.cdiv(D, B)
|
|
68
|
+
|
|
69
|
+
z = x.new_empty(N, ND, dtype=torch.float)
|
|
70
|
+
logsumexp_fwd_kernel[(N, ND)](
|
|
71
|
+
x=x,
|
|
72
|
+
z=z,
|
|
73
|
+
scale=scale,
|
|
74
|
+
D=D,
|
|
75
|
+
B=B
|
|
76
|
+
)
|
|
77
|
+
z = z.logsumexp(-1).view(*shape[:-1])
|
|
78
|
+
if dtype is not None and dtype != torch.float:
|
|
79
|
+
z = z.to(dtype)
|
|
80
|
+
return z
|
fla/ops/utils/matmul.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
# code adapted from
|
|
5
|
+
# https://triton-lang.org/main/getting-started/tutorials/03-matrix-multiplication.html
|
|
6
|
+
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import triton
|
|
11
|
+
import triton.language as tl
|
|
12
|
+
|
|
13
|
+
from fla.ops.utils.op import exp
|
|
14
|
+
from fla.utils import input_guard
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# `triton.jit`'ed functions can be auto-tuned by using the `triton.autotune` decorator, which consumes:
|
|
18
|
+
# - A list of `triton.Config` objects that define different configurations of
|
|
19
|
+
# meta-parameters (e.g., `BM`) and compilation options (e.g., `num_warps`) to try
|
|
20
|
+
# - An auto-tuning *key* whose change in values will trigger evaluation of all the
|
|
21
|
+
# provided configs
|
|
22
|
+
@triton.heuristics({
|
|
23
|
+
'HAS_ALPHA': lambda args: args['alpha'] is not None,
|
|
24
|
+
'HAS_BETA': lambda args: args['beta'] is not None
|
|
25
|
+
})
|
|
26
|
+
@triton.autotune(
|
|
27
|
+
configs=[
|
|
28
|
+
triton.Config({'BM': 128, 'BK': 64, 'BN': 256, 'G': 4}, num_stages=3, num_warps=8),
|
|
29
|
+
triton.Config({'BM': 64, 'BK': 32, 'BN': 256, 'G': 4}, num_stages=4, num_warps=4),
|
|
30
|
+
triton.Config({'BM': 128, 'BK': 32, 'BN': 128, 'G': 4}, num_stages=4, num_warps=4),
|
|
31
|
+
triton.Config({'BM': 128, 'BK': 32, 'BN': 64, 'G': 4}, num_stages=4, num_warps=4),
|
|
32
|
+
triton.Config({'BM': 64, 'BK': 32, 'BN': 128, 'G': 4}, num_stages=4, num_warps=4),
|
|
33
|
+
triton.Config({'BM': 128, 'BK': 32, 'BN': 32, 'G': 4}, num_stages=4, num_warps=4),
|
|
34
|
+
triton.Config({'BM': 64, 'BK': 32, 'BN': 32, 'G': 4}, num_stages=5, num_warps=2),
|
|
35
|
+
triton.Config({'BM': 32, 'BK': 32, 'BN': 64, 'G': 4}, num_stages=5, num_warps=2),
|
|
36
|
+
# Good config for fp8 inputs.
|
|
37
|
+
# triton.Config({'BM': 128, 'BK': 128, 'BN': 256, 'G': 4}, num_stages=3, num_warps=8),
|
|
38
|
+
# triton.Config({'BM': 256, 'BK': 128, 'BN': 128, 'G': 4}, num_stages=3, num_warps=8),
|
|
39
|
+
# triton.Config({'BM': 256, 'BK': 128, 'BN': 64, 'G': 4}, num_stages=4, num_warps=4),
|
|
40
|
+
# triton.Config({'BM': 64, 'BK': 128, 'BN': 256, 'G': 4}, num_stages=4, num_warps=4),
|
|
41
|
+
# triton.Config({'BM': 128, 'BK': 128, 'BN': 128, 'G': 4}, num_stages=4, num_warps=4),
|
|
42
|
+
# triton.Config({'BM': 128, 'BK': 64, 'BN': 64, 'G': 4}, num_stages=4, num_warps=4),
|
|
43
|
+
# triton.Config({'BM': 64, 'BK': 64, 'BN': 128, 'G': 4}, num_stages=4, num_warps=4),
|
|
44
|
+
# triton.Config({'BM': 128, 'BK': 64, 'BN': 32, 'G': 4}, num_stages=4, num_warps=4)
|
|
45
|
+
],
|
|
46
|
+
key=['M', 'N', 'K']
|
|
47
|
+
)
|
|
48
|
+
@triton.jit
|
|
49
|
+
def matmul_kernel(
|
|
50
|
+
# Pointers to matrices
|
|
51
|
+
a,
|
|
52
|
+
b,
|
|
53
|
+
c,
|
|
54
|
+
input,
|
|
55
|
+
alpha,
|
|
56
|
+
beta,
|
|
57
|
+
# Matrix dimensions
|
|
58
|
+
M,
|
|
59
|
+
N,
|
|
60
|
+
K,
|
|
61
|
+
# The stride variables represent how much to increase the ptr by when moving by 1
|
|
62
|
+
# element in a particular dimension. E.g. `s_am` is how much to increase `a`
|
|
63
|
+
# by to get the element one row down (A has M rows).
|
|
64
|
+
stride_ab, stride_am, stride_ak, # a: batch, M, K
|
|
65
|
+
stride_bk, stride_bn, # b: K, N
|
|
66
|
+
stride_cb, stride_cm, stride_cn, # c: batch, M, N
|
|
67
|
+
# Meta-parameters
|
|
68
|
+
BM: tl.constexpr,
|
|
69
|
+
BK: tl.constexpr,
|
|
70
|
+
BN: tl.constexpr,
|
|
71
|
+
G: tl.constexpr,
|
|
72
|
+
ACTIVATION: tl.constexpr,
|
|
73
|
+
HAS_INPUT: tl.constexpr,
|
|
74
|
+
HAS_ALPHA: tl.constexpr,
|
|
75
|
+
HAS_BETA: tl.constexpr,
|
|
76
|
+
ALLOW_TF32: tl.constexpr,
|
|
77
|
+
X_DIM: tl.constexpr = 1,
|
|
78
|
+
):
|
|
79
|
+
"""Kernel for computing the matmul C = A x B.
|
|
80
|
+
A has shape (M, K), B has shape (K, N) and C has shape (M, N)
|
|
81
|
+
"""
|
|
82
|
+
# -----------------------------------------------------------
|
|
83
|
+
# Map program ids `pid` to the block of C it should compute.
|
|
84
|
+
# This is done in a grouped ordering to promote L2 data reuse.
|
|
85
|
+
# See above `L2 Cache Optimizations` section for details.
|
|
86
|
+
i_b, i_m, i_n = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
|
87
|
+
|
|
88
|
+
NM, NN = tl.num_programs(1), tl.num_programs(2)
|
|
89
|
+
i_m, i_n = tl.swizzle2d(i_m, i_n, NM, NN, G)
|
|
90
|
+
|
|
91
|
+
# ----------------------------------------------------------
|
|
92
|
+
# Create pointers for the first blocks of A and B.
|
|
93
|
+
# We will advance this pointer as we move in the K direction
|
|
94
|
+
# and accumulate
|
|
95
|
+
# `p_a` is a block of [BM, BK] pointers
|
|
96
|
+
# `p_b` is a block of [BK, BN] pointers
|
|
97
|
+
# See above `Pointer Arithmetic` section for details
|
|
98
|
+
a_batch_ptr = a + i_b * stride_ab
|
|
99
|
+
o_am = (i_m * BM + tl.arange(0, BM)) % M
|
|
100
|
+
o_bn = (i_n * BN + tl.arange(0, BN)) % N
|
|
101
|
+
o_k = tl.arange(0, BK)
|
|
102
|
+
|
|
103
|
+
p_a = a_batch_ptr + (o_am[:, None] * stride_am + o_k[None, :] * stride_ak)
|
|
104
|
+
p_b = b + (o_k[:, None] * stride_bk + o_bn[None, :] * stride_bn)
|
|
105
|
+
|
|
106
|
+
b_acc = tl.zeros((BM, BN), dtype=tl.float32)
|
|
107
|
+
for k in range(0, tl.cdiv(K, BK)):
|
|
108
|
+
# Load the next block of A and B, generate a mask by checking the K dimension.
|
|
109
|
+
# If it is out of bounds, set it to 0.
|
|
110
|
+
b_a = tl.load(p_a, mask=o_k[None, :] < K - k * BK, other=0.0)
|
|
111
|
+
b_b = tl.load(p_b, mask=o_k[:, None] < K - k * BK, other=0.0)
|
|
112
|
+
# We accumulate along the K dimension.
|
|
113
|
+
b_acc = tl.dot(b_a, b_b, acc=b_acc, allow_tf32=ALLOW_TF32)
|
|
114
|
+
# Advance the ptrs to the next K block.
|
|
115
|
+
p_a += BK * stride_ak
|
|
116
|
+
p_b += BK * stride_bk
|
|
117
|
+
|
|
118
|
+
o_cm = i_m * BM + tl.arange(0, BM)
|
|
119
|
+
o_cn = i_n * BN + tl.arange(0, BN)
|
|
120
|
+
mask = (o_cm[:, None] < M) & (o_cn[None, :] < N)
|
|
121
|
+
|
|
122
|
+
b_c = b_acc
|
|
123
|
+
# You can fuse arbitrary activation functions here
|
|
124
|
+
# while the b_acc is still in FP32!
|
|
125
|
+
if ACTIVATION == "leaky_relu":
|
|
126
|
+
b_c = leaky_relu(b_c)
|
|
127
|
+
elif ACTIVATION == "relu":
|
|
128
|
+
b_c = relu(b_c)
|
|
129
|
+
elif ACTIVATION == "sigmoid":
|
|
130
|
+
b_c = sigmoid(b_c)
|
|
131
|
+
elif ACTIVATION == "tanh":
|
|
132
|
+
b_c = tanh(b_c)
|
|
133
|
+
|
|
134
|
+
if HAS_ALPHA:
|
|
135
|
+
b_c *= tl.load(alpha)
|
|
136
|
+
|
|
137
|
+
if HAS_INPUT:
|
|
138
|
+
p_i = input + (stride_cm * o_cm[:, None] if X_DIM == 2 else 0) + stride_cn * o_cn[None, :]
|
|
139
|
+
mask_p = (o_cn[None, :] < N) if X_DIM == 1 else mask
|
|
140
|
+
b_i = tl.load(p_i, mask=mask_p, other=0.0).to(tl.float32)
|
|
141
|
+
if HAS_BETA:
|
|
142
|
+
b_i *= tl.load(beta)
|
|
143
|
+
b_c += b_i
|
|
144
|
+
|
|
145
|
+
# -----------------------------------------------------------
|
|
146
|
+
# Write back the block of the output matrix C with masks.
|
|
147
|
+
c_batch_ptr = c + i_b * stride_cb
|
|
148
|
+
p_c = c_batch_ptr + stride_cm * o_cm[:, None] + stride_cn * o_cn[None, :]
|
|
149
|
+
tl.store(p_c, b_c.to(c.dtype.element_ty), mask=mask)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# We can fuse `leaky_relu` by providing it as an `ACTIVATION` meta-parameter in `matmul_kernel`.
|
|
153
|
+
@triton.jit
|
|
154
|
+
def leaky_relu(x):
|
|
155
|
+
return tl.where(x >= 0, x, 0.01 * x)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
@triton.jit
|
|
159
|
+
def sigmoid(x):
|
|
160
|
+
# σ(x) = 1 / (1 + exp(-x))
|
|
161
|
+
return 1.0 / (1.0 + exp(-x))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@triton.jit
|
|
165
|
+
def tanh(x):
|
|
166
|
+
# tanh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))
|
|
167
|
+
# 2 * sigmoid(2x) - 1
|
|
168
|
+
return (exp(x) - exp(-x)) / (exp(x) + exp(-x))
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@triton.jit
|
|
172
|
+
def relu(x):
|
|
173
|
+
# ReLU(x) = max(0, x)
|
|
174
|
+
return tl.maximum(x, 0.0)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@input_guard
|
|
178
|
+
def matmul(a, b, activation=''):
|
|
179
|
+
assert a.dim() in [2, 3], "a must be 2D or 3D"
|
|
180
|
+
assert b.dim() == 2, "b must be 2D"
|
|
181
|
+
assert a.shape[-1] == b.shape[0], f"Incompatible dimensions: A {a.shape}, B {b.shape}"
|
|
182
|
+
|
|
183
|
+
if a.dim() == 2:
|
|
184
|
+
a_dim = 2
|
|
185
|
+
a = a.unsqueeze(0).contiguous() # (1, M, K)
|
|
186
|
+
else:
|
|
187
|
+
a_dim = 3
|
|
188
|
+
allow_tf32 = False if a.dtype == torch.float32 else True
|
|
189
|
+
|
|
190
|
+
B, M, K = a.shape[0], a.shape[1], a.shape[2]
|
|
191
|
+
K_b, N = b.shape
|
|
192
|
+
assert K == K_b, f"Incompatible K dimension: A {K} vs B {K_b}"
|
|
193
|
+
c = a.new_empty(B, M, N)
|
|
194
|
+
|
|
195
|
+
def grid(meta): return (B, triton.cdiv(M, meta['BM']), triton.cdiv(N, meta['BN']))
|
|
196
|
+
matmul_kernel[grid](
|
|
197
|
+
a, b, c, None, None, None,
|
|
198
|
+
M, N, K,
|
|
199
|
+
a.stride(0), a.stride(1), a.stride(2), # stride_ab, stride_am, stride_ak
|
|
200
|
+
b.stride(0), b.stride(1), # stride_bk, stride_bn (b.dim() == 2)
|
|
201
|
+
c.stride(0), c.stride(1), c.stride(2), # stride_cb, stride_cm, stride_cn
|
|
202
|
+
ACTIVATION=activation,
|
|
203
|
+
ALLOW_TF32=allow_tf32,
|
|
204
|
+
HAS_INPUT=False,
|
|
205
|
+
)
|
|
206
|
+
return c.squeeze(0) if a_dim == 2 else c
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@input_guard
|
|
210
|
+
def addmm(
|
|
211
|
+
x: torch.Tensor,
|
|
212
|
+
a: torch.Tensor,
|
|
213
|
+
b: torch.Tensor,
|
|
214
|
+
alpha: Optional[float] = None,
|
|
215
|
+
beta: Optional[float] = None,
|
|
216
|
+
) -> torch.Tensor:
|
|
217
|
+
assert a.dim() in [2, 3], "a must be 2D or 3D"
|
|
218
|
+
assert b.dim() == 2, "b must be 2D"
|
|
219
|
+
assert a.shape[-1] == b.shape[0], f"Incompatible dimensions: A {a.shape}, B {b.shape}"
|
|
220
|
+
|
|
221
|
+
if a.dim() == 2:
|
|
222
|
+
a_dim = 2
|
|
223
|
+
a = a.unsqueeze(0).contiguous() # (1, M, K)
|
|
224
|
+
else:
|
|
225
|
+
a_dim = 3
|
|
226
|
+
allow_tf32 = False if a.dtype == torch.float32 else True
|
|
227
|
+
|
|
228
|
+
B, M, K = a.shape[0], a.shape[1], a.shape[2]
|
|
229
|
+
K_b, N = b.shape
|
|
230
|
+
assert K == K_b, f"Incompatible K dimension: A {K} vs B {K_b}"
|
|
231
|
+
c = a.new_empty(B, M, N)
|
|
232
|
+
|
|
233
|
+
def grid(meta): return (B, triton.cdiv(M, meta['BM']), triton.cdiv(N, meta['BN']))
|
|
234
|
+
matmul_kernel[grid](
|
|
235
|
+
a, b, c, x, alpha, beta,
|
|
236
|
+
M, N, K,
|
|
237
|
+
a.stride(0), a.stride(1), a.stride(2), # stride_ab, stride_am, stride_ak
|
|
238
|
+
b.stride(0), b.stride(1), # stride_bk, stride_bn (b.dim() == 2)
|
|
239
|
+
c.stride(0), c.stride(1), c.stride(2), # stride_cb, stride_cm, stride_cn
|
|
240
|
+
ACTIVATION=None,
|
|
241
|
+
ALLOW_TF32=allow_tf32,
|
|
242
|
+
HAS_INPUT=True,
|
|
243
|
+
X_DIM=x.dim(),
|
|
244
|
+
)
|
|
245
|
+
return c.squeeze(0) if a_dim == 2 else c
|
fla/ops/utils/op.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
import triton
|
|
7
|
+
import triton.language as tl
|
|
8
|
+
import triton.language.extra.libdevice as tldevice
|
|
9
|
+
|
|
10
|
+
from fla.utils import is_gather_supported
|
|
11
|
+
|
|
12
|
+
if os.environ.get('FLA_USE_FAST_OPS', '0') == '1':
|
|
13
|
+
exp = tldevice.fast_expf
|
|
14
|
+
exp2 = tldevice.exp2
|
|
15
|
+
log = tldevice.fast_logf
|
|
16
|
+
log2 = tldevice.fast_log2f
|
|
17
|
+
else:
|
|
18
|
+
exp = tl.exp
|
|
19
|
+
exp2 = tl.math.exp2
|
|
20
|
+
log = tl.log
|
|
21
|
+
log2 = tl.log2
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@triton.jit
|
|
25
|
+
def safe_exp(x):
|
|
26
|
+
return exp(tl.where(x <= 0, x, float('-inf')))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
if not is_gather_supported:
|
|
30
|
+
@triton.jit
|
|
31
|
+
def gather(src, index, axis, _builder=None):
|
|
32
|
+
"""
|
|
33
|
+
Gather operation that works when tl.gather is not supported.
|
|
34
|
+
This is a fallback implementation that returns None.
|
|
35
|
+
Just to make triton compiler happy.
|
|
36
|
+
"""
|
|
37
|
+
return None
|
|
38
|
+
else:
|
|
39
|
+
gather = tl.gather
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if hasattr(triton.language, '_experimental_make_tensor_descriptor'):
|
|
43
|
+
# For Triton 3.3.x
|
|
44
|
+
make_tensor_descriptor = triton.language._experimental_make_tensor_descriptor
|
|
45
|
+
elif hasattr(triton.language, 'make_tensor_descriptor'):
|
|
46
|
+
# For Triton 3.4.x and later
|
|
47
|
+
make_tensor_descriptor = triton.language.make_tensor_descriptor
|
|
48
|
+
else:
|
|
49
|
+
"""
|
|
50
|
+
Fallback implementation when TMA is not supported.
|
|
51
|
+
Returns None to indicate TMA descriptors are unavailable.
|
|
52
|
+
Just make triton compiler happy.
|
|
53
|
+
"""
|
|
54
|
+
@triton.jit
|
|
55
|
+
def make_tensor_descriptor(
|
|
56
|
+
base,
|
|
57
|
+
shape,
|
|
58
|
+
strides,
|
|
59
|
+
block_shape,
|
|
60
|
+
_builder=None,
|
|
61
|
+
):
|
|
62
|
+
return None
|