flash-linear-attention 0.1__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 +104 -0
- fla/layers/__init__.py +40 -0
- fla/layers/abc.py +211 -0
- fla/layers/attn.py +193 -0
- fla/layers/based.py +95 -0
- fla/layers/bitattn.py +188 -0
- fla/layers/delta_net.py +290 -0
- fla/layers/gated_deltanet.py +298 -0
- fla/layers/gla.py +285 -0
- fla/layers/gsa.py +226 -0
- fla/layers/hgrn.py +153 -0
- fla/layers/hgrn2.py +212 -0
- fla/layers/lightnet.py +202 -0
- fla/layers/linear_attn.py +159 -0
- fla/layers/multiscale_retention.py +294 -0
- fla/layers/nsa.py +138 -0
- fla/layers/rebased.py +133 -0
- fla/layers/rwkv6.py +307 -0
- fla/layers/rwkv7.py +220 -0
- fla/layers/simple_gla.py +254 -0
- fla/models/__init__.py +41 -0
- fla/models/abc/__init__.py +13 -0
- fla/models/abc/configuration_abc.py +89 -0
- fla/models/abc/modeling_abc.py +408 -0
- fla/models/bitnet/__init__.py +13 -0
- fla/models/bitnet/configuration_bitnet.py +67 -0
- fla/models/bitnet/modeling_bitnet.py +437 -0
- fla/models/delta_net/__init__.py +12 -0
- fla/models/delta_net/configuration_delta_net.py +91 -0
- fla/models/delta_net/modeling_delta_net.py +415 -0
- fla/models/gated_deltanet/__init__.py +12 -0
- fla/models/gated_deltanet/configuration_gated_deltanet.py +83 -0
- fla/models/gated_deltanet/modeling_gated_deltanet.py +412 -0
- fla/models/gla/__init__.py +13 -0
- fla/models/gla/configuration_gla.py +95 -0
- fla/models/gla/modeling_gla.py +417 -0
- fla/models/gsa/__init__.py +13 -0
- fla/models/gsa/configuration_gsa.py +97 -0
- fla/models/gsa/modeling_gsa.py +420 -0
- fla/models/hgrn/__init__.py +13 -0
- fla/models/hgrn/configuration_hgrn.py +81 -0
- fla/models/hgrn/modeling_hgrn.py +420 -0
- fla/models/hgrn2/__init__.py +13 -0
- fla/models/hgrn2/configuration_hgrn2.py +91 -0
- fla/models/hgrn2/modeling_hgrn2.py +421 -0
- fla/models/lightnet/__init__.py +13 -0
- fla/models/lightnet/configuration_lightnet.py +83 -0
- fla/models/lightnet/modeling_lightnet.py +410 -0
- fla/models/linear_attn/__init__.py +12 -0
- fla/models/linear_attn/configuration_linear_attn.py +90 -0
- fla/models/linear_attn/modeling_linear_attn.py +416 -0
- fla/models/mamba/__init__.py +13 -0
- fla/models/mamba/configuration_mamba.py +166 -0
- fla/models/mamba/modeling_mamba.py +843 -0
- fla/models/mamba2/__init__.py +13 -0
- fla/models/mamba2/configuration_mamba2.py +170 -0
- fla/models/mamba2/modeling_mamba2.py +1093 -0
- fla/models/nsa/__init__.py +15 -0
- fla/models/nsa/configuration_nsa.py +75 -0
- fla/models/nsa/modeling_nsa.py +399 -0
- fla/models/retnet/__init__.py +13 -0
- fla/models/retnet/configuration_retnet.py +92 -0
- fla/models/retnet/modeling_retnet.py +425 -0
- fla/models/rwkv6/__init__.py +13 -0
- fla/models/rwkv6/configuration_rwkv6.py +82 -0
- fla/models/rwkv6/modeling_rwkv6.py +480 -0
- fla/models/rwkv7/__init__.py +13 -0
- fla/models/rwkv7/configuration_rwkv7.py +105 -0
- fla/models/rwkv7/modeling_rwkv7.py +491 -0
- fla/models/samba/__init__.py +13 -0
- fla/models/samba/configuration_samba.py +92 -0
- fla/models/samba/modeling_samba.py +413 -0
- fla/models/transformer/__init__.py +13 -0
- fla/models/transformer/configuration_transformer.py +69 -0
- fla/models/transformer/modeling_transformer.py +404 -0
- fla/models/utils.py +147 -0
- fla/modules/__init__.py +26 -0
- fla/modules/activations.py +470 -0
- fla/modules/convolution.py +363 -0
- fla/modules/feature_map.py +300 -0
- fla/modules/fused_bitlinear.py +638 -0
- fla/modules/fused_cross_entropy.py +418 -0
- fla/modules/fused_kl_div.py +321 -0
- fla/modules/fused_linear_cross_entropy.py +568 -0
- fla/modules/fused_norm_gate.py +817 -0
- fla/modules/grpo.py +395 -0
- fla/modules/l2norm.py +201 -0
- fla/modules/layernorm.py +1088 -0
- fla/modules/layernorm_gated.py +528 -0
- fla/modules/mlp.py +126 -0
- fla/modules/parallel.py +36 -0
- fla/modules/rotary.py +512 -0
- fla/ops/__init__.py +41 -0
- fla/ops/abc/__init__.py +7 -0
- fla/ops/abc/chunk.py +1115 -0
- fla/ops/abc/naive.py +96 -0
- fla/ops/based/__init__.py +9 -0
- fla/ops/based/fused_chunk.py +374 -0
- fla/ops/based/naive.py +72 -0
- fla/ops/based/parallel.py +410 -0
- fla/ops/common/__init__.py +1 -0
- fla/ops/common/chunk_delta_h.py +391 -0
- fla/ops/common/chunk_h.py +418 -0
- fla/ops/common/chunk_h_parallel.py +648 -0
- fla/ops/common/chunk_h_split.py +675 -0
- fla/ops/common/chunk_o.py +649 -0
- fla/ops/common/fused_recurrent.py +574 -0
- fla/ops/common/utils.py +69 -0
- fla/ops/delta_rule/__init__.py +11 -0
- fla/ops/delta_rule/chunk.py +356 -0
- fla/ops/delta_rule/fused_chunk.py +6 -0
- fla/ops/delta_rule/fused_recurrent.py +593 -0
- fla/ops/delta_rule/naive.py +120 -0
- fla/ops/delta_rule/parallel.py +394 -0
- fla/ops/delta_rule/wy_fast.py +504 -0
- fla/ops/gated_delta_rule/__init__.py +7 -0
- fla/ops/gated_delta_rule/chunk.py +374 -0
- fla/ops/gated_delta_rule/fused_recurrent.py +319 -0
- fla/ops/gated_delta_rule/wy_fast.py +626 -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 +385 -0
- fla/ops/generalized_delta_rule/dplr/chunk_A_bwd.py +418 -0
- fla/ops/generalized_delta_rule/dplr/chunk_A_fwd.py +314 -0
- fla/ops/generalized_delta_rule/dplr/chunk_h_bwd.py +197 -0
- fla/ops/generalized_delta_rule/dplr/chunk_h_fwd.py +198 -0
- fla/ops/generalized_delta_rule/dplr/chunk_o_bwd.py +482 -0
- fla/ops/generalized_delta_rule/dplr/chunk_o_fwd.py +138 -0
- fla/ops/generalized_delta_rule/dplr/fused_recurrent.py +292 -0
- fla/ops/generalized_delta_rule/dplr/naive.py +158 -0
- fla/ops/generalized_delta_rule/dplr/wy_fast_bwd.py +189 -0
- fla/ops/generalized_delta_rule/dplr/wy_fast_fwd.py +319 -0
- fla/ops/generalized_delta_rule/iplr/__init__.py +7 -0
- fla/ops/generalized_delta_rule/iplr/chunk.py +525 -0
- fla/ops/generalized_delta_rule/iplr/fused_recurrent.py +451 -0
- fla/ops/generalized_delta_rule/iplr/naive.py +69 -0
- fla/ops/generalized_delta_rule/iplr/wy_fast.py +345 -0
- fla/ops/gla/__init__.py +11 -0
- fla/ops/gla/chunk.py +1483 -0
- fla/ops/gla/fused_chunk.py +631 -0
- fla/ops/gla/fused_recurrent.py +113 -0
- fla/ops/gla/naive.py +41 -0
- fla/ops/gsa/__init__.py +9 -0
- fla/ops/gsa/chunk.py +1264 -0
- fla/ops/gsa/fused_recurrent.py +563 -0
- fla/ops/gsa/naive.py +68 -0
- fla/ops/hgrn/__init__.py +9 -0
- fla/ops/hgrn/chunk.py +281 -0
- fla/ops/hgrn/fused_recurrent.py +307 -0
- fla/ops/hgrn/naive.py +63 -0
- fla/ops/lightning_attn/__init__.py +9 -0
- fla/ops/lightning_attn/chunk.py +74 -0
- fla/ops/lightning_attn/fused_recurrent.py +75 -0
- fla/ops/linear_attn/__init__.py +11 -0
- fla/ops/linear_attn/chunk.py +65 -0
- fla/ops/linear_attn/fused_chunk.py +318 -0
- fla/ops/linear_attn/fused_recurrent.py +251 -0
- fla/ops/linear_attn/naive.py +36 -0
- fla/ops/linear_attn/utils.py +10 -0
- fla/ops/nsa/__init__.py +9 -0
- fla/ops/nsa/naive.py +94 -0
- fla/ops/nsa/parallel.py +1434 -0
- fla/ops/nsa/utils.py +90 -0
- fla/ops/rebased/__init__.py +7 -0
- fla/ops/rebased/naive.py +27 -0
- fla/ops/rebased/parallel.py +466 -0
- fla/ops/retention/__init__.py +13 -0
- fla/ops/retention/chunk.py +72 -0
- fla/ops/retention/fused_chunk.py +365 -0
- fla/ops/retention/fused_recurrent.py +42 -0
- fla/ops/retention/naive.py +15 -0
- fla/ops/retention/parallel.py +64 -0
- fla/ops/rwkv4/__init__.py +7 -0
- fla/ops/rwkv4/fused_recurrent.py +474 -0
- fla/ops/rwkv6/__init__.py +9 -0
- fla/ops/rwkv6/chunk.py +1464 -0
- fla/ops/rwkv6/chunk_naive.py +43 -0
- fla/ops/rwkv6/fused_recurrent.py +708 -0
- fla/ops/rwkv6/recurrent_naive.py +103 -0
- fla/ops/rwkv7/__init__.py +9 -0
- fla/ops/rwkv7/chunk.py +64 -0
- fla/ops/rwkv7/fused_recurrent.py +62 -0
- fla/ops/simple_gla/__init__.py +11 -0
- fla/ops/simple_gla/chunk.py +301 -0
- fla/ops/simple_gla/fused_recurrent.py +109 -0
- fla/ops/simple_gla/naive.py +54 -0
- fla/ops/simple_gla/parallel.py +716 -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 +1554 -0
- fla/ops/ttt/fused_chunk.py +896 -0
- fla/ops/ttt/naive.py +126 -0
- fla/ops/utils/__init__.py +45 -0
- fla/ops/utils/asm.py +17 -0
- fla/ops/utils/cumsum.py +398 -0
- fla/ops/utils/exp.py +18 -0
- fla/ops/utils/logcumsumexp.py +52 -0
- fla/ops/utils/logsumexp.py +78 -0
- fla/ops/utils/matmul.py +245 -0
- fla/ops/utils/pooling.py +216 -0
- fla/ops/utils/softmax.py +109 -0
- fla/utils.py +207 -0
- flash_linear_attention-0.1.dist-info/LICENSE +21 -0
- flash_linear_attention-0.1.dist-info/METADATA +515 -0
- flash_linear_attention-0.1.dist-info/RECORD +209 -0
- flash_linear_attention-0.1.dist-info/WHEEL +5 -0
- flash_linear_attention-0.1.dist-info/top_level.txt +1 -0
fla/__init__.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
from fla.layers import (
|
|
4
|
+
ABCAttention,
|
|
5
|
+
Attention,
|
|
6
|
+
BasedLinearAttention,
|
|
7
|
+
BitAttention,
|
|
8
|
+
DeltaNet,
|
|
9
|
+
GatedDeltaNet,
|
|
10
|
+
GatedLinearAttention,
|
|
11
|
+
GatedSlotAttention,
|
|
12
|
+
HGRN2Attention,
|
|
13
|
+
HGRNAttention,
|
|
14
|
+
LightNetAttention,
|
|
15
|
+
LinearAttention,
|
|
16
|
+
MultiScaleRetention,
|
|
17
|
+
NativeSparseAttention,
|
|
18
|
+
ReBasedLinearAttention,
|
|
19
|
+
RWKV6Attention,
|
|
20
|
+
RWKV7Attention
|
|
21
|
+
)
|
|
22
|
+
from fla.models import (
|
|
23
|
+
ABCForCausalLM,
|
|
24
|
+
ABCModel,
|
|
25
|
+
BitNetForCausalLM,
|
|
26
|
+
BitNetModel,
|
|
27
|
+
DeltaNetForCausalLM,
|
|
28
|
+
DeltaNetModel,
|
|
29
|
+
GatedDeltaNetForCausalLM,
|
|
30
|
+
GatedDeltaNetModel,
|
|
31
|
+
GLAForCausalLM,
|
|
32
|
+
GLAModel,
|
|
33
|
+
GSAForCausalLM,
|
|
34
|
+
GSAModel,
|
|
35
|
+
HGRN2ForCausalLM,
|
|
36
|
+
HGRN2Model,
|
|
37
|
+
HGRNForCausalLM,
|
|
38
|
+
LightNetForCausalLM,
|
|
39
|
+
LightNetModel,
|
|
40
|
+
LinearAttentionForCausalLM,
|
|
41
|
+
LinearAttentionModel,
|
|
42
|
+
NSAForCausalLM,
|
|
43
|
+
NSAModel,
|
|
44
|
+
RetNetForCausalLM,
|
|
45
|
+
RetNetModel,
|
|
46
|
+
RWKV6ForCausalLM,
|
|
47
|
+
RWKV6Model,
|
|
48
|
+
RWKV7ForCausalLM,
|
|
49
|
+
RWKV7Model,
|
|
50
|
+
TransformerForCausalLM,
|
|
51
|
+
TransformerModel
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
__all__ = [
|
|
55
|
+
'ABCAttention',
|
|
56
|
+
'Attention',
|
|
57
|
+
'BasedLinearAttention',
|
|
58
|
+
'BitAttention',
|
|
59
|
+
'DeltaNet',
|
|
60
|
+
'GatedDeltaNet',
|
|
61
|
+
'HGRNAttention',
|
|
62
|
+
'HGRN2Attention',
|
|
63
|
+
'GatedLinearAttention',
|
|
64
|
+
'GatedSlotAttention',
|
|
65
|
+
'LightNetAttention',
|
|
66
|
+
'LinearAttention',
|
|
67
|
+
'MultiScaleRetention',
|
|
68
|
+
'NativeSparseAttention',
|
|
69
|
+
'ReBasedLinearAttention',
|
|
70
|
+
'RWKV6Attention',
|
|
71
|
+
'RWKV7Attention',
|
|
72
|
+
'ABCForCausalLM',
|
|
73
|
+
'ABCModel',
|
|
74
|
+
'BitNetForCausalLM',
|
|
75
|
+
'BitNetModel',
|
|
76
|
+
'DeltaNetForCausalLM',
|
|
77
|
+
'DeltaNetModel',
|
|
78
|
+
'GatedDeltaNetForCausalLM',
|
|
79
|
+
'GatedDeltaNetModel',
|
|
80
|
+
'HGRNForCausalLM',
|
|
81
|
+
'HGRNModel',
|
|
82
|
+
'HGRN2ForCausalLM',
|
|
83
|
+
'HGRN2Model',
|
|
84
|
+
'GLAForCausalLM',
|
|
85
|
+
'GLAModel',
|
|
86
|
+
'GSAForCausalLM',
|
|
87
|
+
'GSAModel',
|
|
88
|
+
'LightNetForCausalLM',
|
|
89
|
+
'LightNetModel',
|
|
90
|
+
'LinearAttentionForCausalLM',
|
|
91
|
+
'LinearAttentionModel',
|
|
92
|
+
'NSAForCausalLM',
|
|
93
|
+
'NSAModel',
|
|
94
|
+
'RetNetForCausalLM',
|
|
95
|
+
'RetNetModel',
|
|
96
|
+
'RWKV6ForCausalLM',
|
|
97
|
+
'RWKV6Model',
|
|
98
|
+
'RWKV7ForCausalLM',
|
|
99
|
+
'RWKV7Model',
|
|
100
|
+
'TransformerForCausalLM',
|
|
101
|
+
'TransformerModel'
|
|
102
|
+
]
|
|
103
|
+
|
|
104
|
+
__version__ = '0.1'
|
fla/layers/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
from .abc import ABCAttention
|
|
5
|
+
from .attn import Attention
|
|
6
|
+
from .based import BasedLinearAttention
|
|
7
|
+
from .bitattn import BitAttention
|
|
8
|
+
from .delta_net import DeltaNet
|
|
9
|
+
from .gated_deltanet import GatedDeltaNet
|
|
10
|
+
from .gla import GatedLinearAttention
|
|
11
|
+
from .gsa import GatedSlotAttention
|
|
12
|
+
from .hgrn import HGRNAttention
|
|
13
|
+
from .hgrn2 import HGRN2Attention
|
|
14
|
+
from .lightnet import LightNetAttention
|
|
15
|
+
from .linear_attn import LinearAttention
|
|
16
|
+
from .multiscale_retention import MultiScaleRetention
|
|
17
|
+
from .nsa import NativeSparseAttention
|
|
18
|
+
from .rebased import ReBasedLinearAttention
|
|
19
|
+
from .rwkv6 import RWKV6Attention
|
|
20
|
+
from .rwkv7 import RWKV7Attention
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
'ABCAttention',
|
|
24
|
+
'Attention',
|
|
25
|
+
'BasedLinearAttention',
|
|
26
|
+
'BitAttention',
|
|
27
|
+
'DeltaNet',
|
|
28
|
+
'GatedDeltaNet',
|
|
29
|
+
'GatedLinearAttention',
|
|
30
|
+
'GatedSlotAttention',
|
|
31
|
+
'HGRNAttention',
|
|
32
|
+
'HGRN2Attention',
|
|
33
|
+
'LightNetAttention',
|
|
34
|
+
'LinearAttention',
|
|
35
|
+
'MultiScaleRetention',
|
|
36
|
+
'NativeSparseAttention',
|
|
37
|
+
'ReBasedLinearAttention',
|
|
38
|
+
'RWKV6Attention',
|
|
39
|
+
'RWKV7Attention',
|
|
40
|
+
]
|
fla/layers/abc.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import warnings
|
|
7
|
+
from typing import TYPE_CHECKING, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import torch.nn as nn
|
|
11
|
+
from einops import rearrange
|
|
12
|
+
|
|
13
|
+
from fla.modules import FusedRMSNormSwishGate, RMSNorm, RotaryEmbedding, ShortConvolution
|
|
14
|
+
from fla.modules.activations import swiglu, swish
|
|
15
|
+
from fla.ops.abc.chunk import chunk_abc
|
|
16
|
+
from fla.ops.common.utils import prepare_position_ids, prepare_sequence_ids
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from fla.models.utils import Cache
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ABCAttention(nn.Module):
|
|
23
|
+
|
|
24
|
+
def __init__(
|
|
25
|
+
self,
|
|
26
|
+
hidden_size: int = 1024,
|
|
27
|
+
expand_k: float = 0.5,
|
|
28
|
+
expand_v: float = 1.0,
|
|
29
|
+
num_heads: int = 4,
|
|
30
|
+
use_short_conv: bool = False,
|
|
31
|
+
conv_size: int = 4,
|
|
32
|
+
conv_bias: bool = False,
|
|
33
|
+
num_slots: Optional[int] = None,
|
|
34
|
+
elementwise_affine: Optional[bool] = True,
|
|
35
|
+
norm_eps: float = 1e-5,
|
|
36
|
+
gate_low_rank_dim: int = 16,
|
|
37
|
+
gate_logit_normalizer: int = 16,
|
|
38
|
+
use_input_gate: bool = False,
|
|
39
|
+
use_output_gate: bool = True,
|
|
40
|
+
use_norm: bool = True,
|
|
41
|
+
clamp_min: Optional[float] = -32,
|
|
42
|
+
clamp_max: Optional[float] = 32,
|
|
43
|
+
layer_idx: Optional[int] = None,
|
|
44
|
+
**kwargs
|
|
45
|
+
) -> ABCAttention:
|
|
46
|
+
super().__init__()
|
|
47
|
+
|
|
48
|
+
self.hidden_size = hidden_size
|
|
49
|
+
self.expand_k = expand_k
|
|
50
|
+
self.expand_v = expand_v
|
|
51
|
+
self.num_heads = num_heads
|
|
52
|
+
self.key_dim = int(self.hidden_size * self.expand_k)
|
|
53
|
+
self.value_dim = int(self.hidden_size * self.expand_v)
|
|
54
|
+
self.head_k_dim = self.key_dim // self.num_heads
|
|
55
|
+
self.head_v_dim = self.value_dim // self.num_heads
|
|
56
|
+
|
|
57
|
+
self.use_short_conv = use_short_conv
|
|
58
|
+
self.conv_size = conv_size
|
|
59
|
+
self.conv_bias = conv_bias
|
|
60
|
+
|
|
61
|
+
self.gate_low_rank_dim = gate_low_rank_dim
|
|
62
|
+
self.gate_logit_normalizer = gate_logit_normalizer
|
|
63
|
+
|
|
64
|
+
self.use_input_gate = use_input_gate
|
|
65
|
+
self.use_output_gate = use_output_gate
|
|
66
|
+
self.use_norm = use_norm
|
|
67
|
+
|
|
68
|
+
if num_slots is None:
|
|
69
|
+
num_slots = self.head_k_dim
|
|
70
|
+
self.num_slots = num_slots
|
|
71
|
+
|
|
72
|
+
self.norm_eps = norm_eps
|
|
73
|
+
|
|
74
|
+
self.clamp_min = clamp_min
|
|
75
|
+
self.clamp_max = clamp_max
|
|
76
|
+
self.layer_idx = layer_idx
|
|
77
|
+
|
|
78
|
+
if layer_idx is None:
|
|
79
|
+
warnings.warn(
|
|
80
|
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
|
81
|
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
|
82
|
+
"when creating this class."
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
self.q_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
|
|
86
|
+
self.k_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
|
|
87
|
+
self.v_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False)
|
|
88
|
+
|
|
89
|
+
if use_output_gate:
|
|
90
|
+
self.g_proj = nn.Linear(self.hidden_size, self.value_dim, bias=False)
|
|
91
|
+
self.s_proj = nn.Linear(self.hidden_size, self.num_heads * self.num_slots, bias=False)
|
|
92
|
+
self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
|
|
93
|
+
|
|
94
|
+
if use_short_conv:
|
|
95
|
+
self.conv_size = conv_size
|
|
96
|
+
self.q_conv1d = ShortConvolution(self.key_dim, conv_size, activation='silu')
|
|
97
|
+
self.k_conv1d = ShortConvolution(self.key_dim, conv_size, activation='silu')
|
|
98
|
+
self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
|
99
|
+
|
|
100
|
+
if self.use_norm:
|
|
101
|
+
if self.use_output_gate:
|
|
102
|
+
self.g_norm = FusedRMSNormSwishGate(self.head_v_dim, elementwise_affine, norm_eps)
|
|
103
|
+
else:
|
|
104
|
+
self.g_norm = RMSNorm(hidden_size=self.head_v_dim, elementwise_affine=elementwise_affine, eps=norm_eps)
|
|
105
|
+
|
|
106
|
+
if self.use_rope:
|
|
107
|
+
self.rotary = RotaryEmbedding(self.head_k_dim)
|
|
108
|
+
|
|
109
|
+
def forward(
|
|
110
|
+
self,
|
|
111
|
+
hidden_states: torch.Tensor,
|
|
112
|
+
attention_mask: Optional[torch.Tensor] = None,
|
|
113
|
+
past_key_values: Optional[Cache] = None,
|
|
114
|
+
use_cache: Optional[bool] = False,
|
|
115
|
+
output_attentions: Optional[bool] = False,
|
|
116
|
+
**kwargs
|
|
117
|
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
|
118
|
+
if attention_mask is not None:
|
|
119
|
+
assert len(attention_mask.shape) == 2, (
|
|
120
|
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
|
121
|
+
"for padding purposes (0 indicating padding). "
|
|
122
|
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
last_state = None
|
|
126
|
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
|
127
|
+
last_state = past_key_values[self.layer_idx]
|
|
128
|
+
|
|
129
|
+
cu_seqlens, position_ids, seq_idx = kwargs.get('cu_seqlens', None), kwargs.get('position_ids', None), None
|
|
130
|
+
if self.use_short_conv:
|
|
131
|
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
|
132
|
+
if last_state is not None:
|
|
133
|
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
|
134
|
+
conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
|
|
135
|
+
if cu_seqlens is not None:
|
|
136
|
+
if position_ids is None:
|
|
137
|
+
position_ids = prepare_position_ids(cu_seqlens)
|
|
138
|
+
seq_idx = prepare_sequence_ids(position_ids).to(torch.int32).unsqueeze(0)
|
|
139
|
+
q, conv_state_q = self.q_conv1d(
|
|
140
|
+
x=self.q_proj(hidden_states),
|
|
141
|
+
mask=conv_mask,
|
|
142
|
+
cache=conv_state_q,
|
|
143
|
+
output_final_state=use_cache,
|
|
144
|
+
seq_idx=seq_idx
|
|
145
|
+
)
|
|
146
|
+
k, conv_state_k = self.k_conv1d(
|
|
147
|
+
x=self.k_proj(hidden_states),
|
|
148
|
+
mask=conv_mask,
|
|
149
|
+
cache=conv_state_k,
|
|
150
|
+
output_final_state=use_cache,
|
|
151
|
+
seq_idx=seq_idx
|
|
152
|
+
)
|
|
153
|
+
v, conv_state_v = self.v_conv1d(
|
|
154
|
+
x=self.v_proj(hidden_states),
|
|
155
|
+
mask=conv_mask,
|
|
156
|
+
cache=conv_state_v,
|
|
157
|
+
output_final_state=use_cache,
|
|
158
|
+
seq_idx=seq_idx
|
|
159
|
+
)
|
|
160
|
+
else:
|
|
161
|
+
q = self.q_proj(hidden_states)
|
|
162
|
+
k = self.k_proj(hidden_states)
|
|
163
|
+
v = self.v_proj(hidden_states)
|
|
164
|
+
|
|
165
|
+
if self.use_input_gate:
|
|
166
|
+
q, k, v = map(lambda x: swish(x), (q, k, v))
|
|
167
|
+
# dealing with left-padding
|
|
168
|
+
if attention_mask is not None:
|
|
169
|
+
v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
|
|
170
|
+
|
|
171
|
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k))
|
|
172
|
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
|
173
|
+
if self.use_rope:
|
|
174
|
+
seqlen_offset = 0
|
|
175
|
+
if past_key_values is not None:
|
|
176
|
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
|
177
|
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset)
|
|
178
|
+
|
|
179
|
+
s = rearrange(self.s_proj(hidden_states), '... (h m) -> ... h m', m=self.num_slots)
|
|
180
|
+
s = s.clamp_(self.clamp_min, self.clamp_max)
|
|
181
|
+
|
|
182
|
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
|
183
|
+
o, recurrent_state = chunk_abc(
|
|
184
|
+
q=q,
|
|
185
|
+
k=k,
|
|
186
|
+
v=v,
|
|
187
|
+
s=s,
|
|
188
|
+
initial_state=recurrent_state,
|
|
189
|
+
output_final_state=use_cache,
|
|
190
|
+
head_first=False
|
|
191
|
+
)
|
|
192
|
+
if past_key_values is not None:
|
|
193
|
+
past_key_values.update(
|
|
194
|
+
recurrent_state=recurrent_state,
|
|
195
|
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
|
196
|
+
layer_idx=self.layer_idx,
|
|
197
|
+
offset=q.shape[1]
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
if self.use_norm and not self.use_output_gate:
|
|
201
|
+
o = self.g_norm(o)
|
|
202
|
+
elif self.use_output_gate:
|
|
203
|
+
g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
|
204
|
+
o = self.g_norm(o, g) if self.use_norm else swiglu(g, o)
|
|
205
|
+
o = rearrange(o, '... h d -> ... (h d)')
|
|
206
|
+
o = self.o_proj(o)
|
|
207
|
+
|
|
208
|
+
return o, None, past_key_values
|
|
209
|
+
|
|
210
|
+
def state_size(self, seq_len: int = 2048):
|
|
211
|
+
return 2 * self.num_slots * self.hidden_size
|
fla/layers/attn.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import warnings
|
|
7
|
+
from typing import TYPE_CHECKING, Optional, Tuple
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import torch.nn as nn
|
|
11
|
+
import torch.nn.functional as F
|
|
12
|
+
import torch.utils.checkpoint
|
|
13
|
+
from einops import rearrange
|
|
14
|
+
from transformers.utils import logging
|
|
15
|
+
|
|
16
|
+
from fla.modules import RotaryEmbedding
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from fla.models.utils import Cache
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
|
23
|
+
from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
|
|
24
|
+
except ImportError:
|
|
25
|
+
warnings.warn(
|
|
26
|
+
"Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
|
|
27
|
+
category=ImportWarning
|
|
28
|
+
)
|
|
29
|
+
flash_attn_func = None
|
|
30
|
+
|
|
31
|
+
logger = logging.get_logger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Attention(nn.Module):
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
hidden_size: int = 2048,
|
|
39
|
+
num_heads: int = 32,
|
|
40
|
+
num_kv_heads: Optional[int] = None,
|
|
41
|
+
qkv_bias: bool = False,
|
|
42
|
+
window_size: Optional[int] = None,
|
|
43
|
+
rope_theta: Optional[float] = 10000.,
|
|
44
|
+
max_position_embeddings: Optional[int] = None,
|
|
45
|
+
layer_idx: int = None
|
|
46
|
+
):
|
|
47
|
+
super().__init__()
|
|
48
|
+
|
|
49
|
+
self.hidden_size = hidden_size
|
|
50
|
+
self.num_heads = num_heads
|
|
51
|
+
if num_kv_heads is None:
|
|
52
|
+
self.num_kv_heads = self.num_heads
|
|
53
|
+
else:
|
|
54
|
+
self.num_kv_heads = num_kv_heads
|
|
55
|
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
|
56
|
+
self.head_dim = self.hidden_size // self.num_heads
|
|
57
|
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
|
58
|
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
|
59
|
+
self.qkv_bias = qkv_bias
|
|
60
|
+
|
|
61
|
+
self.window_size = window_size
|
|
62
|
+
self.rope_theta = rope_theta
|
|
63
|
+
self.max_position_embeddings = max_position_embeddings
|
|
64
|
+
self.layer_idx = layer_idx
|
|
65
|
+
|
|
66
|
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
|
|
67
|
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
|
68
|
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
|
69
|
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
|
70
|
+
|
|
71
|
+
self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
|
|
72
|
+
|
|
73
|
+
def forward(
|
|
74
|
+
self,
|
|
75
|
+
hidden_states: torch.Tensor,
|
|
76
|
+
attention_mask: Optional[torch.LongTensor] = None,
|
|
77
|
+
past_key_values: Optional[Cache] = None,
|
|
78
|
+
output_attentions: bool = False,
|
|
79
|
+
use_cache: bool = False,
|
|
80
|
+
**kwargs,
|
|
81
|
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
|
82
|
+
if attention_mask is not None:
|
|
83
|
+
assert len(attention_mask.shape) == 2, (
|
|
84
|
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
|
85
|
+
"for padding purposes (0 indicating padding). "
|
|
86
|
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
batch_size, q_len, _ = hidden_states.size()
|
|
90
|
+
|
|
91
|
+
q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
|
92
|
+
k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
|
93
|
+
v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
|
94
|
+
|
|
95
|
+
# equivalent to cu_seqlens in `flash_attn`
|
|
96
|
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
|
97
|
+
|
|
98
|
+
seqlen_offset, max_seqlen = 0, q_len
|
|
99
|
+
if past_key_values is not None:
|
|
100
|
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
|
101
|
+
max_seqlen = q.shape[1] + seqlen_offset
|
|
102
|
+
|
|
103
|
+
if attention_mask is not None:
|
|
104
|
+
# to deliminate the offsets of padding tokens
|
|
105
|
+
seqlen_offset = (seqlen_offset + attention_mask.sum(-1) - attention_mask.shape[-1]).clamp(min=0)
|
|
106
|
+
max_seqlen = q.shape[1] + max(seqlen_offset)
|
|
107
|
+
|
|
108
|
+
if self.max_position_embeddings is not None:
|
|
109
|
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
|
110
|
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
|
111
|
+
|
|
112
|
+
if past_key_values is not None:
|
|
113
|
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
|
114
|
+
k_cached, v_cached = past_key_values.update(
|
|
115
|
+
attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)),
|
|
116
|
+
layer_idx=self.layer_idx,
|
|
117
|
+
offset=q_len,
|
|
118
|
+
cache_kwargs=dict(window_size=self.window_size)
|
|
119
|
+
)['attn_state']
|
|
120
|
+
if cache_has_content:
|
|
121
|
+
k, v = k_cached, v_cached
|
|
122
|
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
|
123
|
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
|
124
|
+
|
|
125
|
+
if flash_attn_func is None:
|
|
126
|
+
raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
|
|
127
|
+
|
|
128
|
+
# Contains at least one padding token in the sequence
|
|
129
|
+
if attention_mask is not None:
|
|
130
|
+
q, k, v, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(q, k, v, attention_mask, q_len)
|
|
131
|
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
|
132
|
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
|
133
|
+
o = flash_attn_varlen_func(
|
|
134
|
+
q, k, v,
|
|
135
|
+
cu_seqlens_q=cu_seqlens_q,
|
|
136
|
+
cu_seqlens_k=cu_seqlens_k,
|
|
137
|
+
max_seqlen_q=max_seqlen_q,
|
|
138
|
+
max_seqlen_k=max_seqlen_k,
|
|
139
|
+
causal=True,
|
|
140
|
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
|
141
|
+
)
|
|
142
|
+
o = pad_input(o, indices_q, batch_size, q_len)
|
|
143
|
+
elif cu_seqlens is not None:
|
|
144
|
+
o = flash_attn_varlen_func(
|
|
145
|
+
q.squeeze(0), k.squeeze(0), v.squeeze(0),
|
|
146
|
+
cu_seqlens_q=cu_seqlens,
|
|
147
|
+
cu_seqlens_k=cu_seqlens,
|
|
148
|
+
max_seqlen_q=max_seqlen,
|
|
149
|
+
max_seqlen_k=max_seqlen,
|
|
150
|
+
causal=True,
|
|
151
|
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
|
152
|
+
).unsqueeze(0)
|
|
153
|
+
else:
|
|
154
|
+
o = flash_attn_func(
|
|
155
|
+
q, k, v,
|
|
156
|
+
causal=True,
|
|
157
|
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
|
158
|
+
)
|
|
159
|
+
o = o.reshape(batch_size, q_len, -1)
|
|
160
|
+
o = self.o_proj(o)
|
|
161
|
+
|
|
162
|
+
if not output_attentions:
|
|
163
|
+
attentions = None
|
|
164
|
+
|
|
165
|
+
return o, attentions, past_key_values
|
|
166
|
+
|
|
167
|
+
def _upad_input(self, q, k, v, attention_mask, q_len):
|
|
168
|
+
batch_size, seq_len, num_key_value_heads, head_dim = k.shape
|
|
169
|
+
cache_mask = attention_mask[:, -seq_len:]
|
|
170
|
+
seqlens = cache_mask.sum(-1, dtype=torch.int32)
|
|
171
|
+
indices_k = torch.nonzero(cache_mask.flatten(), as_tuple=False).flatten()
|
|
172
|
+
max_seqlen_k = seqlens.max().item()
|
|
173
|
+
cu_seqlens_k = F.pad(torch.cumsum(seqlens, dim=0, dtype=torch.int32), (1, 0))
|
|
174
|
+
|
|
175
|
+
k = index_first_axis(k.reshape(batch_size * seq_len, num_key_value_heads, head_dim), indices_k)
|
|
176
|
+
v = index_first_axis(v.reshape(batch_size * seq_len, num_key_value_heads, head_dim), indices_k)
|
|
177
|
+
if q_len == seq_len:
|
|
178
|
+
q = index_first_axis(q.reshape(batch_size * seq_len, self.num_heads, head_dim), indices_k)
|
|
179
|
+
cu_seqlens_q = cu_seqlens_k
|
|
180
|
+
max_seqlen_q = max_seqlen_k
|
|
181
|
+
indices_q = indices_k
|
|
182
|
+
elif q_len == 1:
|
|
183
|
+
max_seqlen_q = 1
|
|
184
|
+
# There is a memcpy here, that is very bad.
|
|
185
|
+
cu_seqlens_q = torch.arange(batch_size + 1, dtype=torch.int32, device=q.device)
|
|
186
|
+
indices_q = cu_seqlens_q[:-1]
|
|
187
|
+
q = q.squeeze(1)
|
|
188
|
+
else:
|
|
189
|
+
# The -q_len: slice assumes left padding.
|
|
190
|
+
attention_mask = attention_mask[:, -q_len:]
|
|
191
|
+
q, indices_q, cu_seqlens_q, max_seqlen_q = unpad_input(q, attention_mask)
|
|
192
|
+
|
|
193
|
+
return q, k, v, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_q, max_seqlen_k)
|
fla/layers/based.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
Linear attention in Based.
|
|
6
|
+
https://github.com/HazyResearch/zoology/blob/main/zoology/mixers/based.py
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import torch.nn as nn
|
|
11
|
+
from einops import rearrange
|
|
12
|
+
|
|
13
|
+
from fla.modules.feature_map import TaylorFeatureMap
|
|
14
|
+
from fla.ops.based import parallel_based
|
|
15
|
+
from fla.ops.linear_attn import chunk_linear_attn, fused_chunk_linear_attn
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class BasedLinearAttention(nn.Module):
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
hidden_size: int,
|
|
23
|
+
feature_dim: int = 16,
|
|
24
|
+
num_key_value_heads: int = 12,
|
|
25
|
+
num_heads: int = 12,
|
|
26
|
+
feature_name: str = "taylor_exp",
|
|
27
|
+
eps: float = 1e-12,
|
|
28
|
+
causal: bool = True,
|
|
29
|
+
mode: str = "parallel",
|
|
30
|
+
):
|
|
31
|
+
super().__init__()
|
|
32
|
+
|
|
33
|
+
self.hidden_size = hidden_size
|
|
34
|
+
self.mode = mode
|
|
35
|
+
self.feature_name = feature_name
|
|
36
|
+
self.feature_dim = feature_dim
|
|
37
|
+
self.num_key_value_heads = num_key_value_heads
|
|
38
|
+
self.num_heads = num_heads
|
|
39
|
+
self.head_dim = self.hidden_size // self.num_key_value_heads
|
|
40
|
+
self.causal = causal
|
|
41
|
+
|
|
42
|
+
self.q_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False)
|
|
43
|
+
self.k_proj = nn.Linear(self.hidden_size, self.feature_dim * self.num_heads, bias=False)
|
|
44
|
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False)
|
|
45
|
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
|
|
46
|
+
self.dropout = nn.Identity()
|
|
47
|
+
self.feature_map = TaylorFeatureMap(feature_dim)
|
|
48
|
+
self.eps = eps
|
|
49
|
+
|
|
50
|
+
def forward(self, hidden_states: torch.Tensor, **kwargs):
|
|
51
|
+
mode = self.mode
|
|
52
|
+
q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
|
|
53
|
+
q, k, v = map(lambda x: rearrange(x, "... (h d) -> ... h d", d=self.head_dim), [q, k, v])
|
|
54
|
+
if mode == "fused_chunk":
|
|
55
|
+
q, k = self.feature_map(q), self.feature_map(k)
|
|
56
|
+
o, _ = fused_chunk_linear_attn(q, k, v, normalize=True, scale=1, head_first=False)
|
|
57
|
+
elif mode == 'chunk':
|
|
58
|
+
q, k = self.feature_map(q), self.feature_map(k)
|
|
59
|
+
o, _ = chunk_linear_attn(q, k, v, normalize=True, scale=1, head_first=False)
|
|
60
|
+
elif mode == 'parallel':
|
|
61
|
+
assert q.shape[-1] <= 128
|
|
62
|
+
o = parallel_based(q, k, v, scale=1, use_norm=True, head_first=False)
|
|
63
|
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
|
64
|
+
o = self.o_proj(o)
|
|
65
|
+
o = self.dropout(o)
|
|
66
|
+
return o
|
|
67
|
+
|
|
68
|
+
# https://github.com/HazyResearch/zoology/blob/main/zoology/mixers/based.py#L119
|
|
69
|
+
|
|
70
|
+
def forward_reference(self, hidden_states: torch.Tensor, filters: torch.Tensor = None, *args, **kwargs):
|
|
71
|
+
"""
|
|
72
|
+
x (torch.Tensor): tensor of shape (b, d, t)
|
|
73
|
+
y (torch.Tensor): tensor of shape (b, d, t)
|
|
74
|
+
"""
|
|
75
|
+
# hidden_states = hidden_states.transpose(1, 2)
|
|
76
|
+
b, t, _ = hidden_states.size()
|
|
77
|
+
q, k, v = self.q_proj(hidden_states), self.k_proj(hidden_states), self.v_proj(hidden_states)
|
|
78
|
+
|
|
79
|
+
q = q.view(b, t, self.num_heads, self.feature_dim).transpose(1, 2)
|
|
80
|
+
k = k.view(b, t, self.num_key_value_heads, self.feature_dim).transpose(1, 2)
|
|
81
|
+
v = v.view(b, t, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
|
82
|
+
|
|
83
|
+
# Linear attention
|
|
84
|
+
q, k = self.feature_map(q), self.feature_map(k)
|
|
85
|
+
q, k, v = q.unsqueeze(-2), k.unsqueeze(-2), v.unsqueeze(-1)
|
|
86
|
+
|
|
87
|
+
# Compute attention
|
|
88
|
+
if self.causal:
|
|
89
|
+
y = ((q * (k * v).cumsum(2)).sum(-1) / ((q * k.cumsum(2)).sum(-1) + self.eps))
|
|
90
|
+
else:
|
|
91
|
+
y = ((q * (k * v).sum(2, True)).sum(-1) / ((q * k.sum(2, True)).sum(-1) + self.eps))
|
|
92
|
+
y = rearrange(y, 'b h t d -> b t (h d)')
|
|
93
|
+
y = self.o_proj(y.to(hidden_states.dtype))
|
|
94
|
+
y = self.dropout(y)
|
|
95
|
+
return y.to(hidden_states.dtype)
|