Add files using upload-large-folder tool
Browse files- __pycache__/__init__.cpython-310.pyc +0 -0
- __pycache__/attn.cpython-312.pyc +0 -0
- __pycache__/based.cpython-312.pyc +0 -0
- __pycache__/bitattn.cpython-312.pyc +0 -0
- __pycache__/comba.cpython-312.pyc +0 -0
- __pycache__/delta_net.cpython-312.pyc +0 -0
- __pycache__/forgetting_attn.cpython-312.pyc +0 -0
- __pycache__/gated_deltanet.cpython-312.pyc +0 -0
- __pycache__/gated_deltaproduct.cpython-312.pyc +0 -0
- __pycache__/gka.cpython-312.pyc +0 -0
- __pycache__/gka_attn.cpython-312.pyc +0 -0
- __pycache__/gla.cpython-312.pyc +0 -0
- __pycache__/gsa.cpython-312.pyc +0 -0
- __pycache__/hgrn.cpython-312.pyc +0 -0
- __pycache__/hgrn2.cpython-312.pyc +0 -0
- __pycache__/lightnet.cpython-312.pyc +0 -0
- __pycache__/log_linear_mamba2.cpython-312.pyc +0 -0
- __pycache__/mamba2.cpython-312.pyc +0 -0
- __pycache__/mask_gdn.cpython-310.pyc +0 -0
- __pycache__/mask_gdn.cpython-312.pyc +0 -0
- __pycache__/mla.cpython-312.pyc +0 -0
- __pycache__/mom.cpython-312.pyc +0 -0
- __pycache__/multiscale_retention.cpython-312.pyc +0 -0
- __pycache__/nsa.cpython-312.pyc +0 -0
- __pycache__/past_gdn.cpython-312.pyc +0 -0
- __pycache__/rodimus.cpython-312.pyc +0 -0
- __pycache__/rwkv7.cpython-312.pyc +0 -0
- __pycache__/sig_tr_gka.cpython-312.pyc +0 -0
- gka.py +744 -0
- gka_attn.py +303 -0
- gsa.py +240 -0
- hgrn.py +176 -0
- hgrn2.py +212 -0
- lightnet.py +223 -0
- linear_attn.py +165 -0
- mamba.py +335 -0
- mamba2.py +613 -0
- mask_gdn.py +1058 -0
- mla.py +226 -0
- mom.py +834 -0
- multiscale_retention.py +305 -0
- past_gdn.py +1407 -0
- path_attn.py +216 -0
- rodimus.py +390 -0
- rwkv6.py +362 -0
- rwkv7.py +347 -0
- sig_tr_gka.py +336 -0
- sigma_gka.py +1212 -0
- simple_gla.py +274 -0
- utils.py +197 -0
__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (198 Bytes). View file
|
|
|
__pycache__/attn.cpython-312.pyc
ADDED
|
Binary file (7.83 kB). View file
|
|
|
__pycache__/based.cpython-312.pyc
ADDED
|
Binary file (6.41 kB). View file
|
|
|
__pycache__/bitattn.cpython-312.pyc
ADDED
|
Binary file (7.25 kB). View file
|
|
|
__pycache__/comba.cpython-312.pyc
ADDED
|
Binary file (15.4 kB). View file
|
|
|
__pycache__/delta_net.cpython-312.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
__pycache__/forgetting_attn.cpython-312.pyc
ADDED
|
Binary file (6.54 kB). View file
|
|
|
__pycache__/gated_deltanet.cpython-312.pyc
ADDED
|
Binary file (15.1 kB). View file
|
|
|
__pycache__/gated_deltaproduct.cpython-312.pyc
ADDED
|
Binary file (14 kB). View file
|
|
|
__pycache__/gka.cpython-312.pyc
ADDED
|
Binary file (25.5 kB). View file
|
|
|
__pycache__/gka_attn.cpython-312.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
__pycache__/gla.cpython-312.pyc
ADDED
|
Binary file (13.1 kB). View file
|
|
|
__pycache__/gsa.cpython-312.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
__pycache__/hgrn.cpython-312.pyc
ADDED
|
Binary file (6.73 kB). View file
|
|
|
__pycache__/hgrn2.cpython-312.pyc
ADDED
|
Binary file (8.42 kB). View file
|
|
|
__pycache__/lightnet.cpython-312.pyc
ADDED
|
Binary file (8.91 kB). View file
|
|
|
__pycache__/log_linear_mamba2.cpython-312.pyc
ADDED
|
Binary file (21.9 kB). View file
|
|
|
__pycache__/mamba2.cpython-312.pyc
ADDED
|
Binary file (28.7 kB). View file
|
|
|
__pycache__/mask_gdn.cpython-310.pyc
ADDED
|
Binary file (7.57 kB). View file
|
|
|
__pycache__/mask_gdn.cpython-312.pyc
ADDED
|
Binary file (14.2 kB). View file
|
|
|
__pycache__/mla.cpython-312.pyc
ADDED
|
Binary file (9.92 kB). View file
|
|
|
__pycache__/mom.cpython-312.pyc
ADDED
|
Binary file (39.9 kB). View file
|
|
|
__pycache__/multiscale_retention.cpython-312.pyc
ADDED
|
Binary file (12.4 kB). View file
|
|
|
__pycache__/nsa.cpython-312.pyc
ADDED
|
Binary file (6.62 kB). View file
|
|
|
__pycache__/past_gdn.cpython-312.pyc
ADDED
|
Binary file (43.1 kB). View file
|
|
|
__pycache__/rodimus.cpython-312.pyc
ADDED
|
Binary file (17.5 kB). View file
|
|
|
__pycache__/rwkv7.cpython-312.pyc
ADDED
|
Binary file (17.6 kB). View file
|
|
|
__pycache__/sig_tr_gka.cpython-312.pyc
ADDED
|
Binary file (16.4 kB). View file
|
|
|
gka.py
ADDED
|
@@ -0,0 +1,744 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Gated KalmaNet (GKA) layer implementation with Grouped Query Attention (GQA) support.
|
| 3 |
+
|
| 4 |
+
This module implements the Gated KalmaNet layer from the paper:
|
| 5 |
+
"Gated KalmaNet: A Fading Memory Layer Through Test-Time Ridge Regression" (https://arxiv.org/abs/2511.21016).
|
| 6 |
+
|
| 7 |
+
Overview:
|
| 8 |
+
GKA is a state space model (SSM) that updates its state based on the entire history
|
| 9 |
+
of previously seen tokens, rather than just the current token. At each timestep t,
|
| 10 |
+
the optimal state S_t minimizes a ridge regression objective over all past tokens:
|
| 11 |
+
|
| 12 |
+
S_t = argmin_S { λ·||S||²_F + Σ(i=1 to t) η_i·||S·k_i - v_i||² }
|
| 13 |
+
|
| 14 |
+
where λ is the ridge regularization strength and η_i are exponentially decaying weights
|
| 15 |
+
controlled by forgetting gates. This has a closed-form solution:
|
| 16 |
+
|
| 17 |
+
S_t = U_t · (H_t + λI)^(-1)
|
| 18 |
+
|
| 19 |
+
where:
|
| 20 |
+
U_t = Σ(i=1 to t) η_i v_i k_i^T (cumulative value-key outer products)
|
| 21 |
+
H_t = Σ(i=1 to t) η_i k_i k_i^T (cumulative key-key covariance)
|
| 22 |
+
|
| 23 |
+
The output is computed as y_t = S_t · q_t, which reduces to solving the ridge
|
| 24 |
+
regression problem (H_t + λI)·x_t = q_t for x_t, then computing y_t = U_t · x_t.
|
| 25 |
+
This is solved numerically via the Chebyshev iteration algorithm.
|
| 26 |
+
|
| 27 |
+
The layer supports GQA-style head grouping where the number of key/value heads
|
| 28 |
+
can be different from the number of query heads. The hyperparameters in this module
|
| 29 |
+
are set so that we can initialize the module's weights from existing Attention layers.
|
| 30 |
+
|
| 31 |
+
Key Variables:
|
| 32 |
+
- head_dim: Head dimension (same for q/k/v)
|
| 33 |
+
- num_q_heads: Number of query heads
|
| 34 |
+
- num_k_heads: Number of key heads
|
| 35 |
+
- num_v_heads: Number of value heads
|
| 36 |
+
- expanded_num_heads: Maximum of num_q_heads, num_k_heads, num_v_heads
|
| 37 |
+
- num_q_groups: Repetition factor for Q heads, computed as expanded_num_heads // num_q_heads
|
| 38 |
+
- num_k_groups: Repetition factor for K heads, computed as expanded_num_heads // num_k_heads
|
| 39 |
+
- num_v_groups: Repetition factor for V heads, computed as expanded_num_heads // num_v_heads
|
| 40 |
+
- query_dim: Total query dimension, num_q_heads * head_dim
|
| 41 |
+
- key_dim: Total key dimension, num_k_heads * head_dim
|
| 42 |
+
- value_dim: Total value dimension, num_v_heads * head_dim
|
| 43 |
+
- expanded_dim: Expanded dimension, expanded_num_heads * head_dim
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
from __future__ import annotations
|
| 47 |
+
|
| 48 |
+
import math
|
| 49 |
+
from typing import TYPE_CHECKING, Any, Optional, Tuple
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
import torch.nn as nn
|
| 53 |
+
from einops import rearrange, repeat
|
| 54 |
+
from torch import Tensor
|
| 55 |
+
from torch.nn import functional as F
|
| 56 |
+
|
| 57 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 58 |
+
from fla.ops.simple_gla import chunk_simple_gla
|
| 59 |
+
from fla.models.utils import Cache
|
| 60 |
+
# from ..sp_p2p_utils import reorder_for_ssm_p2p
|
| 61 |
+
|
| 62 |
+
from ..ops.chebyshev.chunk_dk_backward_gating_sp import compute_kk_final_with_gating
|
| 63 |
+
# from .sequence_parallel.gka_sp_utils import (
|
| 64 |
+
# state_passing_gka_p2p,
|
| 65 |
+
# recompute_with_initial_states,
|
| 66 |
+
# )
|
| 67 |
+
|
| 68 |
+
from ..ops.chebyshev.gka_chebyshev_solve import (
|
| 69 |
+
gka_chebyshev_gla,
|
| 70 |
+
torch_decoding_one_step,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
from typing import Any, Optional
|
| 75 |
+
|
| 76 |
+
import torch
|
| 77 |
+
import torch.nn as nn
|
| 78 |
+
import torch.nn.init as init
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class LinearLowRank(nn.Module):
|
| 82 |
+
"""
|
| 83 |
+
Low-rank linear layer that factorizes a linear projection into two smaller ones:
|
| 84 |
+
y = linearB(act_fn(linearA(x)))
|
| 85 |
+
|
| 86 |
+
where linearA projects from in_features to rank, and linearB projects from rank to out_features.
|
| 87 |
+
|
| 88 |
+
linearB is zero-initialized so that the module outputs zeros at init time. This makes it safe
|
| 89 |
+
to use as a residual branch (e.g. added on top of a repeat/expand) without perturbing the
|
| 90 |
+
pretrained signal at the start of training.
|
| 91 |
+
|
| 92 |
+
Note: linearB is marked with ``_is_hf_initialized = True`` to prevent transformers'
|
| 93 |
+
``post_init`` from overwriting the zero initialization with a random normal.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
in_features: Input dimension.
|
| 97 |
+
out_features: Output dimension.
|
| 98 |
+
rank: Bottleneck dimension between the two linear layers.
|
| 99 |
+
act_fn: Optional activation applied between linearA and linearB. Defaults to Identity.
|
| 100 |
+
bias: Whether to include bias terms in both linear layers. Defaults to False.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def __init__(
|
| 104 |
+
self,
|
| 105 |
+
in_features: int,
|
| 106 |
+
out_features: int,
|
| 107 |
+
rank: int,
|
| 108 |
+
act_fn: Optional[Any] = None,
|
| 109 |
+
bias: bool = False,
|
| 110 |
+
):
|
| 111 |
+
super().__init__()
|
| 112 |
+
self.linearA = nn.Linear(in_features, rank, bias=bias)
|
| 113 |
+
self.linearB = nn.Linear(rank, out_features, bias=bias)
|
| 114 |
+
|
| 115 |
+
self.in_features = in_features
|
| 116 |
+
self.out_features = out_features
|
| 117 |
+
self.rank = rank
|
| 118 |
+
self.bias = bias
|
| 119 |
+
self.act_fn = act_fn if act_fn is not None else nn.Identity()
|
| 120 |
+
|
| 121 |
+
# Initialize B weights and bias to zero
|
| 122 |
+
init.zeros_(self.linearB.weight)
|
| 123 |
+
if self.linearB.bias is not None:
|
| 124 |
+
init.zeros_(self.linearB.bias)
|
| 125 |
+
self.linearB._is_hf_initialized = (
|
| 126 |
+
True
|
| 127 |
+
) # prevent transformers' post_init from re-initializing
|
| 128 |
+
|
| 129 |
+
def forward(self, x: torch.Tensor):
|
| 130 |
+
return self.linearB(self.act_fn(self.linearA(x)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class GKANet(nn.Module):
|
| 134 |
+
"""
|
| 135 |
+
GKA layer with Chebyshev solver and GQA support.
|
| 136 |
+
|
| 137 |
+
Args:
|
| 138 |
+
hidden_size: The hidden size of the input. Defaults to 2048.
|
| 139 |
+
head_dim: The dimension of each head. Assumes q/k/v have the same head dimension.
|
| 140 |
+
Defaults to 128.
|
| 141 |
+
num_q_heads: The number of query heads. Defaults to 16.
|
| 142 |
+
num_k_heads: The number of key heads for GQA. If None, defaults to num_q_heads.
|
| 143 |
+
Defaults to None.
|
| 144 |
+
num_v_heads: The number of value heads for GQA. If None, defaults to num_q_heads.
|
| 145 |
+
Defaults to None.
|
| 146 |
+
use_beta_gate: Whether to use beta gating mechanism. Defaults to True.
|
| 147 |
+
use_alpha_connection: Whether to use alpha connection for residual paths. Defaults to True.
|
| 148 |
+
use_v_conv: Whether to apply convolution to value vectors. Defaults to True.
|
| 149 |
+
use_forgetting_gate: Whether to use forgetting gate mechanism. Defaults to True.
|
| 150 |
+
use_forgetting_gate_kk: Whether to use forgetting gate for key-key interactions. Defaults to True.
|
| 151 |
+
gla_rescale: Whether to apply GLA-style rescaling. Defaults to True.
|
| 152 |
+
solver_type: Solver method. Currently, we only support "chebyshev". Defaults to "chebyshev".
|
| 153 |
+
bp_lambda: Whether to backpropagate through lambda parameters. Defaults to True.
|
| 154 |
+
num_iter: Number of iterations for iterative solvers. Defaults to 30.
|
| 155 |
+
ridge_strength: Regularization strength for ridge regression. Defaults to 0.02.
|
| 156 |
+
use_gate: Whether to use output gating mechanism. Defaults to True.
|
| 157 |
+
conv_size: Size of the convolution kernel. Defaults to 4.
|
| 158 |
+
layer_idx: The index of the layer. Used for caching during inference. Defaults to None.
|
| 159 |
+
norm_eps: The epsilon value for the normalization layer. Defaults to 1e-6.
|
| 160 |
+
chunk_size: Size of chunks for parallel processing in Triton kernels. Defaults to 64.
|
| 161 |
+
kv_proj_rank: Rank for low-rank KV projection to expand K/V heads. If None, uses
|
| 162 |
+
standard GQA repeat. Defaults to None.
|
| 163 |
+
kv_learnable_residual: Whether to use a learnable residual for the KV head expansion
|
| 164 |
+
instead of a fixed repeat. Only used when kv_proj_rank is set. Defaults to False.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
hidden_size: int = 2048,
|
| 170 |
+
head_dim: int = 128,
|
| 171 |
+
num_heads: int = 8,
|
| 172 |
+
num_q_heads: Optional[int] = None,
|
| 173 |
+
num_k_heads: Optional[int] = None,
|
| 174 |
+
num_v_heads: Optional[int] = None,
|
| 175 |
+
use_beta_gate: bool = True,
|
| 176 |
+
use_alpha_connection: bool = True,
|
| 177 |
+
use_v_conv: bool = True,
|
| 178 |
+
use_forgetting_gate: bool = True,
|
| 179 |
+
use_forgetting_gate_kk: bool = True,
|
| 180 |
+
gla_rescale: bool = True,
|
| 181 |
+
solver_type: str = "chebyshev",
|
| 182 |
+
bp_lambda: bool = True,
|
| 183 |
+
num_iter: int = 30,
|
| 184 |
+
ridge_strength: float = 0.02,
|
| 185 |
+
use_gate: bool = False,
|
| 186 |
+
conv_size: int = 4,
|
| 187 |
+
layer_idx: Optional[int] = None,
|
| 188 |
+
norm_eps: float = 1e-6,
|
| 189 |
+
chunk_size: int = 64,
|
| 190 |
+
kv_proj_rank: Optional[int] = None,
|
| 191 |
+
kv_learnable_residual: bool = False,
|
| 192 |
+
**kwargs,
|
| 193 |
+
) -> None:
|
| 194 |
+
super().__init__()
|
| 195 |
+
|
| 196 |
+
assert solver_type == "chebyshev", f"Received {solver_type=}. Currently, GKA only supports 'chebyshev' solver."
|
| 197 |
+
|
| 198 |
+
self.hidden_size = hidden_size
|
| 199 |
+
|
| 200 |
+
self.use_gate = use_gate
|
| 201 |
+
self.conv_size = conv_size
|
| 202 |
+
self.sequence_parallel_group = None
|
| 203 |
+
self.chunk_size = chunk_size
|
| 204 |
+
|
| 205 |
+
self.head_dim = head_dim
|
| 206 |
+
self.num_heads = num_heads
|
| 207 |
+
self.num_q_heads = num_q_heads if num_q_heads is not None else num_heads
|
| 208 |
+
self.num_k_heads = num_k_heads if num_k_heads is not None else num_heads
|
| 209 |
+
self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
|
| 210 |
+
self.expanded_num_heads = max(
|
| 211 |
+
self.num_q_heads, self.num_k_heads, self.num_v_heads
|
| 212 |
+
)
|
| 213 |
+
self.num_q_groups = self.expanded_num_heads // self.num_q_heads
|
| 214 |
+
self.num_k_groups = self.expanded_num_heads // self.num_k_heads
|
| 215 |
+
self.num_v_groups = self.expanded_num_heads // self.num_v_heads
|
| 216 |
+
|
| 217 |
+
self.query_dim = self.num_q_heads * self.head_dim
|
| 218 |
+
self.key_dim = self.num_k_heads * self.head_dim
|
| 219 |
+
self.value_dim = self.num_v_heads * self.head_dim
|
| 220 |
+
self.expanded_dim = self.expanded_num_heads * self.head_dim
|
| 221 |
+
|
| 222 |
+
self.layer_idx = layer_idx
|
| 223 |
+
|
| 224 |
+
self.ridge_strength = ridge_strength
|
| 225 |
+
self.num_iter = num_iter
|
| 226 |
+
self.use_beta_gate = use_beta_gate
|
| 227 |
+
self.use_alpha_connection = use_alpha_connection
|
| 228 |
+
self.solver_type = solver_type
|
| 229 |
+
self.bp_lambda = bp_lambda
|
| 230 |
+
self.use_v_conv = use_v_conv
|
| 231 |
+
self.use_forgetting_gate = use_forgetting_gate
|
| 232 |
+
self.use_forgetting_gate_kk = use_forgetting_gate_kk
|
| 233 |
+
|
| 234 |
+
if gla_rescale:
|
| 235 |
+
self.gla_scale = self.head_dim ** -0.5
|
| 236 |
+
else:
|
| 237 |
+
self.gla_scale = 1.0
|
| 238 |
+
|
| 239 |
+
# Projection layers
|
| 240 |
+
self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False)
|
| 241 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 242 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 243 |
+
|
| 244 |
+
self.a_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=False)
|
| 245 |
+
|
| 246 |
+
self.b_proj = (
|
| 247 |
+
nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
|
| 248 |
+
if self.use_beta_gate
|
| 249 |
+
else None
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if self.use_alpha_connection:
|
| 253 |
+
self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
|
| 254 |
+
|
| 255 |
+
# Initialize A parameter (log scale)
|
| 256 |
+
A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 257 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 258 |
+
self.A_log._no_weight_decay = True
|
| 259 |
+
|
| 260 |
+
# Initialize dt bias parameter
|
| 261 |
+
dt_min = 0.001
|
| 262 |
+
dt_max = 0.1
|
| 263 |
+
dt_init_floor = 1e-4
|
| 264 |
+
dt = torch.exp(
|
| 265 |
+
torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 266 |
+
+ math.log(dt_min)
|
| 267 |
+
)
|
| 268 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 269 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 270 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 271 |
+
|
| 272 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 273 |
+
self.dt_bias._no_weight_decay = True
|
| 274 |
+
|
| 275 |
+
# Short convolution layers
|
| 276 |
+
self.conv_size = conv_size
|
| 277 |
+
self.q_conv1d = ShortConvolution(
|
| 278 |
+
hidden_size=self.query_dim, kernel_size=conv_size, activation="silu"
|
| 279 |
+
)
|
| 280 |
+
self.k_conv1d = ShortConvolution(
|
| 281 |
+
hidden_size=self.key_dim, kernel_size=conv_size, activation="silu"
|
| 282 |
+
)
|
| 283 |
+
if self.use_v_conv:
|
| 284 |
+
self.v_conv1d = ShortConvolution(
|
| 285 |
+
hidden_size=self.value_dim, kernel_size=conv_size, activation="silu"
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
# Output gating and normalization
|
| 289 |
+
if use_gate:
|
| 290 |
+
self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False)
|
| 291 |
+
self.o_norm = FusedRMSNormGated(self.head_dim, eps=norm_eps)
|
| 292 |
+
else:
|
| 293 |
+
self.o_norm = RMSNorm(self.head_dim, eps=norm_eps)
|
| 294 |
+
self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False)
|
| 295 |
+
|
| 296 |
+
# Optional KV projection for GQA
|
| 297 |
+
self.kv_proj_rank = kv_proj_rank
|
| 298 |
+
self.kv_learnable_residual = kv_learnable_residual
|
| 299 |
+
if self.kv_proj_rank is not None:
|
| 300 |
+
act_fn = nn.SiLU()
|
| 301 |
+
self.proj_k = LinearLowRank(
|
| 302 |
+
in_features=self.key_dim,
|
| 303 |
+
out_features=self.expanded_num_heads * self.head_dim,
|
| 304 |
+
rank=self.kv_proj_rank,
|
| 305 |
+
act_fn=act_fn,
|
| 306 |
+
)
|
| 307 |
+
self.proj_v = LinearLowRank(
|
| 308 |
+
in_features=self.value_dim,
|
| 309 |
+
out_features=self.expanded_num_heads * self.head_dim,
|
| 310 |
+
rank=self.kv_proj_rank,
|
| 311 |
+
act_fn=act_fn,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
if self.kv_learnable_residual:
|
| 315 |
+
# Learnable mixing matrices initialized to mimic repeat_kv
|
| 316 |
+
eye_k = torch.eye(self.num_k_heads)
|
| 317 |
+
ones_k = torch.ones((self.num_k_groups, 1))
|
| 318 |
+
self.k_rep = nn.Parameter(
|
| 319 |
+
torch.kron(eye_k, ones_k)
|
| 320 |
+
) # [expanded_num_heads, num_k_heads]
|
| 321 |
+
|
| 322 |
+
eye_v = torch.eye(self.num_v_heads)
|
| 323 |
+
ones_v = torch.ones((self.num_v_groups, 1))
|
| 324 |
+
self.v_rep = nn.Parameter(
|
| 325 |
+
torch.kron(eye_v, ones_v)
|
| 326 |
+
) # [expanded_num_heads, num_v_heads]
|
| 327 |
+
|
| 328 |
+
def _expand_kv(self, k: Tensor, v: Tensor) -> Tuple[Tensor, Tensor]:
|
| 329 |
+
"""
|
| 330 |
+
Expand k and v from their native head counts to expanded_num_heads.
|
| 331 |
+
|
| 332 |
+
Three modes:
|
| 333 |
+
1. kv_proj_rank + kv_learnable_residual: learnable mixing residual + low-rank projection
|
| 334 |
+
2. kv_proj_rank without learnable residual: plain repeat residual + low-rank projection
|
| 335 |
+
3. No projection: simple repeat (or rearrange if groups == 1). This is the standard GQA repeat.
|
| 336 |
+
|
| 337 |
+
Args:
|
| 338 |
+
k: [B, L, Dk] raw key tensor (flat, not yet reshaped to heads)
|
| 339 |
+
v: [B, L, Dv] raw value tensor (flat, not yet reshaped to heads)
|
| 340 |
+
|
| 341 |
+
Returns:
|
| 342 |
+
k: [B, L, H, D] expanded keys
|
| 343 |
+
v: [B, L, H, D] expanded values
|
| 344 |
+
"""
|
| 345 |
+
if self.kv_proj_rank is not None and (
|
| 346 |
+
self.num_k_groups > 1 or self.num_v_groups > 1
|
| 347 |
+
):
|
| 348 |
+
# Build residual
|
| 349 |
+
if self.kv_learnable_residual:
|
| 350 |
+
k_heads = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
|
| 351 |
+
k_res = torch.einsum("eh,blhd->bled", self.k_rep, k_heads)
|
| 352 |
+
v_heads = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
|
| 353 |
+
v_res = torch.einsum("eh,blhd->bled", self.v_rep, v_heads)
|
| 354 |
+
else:
|
| 355 |
+
k_res = repeat(
|
| 356 |
+
rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads),
|
| 357 |
+
"... h d -> ... (h g) d",
|
| 358 |
+
g=self.num_k_groups,
|
| 359 |
+
)
|
| 360 |
+
v_res = repeat(
|
| 361 |
+
rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads),
|
| 362 |
+
"... h d -> ... (h g) d",
|
| 363 |
+
g=self.num_v_groups,
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
# Low-rank projection to expanded dim + add residual
|
| 367 |
+
k = (
|
| 368 |
+
rearrange(
|
| 369 |
+
self.proj_k(k), "... (h d) -> ... h d", h=self.expanded_num_heads
|
| 370 |
+
)
|
| 371 |
+
+ k_res
|
| 372 |
+
)
|
| 373 |
+
v = (
|
| 374 |
+
rearrange(
|
| 375 |
+
self.proj_v(v), "... (h d) -> ... h d", h=self.expanded_num_heads
|
| 376 |
+
)
|
| 377 |
+
+ v_res
|
| 378 |
+
)
|
| 379 |
+
else:
|
| 380 |
+
# Plain rearrange + repeat
|
| 381 |
+
k = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
|
| 382 |
+
v = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
|
| 383 |
+
if self.num_k_groups > 1:
|
| 384 |
+
k = repeat(k, "... h d -> ... (h g) d", g=self.num_k_groups)
|
| 385 |
+
if self.num_v_groups > 1:
|
| 386 |
+
v = repeat(v, "... h d -> ... (h g) d", g=self.num_v_groups)
|
| 387 |
+
|
| 388 |
+
return k, v
|
| 389 |
+
|
| 390 |
+
def forward(
|
| 391 |
+
self,
|
| 392 |
+
hidden_states: Tensor,
|
| 393 |
+
attention_mask: Optional[Tensor] = None,
|
| 394 |
+
past_key_values: Optional[Cache] = None,
|
| 395 |
+
use_cache: Optional[bool] = False,
|
| 396 |
+
output_attentions: Optional[bool] = False,
|
| 397 |
+
**kwargs,
|
| 398 |
+
) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]:
|
| 399 |
+
"""
|
| 400 |
+
GKA forward pass with optional caching.
|
| 401 |
+
|
| 402 |
+
NOTE: We use the following variables for tensor shape hints:
|
| 403 |
+
- B: Input batch size
|
| 404 |
+
- L: Sequence length (full sequence length before SP distribution)
|
| 405 |
+
- Dh: Hidden dimension (self.hidden_size)
|
| 406 |
+
- H: Expanded number of heads (self.expanded_num_heads)
|
| 407 |
+
- Hq: Number of query heads (self.num_q_heads)
|
| 408 |
+
- Hk: Number of key heads (self.num_k_heads)
|
| 409 |
+
- Hv: Number of value heads (self.num_v_heads)
|
| 410 |
+
- D: Head dimension (self.head_dim)
|
| 411 |
+
- Dq: Query dimension (self.query_dim)
|
| 412 |
+
- Dk: Key dimension (self.key_dim)
|
| 413 |
+
- Dv: Value dimension (self.value_dim)
|
| 414 |
+
- Dexp: Expanded dimension (self.expanded_dim)
|
| 415 |
+
- C: Convolution size (self.conv_size)
|
| 416 |
+
- SP: Sequence parallel size. 1 if not using sequence parallel
|
| 417 |
+
|
| 418 |
+
- B_sp: Batch size after SP reordering. B_sp = B*2 if self.sequence_parallel_group else B_sp = B
|
| 419 |
+
- L_sp: Sequence length after SP reordering. L_sp = L/(SP*2) + C-1 if self.sequence_parallel_group else L_sp = L/SP
|
| 420 |
+
- Lp: Sequence length after SP reordering and conv padding removal. Lp = L/(SP*2) if self.sequence_parallel_group else Lp = L/SP
|
| 421 |
+
|
| 422 |
+
Args:
|
| 423 |
+
hidden_states: Input tensor with shape [B, L/SP, Dh].
|
| 424 |
+
attention_mask: Optional 0-1 mask. Not used.
|
| 425 |
+
past_key_values: Optional cache containing conv_state and recurrent_state
|
| 426 |
+
for inference. When provided, performs incremental decoding.
|
| 427 |
+
use_cache: Whether to return updated cache states. Defaults to False.
|
| 428 |
+
output_attentions: Whether to return attention weights (not used). Defaults to False.
|
| 429 |
+
**kwargs: Additional keyword arguments, may include cu_seqlens for packed sequences.
|
| 430 |
+
|
| 431 |
+
Returns:
|
| 432 |
+
Tuple of (output, attention_weights, past_key_values) where:
|
| 433 |
+
- output: Output tensor with same shape as hidden_states [B, L, Dh]
|
| 434 |
+
- attention_weights: None (not computed for GKA)
|
| 435 |
+
- past_key_values: Updated cache (same as input if provided, else None)
|
| 436 |
+
"""
|
| 437 |
+
# During inference, if attention_mask is not None, throw an error
|
| 438 |
+
if attention_mask is not None and not self.training:
|
| 439 |
+
raise NotImplementedError(
|
| 440 |
+
"GKA kernels currently do not support varlen inputs."
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 444 |
+
|
| 445 |
+
last_state = None
|
| 446 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 447 |
+
last_state = past_key_values[self.layer_idx]
|
| 448 |
+
|
| 449 |
+
cu_seqlens = kwargs.get("cu_seqlens", None)
|
| 450 |
+
|
| 451 |
+
# Apply P2P reordering to hidden_states first for custom zigzag SP
|
| 452 |
+
# if self.sequence_parallel_group is not None:
|
| 453 |
+
# assert (
|
| 454 |
+
# cu_seqlens is None
|
| 455 |
+
# ), "SP not implemented for cu_seqlens (variable length samples in a batch)."
|
| 456 |
+
# sp_size = torch.distributed.get_world_size(
|
| 457 |
+
# group=self.sequence_parallel_group
|
| 458 |
+
# )
|
| 459 |
+
# sp_rank = torch.distributed.get_rank(group=self.sequence_parallel_group)
|
| 460 |
+
|
| 461 |
+
# hidden_states = reorder_for_ssm_p2p(
|
| 462 |
+
# hidden_states,
|
| 463 |
+
# self.sequence_parallel_group,
|
| 464 |
+
# torch.cuda.Stream(),
|
| 465 |
+
# sp_size,
|
| 466 |
+
# sp_rank,
|
| 467 |
+
# self.conv_size,
|
| 468 |
+
# )
|
| 469 |
+
# # hidden_states: [B_sp, L_sp, Dh]
|
| 470 |
+
|
| 471 |
+
# Apply projections and convolutions
|
| 472 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 473 |
+
if last_state is not None:
|
| 474 |
+
conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"]
|
| 475 |
+
|
| 476 |
+
q, conv_state_q = self.q_conv1d(
|
| 477 |
+
x=self.q_proj(hidden_states),
|
| 478 |
+
cache=conv_state_q,
|
| 479 |
+
output_final_state=use_cache,
|
| 480 |
+
cu_seqlens=cu_seqlens,
|
| 481 |
+
)
|
| 482 |
+
# q: [B_sp, L_sp, Dq]
|
| 483 |
+
# conv_state_q: [B, Dq, C] or None
|
| 484 |
+
|
| 485 |
+
k, conv_state_k = self.k_conv1d(
|
| 486 |
+
x=self.k_proj(hidden_states),
|
| 487 |
+
cache=conv_state_k,
|
| 488 |
+
output_final_state=use_cache,
|
| 489 |
+
cu_seqlens=cu_seqlens,
|
| 490 |
+
)
|
| 491 |
+
# k: [B_sp, L_sp, Dk]
|
| 492 |
+
# conv_state_k: [B, Dk, C] or None
|
| 493 |
+
|
| 494 |
+
if self.use_v_conv:
|
| 495 |
+
v, conv_state_v = self.v_conv1d(
|
| 496 |
+
x=self.v_proj(hidden_states),
|
| 497 |
+
cache=conv_state_v,
|
| 498 |
+
output_final_state=use_cache,
|
| 499 |
+
cu_seqlens=cu_seqlens,
|
| 500 |
+
)
|
| 501 |
+
# v: [B_sp, L_sp, Dv]
|
| 502 |
+
# conv_state_v: [B, Dv, C] or None
|
| 503 |
+
else:
|
| 504 |
+
v = self.v_proj(hidden_states) # [B_sp, L_sp, Dv]
|
| 505 |
+
conv_state_v = None
|
| 506 |
+
|
| 507 |
+
# Remove padding for custom zigzag SP (first conv_size-1 tokens added by P2P)
|
| 508 |
+
# if self.sequence_parallel_group is not None:
|
| 509 |
+
# q = q[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dq]
|
| 510 |
+
# k = k[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dk]
|
| 511 |
+
# if self.use_v_conv:
|
| 512 |
+
# v = v[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dv]
|
| 513 |
+
# # Also remove padding from hidden_states so beta/alpha/g/gk match seq length
|
| 514 |
+
# hidden_states = hidden_states[
|
| 515 |
+
# :, self.conv_size - 1 :, :
|
| 516 |
+
# ].contiguous() # [B_sp, Lp, Dh]
|
| 517 |
+
|
| 518 |
+
# Reshape q to heads and expand k/v (handles projection + residual if configured)
|
| 519 |
+
q = rearrange(
|
| 520 |
+
q, "... (h d) -> ... h d", h=self.num_q_heads
|
| 521 |
+
) # [B_sp, Lp, Hq, D]
|
| 522 |
+
k, v = self._expand_kv(k, v) # [B_sp, Lp, H, D] each
|
| 523 |
+
|
| 524 |
+
# Apply GQA/head repeats for q to match expanded_num_heads
|
| 525 |
+
if self.num_q_groups > 1:
|
| 526 |
+
q = repeat(q, "... h d -> ... (h g) d", g=self.num_q_groups)
|
| 527 |
+
# q: [B_sp, Lp, H, D]
|
| 528 |
+
|
| 529 |
+
# Get recurrent state from cache
|
| 530 |
+
last_h_kk, last_h_kv = (
|
| 531 |
+
last_state["recurrent_state"] if last_state is not None else (None, None)
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
# Normalize queries and keys
|
| 535 |
+
qk_norm_eps = 1e-6
|
| 536 |
+
q = q / (
|
| 537 |
+
torch.linalg.vector_norm(q, dim=-1, keepdim=True).to(q) + qk_norm_eps
|
| 538 |
+
) # [B_sp, Lp, H, D]
|
| 539 |
+
k = k / (
|
| 540 |
+
torch.linalg.vector_norm(k, dim=-1, keepdim=True).to(k) + qk_norm_eps
|
| 541 |
+
) # [B_sp, Lp, H, D]
|
| 542 |
+
|
| 543 |
+
# Apply beta gating if enabled
|
| 544 |
+
if self.use_beta_gate:
|
| 545 |
+
beta = self.b_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 546 |
+
eps = 1e-6
|
| 547 |
+
k = ((beta[..., None] + eps) * k).to(k.dtype) # [B_sp, Lp, H, D]
|
| 548 |
+
v = ((beta[..., None] + eps) * v).to(v.dtype) # [B_sp, Lp, H, D]
|
| 549 |
+
|
| 550 |
+
# Compute alpha connection parameter
|
| 551 |
+
if self.use_alpha_connection:
|
| 552 |
+
alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 553 |
+
else:
|
| 554 |
+
alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H]
|
| 555 |
+
|
| 556 |
+
# Compute forgetting gate
|
| 557 |
+
if self.use_forgetting_gate:
|
| 558 |
+
g = -self.A_log.float().exp() * F.softplus(
|
| 559 |
+
self.a_proj(hidden_states).float() + self.dt_bias
|
| 560 |
+
) # [B_sp, Lp, H]
|
| 561 |
+
else:
|
| 562 |
+
g = None
|
| 563 |
+
|
| 564 |
+
gk = g if self.use_forgetting_gate_kk else None
|
| 565 |
+
|
| 566 |
+
# Backward kernels require sequence length to be divisible by chunk size
|
| 567 |
+
if gk is None and self.training:
|
| 568 |
+
seq_len = hidden_states.shape[1]
|
| 569 |
+
assert (
|
| 570 |
+
seq_len % self.chunk_size == 0
|
| 571 |
+
), f"Triton chunk size must divide the sequence length. Got seq_len={seq_len}, chunk_size={self.chunk_size}"
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
# Apply GKA Chebyshev solver
|
| 575 |
+
if last_state is None:
|
| 576 |
+
# if self.sequence_parallel_group is not None:
|
| 577 |
+
# # Custom zigzag SP: Compute h_kk first, pass states, then compute rest
|
| 578 |
+
|
| 579 |
+
# # 1. Compute h_kk locally (just k @ k^T cumsum) with zero initial state
|
| 580 |
+
# k_proj = k # [B_sp, Lp, H, D]
|
| 581 |
+
|
| 582 |
+
# if gk is not None:
|
| 583 |
+
# # For state passing, we only need the sum (equivalent to cumsum[-1])
|
| 584 |
+
# gkk_final = torch.sum(gk, dim=1) # [B_sp, H]
|
| 585 |
+
# else:
|
| 586 |
+
# gkk_final = torch.zeros(
|
| 587 |
+
# q.shape[0],
|
| 588 |
+
# self.expanded_num_heads,
|
| 589 |
+
# device=q.device,
|
| 590 |
+
# dtype=q.dtype,
|
| 591 |
+
# )
|
| 592 |
+
|
| 593 |
+
# # Extract g sum (total decay across chunk)
|
| 594 |
+
# if g is not None:
|
| 595 |
+
# g_cumsum_last = torch.sum(g, dim=1) # [B_sp, H]
|
| 596 |
+
# else:
|
| 597 |
+
# g_cumsum_last = None
|
| 598 |
+
|
| 599 |
+
# # Compute h_kk: cumsum of k @ k^T with gating
|
| 600 |
+
# with torch.cuda.device(q.device):
|
| 601 |
+
# if self.num_iter > 0:
|
| 602 |
+
# kk_final = compute_kk_final_with_gating(
|
| 603 |
+
# k_proj, gk, chunk_size=self.chunk_size
|
| 604 |
+
# )
|
| 605 |
+
# else:
|
| 606 |
+
# kk_final = torch.zeros(
|
| 607 |
+
# k_proj.shape[0],
|
| 608 |
+
# self.expanded_num_heads,
|
| 609 |
+
# k_proj.shape[3],
|
| 610 |
+
# k_proj.shape[3],
|
| 611 |
+
# device=q.device,
|
| 612 |
+
# dtype=q.dtype,
|
| 613 |
+
# )
|
| 614 |
+
# # kk_final: [B_sp, H, D, D]
|
| 615 |
+
|
| 616 |
+
# # Compute h_kv locally to get final state
|
| 617 |
+
# _, h_kv_final = chunk_simple_gla(
|
| 618 |
+
# q=q,
|
| 619 |
+
# k=k,
|
| 620 |
+
# v=v,
|
| 621 |
+
# scale=self.gla_scale,
|
| 622 |
+
# g=g,
|
| 623 |
+
# output_final_state=True,
|
| 624 |
+
# )
|
| 625 |
+
# # h_kv_final: [B_sp, H, D, D]
|
| 626 |
+
|
| 627 |
+
# # 2. Pass states via P2P in zigzag pattern
|
| 628 |
+
# bs = q.shape[0] # Batch size (B_sp, includes both chunks per GPU)
|
| 629 |
+
|
| 630 |
+
# # Ensure all inputs to state_passing are on the same device
|
| 631 |
+
# with torch.cuda.device(q.device):
|
| 632 |
+
# prev_kk, prev_h_kv = state_passing_gka_p2p(
|
| 633 |
+
# kk_final.to(q.device),
|
| 634 |
+
# gkk_final.to(q.device), # Local only, used for decay
|
| 635 |
+
# h_kv_final.to(q.device),
|
| 636 |
+
# g_cumsum_last.to(q.device)
|
| 637 |
+
# if g_cumsum_last is not None
|
| 638 |
+
# else None,
|
| 639 |
+
# self.sequence_parallel_group,
|
| 640 |
+
# sp_rank,
|
| 641 |
+
# sp_size,
|
| 642 |
+
# bs,
|
| 643 |
+
# )
|
| 644 |
+
# # prev_kk: [B_sp, H, D, D]
|
| 645 |
+
# # prev_h_kv: [B_sp, H, D, D]
|
| 646 |
+
|
| 647 |
+
# # 3. Now recompute with initial states from previous chunk
|
| 648 |
+
# # Ensure all tensors are on the same device before calling recompute
|
| 649 |
+
# with torch.cuda.device(q.device):
|
| 650 |
+
# o, h_kk, h_kv = recompute_with_initial_states(
|
| 651 |
+
# q=q,
|
| 652 |
+
# k=k,
|
| 653 |
+
# v=v,
|
| 654 |
+
# alpha=alpha,
|
| 655 |
+
# g=g,
|
| 656 |
+
# gk=gk,
|
| 657 |
+
# prev_kk=prev_kk.to(q.device),
|
| 658 |
+
# prev_h_kv=prev_h_kv.to(q.device),
|
| 659 |
+
# gla_scale=self.gla_scale,
|
| 660 |
+
# ridge_strength=self.ridge_strength,
|
| 661 |
+
# solver_type=self.solver_type,
|
| 662 |
+
# num_iter=self.num_iter,
|
| 663 |
+
# bp_lambda=self.bp_lambda,
|
| 664 |
+
# chunk_size=self.chunk_size,
|
| 665 |
+
# )
|
| 666 |
+
# # o: [B_sp, Lp, H, D]
|
| 667 |
+
# # h_kk: [B_sp, H, D, D]
|
| 668 |
+
# # h_kv: [B_sp, H, D, D]
|
| 669 |
+
# else:
|
| 670 |
+
# with torch.cuda.device(q.device):
|
| 671 |
+
o, h_kk, h_kv = gka_chebyshev_gla(
|
| 672 |
+
q=q,
|
| 673 |
+
k=k,
|
| 674 |
+
v=v,
|
| 675 |
+
alpha=alpha,###this alpha_connect
|
| 676 |
+
g=g,
|
| 677 |
+
gk=gk,
|
| 678 |
+
gla_scale=self.gla_scale,
|
| 679 |
+
ridge_strength=self.ridge_strength,
|
| 680 |
+
solver_type=self.solver_type,
|
| 681 |
+
num_iter=self.num_iter,
|
| 682 |
+
bp_lambda=self.bp_lambda,
|
| 683 |
+
chunk_size=self.chunk_size,
|
| 684 |
+
)
|
| 685 |
+
# o: [B_sp, Lp, H, D]
|
| 686 |
+
# h_kk: [B_sp, H, D, D]
|
| 687 |
+
# h_kv: [B_sp, H, D, D]
|
| 688 |
+
else:
|
| 689 |
+
# with torch.cuda.device(q.device):
|
| 690 |
+
o, h_kk, h_kv = torch_decoding_one_step(
|
| 691 |
+
q=q.squeeze(0),
|
| 692 |
+
k=k.squeeze(0),
|
| 693 |
+
v=v.squeeze(0),
|
| 694 |
+
alpha=alpha.squeeze(0),
|
| 695 |
+
g=g,
|
| 696 |
+
gk=gk,
|
| 697 |
+
gla_scale=self.gla_scale,
|
| 698 |
+
ridge_strength=self.ridge_strength,
|
| 699 |
+
solver_type=self.solver_type,
|
| 700 |
+
num_iter=self.num_iter,
|
| 701 |
+
prev_h_kk=last_h_kk,
|
| 702 |
+
prev_h_kv=last_h_kv,
|
| 703 |
+
)
|
| 704 |
+
# o: [Lp, H, D] (batch squeezed)
|
| 705 |
+
# h_kk: [H, D, D]
|
| 706 |
+
# h_kv: [H, D, D]
|
| 707 |
+
if len(o.shape) == 3:
|
| 708 |
+
o = o.unsqueeze(0) # [1, Lp, H, D]
|
| 709 |
+
|
| 710 |
+
o = o.to(q)
|
| 711 |
+
|
| 712 |
+
# Update cache
|
| 713 |
+
if past_key_values is not None:
|
| 714 |
+
past_key_values.update(
|
| 715 |
+
recurrent_state=(h_kk, h_kv),
|
| 716 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v),
|
| 717 |
+
layer_idx=self.layer_idx,
|
| 718 |
+
offset=q_len,
|
| 719 |
+
)
|
| 720 |
+
|
| 721 |
+
# Apply output gating and normalization
|
| 722 |
+
if self.use_gate:
|
| 723 |
+
g = rearrange(
|
| 724 |
+
self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim
|
| 725 |
+
) # [B_sp, Lp, H, D]
|
| 726 |
+
o = self.o_norm(o, g) # [B_sp, Lp, H, D]
|
| 727 |
+
else:
|
| 728 |
+
o = self.o_norm(o) # [B_sp, Lp, H, D]
|
| 729 |
+
|
| 730 |
+
# Reshape and project output
|
| 731 |
+
o = rearrange(o, "b t h d -> b t (h d)") # [B_sp, Lp, Dexp]
|
| 732 |
+
o = self.o_proj(o) # [B_sp, Lp, Dh]
|
| 733 |
+
|
| 734 |
+
# Scatter sequence if using sequence parallel
|
| 735 |
+
# if self.sequence_parallel_group is not None:
|
| 736 |
+
# # Recombine zigzag chunks to contiguous
|
| 737 |
+
# bz, len_o, dim = o.shape
|
| 738 |
+
# if bz == 2:
|
| 739 |
+
# o = o.view(bz // 2, len_o * 2, dim)
|
| 740 |
+
# else:
|
| 741 |
+
# o = torch.cat([o[: bz // 2], o[bz // 2 :]], dim=1).contiguous()
|
| 742 |
+
# o: [B, L/SP, Dh]
|
| 743 |
+
|
| 744 |
+
return o, None, past_key_values
|
gka_attn.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from transformers.utils import logging
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 15 |
+
from fla.modules import RMSNorm, RotaryEmbedding
|
| 16 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 17 |
+
from fla.models.utils import Cache
|
| 18 |
+
|
| 19 |
+
from ..ops.chebyshev.chebyshev_iteration import ChebyshevIteration
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
import math
|
| 24 |
+
from torch.nn import functional as F
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 28 |
+
except ImportError:
|
| 29 |
+
warnings.warn(
|
| 30 |
+
"Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
|
| 31 |
+
category=ImportWarning
|
| 32 |
+
)
|
| 33 |
+
flash_attn_func = None
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@torch.compiler.disable
|
| 40 |
+
def latent_chebyshev(
|
| 41 |
+
k, q, ridge_strength=0.02, num_iter=30, solver_type="chebyshev", bp_lambda=True, gk=None, chunk_size=64
|
| 42 |
+
):
|
| 43 |
+
"""
|
| 44 |
+
Dispatcher for ridge regression solvers: (H_t + λI)·x_t = q_t.
|
| 45 |
+
|
| 46 |
+
Routes to different solver implementations based on solver_type. All solvers
|
| 47 |
+
aim to solve the same problem but with different speed/accuracy tradeoffs.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
k: Key tensor with shape [B, L, H, D]
|
| 51 |
+
q: Query tensor with shape [B, L, H, D]
|
| 52 |
+
ridge_strength: Regularization parameter λ
|
| 53 |
+
num_iter: Number of iterations for iterative solvers
|
| 54 |
+
solver_type: Solver method. Currently only supports 'chebyshev'.
|
| 55 |
+
bp_lambda: Whether to backprop through λ (for Chebyshev solvers)
|
| 56 |
+
gk: Forgetting gate for key-key covariance with shape [B, L, H]
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
x: Solution tensor with shape [B, L, H, D]
|
| 60 |
+
kk_final: Final key-key covariance H_T with shape [B, H, D, D]
|
| 61 |
+
"""
|
| 62 |
+
if solver_type == "chebyshev":
|
| 63 |
+
x, kk_final = ChebyshevIteration.apply(
|
| 64 |
+
k, q, gk, num_iter, ridge_strength, bp_lambda, None, chunk_size
|
| 65 |
+
)
|
| 66 |
+
else:
|
| 67 |
+
raise ValueError(f"Unknown GKA solver type: {solver_type}")
|
| 68 |
+
|
| 69 |
+
return x, kk_final
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# from ..ops.chebyshev.gka_chebyshev_solve import (
|
| 73 |
+
# gka_chebyshev_gla,
|
| 74 |
+
# torch_decoding_one_step,
|
| 75 |
+
# )
|
| 76 |
+
|
| 77 |
+
from ..ops.chebyshev.gka_chebyshev_solve import chebyshev_iteration_forward_triton_inference
|
| 78 |
+
# from ..ops.phi_kkt_approx.phi_kkt_solve import phi_kkt_solve
|
| 79 |
+
from ..ops.phi_kkt_approx.q_kkt_solve_abc import q_kkt_solve_approx as q_kkt_solve_approx_abc
|
| 80 |
+
class GKAAttention(nn.Module):
|
| 81 |
+
def __init__(
|
| 82 |
+
self,
|
| 83 |
+
hidden_size: int = 2048,
|
| 84 |
+
num_heads: int = 8,
|
| 85 |
+
num_kv_heads: Optional[int] = None,
|
| 86 |
+
qkv_bias: bool = False,
|
| 87 |
+
qk_norm: bool = False,
|
| 88 |
+
window_size: Optional[int] = None,
|
| 89 |
+
rope_theta: Optional[float] = 10000.,
|
| 90 |
+
max_position_embeddings: Optional[int] = None,
|
| 91 |
+
layer_idx: int = None,
|
| 92 |
+
use_alpha_connection: bool = False,
|
| 93 |
+
learnable_abc: Tuple[float, ...] = (1.0, -0.5, 0.375),
|
| 94 |
+
random_init_abc: bool = True,
|
| 95 |
+
abc_requires_grad: bool = True,
|
| 96 |
+
**kwargs,
|
| 97 |
+
):
|
| 98 |
+
super().__init__()
|
| 99 |
+
|
| 100 |
+
self.hidden_size = hidden_size
|
| 101 |
+
self.num_heads = num_heads
|
| 102 |
+
if num_kv_heads is None:
|
| 103 |
+
self.num_kv_heads = self.num_heads
|
| 104 |
+
else:
|
| 105 |
+
self.num_kv_heads = num_kv_heads
|
| 106 |
+
self.num_kv_groups = num_heads // self.num_kv_heads
|
| 107 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 108 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 109 |
+
self.qkv_bias = qkv_bias
|
| 110 |
+
self.qk_norm = qk_norm
|
| 111 |
+
|
| 112 |
+
self.use_alpha_connection = use_alpha_connection
|
| 113 |
+
self.window_size = window_size
|
| 114 |
+
self.rope_theta = rope_theta
|
| 115 |
+
self.max_position_embeddings = max_position_embeddings
|
| 116 |
+
self.layer_idx = layer_idx
|
| 117 |
+
|
| 118 |
+
if flash_attn_func is None:
|
| 119 |
+
raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
|
| 120 |
+
|
| 121 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
|
| 122 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 123 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=self.qkv_bias)
|
| 124 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 125 |
+
|
| 126 |
+
if qk_norm:
|
| 127 |
+
self.q_norm = RMSNorm(self.head_dim)
|
| 128 |
+
self.k_norm = RMSNorm(self.head_dim)
|
| 129 |
+
|
| 130 |
+
self.expanded_num_heads = max(self.num_heads, self.num_kv_heads)
|
| 131 |
+
|
| 132 |
+
self.a_proj = nn.Linear(self.hidden_size, self.expanded_num_heads, bias=False)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
if self.use_alpha_connection:
|
| 136 |
+
self.alpha_proj = nn.Linear(self.hidden_size, self.expanded_num_heads, bias=True)
|
| 137 |
+
|
| 138 |
+
# A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 139 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 140 |
+
# self.A_log._no_weight_decay = True
|
| 141 |
+
|
| 142 |
+
# # Initialize dt bias parameter
|
| 143 |
+
# dt_min = 0.001
|
| 144 |
+
# dt_max = 0.1
|
| 145 |
+
# dt_init_floor = 1e-4
|
| 146 |
+
# dt = torch.exp(
|
| 147 |
+
# torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 148 |
+
# + math.log(dt_min)
|
| 149 |
+
# )
|
| 150 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 151 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 152 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 153 |
+
|
| 154 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 155 |
+
# self.dt_bias._no_weight_decay = True
|
| 156 |
+
init_abc = torch.tensor(learnable_abc, dtype=torch.float32).reshape(-1)
|
| 157 |
+
n_coeff = int(init_abc.numel())
|
| 158 |
+
if n_coeff not in (3, 4):
|
| 159 |
+
raise ValueError(
|
| 160 |
+
f"learnable_abc must have 3 (abc) or 4 (abcd) coefficients, got {n_coeff}"
|
| 161 |
+
)
|
| 162 |
+
self.learnable_abc = nn.Parameter(
|
| 163 |
+
init_abc.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous()
|
| 164 |
+
)
|
| 165 |
+
if random_init_abc:
|
| 166 |
+
# a, c ~ U(0, 1); b, d ~ U(-1, 0)
|
| 167 |
+
signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32)
|
| 168 |
+
self.learnable_abc = nn.Parameter(
|
| 169 |
+
(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
|
| 170 |
+
)
|
| 171 |
+
print("random init abc")
|
| 172 |
+
print(self.learnable_abc)
|
| 173 |
+
print(self.learnable_abc.requires_grad)
|
| 174 |
+
else:
|
| 175 |
+
print("not random init abc")
|
| 176 |
+
print(self.learnable_abc)
|
| 177 |
+
print(self.learnable_abc.requires_grad)
|
| 178 |
+
self.learnable_abc._no_weight_decay = True
|
| 179 |
+
self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
|
| 180 |
+
|
| 181 |
+
def forward(
|
| 182 |
+
self,
|
| 183 |
+
hidden_states: torch.Tensor,
|
| 184 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 185 |
+
past_key_values: Optional[Cache] = None,
|
| 186 |
+
output_attentions: bool = False,
|
| 187 |
+
use_cache: bool = False,
|
| 188 |
+
**kwargs,
|
| 189 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 190 |
+
if attention_mask is not None:
|
| 191 |
+
assert len(attention_mask.shape) == 2, (
|
| 192 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 193 |
+
"for padding purposes (0 indicating padding). "
|
| 194 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# g = -self.A_log.float().exp() * F.softplus(
|
| 202 |
+
# self.a_proj(hidden_states).float() + self.dt_bias
|
| 203 |
+
# ) # [B_sp, Lp, H]
|
| 204 |
+
q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 205 |
+
k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 206 |
+
v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 207 |
+
|
| 208 |
+
if self.qk_norm:
|
| 209 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 210 |
+
|
| 211 |
+
if self.use_alpha_connection:
|
| 212 |
+
alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 213 |
+
else:
|
| 214 |
+
alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H]
|
| 215 |
+
|
| 216 |
+
# equivalent to cu_seqlens in `flash_attn`
|
| 217 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
seqlen_offset, max_seqlen = 0, q_len
|
| 221 |
+
if past_key_values is not None:
|
| 222 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 223 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 224 |
+
if attention_mask is not None:
|
| 225 |
+
# to deliminate the offsets of padding tokens
|
| 226 |
+
seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1]
|
| 227 |
+
max_seqlen = q.shape[1] + max(seqlen_offset)
|
| 228 |
+
###这里应该改成cu_seqlens
|
| 229 |
+
last_state_h_kk = None
|
| 230 |
+
if past_key_values is not None:
|
| 231 |
+
last_state_h_kk = past_key_values[self.layer_idx]["recurrent_state"]
|
| 232 |
+
|
| 233 |
+
if self.max_position_embeddings is not None:
|
| 234 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 235 |
+
gk = torch.zeros(batch_size, q_len, self.expanded_num_heads, device=q.device, dtype=torch.float32)
|
| 236 |
+
q_, last_state_h_kk = q_kkt_solve_approx_abc.apply(
|
| 237 |
+
k, q, gk, 64, self.learnable_abc.to(torch.float32)
|
| 238 |
+
)
|
| 239 |
+
# if last_state_h_kk is None:
|
| 240 |
+
# q_, last_state_h_kk = latent_chebyshev(
|
| 241 |
+
# k, q, ridge_strength=0.02, num_iter=30, solver_type="chebyshev", bp_lambda=True, gk=g, chunk_size=64
|
| 242 |
+
# )
|
| 243 |
+
# else:
|
| 244 |
+
# q_, last_state_h_kk = chebyshev_iteration_forward_triton_inference(
|
| 245 |
+
# last_state_h_kk, k, q, g, num_iter=30, ridge_ratio=0.02
|
| 246 |
+
# )###这个为啥不考虑用wd变换替代
|
| 247 |
+
# q = q + alpha[..., None] * (q_ - q) # Equivalent to ⍺q_ + (1-⍺)q
|
| 248 |
+
q = q_
|
| 249 |
+
# q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 250 |
+
if past_key_values is not None:
|
| 251 |
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
| 252 |
+
k_cached, v_cached = past_key_values.update(
|
| 253 |
+
recurrent_state=last_state_h_kk,
|
| 254 |
+
attn_state=(k.flatten(-2, -1), v.flatten(-2, -1)),
|
| 255 |
+
layer_idx=self.layer_idx,
|
| 256 |
+
offset=q_len,
|
| 257 |
+
cache_kwargs=dict(window_size=self.window_size)
|
| 258 |
+
)['attn_state']
|
| 259 |
+
if cache_has_content:
|
| 260 |
+
k, v = k_cached, v_cached
|
| 261 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 262 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 263 |
+
|
| 264 |
+
# Contains at least one padding token in the sequence
|
| 265 |
+
if attention_mask is not None:
|
| 266 |
+
if q.shape[1] == 1 and self.window_size is not None:
|
| 267 |
+
attention_mask = attention_mask[:, -self.window_size:]
|
| 268 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len)
|
| 269 |
+
cu_seqlens_q, cu_seqlens_k = cu_seqlens
|
| 270 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 271 |
+
o = flash_attn_varlen_func(
|
| 272 |
+
q, k, v,
|
| 273 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 274 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 275 |
+
max_seqlen_q=max_seqlen_q,
|
| 276 |
+
max_seqlen_k=max_seqlen_k,
|
| 277 |
+
causal=True,
|
| 278 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 279 |
+
)
|
| 280 |
+
o = pad_input(o, indices_q, batch_size, q_len)
|
| 281 |
+
elif cu_seqlens is not None:
|
| 282 |
+
o = flash_attn_varlen_func(
|
| 283 |
+
q.squeeze(0), k.squeeze(0), v.squeeze(0),
|
| 284 |
+
cu_seqlens_q=cu_seqlens,
|
| 285 |
+
cu_seqlens_k=cu_seqlens,
|
| 286 |
+
max_seqlen_q=max_seqlen,
|
| 287 |
+
max_seqlen_k=max_seqlen,
|
| 288 |
+
causal=True,
|
| 289 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 290 |
+
).unsqueeze(0)
|
| 291 |
+
else:
|
| 292 |
+
o = flash_attn_func(
|
| 293 |
+
q, k, v,
|
| 294 |
+
causal=True,
|
| 295 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 296 |
+
)
|
| 297 |
+
o = o.reshape(batch_size, q_len, -1)
|
| 298 |
+
o = self.o_proj(o)
|
| 299 |
+
|
| 300 |
+
if not output_attentions:
|
| 301 |
+
attentions = None
|
| 302 |
+
|
| 303 |
+
return o, attentions, past_key_values
|
gsa.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, Dict, Optional, Tuple
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from einops import rearrange, repeat
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 15 |
+
from fla.modules import RMSNorm, ShortConvolution
|
| 16 |
+
from fla.modules.feature_map import ReLUFeatureMap, SwishFeatureMap, T2RFeatureMap
|
| 17 |
+
from fla.modules.layernorm import rms_norm_linear
|
| 18 |
+
from fla.ops.gsa import chunk_gsa, fused_recurrent_gsa
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from transformers.processing_utils import Unpack
|
| 22 |
+
|
| 23 |
+
from fla.models.utils import Cache
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class GatedSlotAttention(nn.Module):
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
mode: str = 'chunk',
|
| 31 |
+
hidden_size: int = 1024,
|
| 32 |
+
expand_k: float = 1.,
|
| 33 |
+
expand_v: float = 1.,
|
| 34 |
+
num_heads: int = 4,
|
| 35 |
+
num_kv_heads: Optional[int] = None,
|
| 36 |
+
use_short_conv: bool = False,
|
| 37 |
+
conv_size: int = 4,
|
| 38 |
+
conv_bias: bool = False,
|
| 39 |
+
num_slots: Optional[int] = None,
|
| 40 |
+
elementwise_affine: Optional[bool] = True,
|
| 41 |
+
norm_eps: float = 1e-5,
|
| 42 |
+
gate_logit_normalizer: int = 8,
|
| 43 |
+
feature_map: str = 'swish',
|
| 44 |
+
use_output_gate: bool = False,
|
| 45 |
+
use_norm: bool = True,
|
| 46 |
+
layer_idx: Optional[int] = None,
|
| 47 |
+
scale: Optional[float] = 1.,
|
| 48 |
+
**kwargs
|
| 49 |
+
) -> GatedSlotAttention:
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
self.mode = mode
|
| 53 |
+
self.hidden_size = hidden_size
|
| 54 |
+
self.expand_k = expand_k
|
| 55 |
+
self.expand_v = expand_v
|
| 56 |
+
self.num_heads = num_heads
|
| 57 |
+
self.num_kv_heads = num_heads if num_kv_heads is None else num_kv_heads
|
| 58 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 59 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 60 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 61 |
+
self.key_dim_per_group = self.key_dim // self.num_kv_groups
|
| 62 |
+
self.value_dim_per_group = self.value_dim // self.num_kv_groups
|
| 63 |
+
self.head_k_dim = self.key_dim // self.num_heads
|
| 64 |
+
self.head_v_dim = self.value_dim // self.num_heads
|
| 65 |
+
|
| 66 |
+
self.use_short_conv = use_short_conv
|
| 67 |
+
self.conv_size = conv_size
|
| 68 |
+
self.conv_bias = conv_bias
|
| 69 |
+
|
| 70 |
+
self.gate_logit_normalizer = gate_logit_normalizer
|
| 71 |
+
|
| 72 |
+
self.use_output_gate = use_output_gate
|
| 73 |
+
self.use_norm = use_norm
|
| 74 |
+
self.scale = scale
|
| 75 |
+
|
| 76 |
+
if num_slots is None:
|
| 77 |
+
num_slots = self.head_k_dim
|
| 78 |
+
self.num_slots = num_slots
|
| 79 |
+
|
| 80 |
+
self.layer_idx = layer_idx
|
| 81 |
+
|
| 82 |
+
if layer_idx is None:
|
| 83 |
+
warnings.warn(
|
| 84 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
| 85 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
| 86 |
+
"when creating this class."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
self.register_module('feature_map', None)
|
| 90 |
+
if feature_map == 'swish':
|
| 91 |
+
self.feature_map = SwishFeatureMap()
|
| 92 |
+
elif feature_map == 'relu':
|
| 93 |
+
self.feature_map = ReLUFeatureMap()
|
| 94 |
+
elif feature_map == 't2r':
|
| 95 |
+
self.feature_map = T2RFeatureMap(self.head_k_dim, self.head_k_dim)
|
| 96 |
+
else:
|
| 97 |
+
raise NotImplementedError(f"Feature map `{feature_map}` is not supported now.")
|
| 98 |
+
|
| 99 |
+
self.q_proj = nn.Linear(self.hidden_size, self.key_dim, bias=False)
|
| 100 |
+
self.k_proj = nn.Linear(self.hidden_size, self.key_dim_per_group, bias=False)
|
| 101 |
+
self.v_proj = nn.Linear(self.hidden_size, self.value_dim_per_group, bias=False)
|
| 102 |
+
self.f_proj = nn.Linear(self.hidden_size, self.num_kv_heads * self.num_slots, bias=False)
|
| 103 |
+
|
| 104 |
+
if use_short_conv:
|
| 105 |
+
self.conv_size = conv_size
|
| 106 |
+
self.q_conv1d = ShortConvolution(
|
| 107 |
+
hidden_size=self.key_dim,
|
| 108 |
+
kernel_size=conv_size,
|
| 109 |
+
bias=conv_bias,
|
| 110 |
+
activation='silu',
|
| 111 |
+
)
|
| 112 |
+
self.k_conv1d = ShortConvolution(
|
| 113 |
+
hidden_size=self.key_dim_per_group,
|
| 114 |
+
kernel_size=conv_size,
|
| 115 |
+
bias=conv_bias,
|
| 116 |
+
activation='silu',
|
| 117 |
+
)
|
| 118 |
+
self.v_conv1d = ShortConvolution(
|
| 119 |
+
hidden_size=self.value_dim_per_group,
|
| 120 |
+
kernel_size=conv_size,
|
| 121 |
+
bias=conv_bias,
|
| 122 |
+
activation='silu',
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
self.g_norm = RMSNorm(self.hidden_size, elementwise_affine, eps=norm_eps)
|
| 126 |
+
self.o_proj = nn.Linear(self.value_dim, self.hidden_size, bias=False)
|
| 127 |
+
|
| 128 |
+
def forward(
|
| 129 |
+
self,
|
| 130 |
+
hidden_states: torch.Tensor,
|
| 131 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 132 |
+
past_key_values: Optional[Cache] = None,
|
| 133 |
+
use_cache: Optional[bool] = False,
|
| 134 |
+
output_attentions: Optional[bool] = False,
|
| 135 |
+
**kwargs: Unpack[Dict]
|
| 136 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 137 |
+
if attention_mask is not None:
|
| 138 |
+
assert len(attention_mask.shape) == 2, (
|
| 139 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 140 |
+
"for padding purposes (0 indicating padding). "
|
| 141 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 145 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 146 |
+
|
| 147 |
+
last_state = None
|
| 148 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 149 |
+
last_state = past_key_values[self.layer_idx]
|
| 150 |
+
|
| 151 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 152 |
+
if attention_mask is not None:
|
| 153 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 154 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 155 |
+
|
| 156 |
+
if self.use_short_conv:
|
| 157 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 158 |
+
if last_state is not None:
|
| 159 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 160 |
+
q, conv_state_q = self.q_conv1d(
|
| 161 |
+
x=self.q_proj(hidden_states),
|
| 162 |
+
cache=conv_state_q,
|
| 163 |
+
output_final_state=use_cache,
|
| 164 |
+
cu_seqlens=cu_seqlens
|
| 165 |
+
)
|
| 166 |
+
k, conv_state_k = self.k_conv1d(
|
| 167 |
+
x=self.k_proj(hidden_states),
|
| 168 |
+
cache=conv_state_k,
|
| 169 |
+
output_final_state=use_cache,
|
| 170 |
+
cu_seqlens=cu_seqlens
|
| 171 |
+
)
|
| 172 |
+
v, conv_state_v = self.v_conv1d(
|
| 173 |
+
x=self.v_proj(hidden_states),
|
| 174 |
+
cache=conv_state_v,
|
| 175 |
+
output_final_state=use_cache,
|
| 176 |
+
cu_seqlens=cu_seqlens
|
| 177 |
+
)
|
| 178 |
+
else:
|
| 179 |
+
q = self.q_proj(hidden_states)
|
| 180 |
+
k = self.k_proj(hidden_states)
|
| 181 |
+
v = self.v_proj(hidden_states)
|
| 182 |
+
f = self.f_proj(hidden_states)
|
| 183 |
+
|
| 184 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 185 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 186 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 187 |
+
f = rearrange(f, '... (h m) -> ... h m', m=self.num_slots)
|
| 188 |
+
|
| 189 |
+
if self.feature_map is not None:
|
| 190 |
+
q, k = map(lambda x: self.feature_map(x), (q, k))
|
| 191 |
+
v = F.silu(v)
|
| 192 |
+
|
| 193 |
+
f = F.logsigmoid(f) / self.gate_logit_normalizer
|
| 194 |
+
s = (1 - f.exp()).to(f.dtype)
|
| 195 |
+
|
| 196 |
+
if self.num_kv_groups > 1:
|
| 197 |
+
k, v, f, s = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_kv_groups), (k, v, f, s))
|
| 198 |
+
|
| 199 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 200 |
+
if mode == 'fused_recurrent':
|
| 201 |
+
o, recurrent_state = fused_recurrent_gsa(
|
| 202 |
+
q=q,
|
| 203 |
+
k=k,
|
| 204 |
+
v=v,
|
| 205 |
+
s=s,
|
| 206 |
+
g=f,
|
| 207 |
+
initial_state=recurrent_state,
|
| 208 |
+
output_final_state=use_cache,
|
| 209 |
+
scale=self.scale,
|
| 210 |
+
cu_seqlens=cu_seqlens,
|
| 211 |
+
)
|
| 212 |
+
elif mode == 'chunk':
|
| 213 |
+
o, recurrent_state = chunk_gsa(
|
| 214 |
+
q=q,
|
| 215 |
+
k=k,
|
| 216 |
+
v=v,
|
| 217 |
+
s=s,
|
| 218 |
+
g=f,
|
| 219 |
+
initial_state=recurrent_state,
|
| 220 |
+
output_final_state=use_cache,
|
| 221 |
+
scale=self.scale,
|
| 222 |
+
cu_seqlens=cu_seqlens,
|
| 223 |
+
)
|
| 224 |
+
else:
|
| 225 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 226 |
+
|
| 227 |
+
if past_key_values is not None:
|
| 228 |
+
past_key_values.update(
|
| 229 |
+
recurrent_state=recurrent_state,
|
| 230 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 231 |
+
layer_idx=self.layer_idx,
|
| 232 |
+
offset=q_len
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 236 |
+
o = rms_norm_linear(F.silu(o), self.g_norm.weight, self.g_norm.bias, self.o_proj.weight, self.o_proj.bias)
|
| 237 |
+
if attention_mask is not None:
|
| 238 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# "Hierarchically Gated Recurrent Neural Network for Sequence Modeling" [https://arxiv.org/abs/2311.04823]
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
|
| 14 |
+
from fla.modules import FusedRMSNormGated, ShortConvolution
|
| 15 |
+
from fla.modules.activations import swiglu
|
| 16 |
+
from fla.ops.hgrn import chunk_hgrn, fused_recurrent_hgrn
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from transformers.processing_utils import Unpack
|
| 20 |
+
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class HGRNAttention(nn.Module):
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
mode: str = 'chunk',
|
| 29 |
+
hidden_size: int = 1024,
|
| 30 |
+
expand_ratio: Optional[int] = 1,
|
| 31 |
+
use_short_conv: bool = False,
|
| 32 |
+
conv_size: int = 4,
|
| 33 |
+
conv_bias: bool = False,
|
| 34 |
+
elementwise_affine: Optional[bool] = True,
|
| 35 |
+
norm_eps: float = 1e-5,
|
| 36 |
+
layer_idx: int = None
|
| 37 |
+
) -> HGRNAttention:
|
| 38 |
+
super().__init__()
|
| 39 |
+
|
| 40 |
+
self.mode = mode
|
| 41 |
+
self.hidden_size = hidden_size
|
| 42 |
+
self.expand_ratio = expand_ratio
|
| 43 |
+
self.input_dim = int(hidden_size * expand_ratio)
|
| 44 |
+
|
| 45 |
+
self.use_short_conv = use_short_conv
|
| 46 |
+
self.conv_size = conv_size
|
| 47 |
+
self.conv_bias = conv_bias
|
| 48 |
+
|
| 49 |
+
self.layer_idx = layer_idx
|
| 50 |
+
|
| 51 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 52 |
+
|
| 53 |
+
self.i_proj = nn.Linear(hidden_size, self.input_dim, bias=False)
|
| 54 |
+
self.f_proj = nn.Linear(hidden_size, self.input_dim, bias=False)
|
| 55 |
+
self.g_proj = nn.Linear(hidden_size, self.input_dim, bias=False)
|
| 56 |
+
|
| 57 |
+
if use_short_conv:
|
| 58 |
+
self.conv_size = conv_size
|
| 59 |
+
self.f_conv1d = ShortConvolution(
|
| 60 |
+
hidden_size=self.input_dim,
|
| 61 |
+
kernel_size=conv_size,
|
| 62 |
+
bias=conv_bias,
|
| 63 |
+
activation=None,
|
| 64 |
+
)
|
| 65 |
+
self.i_conv1d = ShortConvolution(
|
| 66 |
+
hidden_size=self.input_dim,
|
| 67 |
+
kernel_size=conv_size,
|
| 68 |
+
bias=conv_bias,
|
| 69 |
+
activation=None,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
self.g_norm = FusedRMSNormGated(
|
| 73 |
+
hidden_size=self.input_dim,
|
| 74 |
+
elementwise_affine=elementwise_affine,
|
| 75 |
+
eps=norm_eps
|
| 76 |
+
)
|
| 77 |
+
self.o_proj = nn.Linear(self.input_dim, hidden_size, bias=False)
|
| 78 |
+
|
| 79 |
+
def forward(
|
| 80 |
+
self,
|
| 81 |
+
hidden_states: torch.Tensor,
|
| 82 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 83 |
+
past_key_values: Optional[Cache] = None,
|
| 84 |
+
use_cache: Optional[bool] = False,
|
| 85 |
+
output_attentions: Optional[bool] = False,
|
| 86 |
+
lower_bound: Optional[torch.Tensor] = None,
|
| 87 |
+
**kwargs: Unpack[Dict]
|
| 88 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 89 |
+
if attention_mask is not None:
|
| 90 |
+
assert len(attention_mask.shape) == 2, (
|
| 91 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 92 |
+
"for padding purposes (0 indicating padding). "
|
| 93 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
# launching the triton kernel for just one token will actually be slower
|
| 97 |
+
mode = 'fused_recurrent' if not self.training and hidden_states.shape[1] <= 64 else self.mode
|
| 98 |
+
|
| 99 |
+
last_state = None
|
| 100 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 101 |
+
last_state = past_key_values[self.layer_idx]
|
| 102 |
+
|
| 103 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 104 |
+
if self.use_short_conv:
|
| 105 |
+
conv_state_i, conv_state_f = None, None
|
| 106 |
+
if last_state is not None:
|
| 107 |
+
conv_state_i, conv_state_f = last_state['conv_state']
|
| 108 |
+
conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
|
| 109 |
+
i, conv_state_i = self.i_conv1d(
|
| 110 |
+
x=self.i_proj(hidden_states),
|
| 111 |
+
mask=conv_mask,
|
| 112 |
+
cache=conv_state_i,
|
| 113 |
+
output_final_state=use_cache,
|
| 114 |
+
cu_seqlens=cu_seqlens
|
| 115 |
+
)
|
| 116 |
+
f, conv_state_f = self.f_conv1d(
|
| 117 |
+
x=self.f_proj(hidden_states),
|
| 118 |
+
mask=conv_mask,
|
| 119 |
+
cache=conv_state_f,
|
| 120 |
+
output_final_state=use_cache,
|
| 121 |
+
cu_seqlens=cu_seqlens
|
| 122 |
+
)
|
| 123 |
+
else:
|
| 124 |
+
i = self.i_proj(hidden_states)
|
| 125 |
+
f = self.f_proj(hidden_states)
|
| 126 |
+
|
| 127 |
+
f = F.logsigmoid(f)
|
| 128 |
+
# the lower bound for the first layer is zero
|
| 129 |
+
if lower_bound is not None and self.layer_idx > 0:
|
| 130 |
+
f = torch.logaddexp(lower_bound.log(), torch.log1p(-lower_bound) + f).to(f)
|
| 131 |
+
i = swiglu(i, 1 - f.exp())
|
| 132 |
+
|
| 133 |
+
# dealing with left-padding
|
| 134 |
+
if attention_mask is not None:
|
| 135 |
+
i = i.mul_(attention_mask[:, -i.shape[-2]:, None])
|
| 136 |
+
|
| 137 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 138 |
+
if mode == 'chunk':
|
| 139 |
+
if cu_seqlens is not None:
|
| 140 |
+
raise NotImplementedError("Chunk mode does not support variable-length sequences.")
|
| 141 |
+
o, recurrent_state = chunk_hgrn(
|
| 142 |
+
x=i,
|
| 143 |
+
g=f,
|
| 144 |
+
initial_state=recurrent_state,
|
| 145 |
+
output_final_state=use_cache,
|
| 146 |
+
)
|
| 147 |
+
elif mode == 'fused_recurrent':
|
| 148 |
+
o, recurrent_state = fused_recurrent_hgrn(
|
| 149 |
+
x=i,
|
| 150 |
+
g=f,
|
| 151 |
+
initial_state=recurrent_state,
|
| 152 |
+
output_final_state=use_cache,
|
| 153 |
+
cu_seqlens=cu_seqlens
|
| 154 |
+
)
|
| 155 |
+
else:
|
| 156 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 157 |
+
|
| 158 |
+
if past_key_values is not None:
|
| 159 |
+
past_key_values.update(
|
| 160 |
+
recurrent_state=recurrent_state,
|
| 161 |
+
conv_state=(conv_state_i, conv_state_f) if self.use_short_conv else None,
|
| 162 |
+
layer_idx=self.layer_idx,
|
| 163 |
+
offset=i.shape[2]
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
o = self.g_norm(o, self.g_proj(hidden_states))
|
| 167 |
+
o = self.o_proj(o)
|
| 168 |
+
|
| 169 |
+
return o, None, past_key_values
|
| 170 |
+
|
| 171 |
+
def state_size(self, **kwargs) -> int:
|
| 172 |
+
state_size = self.hidden_size
|
| 173 |
+
for module in self.children():
|
| 174 |
+
if isinstance(module, ShortConvolution):
|
| 175 |
+
state_size += module.state_size
|
| 176 |
+
return state_size
|
hgrn2.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# "HGRN2: Gated Linear RNNs with State Expansion"[https://arxiv.org/abs/2404.07904]
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from einops import rearrange
|
| 14 |
+
|
| 15 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 16 |
+
from fla.modules import RMSNorm, ShortConvolution
|
| 17 |
+
from fla.modules.activations import swish
|
| 18 |
+
from fla.modules.layernorm import rms_norm_linear
|
| 19 |
+
from fla.ops.gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from transformers.processing_utils import Unpack
|
| 23 |
+
|
| 24 |
+
from fla.models.utils import Cache
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class HGRN2Attention(nn.Module):
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
mode: str = 'chunk',
|
| 32 |
+
hidden_size: int = 1024,
|
| 33 |
+
num_heads: Optional[int] = None,
|
| 34 |
+
expand_ratio: Optional[int] = 128,
|
| 35 |
+
use_short_conv: bool = False,
|
| 36 |
+
conv_size: int = 4,
|
| 37 |
+
conv_bias: bool = False,
|
| 38 |
+
elementwise_affine: Optional[bool] = True,
|
| 39 |
+
norm_eps: float = 1e-5,
|
| 40 |
+
layer_idx: int = None
|
| 41 |
+
) -> HGRN2Attention:
|
| 42 |
+
super().__init__()
|
| 43 |
+
|
| 44 |
+
self.mode = mode
|
| 45 |
+
self.hidden_size = hidden_size
|
| 46 |
+
|
| 47 |
+
if expand_ratio is not None:
|
| 48 |
+
num_heads = hidden_size // expand_ratio
|
| 49 |
+
elif expand_ratio is None and num_heads is not None:
|
| 50 |
+
expand_ratio = hidden_size // num_heads
|
| 51 |
+
elif expand_ratio is None and num_heads is None:
|
| 52 |
+
raise RuntimeError("One of `expand_ratio` or `num_heads` should be provided.")
|
| 53 |
+
self.num_heads = num_heads
|
| 54 |
+
self.expand_ratio = expand_ratio
|
| 55 |
+
|
| 56 |
+
self.use_short_conv = use_short_conv
|
| 57 |
+
self.conv_size = conv_size
|
| 58 |
+
self.conv_bias = conv_bias
|
| 59 |
+
|
| 60 |
+
self.forget_dim = int(self.num_heads * self.expand_ratio)
|
| 61 |
+
self.input_dim = hidden_size
|
| 62 |
+
self.layer_idx = layer_idx
|
| 63 |
+
|
| 64 |
+
assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`."
|
| 65 |
+
assert self.forget_dim % num_heads == 0, f"forget dim must be divisible by num_heads of {num_heads}"
|
| 66 |
+
assert self.input_dim % num_heads == 0, f"input dim must be divisible by num_heads of {num_heads}"
|
| 67 |
+
|
| 68 |
+
self.head_f_dim = self.expand_ratio
|
| 69 |
+
self.head_i_dim = self.hidden_size // num_heads
|
| 70 |
+
|
| 71 |
+
self.q_proj = nn.Linear(hidden_size, self.forget_dim, bias=False)
|
| 72 |
+
self.f_proj = nn.Linear(hidden_size, self.forget_dim, bias=False)
|
| 73 |
+
self.i_proj = nn.Linear(hidden_size, self.input_dim, bias=False)
|
| 74 |
+
|
| 75 |
+
if use_short_conv:
|
| 76 |
+
self.conv_size = conv_size
|
| 77 |
+
self.q_conv1d = ShortConvolution(
|
| 78 |
+
hidden_size=self.forget_dim,
|
| 79 |
+
kernel_size=conv_size,
|
| 80 |
+
bias=conv_bias,
|
| 81 |
+
activation=None,
|
| 82 |
+
)
|
| 83 |
+
self.f_conv1d = ShortConvolution(
|
| 84 |
+
hidden_size=self.forget_dim,
|
| 85 |
+
kernel_size=conv_size,
|
| 86 |
+
bias=conv_bias,
|
| 87 |
+
activation=None,
|
| 88 |
+
)
|
| 89 |
+
self.i_conv1d = ShortConvolution(
|
| 90 |
+
hidden_size=self.input_dim,
|
| 91 |
+
kernel_size=conv_size,
|
| 92 |
+
bias=conv_bias,
|
| 93 |
+
activation=None,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
self.g_norm = RMSNorm(hidden_size=self.hidden_size, elementwise_affine=elementwise_affine, eps=norm_eps)
|
| 97 |
+
self.o_proj = nn.Linear(self.input_dim, hidden_size, bias=False)
|
| 98 |
+
|
| 99 |
+
def forward(
|
| 100 |
+
self,
|
| 101 |
+
hidden_states: torch.Tensor,
|
| 102 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 103 |
+
past_key_values: Optional[Cache] = None,
|
| 104 |
+
use_cache: Optional[bool] = False,
|
| 105 |
+
output_attentions: Optional[bool] = False,
|
| 106 |
+
lower_bound: Optional[torch.Tensor] = None,
|
| 107 |
+
**kwargs: Unpack[Dict]
|
| 108 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 109 |
+
if attention_mask is not None:
|
| 110 |
+
assert len(attention_mask.shape) == 2, (
|
| 111 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 112 |
+
"for padding purposes (0 indicating padding). "
|
| 113 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 117 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 118 |
+
|
| 119 |
+
last_state = None
|
| 120 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 121 |
+
last_state = past_key_values[self.layer_idx]
|
| 122 |
+
|
| 123 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 124 |
+
if attention_mask is not None:
|
| 125 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 126 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 127 |
+
|
| 128 |
+
if self.use_short_conv:
|
| 129 |
+
conv_state_q, conv_state_f, conv_state_i = None, None, None
|
| 130 |
+
if last_state is not None:
|
| 131 |
+
conv_state_q, conv_state_f, conv_state_i = last_state['conv_state']
|
| 132 |
+
q, conv_state_q = self.q_conv1d(
|
| 133 |
+
x=self.q_proj(hidden_states),
|
| 134 |
+
cache=conv_state_q,
|
| 135 |
+
output_final_state=use_cache,
|
| 136 |
+
cu_seqlens=cu_seqlens
|
| 137 |
+
)
|
| 138 |
+
f, conv_state_f = self.f_conv1d(
|
| 139 |
+
x=self.f_proj(hidden_states),
|
| 140 |
+
cache=conv_state_f,
|
| 141 |
+
output_final_state=use_cache,
|
| 142 |
+
cu_seqlens=cu_seqlens
|
| 143 |
+
)
|
| 144 |
+
i, conv_state_i = self.i_conv1d(
|
| 145 |
+
x=self.i_proj(hidden_states),
|
| 146 |
+
cache=conv_state_i,
|
| 147 |
+
output_final_state=use_cache,
|
| 148 |
+
cu_seqlens=cu_seqlens
|
| 149 |
+
)
|
| 150 |
+
else:
|
| 151 |
+
q = self.q_proj(hidden_states)
|
| 152 |
+
f = self.f_proj(hidden_states)
|
| 153 |
+
i = self.i_proj(hidden_states)
|
| 154 |
+
|
| 155 |
+
q = swish(q)
|
| 156 |
+
|
| 157 |
+
g = F.logsigmoid(f)
|
| 158 |
+
# the lower bound for the first layer is zero
|
| 159 |
+
if lower_bound is not None and self.layer_idx > 0:
|
| 160 |
+
g = torch.logaddexp(lower_bound.log(), torch.log1p(-lower_bound) + g)
|
| 161 |
+
k = 1 - g.exp()
|
| 162 |
+
|
| 163 |
+
q, k, g = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_f_dim), (q, k.to(i), g))
|
| 164 |
+
i = rearrange(i, '... (h d) -> ... h d', d=self.head_i_dim)
|
| 165 |
+
|
| 166 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 167 |
+
if mode == 'fused_recurrent':
|
| 168 |
+
o, recurrent_state = fused_recurrent_gla(
|
| 169 |
+
q=q,
|
| 170 |
+
k=k,
|
| 171 |
+
v=i,
|
| 172 |
+
gk=g,
|
| 173 |
+
initial_state=recurrent_state,
|
| 174 |
+
output_final_state=use_cache,
|
| 175 |
+
cu_seqlens=cu_seqlens,
|
| 176 |
+
)
|
| 177 |
+
elif mode == 'fused_chunk':
|
| 178 |
+
o, recurrent_state = fused_chunk_gla(
|
| 179 |
+
q=q,
|
| 180 |
+
k=k,
|
| 181 |
+
v=i,
|
| 182 |
+
g=g,
|
| 183 |
+
initial_state=recurrent_state,
|
| 184 |
+
output_final_state=use_cache,
|
| 185 |
+
)
|
| 186 |
+
elif mode == 'chunk':
|
| 187 |
+
o, recurrent_state = chunk_gla(
|
| 188 |
+
q=q,
|
| 189 |
+
k=k,
|
| 190 |
+
v=i,
|
| 191 |
+
g=g,
|
| 192 |
+
initial_state=recurrent_state,
|
| 193 |
+
output_final_state=use_cache,
|
| 194 |
+
cu_seqlens=cu_seqlens,
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 198 |
+
|
| 199 |
+
if past_key_values is not None:
|
| 200 |
+
past_key_values.update(
|
| 201 |
+
recurrent_state=recurrent_state,
|
| 202 |
+
conv_state=(conv_state_q, conv_state_f, conv_state_i) if self.use_short_conv else None,
|
| 203 |
+
layer_idx=self.layer_idx,
|
| 204 |
+
offset=q_len
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 208 |
+
o = rms_norm_linear(o, self.g_norm.weight, self.g_norm.bias, self.o_proj.weight, self.o_proj.bias)
|
| 209 |
+
if attention_mask is not None:
|
| 210 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 211 |
+
|
| 212 |
+
return o, None, past_key_values
|
lightnet.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# ["You Only Scan Once: Efficient Multi-dimension Sequential Modeling with LightNet"](https://arxiv.org/abs/2405.21022)
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
from einops import rearrange
|
| 14 |
+
|
| 15 |
+
from fla.modules import FusedRMSNormGated, ShortConvolution
|
| 16 |
+
from fla.modules.fused_norm_gate import rms_norm_swish_gate_linear
|
| 17 |
+
from fla.ops.gla import chunk_gla, fused_recurrent_gla
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from transformers.processing_utils import Unpack
|
| 21 |
+
|
| 22 |
+
from fla.models.utils import Cache
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class LightNetAttention(nn.Module):
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
mode: str = 'chunk',
|
| 30 |
+
hidden_size: int = 1024,
|
| 31 |
+
num_heads: Optional[int] = None,
|
| 32 |
+
expand_ratio: Optional[int] = 128,
|
| 33 |
+
use_short_conv: bool = False,
|
| 34 |
+
conv_size: int = 4,
|
| 35 |
+
conv_bias: bool = False,
|
| 36 |
+
gate_low_rank_dim: int = 128,
|
| 37 |
+
elementwise_affine: Optional[bool] = True,
|
| 38 |
+
norm_eps: float = 1e-5,
|
| 39 |
+
layer_idx: int = None
|
| 40 |
+
) -> LightNetAttention:
|
| 41 |
+
super().__init__()
|
| 42 |
+
|
| 43 |
+
self.mode = mode
|
| 44 |
+
self.hidden_size = hidden_size
|
| 45 |
+
|
| 46 |
+
if expand_ratio is None and num_heads is not None:
|
| 47 |
+
expand_ratio = hidden_size // num_heads
|
| 48 |
+
elif expand_ratio is not None and num_heads is None:
|
| 49 |
+
num_heads = hidden_size // expand_ratio
|
| 50 |
+
elif expand_ratio is None and num_heads is None:
|
| 51 |
+
raise RuntimeError("One of `expand_ratio` or `num_heads` should be provided.")
|
| 52 |
+
self.num_heads = num_heads
|
| 53 |
+
self.expand_ratio = expand_ratio
|
| 54 |
+
|
| 55 |
+
self.use_short_conv = use_short_conv
|
| 56 |
+
self.conv_size = conv_size
|
| 57 |
+
self.conv_bias = conv_bias
|
| 58 |
+
|
| 59 |
+
self.key_dim = int(self.num_heads * self.expand_ratio)
|
| 60 |
+
self.value_dim = hidden_size
|
| 61 |
+
self.gate_low_rank_dim = gate_low_rank_dim
|
| 62 |
+
self.layer_idx = layer_idx
|
| 63 |
+
|
| 64 |
+
assert mode in ['chunk', 'fused_chunk'], f"Not supported mode `{mode}`."
|
| 65 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 66 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 67 |
+
|
| 68 |
+
self.head_f_dim = self.expand_ratio
|
| 69 |
+
self.head_i_dim = self.hidden_size // num_heads
|
| 70 |
+
|
| 71 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 72 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 73 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 74 |
+
|
| 75 |
+
if use_short_conv:
|
| 76 |
+
self.conv_size = conv_size
|
| 77 |
+
self.q_conv1d = ShortConvolution(
|
| 78 |
+
hidden_size=self.key_dim,
|
| 79 |
+
kernel_size=conv_size,
|
| 80 |
+
bias=conv_bias,
|
| 81 |
+
activation=None,
|
| 82 |
+
)
|
| 83 |
+
self.k_conv1d = ShortConvolution(
|
| 84 |
+
hidden_size=self.key_dim,
|
| 85 |
+
kernel_size=conv_size,
|
| 86 |
+
bias=conv_bias,
|
| 87 |
+
activation=None,
|
| 88 |
+
)
|
| 89 |
+
self.v_conv1d = ShortConvolution(
|
| 90 |
+
hidden_size=self.value_dim,
|
| 91 |
+
kernel_size=conv_size,
|
| 92 |
+
bias=conv_bias,
|
| 93 |
+
activation=None,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
self.g_proj = nn.Sequential(
|
| 97 |
+
nn.Linear(hidden_size, gate_low_rank_dim, bias=False),
|
| 98 |
+
nn.Linear(gate_low_rank_dim, hidden_size, bias=False)
|
| 99 |
+
)
|
| 100 |
+
self.g_norm = FusedRMSNormGated(
|
| 101 |
+
hidden_size=hidden_size,
|
| 102 |
+
elementwise_affine=elementwise_affine,
|
| 103 |
+
eps=norm_eps
|
| 104 |
+
)
|
| 105 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 106 |
+
|
| 107 |
+
def forward(
|
| 108 |
+
self,
|
| 109 |
+
hidden_states: torch.Tensor,
|
| 110 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 111 |
+
past_key_values: Optional[Cache] = None,
|
| 112 |
+
use_cache: Optional[bool] = False,
|
| 113 |
+
output_attentions: Optional[bool] = False,
|
| 114 |
+
**kwargs: Unpack[Dict]
|
| 115 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 116 |
+
if attention_mask is not None:
|
| 117 |
+
assert len(attention_mask.shape) == 2, (
|
| 118 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 119 |
+
"for padding purposes (0 indicating padding). "
|
| 120 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# launching the triton kernel for just one token will actually be slower
|
| 124 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 125 |
+
|
| 126 |
+
last_state = None
|
| 127 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 128 |
+
last_state = past_key_values[self.layer_idx]
|
| 129 |
+
|
| 130 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 131 |
+
if self.use_short_conv:
|
| 132 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 133 |
+
if last_state is not None:
|
| 134 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 135 |
+
conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
|
| 136 |
+
q, conv_state_q = self.q_conv1d(
|
| 137 |
+
x=self.q_proj(hidden_states),
|
| 138 |
+
mask=conv_mask,
|
| 139 |
+
cache=conv_state_q,
|
| 140 |
+
output_final_state=use_cache,
|
| 141 |
+
cu_seqlens=cu_seqlens
|
| 142 |
+
)
|
| 143 |
+
k, conv_state_k = self.k_conv1d(
|
| 144 |
+
x=self.k_proj(hidden_states),
|
| 145 |
+
mask=conv_mask,
|
| 146 |
+
cache=conv_state_k,
|
| 147 |
+
output_final_state=use_cache,
|
| 148 |
+
cu_seqlens=cu_seqlens
|
| 149 |
+
)
|
| 150 |
+
v, conv_state_v = self.v_conv1d(
|
| 151 |
+
x=self.v_proj(hidden_states),
|
| 152 |
+
mask=conv_mask,
|
| 153 |
+
cache=conv_state_v,
|
| 154 |
+
output_final_state=use_cache,
|
| 155 |
+
cu_seqlens=cu_seqlens
|
| 156 |
+
)
|
| 157 |
+
else:
|
| 158 |
+
q = self.q_proj(hidden_states)
|
| 159 |
+
k = self.k_proj(hidden_states)
|
| 160 |
+
v = self.v_proj(hidden_states)
|
| 161 |
+
|
| 162 |
+
# dealing with left-padding
|
| 163 |
+
if attention_mask is not None:
|
| 164 |
+
v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
|
| 165 |
+
|
| 166 |
+
q = F.silu(q)
|
| 167 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_f_dim), (q, k))
|
| 168 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_i_dim)
|
| 169 |
+
# TODO: this 2 steps took huge amount of time, which should be optimized
|
| 170 |
+
z = k.float().logcumsumexp(1)
|
| 171 |
+
|
| 172 |
+
if cu_seqlens is not None:
|
| 173 |
+
raise NotImplementedError("LightNet does not support variable-length sequences for now.")
|
| 174 |
+
k, g = torch.exp(k - z).to(k.dtype), (torch.cat((z[:, :1], z[:, :-1]), 1) - z).to(k.dtype)
|
| 175 |
+
|
| 176 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 177 |
+
if mode == 'fused_recurrent':
|
| 178 |
+
o, recurrent_state = fused_recurrent_gla(
|
| 179 |
+
q=q,
|
| 180 |
+
k=k,
|
| 181 |
+
v=v,
|
| 182 |
+
gk=g,
|
| 183 |
+
initial_state=recurrent_state,
|
| 184 |
+
output_final_state=use_cache,
|
| 185 |
+
cu_seqlens=cu_seqlens,
|
| 186 |
+
)
|
| 187 |
+
elif mode == 'chunk':
|
| 188 |
+
o, recurrent_state = chunk_gla(
|
| 189 |
+
q=q,
|
| 190 |
+
k=k,
|
| 191 |
+
v=v,
|
| 192 |
+
g=g,
|
| 193 |
+
initial_state=recurrent_state,
|
| 194 |
+
output_final_state=use_cache,
|
| 195 |
+
cu_seqlens=cu_seqlens,
|
| 196 |
+
)
|
| 197 |
+
else:
|
| 198 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 199 |
+
|
| 200 |
+
if past_key_values is not None:
|
| 201 |
+
past_key_values.update(
|
| 202 |
+
recurrent_state=recurrent_state,
|
| 203 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 204 |
+
layer_idx=self.layer_idx,
|
| 205 |
+
offset=q.shape[1]
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
o = rms_norm_swish_gate_linear(
|
| 209 |
+
rearrange(o, 'b t h d -> b t (h d)'),
|
| 210 |
+
self.g_proj(hidden_states),
|
| 211 |
+
self.g_norm.weight,
|
| 212 |
+
self.g_norm.bias,
|
| 213 |
+
self.o_proj.weight,
|
| 214 |
+
self.o_proj.bias
|
| 215 |
+
)
|
| 216 |
+
return o, None, past_key_values
|
| 217 |
+
|
| 218 |
+
def state_size(self, **kwargs) -> int:
|
| 219 |
+
state_size = self.key_dim * self.head_i_dim
|
| 220 |
+
for module in self.children():
|
| 221 |
+
if isinstance(module, ShortConvolution):
|
| 222 |
+
state_size += module.state_size
|
| 223 |
+
return state_size
|
linear_attn.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
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songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from einops import rearrange, repeat
|
| 10 |
+
|
| 11 |
+
from fla.modules import RMSNorm
|
| 12 |
+
from fla.modules.feature_map import DPFPFeatureMap, HadamardFeatureMap, HedgehogFeatureMap, T2RFeatureMap
|
| 13 |
+
from fla.ops.linear_attn import chunk_linear_attn, fused_chunk_linear_attn, fused_recurrent_linear_attn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class LinearAttention(nn.Module):
|
| 17 |
+
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
mode: str = 'chunk',
|
| 21 |
+
hidden_size: str = 1024,
|
| 22 |
+
expand_k: float = 1.0,
|
| 23 |
+
expand_v: float = 1.0,
|
| 24 |
+
num_heads: int = 8,
|
| 25 |
+
num_kv_heads: Optional[int] = None,
|
| 26 |
+
feature_map: str = 'elementwise_product',
|
| 27 |
+
tie_feature_map_qk: bool = False,
|
| 28 |
+
output_norm: str = 'rmsnorm',
|
| 29 |
+
norm_q: bool = False,
|
| 30 |
+
norm_k: bool = False,
|
| 31 |
+
do_feature_map_norm: bool = False,
|
| 32 |
+
elementwise_affine: bool = True,
|
| 33 |
+
norm_eps: float = 1e-5,
|
| 34 |
+
**kwargs
|
| 35 |
+
):
|
| 36 |
+
super().__init__()
|
| 37 |
+
|
| 38 |
+
self.hidden_size = hidden_size
|
| 39 |
+
self.mode = mode
|
| 40 |
+
self.num_heads = num_heads
|
| 41 |
+
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
| 42 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 43 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 44 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 45 |
+
self.key_dim_per_group = self.key_dim // self.num_kv_groups
|
| 46 |
+
self.value_dim_per_group = self.value_dim // self.num_kv_groups
|
| 47 |
+
|
| 48 |
+
assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 49 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 50 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 51 |
+
|
| 52 |
+
self.head_k_dim = self.key_dim // num_heads
|
| 53 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 54 |
+
self.do_feature_map_norm = do_feature_map_norm
|
| 55 |
+
|
| 56 |
+
if feature_map == 'hedgehog':
|
| 57 |
+
if tie_feature_map_qk:
|
| 58 |
+
self.feature_map_q = self.feature_map_k = HedgehogFeatureMap(head_dim=self.head_k_dim)
|
| 59 |
+
else:
|
| 60 |
+
self.feature_map_q = HedgehogFeatureMap(head_dim=self.head_k_dim)
|
| 61 |
+
self.feature_map_k = HedgehogFeatureMap(head_dim=self.head_k_dim)
|
| 62 |
+
|
| 63 |
+
elif feature_map == 't2r':
|
| 64 |
+
if tie_feature_map_qk:
|
| 65 |
+
self.feature_map_q = self.feature_map_k = T2RFeatureMap(head_dim=self.head_k_dim)
|
| 66 |
+
else:
|
| 67 |
+
self.feature_map_q = T2RFeatureMap(head_dim=self.head_k_dim)
|
| 68 |
+
self.feature_map_k = T2RFeatureMap(head_dim=self.head_k_dim)
|
| 69 |
+
|
| 70 |
+
elif feature_map == 'elementwise_product':
|
| 71 |
+
if tie_feature_map_qk:
|
| 72 |
+
self.feature_map_q = self.feature_map_k = HadamardFeatureMap(head_dim=self.head_k_dim)
|
| 73 |
+
else:
|
| 74 |
+
self.feature_map_q = HadamardFeatureMap(head_dim=self.head_k_dim)
|
| 75 |
+
self.feature_map_k = HadamardFeatureMap(head_dim=self.head_k_dim)
|
| 76 |
+
|
| 77 |
+
elif feature_map == 'dpfp':
|
| 78 |
+
self.feature_map_q = DPFPFeatureMap(head_dim=self.head_k_dim)
|
| 79 |
+
self.feature_map_k = DPFPFeatureMap(head_dim=self.head_k_dim)
|
| 80 |
+
|
| 81 |
+
elif feature_map == 'elu':
|
| 82 |
+
def elu(x):
|
| 83 |
+
return F.elu(x) + 1
|
| 84 |
+
self.feature_map_q = elu
|
| 85 |
+
self.feature_map_k = elu
|
| 86 |
+
|
| 87 |
+
elif feature_map == 'relu':
|
| 88 |
+
self.feature_map_q = nn.ReLU()
|
| 89 |
+
self.feature_map_k = nn.ReLU()
|
| 90 |
+
|
| 91 |
+
elif feature_map == 'identity':
|
| 92 |
+
self.feature_map_q = nn.Identity()
|
| 93 |
+
self.feature_map_k = nn.Identity()
|
| 94 |
+
else:
|
| 95 |
+
raise NotImplementedError(f"Not supported feature map `{feature_map}`.")
|
| 96 |
+
|
| 97 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 98 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
|
| 99 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
|
| 100 |
+
|
| 101 |
+
if output_norm == 'rmsnorm':
|
| 102 |
+
self.norm = RMSNorm(hidden_size=self.head_v_dim, elementwise_affine=elementwise_affine, eps=norm_eps)
|
| 103 |
+
elif output_norm == 'identity':
|
| 104 |
+
self.norm = nn.Identity()
|
| 105 |
+
else:
|
| 106 |
+
raise NotImplementedError(f"Not supported output norm `{output_norm}`.")
|
| 107 |
+
|
| 108 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 109 |
+
|
| 110 |
+
self.norm_q = norm_q
|
| 111 |
+
self.norm_k = norm_k
|
| 112 |
+
|
| 113 |
+
def forward(
|
| 114 |
+
self,
|
| 115 |
+
hidden_states: torch.Tensor,
|
| 116 |
+
**kwargs
|
| 117 |
+
) -> torch.Tensor:
|
| 118 |
+
mode = self.mode
|
| 119 |
+
q = self.q_proj(hidden_states)
|
| 120 |
+
k = self.k_proj(hidden_states)
|
| 121 |
+
v = self.v_proj(hidden_states)
|
| 122 |
+
|
| 123 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 124 |
+
if self.num_kv_groups > 1:
|
| 125 |
+
k = repeat(k, '... (h d) -> ... (h g) d', d=self.head_k_dim, g=self.num_kv_groups)
|
| 126 |
+
v = repeat(v, '... (h d) -> ... (h g) d', d=self.head_v_dim, g=self.num_kv_groups)
|
| 127 |
+
else:
|
| 128 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 129 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 130 |
+
|
| 131 |
+
q = self.feature_map_q(q)
|
| 132 |
+
k = self.feature_map_k(k)
|
| 133 |
+
|
| 134 |
+
if self.norm_q:
|
| 135 |
+
q = q / (q.sum(-1, True) + 1e-4)
|
| 136 |
+
if self.norm_k:
|
| 137 |
+
k = k / (k.sum(-1, True) + 1e-4)
|
| 138 |
+
|
| 139 |
+
if mode == 'chunk':
|
| 140 |
+
o, final_state = chunk_linear_attn(
|
| 141 |
+
q=q,
|
| 142 |
+
k=k,
|
| 143 |
+
v=v,
|
| 144 |
+
normalize=self.do_feature_map_norm,
|
| 145 |
+
)
|
| 146 |
+
elif mode == 'fused_chunk':
|
| 147 |
+
o, final_state = fused_chunk_linear_attn(
|
| 148 |
+
q=q,
|
| 149 |
+
k=k,
|
| 150 |
+
v=v,
|
| 151 |
+
normalize=self.do_feature_map_norm,
|
| 152 |
+
)
|
| 153 |
+
elif mode == 'fused_recurrent':
|
| 154 |
+
o, final_state = fused_recurrent_linear_attn(
|
| 155 |
+
q=q,
|
| 156 |
+
k=k,
|
| 157 |
+
v=v,
|
| 158 |
+
normalize=self.do_feature_map_norm,
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
raise NotImplementedError
|
| 162 |
+
o = self.norm(o)
|
| 163 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 164 |
+
o = self.o_proj(o)
|
| 165 |
+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
|
|
| 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, Dict, Optional
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
from transformers.utils import logging
|
| 12 |
+
|
| 13 |
+
from fla.modules.activations import ACT2FN
|
| 14 |
+
|
| 15 |
+
with warnings.catch_warnings():
|
| 16 |
+
warnings.simplefilter('ignore')
|
| 17 |
+
try:
|
| 18 |
+
from mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, selective_scan_fn
|
| 19 |
+
from mamba_ssm.ops.triton.selective_state_update import selective_state_update
|
| 20 |
+
except ImportError:
|
| 21 |
+
selective_state_update, selective_scan_fn, mamba_inner_fn = None, None, None
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
|
| 25 |
+
except ImportError:
|
| 26 |
+
causal_conv1d_update, causal_conv1d_fn = None, None
|
| 27 |
+
is_fast_path_available = all((
|
| 28 |
+
selective_state_update,
|
| 29 |
+
selective_scan_fn,
|
| 30 |
+
mamba_inner_fn
|
| 31 |
+
))
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from transformers.processing_utils import Unpack
|
| 34 |
+
|
| 35 |
+
from fla.models.mamba.modeling_mamba import MambaCache
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class Mamba(nn.Module):
|
| 41 |
+
"""
|
| 42 |
+
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
|
| 43 |
+
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
|
| 44 |
+
∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
|
| 45 |
+
and is why Mamba is called **selective** state spaces)
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
hidden_size: int = 2048,
|
| 51 |
+
state_size: int = 16,
|
| 52 |
+
conv_kernel: int = 4,
|
| 53 |
+
use_conv_bias: bool = True,
|
| 54 |
+
intermediate_size: int = 2048,
|
| 55 |
+
time_step_rank: int = 256,
|
| 56 |
+
use_bias: bool = True,
|
| 57 |
+
hidden_act: str = "silu",
|
| 58 |
+
layer_idx: int = None,
|
| 59 |
+
backend: str = "cuda",
|
| 60 |
+
):
|
| 61 |
+
super().__init__()
|
| 62 |
+
|
| 63 |
+
self.hidden_size = hidden_size
|
| 64 |
+
self.ssm_state_size = state_size
|
| 65 |
+
self.conv_kernel_size = conv_kernel
|
| 66 |
+
self.use_conv_bias = use_conv_bias
|
| 67 |
+
self.intermediate_size = intermediate_size
|
| 68 |
+
self.time_step_rank = time_step_rank
|
| 69 |
+
self.use_bias = use_bias
|
| 70 |
+
|
| 71 |
+
self.conv1d = nn.Conv1d(
|
| 72 |
+
in_channels=self.intermediate_size,
|
| 73 |
+
out_channels=self.intermediate_size,
|
| 74 |
+
bias=use_conv_bias,
|
| 75 |
+
kernel_size=conv_kernel,
|
| 76 |
+
groups=self.intermediate_size,
|
| 77 |
+
padding=conv_kernel - 1,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
self.activation = hidden_act
|
| 81 |
+
self.act = ACT2FN[hidden_act]
|
| 82 |
+
|
| 83 |
+
self.layer_idx = layer_idx
|
| 84 |
+
|
| 85 |
+
# projection of the input hidden states
|
| 86 |
+
self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=use_bias)
|
| 87 |
+
# selective projection used to make dt, B and C input dependant
|
| 88 |
+
self.x_proj = nn.Linear(self.intermediate_size, self.time_step_rank + self.ssm_state_size * 2, bias=False)
|
| 89 |
+
# time step projection (discretization)
|
| 90 |
+
self.dt_proj = nn.Linear(self.time_step_rank, self.intermediate_size, bias=True)
|
| 91 |
+
|
| 92 |
+
# S4D real initialization. These are not discretized!
|
| 93 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 94 |
+
A = torch.arange(1, self.ssm_state_size + 1, dtype=torch.float32)[None, :]
|
| 95 |
+
A = A.expand(self.intermediate_size, -1).contiguous()
|
| 96 |
+
|
| 97 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 98 |
+
self.D = nn.Parameter(torch.ones(self.intermediate_size))
|
| 99 |
+
self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=use_bias)
|
| 100 |
+
|
| 101 |
+
if not is_fast_path_available:
|
| 102 |
+
logger.warning_once(
|
| 103 |
+
"The fast path is not available because on of "
|
| 104 |
+
"`(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
|
| 105 |
+
" is None. Falling back to the naive implementation. "
|
| 106 |
+
"To install follow https://github.com/state-spaces/mamba/#installation and"
|
| 107 |
+
" https://github.com/Dao-AILab/causal-conv1d"
|
| 108 |
+
)
|
| 109 |
+
import os
|
| 110 |
+
backend = os.environ.get('FLA_CONV_BACKEND', backend)
|
| 111 |
+
assert backend in ['cuda', 'triton'], f"Unsupported backend: {backend}"
|
| 112 |
+
if backend == 'cuda' and causal_conv1d_fn is None:
|
| 113 |
+
logger.warning_once(
|
| 114 |
+
"The CUDA backend is not available because `causal_conv1d` is None. "
|
| 115 |
+
"Falling back to the Triton backend. "
|
| 116 |
+
"To install follow https://github.com/Dao-AILab/causal-conv1d"
|
| 117 |
+
)
|
| 118 |
+
backend = 'triton'
|
| 119 |
+
if backend == 'triton':
|
| 120 |
+
from fla.modules.convolution import causal_conv1d as causal_conv1d_triton
|
| 121 |
+
from fla.modules.convolution import causal_conv1d_update as causal_conv1d_update_triton
|
| 122 |
+
self.causal_conv1d_fn = causal_conv1d_triton
|
| 123 |
+
self.causal_conv1d_update = causal_conv1d_update_triton
|
| 124 |
+
else:
|
| 125 |
+
self.causal_conv1d_fn = causal_conv1d_fn
|
| 126 |
+
self.causal_conv1d_update = causal_conv1d_update
|
| 127 |
+
self.backend = backend
|
| 128 |
+
|
| 129 |
+
def cuda_kernels_forward(
|
| 130 |
+
self,
|
| 131 |
+
hidden_states: torch.Tensor,
|
| 132 |
+
cache_params: Optional[MambaCache] = None,
|
| 133 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 134 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 135 |
+
**kwargs: Unpack[Dict]
|
| 136 |
+
):
|
| 137 |
+
# 1. Gated MLP's linear projection
|
| 138 |
+
projected_states = self.in_proj(hidden_states).transpose(1, 2)
|
| 139 |
+
|
| 140 |
+
if self.training and cache_params is None: # Doesn't support outputting the states -> used for training
|
| 141 |
+
contextualized_states = mamba_inner_fn(
|
| 142 |
+
projected_states,
|
| 143 |
+
self.conv1d.weight,
|
| 144 |
+
self.conv1d.bias if self.use_conv_bias else None,
|
| 145 |
+
self.x_proj.weight,
|
| 146 |
+
self.dt_proj.weight,
|
| 147 |
+
self.out_proj.weight,
|
| 148 |
+
self.out_proj.bias.float() if self.use_bias else None,
|
| 149 |
+
-torch.exp(self.A_log.float()),
|
| 150 |
+
None, # input-dependent B
|
| 151 |
+
None, # input-dependent C
|
| 152 |
+
self.D.float(),
|
| 153 |
+
delta_bias=self.dt_proj.bias.float(),
|
| 154 |
+
delta_softplus=True,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
else:
|
| 158 |
+
hidden_states, gate = projected_states.chunk(2, dim=1)
|
| 159 |
+
|
| 160 |
+
if attention_mask is not None:
|
| 161 |
+
hidden_states = hidden_states * attention_mask.unsqueeze(1)
|
| 162 |
+
|
| 163 |
+
# 2. Convolution sequence transformation
|
| 164 |
+
conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2))
|
| 165 |
+
if cache_params is not None and cache_position[0] > 0:
|
| 166 |
+
hidden_states = self.causal_conv1d_update(
|
| 167 |
+
hidden_states.squeeze(-1),
|
| 168 |
+
cache_params.conv_states[self.layer_idx],
|
| 169 |
+
conv_weights,
|
| 170 |
+
self.conv1d.bias,
|
| 171 |
+
self.activation,
|
| 172 |
+
)
|
| 173 |
+
hidden_states = hidden_states.unsqueeze(-1)
|
| 174 |
+
else:
|
| 175 |
+
if cache_params is not None:
|
| 176 |
+
conv_states = nn.functional.pad(
|
| 177 |
+
hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0)
|
| 178 |
+
)
|
| 179 |
+
cache_params.update_conv_state(self.layer_idx, conv_states, cache_position)
|
| 180 |
+
hidden_states = self.causal_conv1d_fn(
|
| 181 |
+
hidden_states, conv_weights, self.conv1d.bias, activation=self.activation
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
if attention_mask is not None:
|
| 185 |
+
hidden_states = hidden_states * attention_mask.unsqueeze(1)
|
| 186 |
+
|
| 187 |
+
# 3. State Space Model sequence transformation
|
| 188 |
+
# 3.a. input varying initialization of time_step, B and C
|
| 189 |
+
ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
|
| 190 |
+
time_step, B, C = torch.split(
|
| 191 |
+
ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
|
| 192 |
+
)
|
| 193 |
+
discrete_time_step = self.dt_proj.weight @ time_step.transpose(1, 2)
|
| 194 |
+
|
| 195 |
+
A = -torch.exp(self.A_log.float())
|
| 196 |
+
# 3.c perform the recurrence y ← SSM(A, B, C)(x)
|
| 197 |
+
time_proj_bias = self.dt_proj.bias.float() if hasattr(self.dt_proj, "bias") else None
|
| 198 |
+
if cache_params is not None and cache_position[0] > 0:
|
| 199 |
+
scan_outputs = selective_state_update(
|
| 200 |
+
cache_params.ssm_states[self.layer_idx],
|
| 201 |
+
hidden_states[..., 0],
|
| 202 |
+
discrete_time_step[..., 0],
|
| 203 |
+
A,
|
| 204 |
+
B[:, 0],
|
| 205 |
+
C[:, 0],
|
| 206 |
+
self.D,
|
| 207 |
+
gate[..., 0],
|
| 208 |
+
time_proj_bias,
|
| 209 |
+
dt_softplus=True,
|
| 210 |
+
).unsqueeze(-1)
|
| 211 |
+
else:
|
| 212 |
+
scan_outputs, ssm_state = selective_scan_fn(
|
| 213 |
+
hidden_states,
|
| 214 |
+
discrete_time_step,
|
| 215 |
+
A,
|
| 216 |
+
B.transpose(1, 2),
|
| 217 |
+
C.transpose(1, 2),
|
| 218 |
+
self.D.float(),
|
| 219 |
+
gate,
|
| 220 |
+
time_proj_bias,
|
| 221 |
+
delta_softplus=True,
|
| 222 |
+
return_last_state=True,
|
| 223 |
+
)
|
| 224 |
+
if ssm_state is not None and cache_params is not None:
|
| 225 |
+
cache_params.update_ssm_state(self.layer_idx, ssm_state)
|
| 226 |
+
|
| 227 |
+
# 4. Final linear projection
|
| 228 |
+
contextualized_states = self.out_proj(scan_outputs.transpose(1, 2))
|
| 229 |
+
return contextualized_states
|
| 230 |
+
|
| 231 |
+
def slow_forward(
|
| 232 |
+
self,
|
| 233 |
+
input_states,
|
| 234 |
+
cache_params: Optional[MambaCache] = None,
|
| 235 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 236 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 237 |
+
**kwargs: Unpack[Dict]
|
| 238 |
+
):
|
| 239 |
+
batch_size, seq_len, _ = input_states.shape
|
| 240 |
+
dtype = input_states.dtype
|
| 241 |
+
# 1. Gated MLP's linear projection
|
| 242 |
+
# [batch, 2 * intermediate_size, seq_len]
|
| 243 |
+
projected_states = self.in_proj(input_states).transpose(1, 2)
|
| 244 |
+
hidden_states, gate = projected_states.chunk(2, dim=1)
|
| 245 |
+
|
| 246 |
+
if attention_mask is not None:
|
| 247 |
+
hidden_states = hidden_states * attention_mask.unsqueeze(1)
|
| 248 |
+
|
| 249 |
+
# 2. Convolution sequence transformation
|
| 250 |
+
if cache_params is not None:
|
| 251 |
+
ssm_state = cache_params.ssm_states[self.layer_idx].clone()
|
| 252 |
+
ssm_state = ssm_state.to(hidden_states.device)
|
| 253 |
+
# use `cache_position.shape[0]` to check whether we are in prefill
|
| 254 |
+
# stage, it's equivalent to check `cache_position[0] == 0`, which
|
| 255 |
+
# breaks dynamo fullgraph constraints
|
| 256 |
+
if cache_position.shape[0] == self.conv_kernel_size:
|
| 257 |
+
conv_state = nn.functional.pad(
|
| 258 |
+
hidden_states,
|
| 259 |
+
(self.conv_kernel_size - hidden_states.shape[-1], 0)
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
cache_params.update_conv_state(self.layer_idx, conv_state, cache_position)
|
| 263 |
+
# [batch, intermediate_size, seq_len]
|
| 264 |
+
hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
|
| 265 |
+
else:
|
| 266 |
+
conv_state = cache_params.update_conv_state(self.layer_idx, hidden_states, cache_position)
|
| 267 |
+
hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
|
| 268 |
+
if self.use_conv_bias:
|
| 269 |
+
hidden_states += self.conv1d.bias
|
| 270 |
+
# [batch, intermediate_size, 1] : decoding
|
| 271 |
+
hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1)
|
| 272 |
+
else:
|
| 273 |
+
ssm_state = torch.zeros(
|
| 274 |
+
(batch_size, self.intermediate_size, self.ssm_state_size),
|
| 275 |
+
device=hidden_states.device, dtype=dtype
|
| 276 |
+
)
|
| 277 |
+
# [batch, intermediate_size, seq_len]
|
| 278 |
+
hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
|
| 279 |
+
|
| 280 |
+
if attention_mask is not None:
|
| 281 |
+
hidden_states = hidden_states * attention_mask.unsqueeze(1)
|
| 282 |
+
|
| 283 |
+
# 3. State Space Model sequence transformation
|
| 284 |
+
# 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2]
|
| 285 |
+
ssm_parameters = self.x_proj(hidden_states.transpose(1, 2))
|
| 286 |
+
time_step, B, C = torch.split(
|
| 287 |
+
ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
|
| 288 |
+
)
|
| 289 |
+
# [batch, seq_len, intermediate_size]
|
| 290 |
+
discrete_time_step = self.dt_proj(time_step)
|
| 291 |
+
# [batch, intermediate_size, seq_len]
|
| 292 |
+
discrete_time_step = nn.functional.softplus(discrete_time_step).transpose(1, 2)
|
| 293 |
+
|
| 294 |
+
# 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM)
|
| 295 |
+
# [intermediate_size, ssm_state_size]
|
| 296 |
+
A = -torch.exp(self.A_log.float())
|
| 297 |
+
# [batch, intermediate_size, seq_len, ssm_state_size]
|
| 298 |
+
discrete_A = torch.exp(A[None, :, None, :] * discrete_time_step[:, :, :, None])
|
| 299 |
+
# [batch, intermediate_size, seq_len, ssm_state_size]
|
| 300 |
+
discrete_B = discrete_time_step[:, :, :, None] * B[:, None, :, :].float()
|
| 301 |
+
deltaB_u = discrete_B * hidden_states[:, :, :, None].float()
|
| 302 |
+
|
| 303 |
+
# 3.c perform the recurrence y ← SSM(A, B, C)(x)
|
| 304 |
+
scan_outputs = []
|
| 305 |
+
for i in range(seq_len):
|
| 306 |
+
# [batch, intermediade_size, ssm_state]
|
| 307 |
+
ssm_state = discrete_A[:, :, i, :] * ssm_state + deltaB_u[:, :, i, :]
|
| 308 |
+
# [batch, intermediade_size, 1]
|
| 309 |
+
scan_output = torch.matmul(ssm_state.to(dtype), C[:, i, :].unsqueeze(-1))
|
| 310 |
+
scan_outputs.append(scan_output[:, :, 0])
|
| 311 |
+
# [batch, seq_len, intermediade_size]
|
| 312 |
+
scan_output = torch.stack(scan_outputs, dim=-1)
|
| 313 |
+
scan_output = scan_output + (hidden_states * self.D[None, :, None])
|
| 314 |
+
scan_output = (scan_output * self.act(gate))
|
| 315 |
+
|
| 316 |
+
if cache_params is not None:
|
| 317 |
+
cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
|
| 318 |
+
|
| 319 |
+
# 4. Final linear projection
|
| 320 |
+
# [batch, seq_len, hidden_size]
|
| 321 |
+
contextualized_states = self.out_proj(scan_output.transpose(1, 2))
|
| 322 |
+
return contextualized_states
|
| 323 |
+
# fmt: on
|
| 324 |
+
|
| 325 |
+
def forward(
|
| 326 |
+
self,
|
| 327 |
+
hidden_states,
|
| 328 |
+
cache_params: Optional[MambaCache] = None,
|
| 329 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 330 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 331 |
+
**kwargs: Unpack[Dict]
|
| 332 |
+
):
|
| 333 |
+
if is_fast_path_available and "cuda" in self.x_proj.weight.device.type:
|
| 334 |
+
return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask, **kwargs)
|
| 335 |
+
return self.slow_forward(hidden_states, cache_params, cache_position, attention_mask, **kwargs)
|
mamba2.py
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 transformers.utils import logging
|
| 12 |
+
|
| 13 |
+
from fla.modules.activations import ACT2FN
|
| 14 |
+
from fla.modules.layernorm_gated import RMSNormGated
|
| 15 |
+
|
| 16 |
+
with warnings.catch_warnings():
|
| 17 |
+
warnings.simplefilter('ignore')
|
| 18 |
+
try:
|
| 19 |
+
from mamba_ssm.ops.triton.selective_state_update import selective_state_update
|
| 20 |
+
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
|
| 21 |
+
except ImportError:
|
| 22 |
+
selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined = None, None, None
|
| 23 |
+
try:
|
| 24 |
+
from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
|
| 25 |
+
except ImportError:
|
| 26 |
+
causal_conv1d_update, causal_conv1d_fn = None, None
|
| 27 |
+
is_fast_path_available = selective_state_update is not None
|
| 28 |
+
|
| 29 |
+
if TYPE_CHECKING:
|
| 30 |
+
from fla.models.mamba2.modeling_mamba2 import Mamba2Cache
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def apply_mask_to_padding_states(hidden_states, attention_mask):
|
| 36 |
+
"""
|
| 37 |
+
Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 38 |
+
"""
|
| 39 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 40 |
+
dtype = hidden_states.dtype
|
| 41 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 42 |
+
|
| 43 |
+
return hidden_states
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
|
| 47 |
+
"""
|
| 48 |
+
Padding x tensor with `pad_size` on the seq_len dim (dim=1)
|
| 49 |
+
|
| 50 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 51 |
+
"""
|
| 52 |
+
pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
|
| 53 |
+
|
| 54 |
+
return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def reshape_into_chunks(input_tensor, pad_size, chunk_size):
|
| 58 |
+
"""
|
| 59 |
+
Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
|
| 60 |
+
simultaneously splitting it into chunk sequences.
|
| 61 |
+
|
| 62 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 63 |
+
"""
|
| 64 |
+
# [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
|
| 65 |
+
input_tensor = pad_tensor_by_size(input_tensor, pad_size)
|
| 66 |
+
|
| 67 |
+
if len(input_tensor.shape) == 3:
|
| 68 |
+
# [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
|
| 69 |
+
return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
|
| 70 |
+
else:
|
| 71 |
+
# [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] ->
|
| 72 |
+
# [bsz, -1, chunk_size, num_heads, head_dim or state_size]
|
| 73 |
+
return input_tensor.reshape(
|
| 74 |
+
input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def segment_sum(input_tensor):
|
| 79 |
+
"""
|
| 80 |
+
More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
|
| 81 |
+
"""
|
| 82 |
+
chunk_size = input_tensor.size(-1)
|
| 83 |
+
# 1. expand input tensor to have an additional dimension and repeat along that dimension
|
| 84 |
+
# [..., chunk_size] -> [..., chunk_size, chunk_size]
|
| 85 |
+
input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
|
| 86 |
+
# 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
|
| 87 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
|
| 88 |
+
input_tensor = input_tensor.masked_fill(~mask, 0)
|
| 89 |
+
# 3. compute actual cumsum
|
| 90 |
+
tensor_segsum = torch.cumsum(input_tensor, dim=-2)
|
| 91 |
+
|
| 92 |
+
# 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
|
| 93 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
|
| 94 |
+
tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
|
| 95 |
+
return tensor_segsum
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class Mamba2(nn.Module):
|
| 99 |
+
"""
|
| 100 |
+
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
|
| 101 |
+
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
|
| 102 |
+
∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
|
| 103 |
+
and is why Mamba is called **selective** state spaces)
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
num_heads: int,
|
| 109 |
+
head_dim: int = 64,
|
| 110 |
+
hidden_size: int = 2048,
|
| 111 |
+
state_size: int = 128,
|
| 112 |
+
expand: int = 2,
|
| 113 |
+
n_groups: int = 1,
|
| 114 |
+
conv_kernel: int = 4,
|
| 115 |
+
use_conv_bias: bool = False,
|
| 116 |
+
hidden_act: str = "silu",
|
| 117 |
+
rms_norm: bool = True,
|
| 118 |
+
chunk_size: int = 256,
|
| 119 |
+
time_step_rank: float = 256,
|
| 120 |
+
time_step_limit: Tuple[float, float] = (0.0, float("inf")),
|
| 121 |
+
time_step_min: float = 0.001,
|
| 122 |
+
time_step_max: float = 0.1,
|
| 123 |
+
use_bias: bool = True,
|
| 124 |
+
norm_eps: float = 1e-5,
|
| 125 |
+
layer_idx: int = None,
|
| 126 |
+
backend: str = "cuda",
|
| 127 |
+
) -> Mamba2:
|
| 128 |
+
super().__init__()
|
| 129 |
+
|
| 130 |
+
self.num_heads = num_heads
|
| 131 |
+
self.head_dim = head_dim
|
| 132 |
+
self.hidden_size = hidden_size
|
| 133 |
+
self.ssm_state_size = state_size
|
| 134 |
+
self.expand = expand
|
| 135 |
+
self.intermediate_size = int(expand * hidden_size)
|
| 136 |
+
self.n_groups = n_groups
|
| 137 |
+
|
| 138 |
+
self.conv_kernel_size = conv_kernel
|
| 139 |
+
self.use_conv_bias = use_conv_bias
|
| 140 |
+
self.activation = hidden_act
|
| 141 |
+
self.act = ACT2FN[hidden_act]
|
| 142 |
+
|
| 143 |
+
self.rms_norm = rms_norm
|
| 144 |
+
self.norm_eps = norm_eps
|
| 145 |
+
|
| 146 |
+
self.chunk_size = chunk_size
|
| 147 |
+
|
| 148 |
+
self.time_step_rank = int(time_step_rank)
|
| 149 |
+
self.time_step_limit = time_step_limit
|
| 150 |
+
self.time_step_min = time_step_min
|
| 151 |
+
self.time_step_max = time_step_max
|
| 152 |
+
|
| 153 |
+
self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
|
| 154 |
+
self.conv1d = nn.Conv1d(
|
| 155 |
+
in_channels=self.conv_dim,
|
| 156 |
+
out_channels=self.conv_dim,
|
| 157 |
+
bias=use_conv_bias,
|
| 158 |
+
kernel_size=conv_kernel,
|
| 159 |
+
groups=self.conv_dim,
|
| 160 |
+
padding=conv_kernel - 1,
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# projection of the input hidden states
|
| 164 |
+
projection_size = self.intermediate_size + self.conv_dim + self.num_heads
|
| 165 |
+
self.in_proj = nn.Linear(
|
| 166 |
+
self.hidden_size,
|
| 167 |
+
projection_size,
|
| 168 |
+
bias=use_bias,
|
| 169 |
+
)
|
| 170 |
+
# selective projection used to make dt, B and C input dependant
|
| 171 |
+
|
| 172 |
+
# time step projection (discretization)
|
| 173 |
+
# instantiate once and copy inv_dt in init_weights of PretrainedModel
|
| 174 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
|
| 175 |
+
|
| 176 |
+
# S4D real initialization. These are not discretized!
|
| 177 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 178 |
+
A = torch.arange(1, self.num_heads + 1)
|
| 179 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 180 |
+
self.A_log._no_weight_decay = True
|
| 181 |
+
self.norm = RMSNormGated(
|
| 182 |
+
self.intermediate_size, eps=self.norm_eps, norm_before_gate=False
|
| 183 |
+
)
|
| 184 |
+
self.D = nn.Parameter(torch.ones(self.num_heads))
|
| 185 |
+
self.D._no_weight_decay = True
|
| 186 |
+
|
| 187 |
+
self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=use_bias)
|
| 188 |
+
self.use_bias = use_bias
|
| 189 |
+
|
| 190 |
+
self.layer_idx = layer_idx
|
| 191 |
+
|
| 192 |
+
if not is_fast_path_available:
|
| 193 |
+
logger.warning_once(
|
| 194 |
+
"The fast path is not available because one of "
|
| 195 |
+
"`(selective_state_update)` is None. "
|
| 196 |
+
"Falling back to the naive implementation. "
|
| 197 |
+
"To install follow https://github.com/state-spaces/mamba/#installation"
|
| 198 |
+
)
|
| 199 |
+
import os
|
| 200 |
+
backend = os.environ.get('FLA_CONV_BACKEND', backend)
|
| 201 |
+
assert backend in ['cuda', 'triton'], f"Unsupported backend: {backend}"
|
| 202 |
+
if backend == 'cuda' and causal_conv1d_fn is None:
|
| 203 |
+
logger.warning_once(
|
| 204 |
+
"The CUDA backend is not available because `causal_conv1d` is None. "
|
| 205 |
+
"Falling back to the Triton backend. "
|
| 206 |
+
"To install follow https://github.com/Dao-AILab/causal-conv1d"
|
| 207 |
+
)
|
| 208 |
+
backend = 'triton'
|
| 209 |
+
if backend == 'triton':
|
| 210 |
+
from fla.modules.convolution import causal_conv1d as causal_conv1d_triton
|
| 211 |
+
from fla.modules.convolution import causal_conv1d_update as causal_conv1d_update_triton
|
| 212 |
+
self.causal_conv1d_fn = causal_conv1d_triton
|
| 213 |
+
self.causal_conv1d_update = causal_conv1d_update_triton
|
| 214 |
+
logger.warning(
|
| 215 |
+
"Mamba2 does not recommend using Triton's conv1d backend, "
|
| 216 |
+
"as it is untested and may contain bugs."
|
| 217 |
+
)
|
| 218 |
+
else:
|
| 219 |
+
self.causal_conv1d_fn = causal_conv1d_fn
|
| 220 |
+
self.causal_conv1d_update = causal_conv1d_update
|
| 221 |
+
self.backend = backend
|
| 222 |
+
|
| 223 |
+
def cuda_kernels_forward(
|
| 224 |
+
self,
|
| 225 |
+
hidden_states: torch.Tensor,
|
| 226 |
+
cache_params: Optional[Mamba2Cache] = None,
|
| 227 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 228 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 229 |
+
):
|
| 230 |
+
# 1. Gated MLP's linear projection
|
| 231 |
+
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
|
| 232 |
+
projected_states = self.in_proj(hidden_states)
|
| 233 |
+
|
| 234 |
+
# Set up dimensions for reshapes later
|
| 235 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 236 |
+
groups_time_state_size = self.n_groups * self.ssm_state_size
|
| 237 |
+
d_mlp = (
|
| 238 |
+
projected_states.shape[-1]
|
| 239 |
+
- 2 * self.intermediate_size
|
| 240 |
+
- 2 * self.n_groups * self.ssm_state_size
|
| 241 |
+
- self.num_heads
|
| 242 |
+
) // 2
|
| 243 |
+
|
| 244 |
+
# Single step calculations via cache
|
| 245 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 246 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
|
| 247 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
# 2. Convolution sequence transformation
|
| 251 |
+
hidden_states_B_C = self.causal_conv1d_update(
|
| 252 |
+
hidden_states_B_C.contiguous(),
|
| 253 |
+
cache_params.conv_states[self.layer_idx],
|
| 254 |
+
self.conv1d.weight.squeeze(1),
|
| 255 |
+
self.conv1d.bias,
|
| 256 |
+
self.activation,
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
hidden_states, B, C = torch.split(
|
| 260 |
+
hidden_states_B_C,
|
| 261 |
+
[
|
| 262 |
+
self.intermediate_size,
|
| 263 |
+
groups_time_state_size,
|
| 264 |
+
groups_time_state_size,
|
| 265 |
+
],
|
| 266 |
+
dim=-1,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
# 3. SSM transformation
|
| 270 |
+
A = -torch.exp(self.A_log.float()) # (nheads,)
|
| 271 |
+
A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 272 |
+
dt = dt[:, :, None].expand(-1, -1, self.head_dim)
|
| 273 |
+
dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
|
| 274 |
+
D = self.D[:, None, ...].expand(-1, self.head_dim)
|
| 275 |
+
B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
|
| 276 |
+
C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
|
| 277 |
+
hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
|
| 278 |
+
|
| 279 |
+
hidden_states = selective_state_update(
|
| 280 |
+
cache_params.ssm_states[self.layer_idx],
|
| 281 |
+
hidden_states_reshaped,
|
| 282 |
+
dt,
|
| 283 |
+
A,
|
| 284 |
+
B,
|
| 285 |
+
C,
|
| 286 |
+
D,
|
| 287 |
+
z=None,
|
| 288 |
+
dt_bias=dt_bias,
|
| 289 |
+
dt_softplus=True,
|
| 290 |
+
)
|
| 291 |
+
hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
|
| 292 |
+
hidden_states = self.norm(hidden_states, gate)
|
| 293 |
+
|
| 294 |
+
# 4. Final linear projection
|
| 295 |
+
out = self.out_proj(hidden_states)[:, None, ...]
|
| 296 |
+
|
| 297 |
+
# Fused calculations or step by step if no initialized cache is found
|
| 298 |
+
else:
|
| 299 |
+
A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
|
| 300 |
+
dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
|
| 301 |
+
|
| 302 |
+
# 2-4. Fused kernel for conv1d, SSM, and the final projection
|
| 303 |
+
if self.training and cache_params is None:
|
| 304 |
+
out = mamba_split_conv1d_scan_combined(
|
| 305 |
+
projected_states,
|
| 306 |
+
self.conv1d.weight.squeeze(1),
|
| 307 |
+
self.conv1d.bias,
|
| 308 |
+
self.dt_bias,
|
| 309 |
+
A,
|
| 310 |
+
D=self.D,
|
| 311 |
+
chunk_size=self.chunk_size,
|
| 312 |
+
seq_idx=None, # was seq_idx
|
| 313 |
+
activation=self.activation,
|
| 314 |
+
rmsnorm_weight=self.norm.weight,
|
| 315 |
+
rmsnorm_eps=self.norm.eps,
|
| 316 |
+
outproj_weight=self.out_proj.weight,
|
| 317 |
+
outproj_bias=self.out_proj.bias,
|
| 318 |
+
headdim=self.head_dim,
|
| 319 |
+
ngroups=self.n_groups,
|
| 320 |
+
norm_before_gate=False,
|
| 321 |
+
return_final_states=False,
|
| 322 |
+
**dt_limit_kwargs,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
else:
|
| 326 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.split(
|
| 327 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
# 2. Convolution sequence transformation
|
| 331 |
+
# Init cache
|
| 332 |
+
if cache_params is not None:
|
| 333 |
+
hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
|
| 334 |
+
conv_states = nn.functional.pad(
|
| 335 |
+
hidden_states_B_C_transposed,
|
| 336 |
+
(cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
|
| 337 |
+
)
|
| 338 |
+
cache_params.update_conv_state(
|
| 339 |
+
layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
if self.activation not in ["silu", "swish"]:
|
| 343 |
+
hidden_states_B_C = self.act(
|
| 344 |
+
self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
|
| 345 |
+
)
|
| 346 |
+
else:
|
| 347 |
+
_conv1d_output = self.causal_conv1d_fn(
|
| 348 |
+
x=hidden_states_B_C.transpose(1, 2).contiguous(),
|
| 349 |
+
weight=self.conv1d.weight.squeeze(1),
|
| 350 |
+
bias=self.conv1d.bias,
|
| 351 |
+
activation=self.activation,
|
| 352 |
+
)
|
| 353 |
+
if self.backend == 'cuda':
|
| 354 |
+
hidden_states_B_C = _conv1d_output
|
| 355 |
+
hidden_states_B_C = hidden_states_B_C.transpose(1, 2)
|
| 356 |
+
elif self.backend == 'triton':
|
| 357 |
+
hidden_states_B_C, _ = _conv1d_output
|
| 358 |
+
hidden_states_B_C = hidden_states_B_C.transpose(1, 2).contiguous()
|
| 359 |
+
else:
|
| 360 |
+
raise ValueError(f"Unsupported backend: {self.backend}")
|
| 361 |
+
|
| 362 |
+
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
|
| 363 |
+
hidden_states, B, C = torch.split(
|
| 364 |
+
hidden_states_B_C,
|
| 365 |
+
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
| 366 |
+
dim=-1,
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
# 3. SSM transformation
|
| 370 |
+
scan_output, ssm_state = mamba_chunk_scan_combined(
|
| 371 |
+
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
|
| 372 |
+
dt,
|
| 373 |
+
A,
|
| 374 |
+
B.view(batch_size, seq_len, self.n_groups, -1),
|
| 375 |
+
C.view(batch_size, seq_len, self.n_groups, -1),
|
| 376 |
+
chunk_size=self.chunk_size,
|
| 377 |
+
D=self.D,
|
| 378 |
+
z=None,
|
| 379 |
+
seq_idx=None,
|
| 380 |
+
return_final_states=True,
|
| 381 |
+
dt_bias=self.dt_bias,
|
| 382 |
+
dt_softplus=True,
|
| 383 |
+
**dt_limit_kwargs,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
# Init cache
|
| 387 |
+
if ssm_state is not None and cache_params is not None:
|
| 388 |
+
cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
|
| 389 |
+
|
| 390 |
+
scan_output = scan_output.view(batch_size, seq_len, -1)
|
| 391 |
+
# Multiply "gate" branch and apply extra normalization layer
|
| 392 |
+
scan_output = self.norm(scan_output, gate)
|
| 393 |
+
|
| 394 |
+
# 4. Final linear projection
|
| 395 |
+
out = self.out_proj(scan_output)
|
| 396 |
+
return out
|
| 397 |
+
|
| 398 |
+
# fmt: off
|
| 399 |
+
def torch_forward(
|
| 400 |
+
self,
|
| 401 |
+
input_states,
|
| 402 |
+
cache_params: Optional[Mamba2Cache] = None,
|
| 403 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 404 |
+
attention_mask: Optional[torch.Tensor] = None
|
| 405 |
+
):
|
| 406 |
+
batch_size, seq_len, _ = input_states.shape
|
| 407 |
+
dtype = input_states.dtype
|
| 408 |
+
|
| 409 |
+
# 1. Gated MLP's linear projection
|
| 410 |
+
input_states = apply_mask_to_padding_states(input_states, attention_mask)
|
| 411 |
+
projected_states = self.in_proj(input_states)
|
| 412 |
+
d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size -
|
| 413 |
+
2 * self.n_groups * self.ssm_state_size - self.num_heads) // 2
|
| 414 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.split(
|
| 415 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
# 2. Convolution sequence transformation
|
| 419 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 420 |
+
cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
|
| 421 |
+
|
| 422 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 423 |
+
conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
|
| 424 |
+
|
| 425 |
+
hidden_states_B_C = torch.sum(
|
| 426 |
+
conv_states * self.conv1d.weight.squeeze(1), dim=-1
|
| 427 |
+
)
|
| 428 |
+
if self.use_conv_bias:
|
| 429 |
+
hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
|
| 430 |
+
hidden_states_B_C = self.act(hidden_states_B_C)
|
| 431 |
+
else:
|
| 432 |
+
# Init cache
|
| 433 |
+
if cache_params is not None:
|
| 434 |
+
hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
|
| 435 |
+
conv_states = nn.functional.pad(
|
| 436 |
+
hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
|
| 437 |
+
)
|
| 438 |
+
cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
|
| 439 |
+
|
| 440 |
+
hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
|
| 441 |
+
|
| 442 |
+
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
|
| 443 |
+
hidden_states, B, C = torch.split(
|
| 444 |
+
hidden_states_B_C,
|
| 445 |
+
[self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
|
| 446 |
+
dim=-1
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
# 3. SSM transformation
|
| 450 |
+
A = -torch.exp(self.A_log.float()) # [num_heads]
|
| 451 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 452 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 453 |
+
cache_device = cache_params.ssm_states.device
|
| 454 |
+
|
| 455 |
+
# Note: there is no need to pad parameter matrices here, as there is just one new token
|
| 456 |
+
# for batched generation
|
| 457 |
+
dt = dt[:, 0, :][:, None, ...]
|
| 458 |
+
dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
|
| 459 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 460 |
+
dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
|
| 461 |
+
|
| 462 |
+
dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
|
| 463 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 464 |
+
A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 465 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 466 |
+
dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
|
| 467 |
+
|
| 468 |
+
# Discretize B
|
| 469 |
+
# [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
|
| 470 |
+
# -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
|
| 471 |
+
B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 472 |
+
B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
|
| 473 |
+
B = B.reshape(batch_size, -1, B.shape[-1])
|
| 474 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 475 |
+
dB = dt[..., None] * B[..., None, :]
|
| 476 |
+
|
| 477 |
+
# Discretize x into dB
|
| 478 |
+
# [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
|
| 479 |
+
hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
|
| 480 |
+
dBx = (dB * hidden_states[..., None]).to(device=cache_device)
|
| 481 |
+
|
| 482 |
+
# State calculation
|
| 483 |
+
cache_params.update_ssm_state(
|
| 484 |
+
layer_idx=self.layer_idx,
|
| 485 |
+
new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
# Subsequent output
|
| 489 |
+
# [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
|
| 490 |
+
C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 491 |
+
C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
|
| 492 |
+
C = C.reshape(batch_size, -1, C.shape[-1])
|
| 493 |
+
# [bsz, num_heads, head_dim]
|
| 494 |
+
|
| 495 |
+
ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
|
| 496 |
+
# Reshape ssm_states to merge the first two dimensions
|
| 497 |
+
# Shape: [b*h, d, n]
|
| 498 |
+
ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size)
|
| 499 |
+
C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
|
| 500 |
+
y = torch.bmm(ssm_states_reshaped, C_reshaped)
|
| 501 |
+
y = y.view(batch_size, self.num_heads, self.head_dim)
|
| 502 |
+
|
| 503 |
+
# D skip connection
|
| 504 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 505 |
+
D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
|
| 506 |
+
y = (y + hidden_states * D).to(y.dtype)
|
| 507 |
+
|
| 508 |
+
# [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
|
| 509 |
+
y = y.reshape(batch_size, -1)[:, None, ...]
|
| 510 |
+
else:
|
| 511 |
+
# begin ssd naive implementation without einsums
|
| 512 |
+
dt = nn.functional.softplus(dt + self.dt_bias)
|
| 513 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 514 |
+
hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
|
| 515 |
+
B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 516 |
+
C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 517 |
+
B = B.repeat(1, 1, self.num_heads // self.n_groups, 1)
|
| 518 |
+
C = C.repeat(1, 1, self.num_heads // self.n_groups, 1)
|
| 519 |
+
pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
|
| 520 |
+
|
| 521 |
+
D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
|
| 522 |
+
|
| 523 |
+
# Discretize x and A
|
| 524 |
+
hidden_states = hidden_states * dt[..., None]
|
| 525 |
+
A = A.to(hidden_states.dtype) * dt
|
| 526 |
+
|
| 527 |
+
# Rearrange into blocks/chunks
|
| 528 |
+
hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
|
| 529 |
+
|
| 530 |
+
# [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
|
| 531 |
+
A = A.permute(0, 3, 1, 2)
|
| 532 |
+
A_cumsum = torch.cumsum(A, dim=-1)
|
| 533 |
+
|
| 534 |
+
# 1. Compute the output for each intra-chunk (diagonal blocks)
|
| 535 |
+
# This is the analog of a causal mask
|
| 536 |
+
L = torch.exp(segment_sum(A))
|
| 537 |
+
|
| 538 |
+
# Contraction of C and B to get G (attention-weights like)
|
| 539 |
+
# shape: (b, c, l, s, h, n)
|
| 540 |
+
G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :]
|
| 541 |
+
G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
|
| 542 |
+
|
| 543 |
+
# Compute M, equivalent to applying attention mask to weights
|
| 544 |
+
M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
|
| 545 |
+
M = M_intermediate.sum(dim=-1)
|
| 546 |
+
|
| 547 |
+
# Compute Y_diag (apply to values)
|
| 548 |
+
Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
|
| 549 |
+
|
| 550 |
+
# 2. Compute the state for each intra-chunk
|
| 551 |
+
# (right term of low-rank factorization of off-diagonal blocks; B terms)
|
| 552 |
+
decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
|
| 553 |
+
B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
|
| 554 |
+
states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
|
| 555 |
+
|
| 556 |
+
# 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
|
| 557 |
+
# (middle term of factorization of off-diag blocks; A terms)
|
| 558 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 559 |
+
previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
|
| 560 |
+
else:
|
| 561 |
+
previous_states = torch.zeros_like(states[:, :1])
|
| 562 |
+
states = torch.cat([previous_states, states], dim=1)
|
| 563 |
+
decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
|
| 564 |
+
decay_chunk = decay_chunk.transpose(1, 3)
|
| 565 |
+
new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
|
| 566 |
+
states, ssm_state = new_states[:, :-1], new_states[:, -1]
|
| 567 |
+
|
| 568 |
+
# 4. Compute state -> output conversion per chunk
|
| 569 |
+
# (left term of low-rank factorization of off-diagonal blocks; C terms)
|
| 570 |
+
state_decay_out = torch.exp(A_cumsum)
|
| 571 |
+
C_times_states = (C[..., None, :] * states[:, :, None, ...])
|
| 572 |
+
state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
|
| 573 |
+
Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
|
| 574 |
+
|
| 575 |
+
# Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
|
| 576 |
+
y = Y_diag + Y_off
|
| 577 |
+
# [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
|
| 578 |
+
y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
|
| 579 |
+
|
| 580 |
+
y = y + D_residual
|
| 581 |
+
# Cutting off padded chunks
|
| 582 |
+
if pad_size > 0:
|
| 583 |
+
y = y[:, :seq_len, :, :]
|
| 584 |
+
y = y.reshape(batch_size, seq_len, -1)
|
| 585 |
+
|
| 586 |
+
# Init cache
|
| 587 |
+
if ssm_state is not None and cache_params is not None:
|
| 588 |
+
cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
|
| 589 |
+
|
| 590 |
+
scan_output = self.norm(y, gate)
|
| 591 |
+
|
| 592 |
+
# end ssd naive
|
| 593 |
+
|
| 594 |
+
# 4. Final linear projection
|
| 595 |
+
contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
|
| 596 |
+
return contextualized_states
|
| 597 |
+
# fmt: on
|
| 598 |
+
|
| 599 |
+
def forward(
|
| 600 |
+
self,
|
| 601 |
+
hidden_states,
|
| 602 |
+
cache_params: Optional[Mamba2Cache] = None,
|
| 603 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 604 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 605 |
+
):
|
| 606 |
+
if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
|
| 607 |
+
return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
|
| 608 |
+
dtype = hidden_states.dtype
|
| 609 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 610 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 611 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 612 |
+
|
| 613 |
+
return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
|
mask_gdn.py
ADDED
|
@@ -0,0 +1,1058 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from einops import rearrange, repeat
|
| 10 |
+
from ..modules import FusedRMSNormSwishGate, RMSNorm
|
| 11 |
+
from fla.modules import ShortConvolution
|
| 12 |
+
import torch.nn.init as init
|
| 13 |
+
import math
|
| 14 |
+
from ..modules.l2norm import l2norm
|
| 15 |
+
from einops import rearrange
|
| 16 |
+
from fla.models.utils import Cache
|
| 17 |
+
from transformers.processing_utils import Unpack
|
| 18 |
+
import math
|
| 19 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 20 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 21 |
+
# from ..modules import RotaryEmbedding
|
| 22 |
+
# from ..ops.gla import chunk_gla,fused_recurrent_gla
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def simple_norm(x):
|
| 26 |
+
return (F.normalize(x, dim=-1) * x.shape[-1] ** 0.5).to(x)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# @torch.jit.script
|
| 30 |
+
def elu_p1(x):
|
| 31 |
+
return (F.elu(x, 1., False) + 1.).to(x)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# @torch.jit.script
|
| 35 |
+
def sum_norm(x):
|
| 36 |
+
return (x / x.sum(-1, keepdim=True)).to(x)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# @torch.jit.script
|
| 40 |
+
def elu_norm(x):
|
| 41 |
+
dtype = x.dtype
|
| 42 |
+
x = F.elu(x, 1., False) + 1.
|
| 43 |
+
return (x / x.sum(-1, keepdim=True)).to(dtype)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# from ..ops.mask_gated_delta_rule import mask_gated_chunk_delta_rule
|
| 47 |
+
# class mask_gdn(nn.Module):
|
| 48 |
+
# def __init__(
|
| 49 |
+
# self,
|
| 50 |
+
# d_model: int = None,
|
| 51 |
+
# hidden_size: int = 1024,
|
| 52 |
+
# expand_k: float = 1.0,
|
| 53 |
+
# expand_v: float = 1.0,
|
| 54 |
+
# num_heads: int = 4,
|
| 55 |
+
# mode: str = 'chunk',
|
| 56 |
+
# chunk_size: int = 64,
|
| 57 |
+
# use_beta: bool = True,
|
| 58 |
+
# use_gate: bool = False,
|
| 59 |
+
# use_output_norm: bool = True,
|
| 60 |
+
# use_elu: bool = False,
|
| 61 |
+
# use_short_conv: bool = True,
|
| 62 |
+
# conv_size: int = 4,
|
| 63 |
+
# conv_bias: bool = False,
|
| 64 |
+
# layer_idx: int = None,
|
| 65 |
+
# qk_activation: str = 'silu',
|
| 66 |
+
# qk_norm: str = 'l2',
|
| 67 |
+
# norm_first: bool = False,
|
| 68 |
+
# norm_eps: float = 1e-6,
|
| 69 |
+
# ratio :int = 2,
|
| 70 |
+
# topk : int = 1 ,
|
| 71 |
+
# **kwargs
|
| 72 |
+
# ) :
|
| 73 |
+
# super().__init__()
|
| 74 |
+
|
| 75 |
+
# self.mode = mode
|
| 76 |
+
# self.qk_activation = qk_activation
|
| 77 |
+
# self.qk_norm = qk_norm
|
| 78 |
+
|
| 79 |
+
# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 80 |
+
# assert self.qk_norm in ['l2', 'sum']
|
| 81 |
+
|
| 82 |
+
# if d_model is not None:
|
| 83 |
+
# hidden_size = d_model
|
| 84 |
+
# self.hidden_size = hidden_size
|
| 85 |
+
# self.expand_k = expand_k
|
| 86 |
+
# self.expand_v = expand_v
|
| 87 |
+
# self.num_heads = num_heads
|
| 88 |
+
# self.chunk_size = chunk_size
|
| 89 |
+
# self.use_gate = use_gate
|
| 90 |
+
# self.use_output_norm = use_output_norm
|
| 91 |
+
# self.use_short_conv = use_short_conv
|
| 92 |
+
# self.conv_size = conv_size
|
| 93 |
+
# self.conv_bias = conv_bias
|
| 94 |
+
|
| 95 |
+
# self.key_dim = int(hidden_size * expand_k)
|
| 96 |
+
# self.value_dim = int(hidden_size * expand_v)
|
| 97 |
+
# self.head_qk_dim = self.key_dim // num_heads
|
| 98 |
+
# self.head_v_dim = self.value_dim // num_heads
|
| 99 |
+
# self.norm_first = norm_first
|
| 100 |
+
# self.layer_idx = layer_idx
|
| 101 |
+
# self.top_k = topk
|
| 102 |
+
# self.silu = nn.SiLU()
|
| 103 |
+
# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 104 |
+
# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 105 |
+
# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 106 |
+
# if norm_first:
|
| 107 |
+
# self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 108 |
+
# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 109 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 110 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 111 |
+
# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 112 |
+
|
| 113 |
+
# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 114 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 115 |
+
# self.A_log._no_weight_decay = True
|
| 116 |
+
# # hard coded for now
|
| 117 |
+
# dt_min = 0.001
|
| 118 |
+
# dt_max = 0.1
|
| 119 |
+
# dt_init_floor = 1e-4
|
| 120 |
+
# dt = torch.exp(
|
| 121 |
+
# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 122 |
+
# + math.log(dt_min)
|
| 123 |
+
# )
|
| 124 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 125 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 126 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 127 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 128 |
+
# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 129 |
+
# # name.endswith("bias") in param_grouping.py
|
| 130 |
+
# self.dt_bias._no_weight_decay = True
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# self.use_beta = use_beta
|
| 134 |
+
# self.use_elu = use_elu
|
| 135 |
+
# if self.use_beta:
|
| 136 |
+
# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 137 |
+
# if use_short_conv:
|
| 138 |
+
# self.conv_size = conv_size
|
| 139 |
+
# self.q_conv1d = ShortConvolution(self.key_dim,
|
| 140 |
+
# conv_size,
|
| 141 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 142 |
+
# self.k_conv1d = ShortConvolution(self.key_dim,
|
| 143 |
+
# conv_size,
|
| 144 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 145 |
+
# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 146 |
+
# if use_gate:
|
| 147 |
+
# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 148 |
+
# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 149 |
+
# else:
|
| 150 |
+
# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 151 |
+
# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 152 |
+
# r = self.r = 4
|
| 153 |
+
# self.mask = nn.Parameter(torch.empty([r,r],dtype=self.o_proj.weight.dtype),requires_grad=True)
|
| 154 |
+
# self.mask_requiregrad = True
|
| 155 |
+
# print('mask_gdn_learn_mask_qk_r4')
|
| 156 |
+
# init.kaiming_uniform_(self.mask, a=math.sqrt(5))
|
| 157 |
+
# assert self.head_qk_dim % r == 0
|
| 158 |
+
# self.apply(self._initialize_weights)
|
| 159 |
+
|
| 160 |
+
# def _initialize_weights(self, module: nn.Module):
|
| 161 |
+
# if getattr(module, "_is_hf_initialized", False):
|
| 162 |
+
# return
|
| 163 |
+
# if isinstance(module, nn.Linear):
|
| 164 |
+
# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 165 |
+
# if module.bias is not None:
|
| 166 |
+
# nn.init.zeros_(module.bias)
|
| 167 |
+
# module._is_hf_initialized = True
|
| 168 |
+
|
| 169 |
+
# def delta_rule_recurrence(self,q, k, v, beta, mask,initial_state=None,output_final_state=True):
|
| 170 |
+
# b, h, l, d_k = q.shape
|
| 171 |
+
# d_v = v.shape[-1]
|
| 172 |
+
# r = mask.shape[-1]
|
| 173 |
+
# o = torch.zeros_like(v)
|
| 174 |
+
# if initial_state == None:
|
| 175 |
+
# S = torch.zeros(b, h, d_k, d_v).to(v).float()
|
| 176 |
+
# else:
|
| 177 |
+
# S = initial_state
|
| 178 |
+
# q = q * (d_k ** -0.5)
|
| 179 |
+
# if beta.ndim < v.ndim:
|
| 180 |
+
# beta = beta[..., None]
|
| 181 |
+
# if self.training:
|
| 182 |
+
# for i in range(l):
|
| 183 |
+
# _k = k[:, :, i]
|
| 184 |
+
# _q = q[:, :, i]
|
| 185 |
+
# _v = v[:, :, i].clone()
|
| 186 |
+
# beta_i = beta[:, :, i]
|
| 187 |
+
# _v = _v * beta_i
|
| 188 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 189 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 190 |
+
# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt))
|
| 191 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 192 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 193 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2)
|
| 194 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
|
| 195 |
+
# return o,S
|
| 196 |
+
# else:
|
| 197 |
+
# for i in range(l):
|
| 198 |
+
# _k = k[:, :, i]
|
| 199 |
+
# _q = q[:, :, i]
|
| 200 |
+
# _v = v[:, :, i]
|
| 201 |
+
# beta_i = beta[:, :, i]
|
| 202 |
+
# _v = _v * beta_i
|
| 203 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 204 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 205 |
+
# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt))
|
| 206 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 207 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 208 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr.float(),S) + _k.unsqueeze(-1).float() * _v.unsqueeze(-2).float()
|
| 209 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype)
|
| 210 |
+
# return o,S
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# def forward(
|
| 214 |
+
# self,
|
| 215 |
+
# hidden_states: torch.Tensor,
|
| 216 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
| 217 |
+
# past_key_values: Optional[Cache] = None,
|
| 218 |
+
# use_cache: Optional[bool] = False,
|
| 219 |
+
# output_attentions: Optional[bool] = False,
|
| 220 |
+
# **kwargs
|
| 221 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 222 |
+
# # change to inference mode.
|
| 223 |
+
# mode = 'chunk'#'recurrent' if hidden_states.shape[1] < 64 else self.mode
|
| 224 |
+
# b,q_len,d = hidden_states.shape
|
| 225 |
+
# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states)
|
| 226 |
+
# if self.norm_first:
|
| 227 |
+
# hidden_states = self.norm(hidden_states)
|
| 228 |
+
|
| 229 |
+
# cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 230 |
+
# # if attention_mask is not None:
|
| 231 |
+
# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 232 |
+
# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 233 |
+
# last_state = None
|
| 234 |
+
# if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 235 |
+
# last_state = past_key_values[self.layer_idx]
|
| 236 |
+
# offset = past_key_values.get_seq_length()
|
| 237 |
+
# # if attention_mask is not None:
|
| 238 |
+
# # if attention_mask.shape[-1] != hidden_states.shape[-2]:
|
| 239 |
+
# # attention_mask = attention_mask[:, -1:]
|
| 240 |
+
# if self.use_short_conv:
|
| 241 |
+
# conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 242 |
+
# if last_state is not None:
|
| 243 |
+
# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 244 |
+
# q = self.q_proj(hidden_states)
|
| 245 |
+
# k = self.k_proj(hidden_states)
|
| 246 |
+
# v = self.v_proj(hidden_states)
|
| 247 |
+
# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 248 |
+
# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 249 |
+
# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 250 |
+
# else:
|
| 251 |
+
# q = self.q_proj(hidden_states)
|
| 252 |
+
# k = self.k_proj(hidden_states)
|
| 253 |
+
# v = self.v_proj(hidden_states)
|
| 254 |
+
# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v))
|
| 255 |
+
# if self.qk_activation != 'silu':
|
| 256 |
+
# if self.qk_activation == 'relu':
|
| 257 |
+
# q, k = q.relu(), k.relu()
|
| 258 |
+
# elif self.qk_activation == 'elu':
|
| 259 |
+
# q, k = elu_p1(q), elu_p1(k)
|
| 260 |
+
# elif self.qk_activation == 'identity':
|
| 261 |
+
# pass
|
| 262 |
+
# else:
|
| 263 |
+
# raise NotImplementedError
|
| 264 |
+
# if self.qk_norm is not None:
|
| 265 |
+
# if self.qk_norm == 'l2':
|
| 266 |
+
# q = l2_norm_fn(q)
|
| 267 |
+
# k = l2_norm_fn(k)
|
| 268 |
+
# elif self.qk_norm == 'sum':
|
| 269 |
+
# q = sum_norm(q).to(v)
|
| 270 |
+
# k = sum_norm(k).to(v)
|
| 271 |
+
# recurrent_state = None
|
| 272 |
+
# if last_state is not None:
|
| 273 |
+
# recurrent_state = last_state['recurrent_state']
|
| 274 |
+
|
| 275 |
+
# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid()
|
| 276 |
+
# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l')
|
| 277 |
+
|
| 278 |
+
# amask = torch.softmax(self.mask,dim=-1)#未必需要r r-1#适配2*2 4*4
|
| 279 |
+
# r = self.r
|
| 280 |
+
# target_matrix = torch.zeros(r, r, dtype=amask.dtype, device=k.device)
|
| 281 |
+
# mask = torch.ones(r,r, dtype=torch.bool, device=amask.device)
|
| 282 |
+
# target_matrix[mask] = amask.flatten()
|
| 283 |
+
|
| 284 |
+
# eye_mask = torch.eye(r, dtype=torch.bool, device=amask.device)
|
| 285 |
+
# target_matrix[eye_mask] = 1.0
|
| 286 |
+
|
| 287 |
+
# o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state,BT=32,output_final_state=True)
|
| 288 |
+
# o = rearrange(o,'b h l d-> b l h d')
|
| 289 |
+
# if past_key_values is not None:
|
| 290 |
+
# past_key_values.update(
|
| 291 |
+
# recurrent_state=(recurrent_state),
|
| 292 |
+
# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 293 |
+
# layer_idx=self.layer_idx,
|
| 294 |
+
# offset=q_len
|
| 295 |
+
# )
|
| 296 |
+
# if self.use_gate:
|
| 297 |
+
# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 298 |
+
# o = self.o_norm(o, g)
|
| 299 |
+
# else:
|
| 300 |
+
# o = self.o_norm(o)
|
| 301 |
+
# o = rearrange(o, 'b l h d -> b l (h d)')
|
| 302 |
+
# o = self.o_proj(o)
|
| 303 |
+
# return o, None, past_key_values,None
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# from ..ops.mask_gated_delta_rule import mask_gated_chunk_delta_rule
|
| 307 |
+
# class mask_gdn(nn.Module):
|
| 308 |
+
# def __init__(
|
| 309 |
+
# self,
|
| 310 |
+
# d_model: int = None,
|
| 311 |
+
# hidden_size: int = 1024,
|
| 312 |
+
# expand_k: float = 1.0,
|
| 313 |
+
# expand_v: float = 1.0,
|
| 314 |
+
# num_heads: int = 4,
|
| 315 |
+
# mode: str = 'chunk',
|
| 316 |
+
# chunk_size: int = 64,
|
| 317 |
+
# use_beta: bool = True,
|
| 318 |
+
# use_gate: bool = False,
|
| 319 |
+
# use_output_norm: bool = True,
|
| 320 |
+
# use_elu: bool = False,
|
| 321 |
+
# use_short_conv: bool = True,
|
| 322 |
+
# conv_size: int = 4,
|
| 323 |
+
# conv_bias: bool = False,
|
| 324 |
+
# layer_idx: int = None,
|
| 325 |
+
# qk_activation: str = 'silu',
|
| 326 |
+
# qk_norm: str = 'l2',
|
| 327 |
+
# norm_first: bool = False,
|
| 328 |
+
# norm_eps: float = 1e-6,
|
| 329 |
+
# ratio :int = 2,
|
| 330 |
+
# topk : int = 1 ,
|
| 331 |
+
# **kwargs
|
| 332 |
+
# ) :
|
| 333 |
+
# super().__init__()
|
| 334 |
+
|
| 335 |
+
# self.mode = mode
|
| 336 |
+
# self.qk_activation = qk_activation
|
| 337 |
+
# self.qk_norm = qk_norm
|
| 338 |
+
|
| 339 |
+
# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 340 |
+
# assert self.qk_norm in ['l2', 'sum']
|
| 341 |
+
|
| 342 |
+
# if d_model is not None:
|
| 343 |
+
# hidden_size = d_model
|
| 344 |
+
# self.hidden_size = hidden_size
|
| 345 |
+
# self.expand_k = expand_k
|
| 346 |
+
# self.expand_v = expand_v
|
| 347 |
+
# self.num_heads = num_heads
|
| 348 |
+
# self.chunk_size = chunk_size
|
| 349 |
+
# self.use_gate = use_gate
|
| 350 |
+
# self.use_output_norm = use_output_norm
|
| 351 |
+
# self.use_short_conv = use_short_conv
|
| 352 |
+
# self.conv_size = conv_size
|
| 353 |
+
# self.conv_bias = conv_bias
|
| 354 |
+
|
| 355 |
+
# self.key_dim = int(hidden_size * expand_k)
|
| 356 |
+
# self.value_dim = int(hidden_size * expand_v)
|
| 357 |
+
# self.head_qk_dim = self.key_dim // num_heads
|
| 358 |
+
# self.head_v_dim = self.value_dim // num_heads
|
| 359 |
+
# self.norm_first = norm_first
|
| 360 |
+
# self.layer_idx = layer_idx
|
| 361 |
+
# self.top_k = topk
|
| 362 |
+
# self.silu = nn.SiLU()
|
| 363 |
+
# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 364 |
+
# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 365 |
+
# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 366 |
+
# if norm_first:
|
| 367 |
+
# self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 368 |
+
# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 369 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 370 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 371 |
+
# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 372 |
+
|
| 373 |
+
# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 374 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 375 |
+
# self.A_log._no_weight_decay = True
|
| 376 |
+
# # hard coded for now
|
| 377 |
+
# dt_min = 0.001
|
| 378 |
+
# dt_max = 0.1
|
| 379 |
+
# dt_init_floor = 1e-4
|
| 380 |
+
# dt = torch.exp(
|
| 381 |
+
# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 382 |
+
# + math.log(dt_min)
|
| 383 |
+
# )
|
| 384 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 385 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 386 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 387 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 388 |
+
# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 389 |
+
# # name.endswith("bias") in param_grouping.py
|
| 390 |
+
# self.dt_bias._no_weight_decay = True
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
# self.use_beta = use_beta
|
| 394 |
+
# self.use_elu = use_elu
|
| 395 |
+
# if self.use_beta:
|
| 396 |
+
# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 397 |
+
# if use_short_conv:
|
| 398 |
+
# self.conv_size = conv_size
|
| 399 |
+
# self.q_conv1d = ShortConvolution(self.key_dim,
|
| 400 |
+
# conv_size,
|
| 401 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 402 |
+
# self.k_conv1d = ShortConvolution(self.key_dim,
|
| 403 |
+
# conv_size,
|
| 404 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 405 |
+
# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 406 |
+
# if use_gate:
|
| 407 |
+
# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 408 |
+
# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 409 |
+
# else:
|
| 410 |
+
# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 411 |
+
# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 412 |
+
# r = self.r = 2
|
| 413 |
+
# self.mask = nn.Parameter(torch.empty([r,r],dtype=self.o_proj.weight.dtype),requires_grad=True)
|
| 414 |
+
# self.mask_requiregrad = True
|
| 415 |
+
# print('mask_gdn_learn_mask_qk_r2')
|
| 416 |
+
# init.kaiming_uniform_(self.mask, a=math.sqrt(5))
|
| 417 |
+
# assert self.head_qk_dim % r == 0
|
| 418 |
+
# self.apply(self._initialize_weights)
|
| 419 |
+
|
| 420 |
+
# def _initialize_weights(self, module: nn.Module):
|
| 421 |
+
# if getattr(module, "_is_hf_initialized", False):
|
| 422 |
+
# return
|
| 423 |
+
# if isinstance(module, nn.Linear):
|
| 424 |
+
# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 425 |
+
# if module.bias is not None:
|
| 426 |
+
# nn.init.zeros_(module.bias)
|
| 427 |
+
# module._is_hf_initialized = True
|
| 428 |
+
|
| 429 |
+
# def delta_rule_recurrence(self,q, k, v, beta, mask,initial_state=None,output_final_state=True):
|
| 430 |
+
# b, h, l, d_k = q.shape
|
| 431 |
+
# d_v = v.shape[-1]
|
| 432 |
+
# r = mask.shape[-1]
|
| 433 |
+
# o = torch.zeros_like(v)
|
| 434 |
+
# if initial_state == None:
|
| 435 |
+
# S = torch.zeros(b, h, d_k, d_v).to(v).float()
|
| 436 |
+
# else:
|
| 437 |
+
# S = initial_state
|
| 438 |
+
# q = q * (d_k ** -0.5)
|
| 439 |
+
# if beta.ndim < v.ndim:
|
| 440 |
+
# beta = beta[..., None]
|
| 441 |
+
# if self.training:
|
| 442 |
+
# for i in range(l):
|
| 443 |
+
# _k = k[:, :, i]
|
| 444 |
+
# _q = q[:, :, i]
|
| 445 |
+
# _v = v[:, :, i].clone()
|
| 446 |
+
# beta_i = beta[:, :, i]
|
| 447 |
+
# _v = _v * beta_i
|
| 448 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 449 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 450 |
+
# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt))
|
| 451 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 452 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 453 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2)
|
| 454 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
|
| 455 |
+
# return o,S
|
| 456 |
+
# else:
|
| 457 |
+
# for i in range(l):
|
| 458 |
+
# _k = k[:, :, i]
|
| 459 |
+
# _q = q[:, :, i]
|
| 460 |
+
# _v = v[:, :, i]
|
| 461 |
+
# beta_i = beta[:, :, i]
|
| 462 |
+
# _v = _v * beta_i
|
| 463 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 464 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 465 |
+
# kkt = torch.einsum('b h r d l v,r l->b h r d l v',kkt,mask.to(kkt))
|
| 466 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 467 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 468 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr.float(),S) + _k.unsqueeze(-1).float() * _v.unsqueeze(-2).float()
|
| 469 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype)
|
| 470 |
+
# return o,S
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
# def forward(
|
| 474 |
+
# self,
|
| 475 |
+
# hidden_states: torch.Tensor,
|
| 476 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
| 477 |
+
# past_key_values: Optional[Cache] = None,
|
| 478 |
+
# use_cache: Optional[bool] = False,
|
| 479 |
+
# output_attentions: Optional[bool] = False,
|
| 480 |
+
# **kwargs
|
| 481 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 482 |
+
# # change to inference mode.
|
| 483 |
+
# mode = 'chunk'#'recurrent' if hidden_states.shape[1] < 64 else self.mode
|
| 484 |
+
# b,q_len,d = hidden_states.shape
|
| 485 |
+
# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states)
|
| 486 |
+
# if self.norm_first:
|
| 487 |
+
# hidden_states = self.norm(hidden_states)
|
| 488 |
+
|
| 489 |
+
# cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 490 |
+
# # if attention_mask is not None:
|
| 491 |
+
# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 492 |
+
# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 493 |
+
# last_state = None
|
| 494 |
+
# if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 495 |
+
# last_state = past_key_values[self.layer_idx]
|
| 496 |
+
# offset = past_key_values.get_seq_length()
|
| 497 |
+
# # if attention_mask is not None:
|
| 498 |
+
# # if attention_mask.shape[-1] != hidden_states.shape[-2]:
|
| 499 |
+
# # attention_mask = attention_mask[:, -1:]
|
| 500 |
+
# if self.use_short_conv:
|
| 501 |
+
# conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 502 |
+
# if last_state is not None:
|
| 503 |
+
# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 504 |
+
# q = self.q_proj(hidden_states)
|
| 505 |
+
# k = self.k_proj(hidden_states)
|
| 506 |
+
# v = self.v_proj(hidden_states)
|
| 507 |
+
# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 508 |
+
# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 509 |
+
# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 510 |
+
# else:
|
| 511 |
+
# q = self.q_proj(hidden_states)
|
| 512 |
+
# k = self.k_proj(hidden_states)
|
| 513 |
+
# v = self.v_proj(hidden_states)
|
| 514 |
+
# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v))
|
| 515 |
+
# if self.qk_activation != 'silu':
|
| 516 |
+
# if self.qk_activation == 'relu':
|
| 517 |
+
# q, k = q.relu(), k.relu()
|
| 518 |
+
# elif self.qk_activation == 'elu':
|
| 519 |
+
# q, k = elu_p1(q), elu_p1(k)
|
| 520 |
+
# elif self.qk_activation == 'identity':
|
| 521 |
+
# pass
|
| 522 |
+
# else:
|
| 523 |
+
# raise NotImplementedError
|
| 524 |
+
# if self.qk_norm is not None:
|
| 525 |
+
# if self.qk_norm == 'l2':
|
| 526 |
+
# q = l2_norm_fn(q)
|
| 527 |
+
# k = l2_norm_fn(k)
|
| 528 |
+
# elif self.qk_norm == 'sum':
|
| 529 |
+
# q = sum_norm(q).to(v)
|
| 530 |
+
# k = sum_norm(k).to(v)
|
| 531 |
+
# recurrent_state = None
|
| 532 |
+
# if last_state is not None:
|
| 533 |
+
# recurrent_state = last_state['recurrent_state']
|
| 534 |
+
|
| 535 |
+
# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid()
|
| 536 |
+
# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l')
|
| 537 |
+
|
| 538 |
+
# amask = torch.softmax(self.mask,dim=-1)#未必需要r r-1#适配2*2 4*4
|
| 539 |
+
# r = self.r
|
| 540 |
+
# target_matrix = torch.zeros(r, r, dtype=amask.dtype, device=k.device)
|
| 541 |
+
# mask = torch.ones(r,r, dtype=torch.bool, device=amask.device)
|
| 542 |
+
# target_matrix[mask] = amask.flatten()
|
| 543 |
+
|
| 544 |
+
# eye_mask = torch.eye(r, dtype=torch.bool, device=amask.device)
|
| 545 |
+
# target_matrix[eye_mask] = 1.0
|
| 546 |
+
|
| 547 |
+
# o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state,BT=32,output_final_state=True)
|
| 548 |
+
# o = rearrange(o,'b h l d-> b l h d')
|
| 549 |
+
# if past_key_values is not None:
|
| 550 |
+
# past_key_values.update(
|
| 551 |
+
# recurrent_state=(recurrent_state),
|
| 552 |
+
# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 553 |
+
# layer_idx=self.layer_idx,
|
| 554 |
+
# offset=q_len
|
| 555 |
+
# )
|
| 556 |
+
# if self.use_gate:
|
| 557 |
+
# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 558 |
+
# o = self.o_norm(o, g)
|
| 559 |
+
# else:
|
| 560 |
+
# o = self.o_norm(o)
|
| 561 |
+
# o = rearrange(o, 'b l h d -> b l (h d)')
|
| 562 |
+
# o = self.o_proj(o)
|
| 563 |
+
# return o, None, past_key_values,None
|
| 564 |
+
|
| 565 |
+
# from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule
|
| 566 |
+
from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule,mask_fused_recurrent_gated_delta_rule
|
| 567 |
+
class mask_gdn(nn.Module):
|
| 568 |
+
def __init__(
|
| 569 |
+
self,
|
| 570 |
+
d_model: int = None,
|
| 571 |
+
hidden_size: int = 1024,
|
| 572 |
+
expand_k: float = 1.0,
|
| 573 |
+
expand_v: float = 1.0,
|
| 574 |
+
num_heads: int = 4,
|
| 575 |
+
mode: str = 'chunk',
|
| 576 |
+
chunk_size: int = 64,
|
| 577 |
+
use_beta: bool = True,
|
| 578 |
+
use_gate: bool = False,
|
| 579 |
+
use_output_norm: bool = True,
|
| 580 |
+
use_elu: bool = False,
|
| 581 |
+
use_short_conv: bool = True,
|
| 582 |
+
conv_size: int = 4,
|
| 583 |
+
conv_bias: bool = False,
|
| 584 |
+
layer_idx: int = None,
|
| 585 |
+
qk_activation: str = 'silu',
|
| 586 |
+
qk_norm: str = 'l2',
|
| 587 |
+
norm_first: bool = False,
|
| 588 |
+
norm_eps: float = 1e-6,
|
| 589 |
+
ratio :int = 4,
|
| 590 |
+
topk : int = 1,
|
| 591 |
+
**kwargs
|
| 592 |
+
) :
|
| 593 |
+
super().__init__()
|
| 594 |
+
|
| 595 |
+
self.mode = mode
|
| 596 |
+
self.qk_activation = qk_activation
|
| 597 |
+
self.qk_norm = qk_norm
|
| 598 |
+
|
| 599 |
+
assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 600 |
+
assert self.qk_norm in ['l2', 'sum']
|
| 601 |
+
|
| 602 |
+
if d_model is not None:
|
| 603 |
+
hidden_size = d_model
|
| 604 |
+
self.hidden_size = hidden_size
|
| 605 |
+
self.expand_k = expand_k
|
| 606 |
+
self.expand_v = expand_v
|
| 607 |
+
self.num_heads = num_heads
|
| 608 |
+
self.chunk_size = chunk_size
|
| 609 |
+
self.use_gate = use_gate
|
| 610 |
+
self.use_output_norm = use_output_norm
|
| 611 |
+
self.use_short_conv = use_short_conv
|
| 612 |
+
self.conv_size = conv_size
|
| 613 |
+
self.conv_bias = conv_bias
|
| 614 |
+
|
| 615 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 616 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 617 |
+
self.head_qk_dim = self.key_dim // num_heads
|
| 618 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 619 |
+
self.norm_first = norm_first
|
| 620 |
+
self.layer_idx = layer_idx
|
| 621 |
+
self.top_k = topk
|
| 622 |
+
self.silu = nn.SiLU()
|
| 623 |
+
assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 624 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 625 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 626 |
+
if norm_first:
|
| 627 |
+
self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 628 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 629 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 630 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 631 |
+
self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 632 |
+
|
| 633 |
+
A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 634 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 635 |
+
self.A_log._no_weight_decay = True
|
| 636 |
+
# hard coded for now
|
| 637 |
+
dt_min = 0.001
|
| 638 |
+
dt_max = 0.1
|
| 639 |
+
dt_init_floor = 1e-4
|
| 640 |
+
dt = torch.exp(
|
| 641 |
+
torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 642 |
+
+ math.log(dt_min)
|
| 643 |
+
)
|
| 644 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 645 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 646 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 647 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 648 |
+
# Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 649 |
+
# name.endswith("bias") in param_grouping.py
|
| 650 |
+
self.dt_bias._no_weight_decay = True
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
self.use_beta = use_beta
|
| 654 |
+
self.use_elu = use_elu
|
| 655 |
+
if self.use_beta:
|
| 656 |
+
self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 657 |
+
if use_short_conv:
|
| 658 |
+
self.conv_size = conv_size
|
| 659 |
+
self.q_conv1d = ShortConvolution(self.key_dim,
|
| 660 |
+
conv_size,
|
| 661 |
+
activation='silu' if qk_activation == 'silu' else None)
|
| 662 |
+
self.k_conv1d = ShortConvolution(self.key_dim,
|
| 663 |
+
conv_size,
|
| 664 |
+
activation='silu' if qk_activation == 'silu' else None)
|
| 665 |
+
self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 666 |
+
if use_gate:
|
| 667 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 668 |
+
self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 669 |
+
else:
|
| 670 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 671 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 672 |
+
r = self.r = ratio
|
| 673 |
+
self.mask = nn.Linear(hidden_size, (self.num_heads*r*r), bias=False) #nn.Parameter(torch.empty([r,r-1],dtype=self.o_proj.weight.dtype),requires_grad=True)
|
| 674 |
+
self.mask_requiregrad = True
|
| 675 |
+
print('mask_gdn_learn_mask_by_t_fla4____'+str(self.r))
|
| 676 |
+
assert self.head_qk_dim % r == 0
|
| 677 |
+
self.apply(self._initialize_weights)
|
| 678 |
+
|
| 679 |
+
def _initialize_weights(self, module: nn.Module):
|
| 680 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 681 |
+
return
|
| 682 |
+
if isinstance(module, nn.Linear):
|
| 683 |
+
nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 684 |
+
if module.bias is not None:
|
| 685 |
+
nn.init.zeros_(module.bias)
|
| 686 |
+
module._is_hf_initialized = True
|
| 687 |
+
|
| 688 |
+
def forward(
|
| 689 |
+
self,
|
| 690 |
+
hidden_states: torch.Tensor,
|
| 691 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 692 |
+
past_key_values: Optional[Cache] = None,
|
| 693 |
+
use_cache: Optional[bool] = False,
|
| 694 |
+
output_attentions: Optional[bool] = False,
|
| 695 |
+
**kwargs
|
| 696 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 697 |
+
# change to inference mode.
|
| 698 |
+
if attention_mask is not None:
|
| 699 |
+
assert len(attention_mask.shape) == 2, (
|
| 700 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 701 |
+
"for padding purposes (0 indicating padding). "
|
| 702 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 703 |
+
)
|
| 704 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 705 |
+
# change to inference mode.
|
| 706 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 707 |
+
if self.training:
|
| 708 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 709 |
+
|
| 710 |
+
last_state = None
|
| 711 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 712 |
+
last_state = past_key_values[self.layer_idx]
|
| 713 |
+
|
| 714 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 715 |
+
if attention_mask is not None:
|
| 716 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 717 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 718 |
+
|
| 719 |
+
if self.use_short_conv:
|
| 720 |
+
conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 721 |
+
if last_state is not None:
|
| 722 |
+
conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 723 |
+
q = self.q_proj(hidden_states)
|
| 724 |
+
k = self.k_proj(hidden_states)
|
| 725 |
+
v = self.v_proj(hidden_states)
|
| 726 |
+
q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 727 |
+
k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 728 |
+
v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 729 |
+
else:
|
| 730 |
+
q = F.silu(self.q_proj(hidden_states))
|
| 731 |
+
k = F.silu(self.k_proj(hidden_states))
|
| 732 |
+
v = F.silu(self.v_proj(hidden_states))
|
| 733 |
+
|
| 734 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k))
|
| 735 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 736 |
+
|
| 737 |
+
# if self.num_v_heads > self.num_heads:
|
| 738 |
+
# q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k))
|
| 739 |
+
|
| 740 |
+
beta = self.b_proj(hidden_states).sigmoid()
|
| 741 |
+
# if self.allow_neg_eigval:
|
| 742 |
+
# beta = beta * 2.
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
q = l2norm(q)
|
| 746 |
+
k = l2norm(k)
|
| 747 |
+
recurrent_state = None
|
| 748 |
+
if last_state is not None:
|
| 749 |
+
recurrent_state = last_state['recurrent_state']
|
| 750 |
+
g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
|
| 751 |
+
r = self.r
|
| 752 |
+
target_matrix = self.mask(hidden_states).abs()
|
| 753 |
+
target_matrix = rearrange(target_matrix,'b l (h r c)->b l h r c',r=r,h=self.num_heads)#bhlrr
|
| 754 |
+
target_matrix = l2norm(target_matrix)
|
| 755 |
+
target_matrix = target_matrix@target_matrix.transpose(-1,-2)
|
| 756 |
+
# target_matrix = self.mask.abs()
|
| 757 |
+
# target_matrix = l2_norm_fn(target_matrix)
|
| 758 |
+
# target_matrix = target_matrix@target_matrix.transpose(-1,-2)
|
| 759 |
+
# target_matrix = target_matrix.unsqueeze(1).unsqueeze(0).expand(batch,self.num_heads,q_len,self.r,self.r)
|
| 760 |
+
if mode == 'recurrent':
|
| 761 |
+
o,recurrent_state_sf = mask_fused_recurrent_gated_delta_rule(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state_sf,output_final_state=True)
|
| 762 |
+
else:
|
| 763 |
+
if r==8:
|
| 764 |
+
BT = 16
|
| 765 |
+
else:
|
| 766 |
+
BT = 32
|
| 767 |
+
o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(),
|
| 768 |
+
v.contiguous(),
|
| 769 |
+
beta.contiguous(),
|
| 770 |
+
g.contiguous(),
|
| 771 |
+
target_matrix.contiguous(),
|
| 772 |
+
BT = BT,
|
| 773 |
+
initial_state=recurrent_state,
|
| 774 |
+
output_final_state=use_cache,
|
| 775 |
+
cu_seqlens=cu_seqlens,
|
| 776 |
+
use_qk_l2norm_in_kernel=False)
|
| 777 |
+
if past_key_values is not None:
|
| 778 |
+
past_key_values.update(
|
| 779 |
+
recurrent_state=(recurrent_state),
|
| 780 |
+
conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 781 |
+
layer_idx=self.layer_idx,
|
| 782 |
+
offset=q_len
|
| 783 |
+
)
|
| 784 |
+
if self.use_gate:
|
| 785 |
+
g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 786 |
+
o = self.o_norm(o, g)
|
| 787 |
+
else:
|
| 788 |
+
o = self.o_norm(o)
|
| 789 |
+
o = rearrange(o, 'b l h d -> b l (h d)')
|
| 790 |
+
# print(o.shape)
|
| 791 |
+
o = self.o_proj(o)
|
| 792 |
+
if attention_mask is not None:
|
| 793 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 794 |
+
return o, None, past_key_values,None
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
|
| 799 |
+
# from ..ops.mask_gated_delta_rule_t import mask_gated_chunk_delta_rule
|
| 800 |
+
# class mask_gdn(nn.Module):
|
| 801 |
+
# def __init__(
|
| 802 |
+
# self,
|
| 803 |
+
# d_model: int = None,
|
| 804 |
+
# hidden_size: int = 1024,
|
| 805 |
+
# expand_k: float = 1.0,
|
| 806 |
+
# expand_v: float = 1.0,
|
| 807 |
+
# num_heads: int = 4,
|
| 808 |
+
# mode: str = 'chunk',
|
| 809 |
+
# chunk_size: int = 64,
|
| 810 |
+
# use_beta: bool = True,
|
| 811 |
+
# use_gate: bool = False,
|
| 812 |
+
# use_output_norm: bool = True,
|
| 813 |
+
# use_elu: bool = False,
|
| 814 |
+
# use_short_conv: bool = True,
|
| 815 |
+
# conv_size: int = 4,
|
| 816 |
+
# conv_bias: bool = False,
|
| 817 |
+
# layer_idx: int = None,
|
| 818 |
+
# qk_activation: str = 'silu',
|
| 819 |
+
# qk_norm: str = 'l2',
|
| 820 |
+
# norm_first: bool = False,
|
| 821 |
+
# norm_eps: float = 1e-6,
|
| 822 |
+
# ratio :int = 2,
|
| 823 |
+
# topk : int = 1 ,
|
| 824 |
+
# **kwargs
|
| 825 |
+
# ) :
|
| 826 |
+
# super().__init__()
|
| 827 |
+
|
| 828 |
+
# self.mode = mode
|
| 829 |
+
# self.qk_activation = qk_activation
|
| 830 |
+
# self.qk_norm = qk_norm
|
| 831 |
+
|
| 832 |
+
# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 833 |
+
# assert self.qk_norm in ['l2', 'sum']
|
| 834 |
+
|
| 835 |
+
# if d_model is not None:
|
| 836 |
+
# hidden_size = d_model
|
| 837 |
+
# self.hidden_size = hidden_size
|
| 838 |
+
# self.expand_k = expand_k
|
| 839 |
+
# self.expand_v = expand_v
|
| 840 |
+
# self.num_heads = num_heads
|
| 841 |
+
# self.chunk_size = chunk_size
|
| 842 |
+
# self.use_gate = use_gate
|
| 843 |
+
# self.use_output_norm = use_output_norm
|
| 844 |
+
# self.use_short_conv = use_short_conv
|
| 845 |
+
# self.conv_size = conv_size
|
| 846 |
+
# self.conv_bias = conv_bias
|
| 847 |
+
|
| 848 |
+
# self.key_dim = int(hidden_size * expand_k)
|
| 849 |
+
# self.value_dim = int(hidden_size * expand_v)
|
| 850 |
+
# self.head_qk_dim = self.key_dim // num_heads
|
| 851 |
+
# self.head_v_dim = self.value_dim // num_heads
|
| 852 |
+
# self.norm_first = norm_first
|
| 853 |
+
# self.layer_idx = layer_idx
|
| 854 |
+
# self.top_k = topk
|
| 855 |
+
# self.silu = nn.SiLU()
|
| 856 |
+
# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 857 |
+
# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 858 |
+
# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 859 |
+
# if norm_first:
|
| 860 |
+
# self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 861 |
+
# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 862 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 863 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 864 |
+
# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 865 |
+
|
| 866 |
+
# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 867 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 868 |
+
# self.A_log._no_weight_decay = True
|
| 869 |
+
# # hard coded for now
|
| 870 |
+
# dt_min = 0.001
|
| 871 |
+
# dt_max = 0.1
|
| 872 |
+
# dt_init_floor = 1e-4
|
| 873 |
+
# dt = torch.exp(
|
| 874 |
+
# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 875 |
+
# + math.log(dt_min)
|
| 876 |
+
# )
|
| 877 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 878 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 879 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 880 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 881 |
+
# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 882 |
+
# # name.endswith("bias") in param_grouping.py
|
| 883 |
+
# self.dt_bias._no_weight_decay = True
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
# self.use_beta = use_beta
|
| 887 |
+
# self.use_elu = use_elu
|
| 888 |
+
# if self.use_beta:
|
| 889 |
+
# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 890 |
+
# if use_short_conv:
|
| 891 |
+
# self.conv_size = conv_size
|
| 892 |
+
# self.q_conv1d = ShortConvolution(self.key_dim,
|
| 893 |
+
# conv_size,
|
| 894 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 895 |
+
# self.k_conv1d = ShortConvolution(self.key_dim,
|
| 896 |
+
# conv_size,
|
| 897 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 898 |
+
# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 899 |
+
# if use_gate:
|
| 900 |
+
# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 901 |
+
# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 902 |
+
# else:
|
| 903 |
+
# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 904 |
+
# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 905 |
+
# r = self.r = 4
|
| 906 |
+
# self.mask = nn.Parameter(torch.empty([self.num_heads,r,r],dtype=self.o_proj.weight.dtype),requires_grad=True)
|
| 907 |
+
# self.mask_requiregrad = True
|
| 908 |
+
|
| 909 |
+
# print('mask_gdn_learn_mask_r4_hrr')
|
| 910 |
+
# init.kaiming_uniform_(self.mask, a=math.sqrt(5))
|
| 911 |
+
# assert self.head_qk_dim % r == 0
|
| 912 |
+
# self.apply(self._initialize_weights)
|
| 913 |
+
|
| 914 |
+
# def _initialize_weights(self, module: nn.Module):
|
| 915 |
+
# if getattr(module, "_is_hf_initialized", False):
|
| 916 |
+
# return
|
| 917 |
+
# if isinstance(module, nn.Linear):
|
| 918 |
+
# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 919 |
+
# if module.bias is not None:
|
| 920 |
+
# nn.init.zeros_(module.bias)
|
| 921 |
+
# module._is_hf_initialized = True
|
| 922 |
+
|
| 923 |
+
# def delta_rule_recurrence(self,q, k, v, beta, g, mask,initial_state=None,output_final_state=True):
|
| 924 |
+
# b, h, l, d_k = q.shape
|
| 925 |
+
# d_v = v.shape[-1]
|
| 926 |
+
# r = mask.shape[-1]
|
| 927 |
+
# o = torch.zeros_like(v)
|
| 928 |
+
# if initial_state == None:
|
| 929 |
+
# S = torch.zeros(b, h, d_k, d_v,device=k.device,dtype=torch.float32)
|
| 930 |
+
# else:
|
| 931 |
+
# S = initial_state
|
| 932 |
+
# q = q * (d_k ** -0.5)
|
| 933 |
+
# if beta.ndim < v.ndim:
|
| 934 |
+
# beta = beta[..., None]
|
| 935 |
+
# g = torch.exp(g)
|
| 936 |
+
# if self.training:
|
| 937 |
+
# for i in range(l):
|
| 938 |
+
# _k = k[:, :, i]
|
| 939 |
+
# _q = q[:, :, i]
|
| 940 |
+
# _v = v[:, :, i].clone()
|
| 941 |
+
# beta_i = beta[:, :, i]
|
| 942 |
+
# _v = _v * beta_i
|
| 943 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 944 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 945 |
+
# kkt = torch.einsum('b h r d l v,b h r l->b h r d l v',kkt,mask[:,:,i,:,:].to(kkt))
|
| 946 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 947 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 948 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr,S.clone()) + _k.unsqueeze(-1) * _v.unsqueeze(-2)
|
| 949 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q, S)
|
| 950 |
+
# return o,S
|
| 951 |
+
# else:
|
| 952 |
+
# for i in range(l):
|
| 953 |
+
# _k = k[:, :, i]
|
| 954 |
+
# _q = q[:, :, i]
|
| 955 |
+
# _v = v[:, :, i]
|
| 956 |
+
# beta_i = beta[:, :, i]
|
| 957 |
+
# _v = _v * beta_i
|
| 958 |
+
# kkt = torch.einsum('b h d,b h v->b h d v',_k*beta_i,_k)
|
| 959 |
+
# kkt = rearrange(kkt,' b h (r d) (l v)-> b h r d l v',r= r,l=r)
|
| 960 |
+
# kkt = torch.einsum('b h r d l v,b h r l->b h r d l v',kkt,mask[:,:,i,:,:].to(kkt))
|
| 961 |
+
# kkt = rearrange(kkt,'b h r d l v-> b h (r d) (l v)')
|
| 962 |
+
# iplr = torch.eye(d_k).to(q)-kkt
|
| 963 |
+
# S = torch.einsum(' b h q k ,b h k v->b h q v',iplr.float(),S) + _k.unsqueeze(-1).float() * _v.unsqueeze(-2).float()
|
| 964 |
+
# o[:, :, i] = torch.einsum('bhd,bhdm->bhm', _q.float(), S).to(k.dtype)
|
| 965 |
+
# return o,S
|
| 966 |
+
|
| 967 |
+
# def forward(
|
| 968 |
+
# self,
|
| 969 |
+
# hidden_states: torch.Tensor,
|
| 970 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
| 971 |
+
# past_key_values: Optional[Cache] = None,
|
| 972 |
+
# use_cache: Optional[bool] = False,
|
| 973 |
+
# output_attentions: Optional[bool] = False,
|
| 974 |
+
# **kwargs
|
| 975 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 976 |
+
# # change to inference mode.
|
| 977 |
+
# mode = 'recurrent' if hidden_states.shape[1] < 32 else self.mode
|
| 978 |
+
# batch,q_len,d = hidden_states.shape
|
| 979 |
+
# # assert torch.isnan(hidden_states).sum() == 0, print(hidden_states)
|
| 980 |
+
# if self.norm_first:
|
| 981 |
+
# hidden_states = self.norm(hidden_states)
|
| 982 |
+
|
| 983 |
+
# cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 984 |
+
# # if attention_mask is not None:
|
| 985 |
+
# # indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 986 |
+
# # hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 987 |
+
# last_state = None
|
| 988 |
+
# if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 989 |
+
# last_state = past_key_values[self.layer_idx]
|
| 990 |
+
# offset = past_key_values.get_seq_length()
|
| 991 |
+
# # if attention_mask is not None:
|
| 992 |
+
# # if attention_mask.shape[-1] != hidden_states.shape[-2]:
|
| 993 |
+
# # attention_mask = attention_mask[:, -1:]
|
| 994 |
+
# if self.use_short_conv:
|
| 995 |
+
# conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 996 |
+
# if last_state is not None:
|
| 997 |
+
# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 998 |
+
# q = self.q_proj(hidden_states)
|
| 999 |
+
# k = self.k_proj(hidden_states)
|
| 1000 |
+
# v = self.v_proj(hidden_states)
|
| 1001 |
+
# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1002 |
+
# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1003 |
+
# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1004 |
+
# else:
|
| 1005 |
+
# q = self.q_proj(hidden_states)
|
| 1006 |
+
# k = self.k_proj(hidden_states)
|
| 1007 |
+
# v = self.v_proj(hidden_states)
|
| 1008 |
+
# q, k, v = map(lambda x: rearrange(x, 'b l (h d) -> b h l d', h=self.num_heads), (q, k, v))
|
| 1009 |
+
# if self.qk_activation != 'silu':
|
| 1010 |
+
# if self.qk_activation == 'relu':
|
| 1011 |
+
# q, k = q.relu(), k.relu()
|
| 1012 |
+
# elif self.qk_activation == 'elu':
|
| 1013 |
+
# q, k = elu_p1(q), elu_p1(k)
|
| 1014 |
+
# elif self.qk_activation == 'identity':
|
| 1015 |
+
# pass
|
| 1016 |
+
# else:
|
| 1017 |
+
# raise NotImplementedError
|
| 1018 |
+
# if self.qk_norm is not None:
|
| 1019 |
+
# if self.qk_norm == 'l2':
|
| 1020 |
+
# q = l2_norm_fn(q)
|
| 1021 |
+
# k = l2_norm_fn(k)
|
| 1022 |
+
# elif self.qk_norm == 'sum':
|
| 1023 |
+
# q = sum_norm(q).to(v)
|
| 1024 |
+
# k = sum_norm(k).to(v)
|
| 1025 |
+
# recurrent_state = None
|
| 1026 |
+
# if last_state is not None:
|
| 1027 |
+
# recurrent_state = last_state['recurrent_state']
|
| 1028 |
+
|
| 1029 |
+
# beta = rearrange(self.b_proj(hidden_states), 'b l h -> b h l').sigmoid()
|
| 1030 |
+
# g = rearrange(-self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias), 'b l h -> b h l')
|
| 1031 |
+
|
| 1032 |
+
# r = self.r
|
| 1033 |
+
# target_matrix = self.mask#hrr
|
| 1034 |
+
# target_matrix = torch.softmax(target_matrix,dim=-1)#h r c
|
| 1035 |
+
# eye_mask = torch.eye(r, dtype=torch.bool, device=target_matrix.device).unsqueeze(0)
|
| 1036 |
+
# target_matrix = torch.where(eye_mask, torch.tensor(1.0, device=target_matrix.device), target_matrix)
|
| 1037 |
+
# target_matrix = target_matrix.unsqueeze(1).unsqueeze(0).expand(batch,self.num_heads,q_len,self.r,self.r)
|
| 1038 |
+
|
| 1039 |
+
# if mode == 'recurrent':
|
| 1040 |
+
# o,recurrent_state = self.delta_rule_recurrence(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state,output_final_state=True)
|
| 1041 |
+
# else:
|
| 1042 |
+
# o,recurrent_state = mask_gated_chunk_delta_rule(q.contiguous(),k.contiguous(),v.contiguous(),beta.contiguous(),g.contiguous(),target_matrix.contiguous(),initial_state=recurrent_state,BT=32,output_final_state=True)
|
| 1043 |
+
# o = rearrange(o,'b h l d-> b l h d')
|
| 1044 |
+
# if past_key_values is not None:
|
| 1045 |
+
# past_key_values.update(
|
| 1046 |
+
# recurrent_state=(recurrent_state),
|
| 1047 |
+
# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 1048 |
+
# layer_idx=self.layer_idx,
|
| 1049 |
+
# offset=q_len
|
| 1050 |
+
# )
|
| 1051 |
+
# if self.use_gate:
|
| 1052 |
+
# g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 1053 |
+
# o = self.o_norm(o, g)
|
| 1054 |
+
# else:
|
| 1055 |
+
# o = self.o_norm(o)
|
| 1056 |
+
# o = rearrange(o, 'b l h d -> b l (h d)')
|
| 1057 |
+
# o = self.o_proj(o)
|
| 1058 |
+
# return o, None, past_key_values,None
|
mla.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
""" Implementing the Deepseek Multi Latent Attention (MLA) module. Reference:
|
| 5 |
+
|
| 6 |
+
https://github.com/huggingface/transformers/blob/main/src/transformers/models/deepseek_v3/modeling_deepseek_v3.py#L328
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import math
|
| 12 |
+
import warnings
|
| 13 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
from einops import rearrange, repeat
|
| 19 |
+
from transformers.utils import logging
|
| 20 |
+
|
| 21 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 22 |
+
from fla.modules import RMSNorm, RotaryEmbedding
|
| 23 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from fla.models.utils import Cache
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 30 |
+
except ImportError:
|
| 31 |
+
warnings.warn(
|
| 32 |
+
"Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
|
| 33 |
+
category=ImportWarning
|
| 34 |
+
)
|
| 35 |
+
flash_attn_func = None
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def yarn_get_mscale(scale=1, mscale=1):
|
| 41 |
+
if scale <= 1:
|
| 42 |
+
return 1.0
|
| 43 |
+
return 0.1 * mscale * math.log(scale) + 1.0
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class MultiheadLatentAttention(nn.Module):
|
| 47 |
+
r"""
|
| 48 |
+
Multi-headed attention from [Deepseek V2](https://arxiv.org/abs/2405.04434)
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
hidden_size: int = 2048,
|
| 54 |
+
num_heads: int = 16,
|
| 55 |
+
q_lora_rank: Optional[int] = 1536, # q lora rank is optional, None indicates no q lora
|
| 56 |
+
qk_rope_head_dim: int = 64,
|
| 57 |
+
kv_lora_rank: int = 512, # following the original Deepseek paper
|
| 58 |
+
v_head_dim: int = 128,
|
| 59 |
+
qk_nope_head_dim: int = 128,
|
| 60 |
+
qk_head_dim: Optional[int] = 192, # qk_nope_head_dim + qk_rope_head_dim
|
| 61 |
+
window_size: Optional[int] = None,
|
| 62 |
+
rope_theta: float = 10000.,
|
| 63 |
+
max_position_embeddings: Optional[int] = None,
|
| 64 |
+
rope_scaling: Optional[dict] = None,
|
| 65 |
+
layer_idx: int = None
|
| 66 |
+
) -> MultiheadLatentAttention:
|
| 67 |
+
super().__init__()
|
| 68 |
+
|
| 69 |
+
# sanity check
|
| 70 |
+
if qk_head_dim is not None:
|
| 71 |
+
assert qk_head_dim == qk_nope_head_dim + qk_rope_head_dim, \
|
| 72 |
+
f"qk_head_dim {qk_head_dim} != qk_nope_head_dim {qk_nope_head_dim} + qk_rope_head_dim {qk_rope_head_dim}"
|
| 73 |
+
else:
|
| 74 |
+
qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
|
| 75 |
+
|
| 76 |
+
# attention params info
|
| 77 |
+
self.hidden_size = hidden_size
|
| 78 |
+
self.num_heads = num_heads
|
| 79 |
+
self.q_lora_rank = q_lora_rank
|
| 80 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
| 81 |
+
self.kv_lora_rank = kv_lora_rank
|
| 82 |
+
self.v_head_dim = v_head_dim
|
| 83 |
+
self.qk_nope_head_dim = qk_nope_head_dim
|
| 84 |
+
self.qk_head_dim = qk_head_dim
|
| 85 |
+
|
| 86 |
+
self.window_size = window_size
|
| 87 |
+
self.rope_theta = rope_theta
|
| 88 |
+
self.max_position_embeddings = max_position_embeddings
|
| 89 |
+
self.layer_idx = layer_idx
|
| 90 |
+
|
| 91 |
+
if flash_attn_func is None:
|
| 92 |
+
raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
|
| 93 |
+
|
| 94 |
+
if q_lora_rank is not None:
|
| 95 |
+
self.q_proj = nn.Sequential(
|
| 96 |
+
nn.Linear(hidden_size, q_lora_rank, bias=False),
|
| 97 |
+
RMSNorm(q_lora_rank),
|
| 98 |
+
nn.Linear(q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
|
| 99 |
+
)
|
| 100 |
+
else:
|
| 101 |
+
self.q_proj = nn.Linear(hidden_size, self.num_heads * self.qk_head_dim, bias=False)
|
| 102 |
+
|
| 103 |
+
self.k_rope = nn.Linear(hidden_size, self.qk_rope_head_dim, bias=False)
|
| 104 |
+
self.kv_proj = nn.Sequential(
|
| 105 |
+
nn.Linear(hidden_size, self.kv_lora_rank, bias=False),
|
| 106 |
+
RMSNorm(self.kv_lora_rank),
|
| 107 |
+
nn.Linear(self.kv_lora_rank, self.num_heads * (self.qk_nope_head_dim + self.v_head_dim), bias=False)
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
self.o_proj = nn.Linear(self.num_heads * self.v_head_dim, hidden_size, bias=False)
|
| 111 |
+
|
| 112 |
+
self.scaling = self.qk_head_dim ** (-0.5)
|
| 113 |
+
if rope_scaling is not None:
|
| 114 |
+
mscale_all_dim = rope_scaling.get("mscale_all_dim", 0)
|
| 115 |
+
scaling_factor = rope_scaling["factor"]
|
| 116 |
+
if mscale_all_dim:
|
| 117 |
+
mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
|
| 118 |
+
self.scaling = self.scaling * mscale * mscale
|
| 119 |
+
|
| 120 |
+
self.rotary = RotaryEmbedding(dim=self.qk_rope_head_dim, base=self.rope_theta)
|
| 121 |
+
|
| 122 |
+
def forward(
|
| 123 |
+
self,
|
| 124 |
+
hidden_states: torch.Tensor,
|
| 125 |
+
attention_mask: Optional[torch.Tensor],
|
| 126 |
+
past_key_values: Optional[Cache] = None,
|
| 127 |
+
output_attentions: bool = False,
|
| 128 |
+
use_cache: bool = False,
|
| 129 |
+
**kwargs,
|
| 130 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 131 |
+
# if attention_mask is not None, this is doing inference
|
| 132 |
+
if attention_mask is not None:
|
| 133 |
+
assert len(attention_mask.shape) == 2, (
|
| 134 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 135 |
+
"for padding purposes (0 indicating padding). "
|
| 136 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# prepare q, k, v
|
| 140 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 141 |
+
|
| 142 |
+
q_states = self.q_proj(hidden_states)
|
| 143 |
+
q_states = rearrange(q_states, '... (h d) -> ... h d', d=self.qk_head_dim)
|
| 144 |
+
q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
|
| 145 |
+
k_pass, k_rot = self.kv_proj(hidden_states), self.k_rope(hidden_states)
|
| 146 |
+
|
| 147 |
+
k_rot = rearrange(k_rot, 'b t d -> b t 1 d')
|
| 148 |
+
k_pass = rearrange(k_pass, '... (h d) -> ... h d', d=self.qk_nope_head_dim + self.v_head_dim)
|
| 149 |
+
k_pass, v = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
|
| 150 |
+
|
| 151 |
+
# apply rotary position embedding
|
| 152 |
+
seqlen_offset, max_seqlen = 0, q_len
|
| 153 |
+
if past_key_values is not None:
|
| 154 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 155 |
+
max_seqlen = q_len + seqlen_offset
|
| 156 |
+
|
| 157 |
+
if attention_mask is not None:
|
| 158 |
+
seqlen_offset = seqlen_offset + prepare_lens_from_mask(attention_mask) - attention_mask.shape[-1]
|
| 159 |
+
max_seqlen = q_len + max(seqlen_offset)
|
| 160 |
+
|
| 161 |
+
if self.max_position_embeddings is not None:
|
| 162 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 163 |
+
cu_seqlens = kwargs.get("cu_seqlens", None)
|
| 164 |
+
q_rot, k_rot = self.rotary(
|
| 165 |
+
q_rot, k_rot, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
k_rot = repeat(k_rot, 'b t 1 d -> b t h d', h=self.num_heads)
|
| 169 |
+
q = torch.cat((q_pass, q_rot), dim=-1)
|
| 170 |
+
k = torch.cat((k_pass, k_rot), dim=-1)
|
| 171 |
+
|
| 172 |
+
# TODO: instead of caching the full k, v, we can actually only cache the compressed_kv and k_rot
|
| 173 |
+
# and recover the full k, v from compressed_kv and k_rot
|
| 174 |
+
if past_key_values is not None:
|
| 175 |
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
| 176 |
+
k_cached, v_cached = past_key_values.update(
|
| 177 |
+
attn_state=(k, v),
|
| 178 |
+
layer_idx=self.layer_idx,
|
| 179 |
+
offset=q_len,
|
| 180 |
+
)['attn_state']
|
| 181 |
+
if cache_has_content:
|
| 182 |
+
k, v = k_cached, v_cached
|
| 183 |
+
|
| 184 |
+
# Head dim match to use flash-attn
|
| 185 |
+
if self.qk_head_dim != self.v_head_dim:
|
| 186 |
+
v = F.pad(v, [0, self.qk_head_dim - self.v_head_dim])
|
| 187 |
+
|
| 188 |
+
# Contains at least one padding token in the sequence
|
| 189 |
+
if attention_mask is not None:
|
| 190 |
+
if q.shape[1] == 1 and self.window_size is not None:
|
| 191 |
+
attention_mask = attention_mask[:, -self.window_size:]
|
| 192 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(q, (k, v), attention_mask, q_len)
|
| 193 |
+
cu_seqlens_q, cu_seqlens_k = cu_seqlens
|
| 194 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 195 |
+
o = flash_attn_varlen_func(
|
| 196 |
+
q, k, v,
|
| 197 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 198 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 199 |
+
max_seqlen_q=max_seqlen_q,
|
| 200 |
+
max_seqlen_k=max_seqlen_k,
|
| 201 |
+
causal=True,
|
| 202 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 203 |
+
)
|
| 204 |
+
o = pad_input(o, indices_q, batch_size, q_len)
|
| 205 |
+
elif cu_seqlens is not None:
|
| 206 |
+
o = flash_attn_varlen_func(
|
| 207 |
+
q.squeeze(0), k.squeeze(0), v.squeeze(0),
|
| 208 |
+
cu_seqlens_q=cu_seqlens,
|
| 209 |
+
cu_seqlens_k=cu_seqlens,
|
| 210 |
+
max_seqlen_q=max_seqlen,
|
| 211 |
+
max_seqlen_k=max_seqlen,
|
| 212 |
+
causal=True,
|
| 213 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 214 |
+
).unsqueeze(0)
|
| 215 |
+
else:
|
| 216 |
+
o = flash_attn_func(
|
| 217 |
+
q, k, v,
|
| 218 |
+
causal=True,
|
| 219 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
if self.qk_head_dim != self.v_head_dim:
|
| 223 |
+
o = o[:, :, :, :self.v_head_dim]
|
| 224 |
+
o = o.reshape(batch_size, q_len, -1)
|
| 225 |
+
o = self.o_proj(o)
|
| 226 |
+
return o, None, past_key_values
|
mom.py
ADDED
|
@@ -0,0 +1,834 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from einops import rearrange
|
| 11 |
+
from torch.nn import functional as F
|
| 12 |
+
|
| 13 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 14 |
+
from fla.ops.gated_delta_rule import chunk_gated_delta_rule, fused_recurrent_gated_delta_rule
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from transformers.processing_utils import Unpack
|
| 18 |
+
|
| 19 |
+
from fla.models.utils import Cache
|
| 20 |
+
|
| 21 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input, unpad_input
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _upad_input(
|
| 25 |
+
query_layer: torch.Tensor,
|
| 26 |
+
key_layer: torch.Tensor,
|
| 27 |
+
value_layer: torch.Tensor,
|
| 28 |
+
gate_layer: torch.Tensor,
|
| 29 |
+
beta_layer: torch.Tensor,
|
| 30 |
+
attention_mask: torch.Tensor,
|
| 31 |
+
):
|
| 32 |
+
"""
|
| 33 |
+
Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to
|
| 34 |
+
different batches.
|
| 35 |
+
|
| 36 |
+
This function is used instead of `flash_attn.bert_padding.unpad_input` in order to avoid the recomputation
|
| 37 |
+
of the same intermediary
|
| 38 |
+
tensors for query, key, value tensors.
|
| 39 |
+
|
| 40 |
+
Arguments:
|
| 41 |
+
query_layer (`torch.Tensor`):
|
| 42 |
+
Query state with padding. Shape: (batch_size, query_length, num_heads, head_dim).
|
| 43 |
+
key_layer (`torch.Tensor`):
|
| 44 |
+
Key state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
|
| 45 |
+
value_layer (`torch.Tensor`):
|
| 46 |
+
Value state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
|
| 47 |
+
attention_mask (`torch.Tensor`):
|
| 48 |
+
Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.
|
| 49 |
+
query_length (`int`):
|
| 50 |
+
Target length.
|
| 51 |
+
|
| 52 |
+
Return:
|
| 53 |
+
query_layer (`torch.Tensor`):
|
| 54 |
+
Query state without padding. Shape: (total_target_length, num_heads, head_dim).
|
| 55 |
+
key_layer (`torch.Tensor`):
|
| 56 |
+
Key state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
|
| 57 |
+
value_layer (`torch.Tensor`):
|
| 58 |
+
Value state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
|
| 59 |
+
indices_q (`torch.Tensor`):
|
| 60 |
+
The indices of non-masked tokens from the flattened input target sequence.
|
| 61 |
+
(cu_seqlens_q, cu_seqlens_k) (`Tuple[int]`):
|
| 62 |
+
The cumulative sequence lengths for the target (query) and source (key, value), used to index
|
| 63 |
+
into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,).
|
| 64 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`Tuple[int]`):
|
| 65 |
+
Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query,
|
| 66 |
+
`max_seqlen_in_batch_k` for the source sequence i.e. key/value).
|
| 67 |
+
"""
|
| 68 |
+
query_length = query_layer.shape[1]
|
| 69 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = get_unpad_data(attention_mask)
|
| 70 |
+
batch_size, kv_seq_len, dim = key_layer.shape
|
| 71 |
+
v_dim = value_layer.shape[-1]
|
| 72 |
+
|
| 73 |
+
key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, dim), indices_k)
|
| 74 |
+
value_layer = index_first_axis(
|
| 75 |
+
value_layer.reshape(batch_size * kv_seq_len, v_dim), indices_k
|
| 76 |
+
)
|
| 77 |
+
gate_layer = index_first_axis(gate_layer.reshape(batch_size * kv_seq_len, -1), indices_k)
|
| 78 |
+
beta_layer = index_first_axis(beta_layer.reshape(batch_size * kv_seq_len, -1), indices_k)
|
| 79 |
+
if query_length == kv_seq_len:
|
| 80 |
+
query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, dim), indices_k)
|
| 81 |
+
cu_seqlens_q = cu_seqlens_k
|
| 82 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 83 |
+
indices_q = indices_k
|
| 84 |
+
elif query_length == 1:
|
| 85 |
+
max_seqlen_in_batch_q = 1
|
| 86 |
+
cu_seqlens_q = torch.arange(
|
| 87 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
| 88 |
+
) # There is a memcpy here, that is very bad.
|
| 89 |
+
indices_q = cu_seqlens_q[:-1]
|
| 90 |
+
query_layer = query_layer.squeeze(1)
|
| 91 |
+
else:
|
| 92 |
+
# The -q_len: slice assumes left padding.
|
| 93 |
+
attention_mask = attention_mask[:, -query_length:]
|
| 94 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
| 95 |
+
|
| 96 |
+
return (
|
| 97 |
+
query_layer,
|
| 98 |
+
key_layer,
|
| 99 |
+
value_layer,
|
| 100 |
+
gate_layer,
|
| 101 |
+
beta_layer,
|
| 102 |
+
indices_q,
|
| 103 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 104 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def transform(
|
| 109 |
+
x: torch.Tensor,
|
| 110 |
+
routing_mask: torch.Tensor,
|
| 111 |
+
num_memories: int,
|
| 112 |
+
selected_memories: torch.Tensor,
|
| 113 |
+
attention_mask: torch.Tensor,
|
| 114 |
+
):
|
| 115 |
+
"""
|
| 116 |
+
Reorganize token embeddings into memory-aligned chunks.
|
| 117 |
+
|
| 118 |
+
Steps:
|
| 119 |
+
- Expand for top-k routing if needed.
|
| 120 |
+
- Mask out padded tokens via `attention_mask`.
|
| 121 |
+
- Sort tokens by (batch, memory).
|
| 122 |
+
- Gather and pad tokens per memory slot.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
x: (batch, seq, hidden) input embeddings.
|
| 126 |
+
routing_mask: (batch, seq, num_memories) binary routing mask.
|
| 127 |
+
num_memories: number of memory slots.
|
| 128 |
+
selected_memories: memory indices per token,
|
| 129 |
+
(batch, seq) if k=1 else (batch, seq, topk).
|
| 130 |
+
attention_mask: (batch, seq) valid-token mask.
|
| 131 |
+
|
| 132 |
+
Returns:
|
| 133 |
+
transformed_x: (num_memories, batch, max_len, hidden) reorganized tokens.
|
| 134 |
+
truncation_indices: (batch*num_memories, max_len) gather indices.
|
| 135 |
+
sorted_indices: (batch*seq*topk,) global sort order.
|
| 136 |
+
max_len: int, max tokens per memory.
|
| 137 |
+
mask: (batch*num_memories, max_len) validity mask.
|
| 138 |
+
mask_2: (num_memories, batch, max_len) validity mask reshaped.
|
| 139 |
+
"""
|
| 140 |
+
if selected_memories.dim() == 3:
|
| 141 |
+
# (batch, seq, topk)
|
| 142 |
+
topk = selected_memories.shape[2]
|
| 143 |
+
# x (batch, seq, hidden)
|
| 144 |
+
x = x.repeat_interleave(topk, dim=1)
|
| 145 |
+
# x (batch, seq * topk, hidden)
|
| 146 |
+
# (batch, seq, topk)
|
| 147 |
+
selected_memories = selected_memories.reshape(selected_memories.shape[0], -1)
|
| 148 |
+
# (batch, seq * topk)
|
| 149 |
+
|
| 150 |
+
if attention_mask is not None:
|
| 151 |
+
attention_mask = attention_mask[:, -routing_mask.shape[1]:]
|
| 152 |
+
# mask out the masked tokens
|
| 153 |
+
routing_mask[attention_mask.bitwise_not().unsqueeze(-1).expand(-1, -1, num_memories)] = 0
|
| 154 |
+
|
| 155 |
+
b, s, d = x.shape
|
| 156 |
+
x_flat = x.reshape(b * s, d) # [b*s, d]
|
| 157 |
+
|
| 158 |
+
with torch.no_grad():
|
| 159 |
+
batch_indices = torch.arange(b, device=x.device).unsqueeze(-1)
|
| 160 |
+
batch_indices = batch_indices.repeat(1, s).reshape(-1)
|
| 161 |
+
if attention_mask is not None:
|
| 162 |
+
# sort the masked tokens to the end
|
| 163 |
+
batch_indices[attention_mask.repeat_interleave(topk, dim=1).bitwise_not().flatten()] = b
|
| 164 |
+
# (b * s)
|
| 165 |
+
memories_flat = selected_memories.reshape(-1) # [b*s]
|
| 166 |
+
|
| 167 |
+
combined = batch_indices * (memories_flat.max() + 1) + memories_flat
|
| 168 |
+
sorted_indices = combined.argsort()
|
| 169 |
+
|
| 170 |
+
x_sorted = x_flat[sorted_indices] # [b*s, d]
|
| 171 |
+
# (b*s, hidden) -> (b, s, hidd)
|
| 172 |
+
with torch.no_grad():
|
| 173 |
+
# routing_mask (b, s, num_memories)
|
| 174 |
+
batch_memory_tokens = routing_mask.sum(dim=1)
|
| 175 |
+
# (b, num_memories)
|
| 176 |
+
flatten_offset = batch_memory_tokens.flatten().cumsum(dim=0)
|
| 177 |
+
max_len = batch_memory_tokens.max()
|
| 178 |
+
indices = (
|
| 179 |
+
torch.arange(max_len, device=flatten_offset.device).unsqueeze(0).expand(b * num_memories, -1)
|
| 180 |
+
+ torch.cat([torch.tensor([0], device=flatten_offset.device), flatten_offset[:-1]], dim=0).unsqueeze(1)
|
| 181 |
+
)
|
| 182 |
+
mask = indices < flatten_offset.unsqueeze(-1)
|
| 183 |
+
truncation_indices = torch.where(mask, indices, torch.zeros_like(indices))
|
| 184 |
+
|
| 185 |
+
gathered_x = torch.gather(x_sorted, 0, truncation_indices.reshape(-1).unsqueeze(-1).expand(-1, d))
|
| 186 |
+
transformed_x = gathered_x.reshape(b * num_memories, -1, d).reshape((b, num_memories, max_len, d)).transpose(0, 1)
|
| 187 |
+
# transformed_x = transformed_x * mask.unsqueeze(-1).expand_as(transformed_x)
|
| 188 |
+
# pad_x = torch.zeros((b * num_memories, capacity_len-max_len, d), dtype=transformed_x.dtype, device=transformed_x.device)
|
| 189 |
+
# pad_mask = torch.zeros((b * num_memories, capacity_len-max_len), dtype=transformed_x.dtype, device=transformed_x.device)
|
| 190 |
+
# left pad
|
| 191 |
+
# transformed_x = torch.cat((pad_x, transformed_x), dim=1).reshape((b, num_memories, capacity_len, d)).transpose(0, 1)
|
| 192 |
+
mask_2 = mask.reshape((b, num_memories, max_len)).transpose(0, 1)
|
| 193 |
+
# truncation_indices += capacity_len-max_len
|
| 194 |
+
# if attention_mask is not None:
|
| 195 |
+
# mask_2
|
| 196 |
+
|
| 197 |
+
return transformed_x, truncation_indices, sorted_indices, max_len, mask, mask_2
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def reconstruct(
|
| 201 |
+
transformed_x,
|
| 202 |
+
indices: torch.Tensor,
|
| 203 |
+
sorted_indices: torch.Tensor,
|
| 204 |
+
batch_size: int,
|
| 205 |
+
seq_len: int,
|
| 206 |
+
topk: int,
|
| 207 |
+
routing_weights: torch.Tensor,
|
| 208 |
+
mask: torch.Tensor
|
| 209 |
+
):
|
| 210 |
+
'''
|
| 211 |
+
Reconstruct and mix transformed outputs back into the original input sequence shape.
|
| 212 |
+
|
| 213 |
+
Key operations:
|
| 214 |
+
1. Reshapes and transposes `transformed_x` to prepare for scattering.
|
| 215 |
+
2. Applies the `mask` to zero out invalid positions.
|
| 216 |
+
3. Uses `torch.scatter_add_` to scatter and sum the transformed outputs back to their original positions
|
| 217 |
+
based on `indices`.
|
| 218 |
+
4. Rearranges the scattered outputs using `sorted_indices` to ensure correct ordering.
|
| 219 |
+
5. Applies the `routing_weights` to weight the outputs.
|
| 220 |
+
6. Sums over the `topk` dimension to produce the final reconstructed output.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
transformed_x (torch.Tensor):
|
| 224 |
+
The transformed output tensor from memory units or experts.
|
| 225 |
+
Shape: (num_memories, batch_size, capacity_len, hidden_size)
|
| 226 |
+
indices (torch.Tensor):
|
| 227 |
+
Indices used for scattering the transformed outputs back to their corresponding positions.
|
| 228 |
+
Shape: (batch*num_memories, max_len)
|
| 229 |
+
sorted_indices (torch.Tensor):
|
| 230 |
+
Sorting indices used to rearrange the scattered outputs back into the original sequence order.
|
| 231 |
+
Shape: (batch_size*seq_len*topk)
|
| 232 |
+
batch_size (int):
|
| 233 |
+
The size of the batch.
|
| 234 |
+
seq_len (int):
|
| 235 |
+
The length of the input sequence.
|
| 236 |
+
topk (int):
|
| 237 |
+
The number of top elements selected (`topk`) per token during the selection process.
|
| 238 |
+
routing_weights (torch.Tensor):
|
| 239 |
+
Routing weights assigned to the top-k selected outputs when reconstructing the final output.
|
| 240 |
+
Shape: (batch_size, seq_len, topk)
|
| 241 |
+
mask (torch.Tensor):
|
| 242 |
+
Boolean mask indicating valid positions in the sequence.
|
| 243 |
+
Shape: (batch*num_memories, max_len)
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
restored_x (torch.Tensor):
|
| 247 |
+
The reconstructed output tensor in the original input sequence shape.
|
| 248 |
+
Shape: (batch_size, seq_len, hidden_size)
|
| 249 |
+
'''
|
| 250 |
+
transformed_x = transformed_x.transpose(0, 1).reshape(
|
| 251 |
+
(-1, transformed_x.shape[2], transformed_x.shape[3]))
|
| 252 |
+
b, s, k, d = batch_size, seq_len, topk, transformed_x.shape[2]
|
| 253 |
+
gathered_x = transformed_x.reshape(
|
| 254 |
+
(transformed_x.shape[0] * transformed_x.shape[1], transformed_x.shape[2]))
|
| 255 |
+
mask_expanded = mask.reshape(-1).unsqueeze(-1).expand_as(gathered_x)
|
| 256 |
+
gathered_x = gathered_x * mask_expanded
|
| 257 |
+
|
| 258 |
+
assert (indices >= 0).all(), "Indices should be non-negative"
|
| 259 |
+
|
| 260 |
+
resortd_x = torch.zeros((b * s * k, d), device=gathered_x.device, dtype=gathered_x.dtype).scatter_add_(
|
| 261 |
+
0,
|
| 262 |
+
indices.reshape(-1).unsqueeze(-1).expand(-1, d),
|
| 263 |
+
gathered_x,
|
| 264 |
+
)
|
| 265 |
+
assert (indices < resortd_x.size(0)).all(), "Indices should be less than resortd_x size"
|
| 266 |
+
|
| 267 |
+
inverse_indices = sorted_indices.argsort()
|
| 268 |
+
rearranged_x_flat = resortd_x[inverse_indices]
|
| 269 |
+
restored_x = rearranged_x_flat.reshape((b, s * k, d))
|
| 270 |
+
restored_x = restored_x.reshape(b, s, k, d) * routing_weights.reshape(b, s, k).unsqueeze(-1)
|
| 271 |
+
restored_x = restored_x.sum(dim=2)
|
| 272 |
+
return restored_x
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class MomAttention(nn.Module):
|
| 276 |
+
"""
|
| 277 |
+
The layer implementaion for [MoM: Linear Sequence Modeling with Mixture-of-Memories](https://arxiv.org/abs/2502.13685).
|
| 278 |
+
"""
|
| 279 |
+
|
| 280 |
+
def __init__(
|
| 281 |
+
self,
|
| 282 |
+
hidden_size: int = 2048,
|
| 283 |
+
head_dim: int = 256,
|
| 284 |
+
num_heads: int = 4,
|
| 285 |
+
expand_v: float = 2,
|
| 286 |
+
mode: str = 'chunk',
|
| 287 |
+
use_output_gate: bool = True,
|
| 288 |
+
use_short_conv: bool = True,
|
| 289 |
+
conv_size: int = 4,
|
| 290 |
+
conv_bias: bool = False,
|
| 291 |
+
layer_idx: int = None,
|
| 292 |
+
norm_eps: float = 1e-5,
|
| 293 |
+
num_memories: int = 8,
|
| 294 |
+
topk: int = 2,
|
| 295 |
+
capacity: float = 1.0,
|
| 296 |
+
shared_mem: bool = False,
|
| 297 |
+
single_kv_proj: bool = False,
|
| 298 |
+
**kwargs
|
| 299 |
+
) -> MomAttention:
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.num_memories = num_memories
|
| 302 |
+
self.topk = topk
|
| 303 |
+
self.capacity = capacity
|
| 304 |
+
self.shared_mem = shared_mem
|
| 305 |
+
self.single_kv_proj = single_kv_proj
|
| 306 |
+
|
| 307 |
+
self.mode = mode
|
| 308 |
+
|
| 309 |
+
self.hidden_size = hidden_size
|
| 310 |
+
self.expand_v = expand_v
|
| 311 |
+
|
| 312 |
+
self.use_output_gate = use_output_gate
|
| 313 |
+
self.use_short_conv = use_short_conv
|
| 314 |
+
self.conv_size = conv_size
|
| 315 |
+
self.conv_bias = conv_bias
|
| 316 |
+
|
| 317 |
+
self.head_dim = head_dim
|
| 318 |
+
self.num_heads = num_heads
|
| 319 |
+
|
| 320 |
+
self.key_dim = int(self.num_heads * self.head_dim)
|
| 321 |
+
self.value_dim = int(self.key_dim * self.expand_v)
|
| 322 |
+
self.head_qk_dim = head_dim
|
| 323 |
+
self.head_v_dim = int(head_dim * self.expand_v)
|
| 324 |
+
self.layer_idx = layer_idx
|
| 325 |
+
self.silu = nn.SiLU()
|
| 326 |
+
|
| 327 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 328 |
+
|
| 329 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 330 |
+
self.gate = nn.Linear(self.hidden_size, self.num_memories, bias=False)
|
| 331 |
+
if self.single_kv_proj:
|
| 332 |
+
self.shared_k = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 333 |
+
self.shared_v = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 334 |
+
self.shared_b = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 335 |
+
self.shared_a = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 336 |
+
else:
|
| 337 |
+
self.k_proj = nn.ModuleList([
|
| 338 |
+
nn.Linear(self.hidden_size, self.key_dim, bias=False)
|
| 339 |
+
for _ in range(self.num_memories)
|
| 340 |
+
])
|
| 341 |
+
self.v_proj = nn.ModuleList([
|
| 342 |
+
nn.Linear(self.hidden_size, self.value_dim, bias=False)
|
| 343 |
+
for _ in range(self.num_memories)
|
| 344 |
+
])
|
| 345 |
+
self.b_proj = nn.ModuleList([
|
| 346 |
+
nn.Linear(self.hidden_size, self.num_heads, bias=False)
|
| 347 |
+
for _ in range(self.num_memories)
|
| 348 |
+
])
|
| 349 |
+
self.a_proj = nn.ModuleList([
|
| 350 |
+
nn.Linear(self.hidden_size, self.num_heads, bias=False)
|
| 351 |
+
for _ in range(self.num_memories)
|
| 352 |
+
])
|
| 353 |
+
if self.shared_mem:
|
| 354 |
+
self.shared_k = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 355 |
+
self.shared_v = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 356 |
+
self.shared_b = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 357 |
+
self.shared_a = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 358 |
+
|
| 359 |
+
A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 360 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 361 |
+
self.A_log._no_weight_decay = True
|
| 362 |
+
# hard coded for now
|
| 363 |
+
dt_min = 0.001
|
| 364 |
+
dt_max = 0.1
|
| 365 |
+
dt_init_floor = 1e-4
|
| 366 |
+
dt = torch.exp(
|
| 367 |
+
torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 368 |
+
+ math.log(dt_min)
|
| 369 |
+
)
|
| 370 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 371 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 372 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 373 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 374 |
+
# Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 375 |
+
# name.endswith("bias") in param_grouping.py
|
| 376 |
+
self.dt_bias._no_weight_decay = True
|
| 377 |
+
|
| 378 |
+
if use_short_conv:
|
| 379 |
+
self.conv_size = conv_size
|
| 380 |
+
self.q_conv1d = ShortConvolution(
|
| 381 |
+
hidden_size=self.key_dim,
|
| 382 |
+
kernel_size=conv_size,
|
| 383 |
+
bias=conv_bias,
|
| 384 |
+
activation='silu'
|
| 385 |
+
)
|
| 386 |
+
self.k_conv1d = ShortConvolution(
|
| 387 |
+
hidden_size=self.key_dim,
|
| 388 |
+
kernel_size=conv_size,
|
| 389 |
+
bias=conv_bias,
|
| 390 |
+
activation='silu'
|
| 391 |
+
)
|
| 392 |
+
self.v_conv1d = ShortConvolution(
|
| 393 |
+
hidden_size=self.value_dim,
|
| 394 |
+
kernel_size=conv_size,
|
| 395 |
+
bias=conv_bias,
|
| 396 |
+
activation='silu'
|
| 397 |
+
)
|
| 398 |
+
else:
|
| 399 |
+
raise UserWarning(
|
| 400 |
+
"ShortConvolution is crucial to the performance. "
|
| 401 |
+
"Do not turn it off, i.e., setting `use_short_conv=False` unless you know what you are doing."
|
| 402 |
+
)
|
| 403 |
+
if use_output_gate:
|
| 404 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 405 |
+
self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=norm_eps)
|
| 406 |
+
else:
|
| 407 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 408 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 409 |
+
self.apply(self._initialize_weights)
|
| 410 |
+
|
| 411 |
+
def _initialize_weights(self, module: nn.Module):
|
| 412 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 413 |
+
return
|
| 414 |
+
if isinstance(module, nn.Linear):
|
| 415 |
+
nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 416 |
+
if module.bias is not None:
|
| 417 |
+
nn.init.zeros_(module.bias)
|
| 418 |
+
module._is_hf_initialized = True
|
| 419 |
+
|
| 420 |
+
def forward(
|
| 421 |
+
self,
|
| 422 |
+
hidden_states: torch.Tensor,
|
| 423 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 424 |
+
past_key_values: Optional[Cache] = None,
|
| 425 |
+
use_cache: Optional[bool] = False,
|
| 426 |
+
output_attentions: Optional[bool] = False,
|
| 427 |
+
**kwargs: Unpack[Dict]
|
| 428 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 429 |
+
if attention_mask is not None:
|
| 430 |
+
attention_mask = (attention_mask == 1)
|
| 431 |
+
assert len(attention_mask.shape) == 2, (
|
| 432 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 433 |
+
"for padding purposes (0 indicating padding). "
|
| 434 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
origin_cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 438 |
+
if origin_cu_seqlens is not None:
|
| 439 |
+
hidden_states, attention_mask = self.cu2pad(hidden_states, origin_cu_seqlens)
|
| 440 |
+
|
| 441 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 442 |
+
if self.training:
|
| 443 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 444 |
+
|
| 445 |
+
last_state = None
|
| 446 |
+
# _, q_len = hidden_states.shape[0], hidden_states.shape[1]
|
| 447 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 448 |
+
last_state = past_key_values[self.layer_idx]
|
| 449 |
+
|
| 450 |
+
# 🔍 topk gating
|
| 451 |
+
router_logits = self.gate(hidden_states) # (bsz, q_len, num_memories)
|
| 452 |
+
scores = F.softmax(router_logits, dim=2, dtype=torch.float)
|
| 453 |
+
routing_weights, selected_memories = torch.topk(scores, self.topk, dim=-1) # (bsz, seq, topk)
|
| 454 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 455 |
+
routing_weights = routing_weights.to(hidden_states.dtype) # we cast back to the input dtype
|
| 456 |
+
routing_weights_full = torch.zeros(
|
| 457 |
+
routing_weights.shape[0],
|
| 458 |
+
routing_weights.shape[1],
|
| 459 |
+
self.num_memories,
|
| 460 |
+
dtype=routing_weights.dtype,
|
| 461 |
+
device=routing_weights.device
|
| 462 |
+
).scatter(-1, selected_memories, routing_weights)
|
| 463 |
+
routing_mask = routing_weights_full.bool().int()
|
| 464 |
+
|
| 465 |
+
# if self.use_output_gate:
|
| 466 |
+
# o_g = self.g_proj(hidden_states)
|
| 467 |
+
|
| 468 |
+
batch_size, seq_len = hidden_states.shape[0], hidden_states.shape[1]
|
| 469 |
+
|
| 470 |
+
shared_hidden_states = hidden_states
|
| 471 |
+
hidden_states, indices, sorted_indices, max_len, mask, mask_2 = transform(
|
| 472 |
+
hidden_states, routing_mask, self.num_memories, selected_memories, attention_mask)
|
| 473 |
+
|
| 474 |
+
q = self.q_proj(hidden_states)
|
| 475 |
+
if self.single_kv_proj:
|
| 476 |
+
k = self.shared_k(hidden_states)
|
| 477 |
+
v = self.shared_v(hidden_states)
|
| 478 |
+
beta = self.shared_b(hidden_states).sigmoid()
|
| 479 |
+
g = -self.A_log.float().exp() * F.softplus(self.shared_a(hidden_states).float() + self.dt_bias)
|
| 480 |
+
else:
|
| 481 |
+
k = torch.stack([k_expert(hidden_states[i]) for i, k_expert in enumerate(self.k_proj)], dim=0)
|
| 482 |
+
v = torch.stack([v_expert(hidden_states[i]) for i, v_expert in enumerate(self.v_proj)], dim=0)
|
| 483 |
+
beta = torch.stack([b_expert(hidden_states[i]).sigmoid() for i, b_expert in enumerate(self.b_proj)], dim=0)
|
| 484 |
+
g = torch.stack([-self.A_log.float().exp() * F.softplus(a_expert(hidden_states[i]).float() + self.dt_bias)
|
| 485 |
+
for i, a_expert in enumerate(self.a_proj)], dim=0)
|
| 486 |
+
|
| 487 |
+
q, k, v, g, beta, mask_2 = (rearrange(x, 'e b l ... -> (e b) l ...') for x in (q, k, v, g, beta, mask_2))
|
| 488 |
+
cu_q, cu_k, cu_v, cu_g, cu_beta, indices_q, cu_seqlen_all, max_seq_lens = _upad_input(q, k, v, g, beta, mask_2)
|
| 489 |
+
cu_seqlens, reverse_indices = cu_seqlen_all[0].to(torch.long).unique(return_inverse=True)
|
| 490 |
+
cu_q, cu_k, cu_v, cu_g, cu_beta = (x.unsqueeze(0).contiguous() for x in (cu_q, cu_k, cu_v, cu_g, cu_beta))
|
| 491 |
+
|
| 492 |
+
if self.use_short_conv:
|
| 493 |
+
conv_state_q, conv_state_k, conv_state_v = [None, None], [None, None], [None, None]
|
| 494 |
+
if last_state is not None:
|
| 495 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 496 |
+
|
| 497 |
+
conv_cu_seqlens = cu_seqlens
|
| 498 |
+
padded = False
|
| 499 |
+
if self.training:
|
| 500 |
+
conv_cu_seqlens = None
|
| 501 |
+
elif seq_len != 1 and (cu_seqlens[1:] - cu_seqlens[:-1]).min().item() < self.conv_size:
|
| 502 |
+
padded = True
|
| 503 |
+
conv_cu_seqlens, cu_q, cu_k, cu_v, pad_lengths = self.pad_for_conv(cu_seqlens, cu_q, cu_k, cu_v)
|
| 504 |
+
|
| 505 |
+
conv_q = self.prepare_recurrent_state(
|
| 506 |
+
conv_state_q[0],
|
| 507 |
+
conv_cu_seqlens,
|
| 508 |
+
cu_seqlen_all[0],
|
| 509 |
+
reverse_indices,
|
| 510 |
+
batch_size
|
| 511 |
+
)
|
| 512 |
+
cu_q, conv_q_new = self.q_conv1d(
|
| 513 |
+
x=cu_q,
|
| 514 |
+
cache=conv_q,
|
| 515 |
+
output_final_state=use_cache,
|
| 516 |
+
cu_seqlens=conv_cu_seqlens,
|
| 517 |
+
)
|
| 518 |
+
conv_state_q[0] = self.handle_recurrent_state(
|
| 519 |
+
conv_state_q[0],
|
| 520 |
+
conv_q_new,
|
| 521 |
+
conv_cu_seqlens,
|
| 522 |
+
cu_seqlen_all[0],
|
| 523 |
+
reverse_indices
|
| 524 |
+
)
|
| 525 |
+
conv_k = self.prepare_recurrent_state(
|
| 526 |
+
conv_state_k[0],
|
| 527 |
+
conv_cu_seqlens,
|
| 528 |
+
cu_seqlen_all[0],
|
| 529 |
+
reverse_indices,
|
| 530 |
+
batch_size
|
| 531 |
+
)
|
| 532 |
+
cu_k, conv_k_new = self.k_conv1d(
|
| 533 |
+
x=cu_k,
|
| 534 |
+
cache=conv_k,
|
| 535 |
+
output_final_state=use_cache,
|
| 536 |
+
cu_seqlens=conv_cu_seqlens,
|
| 537 |
+
)
|
| 538 |
+
conv_state_k[0] = self.handle_recurrent_state(
|
| 539 |
+
conv_state_k[0],
|
| 540 |
+
conv_k_new,
|
| 541 |
+
conv_cu_seqlens,
|
| 542 |
+
cu_seqlen_all[0],
|
| 543 |
+
reverse_indices
|
| 544 |
+
)
|
| 545 |
+
conv_v = self.prepare_recurrent_state(
|
| 546 |
+
conv_state_v[0],
|
| 547 |
+
conv_cu_seqlens,
|
| 548 |
+
cu_seqlen_all[0],
|
| 549 |
+
reverse_indices,
|
| 550 |
+
batch_size
|
| 551 |
+
)
|
| 552 |
+
cu_v, conv_v_new = self.v_conv1d(
|
| 553 |
+
x=cu_v,
|
| 554 |
+
cache=conv_v,
|
| 555 |
+
output_final_state=use_cache,
|
| 556 |
+
cu_seqlens=conv_cu_seqlens,
|
| 557 |
+
)
|
| 558 |
+
conv_state_v[0] = self.handle_recurrent_state(
|
| 559 |
+
conv_state_v[0],
|
| 560 |
+
conv_v_new, conv_cu_seqlens,
|
| 561 |
+
cu_seqlen_all[0],
|
| 562 |
+
reverse_indices
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
if padded:
|
| 566 |
+
cu_q, cu_k, cu_v = self.unpad_after_conv(conv_cu_seqlens, cu_seqlens, cu_q, cu_k, cu_v, pad_lengths)
|
| 567 |
+
|
| 568 |
+
else:
|
| 569 |
+
q, k, v = self.silu(q), self.silu(k), self.silu(v),
|
| 570 |
+
|
| 571 |
+
cu_q, cu_k, cu_v = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', h=self.num_heads), (cu_q, cu_k, cu_v))
|
| 572 |
+
|
| 573 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else [
|
| 574 |
+
None for _ in range(1 + self.shared_mem)]
|
| 575 |
+
if mode == 'chunk':
|
| 576 |
+
o, recurrent_state_ = chunk_gated_delta_rule(
|
| 577 |
+
q=cu_q,
|
| 578 |
+
k=cu_k,
|
| 579 |
+
v=cu_v,
|
| 580 |
+
g=cu_g,
|
| 581 |
+
beta=cu_beta,
|
| 582 |
+
initial_state=recurrent_state[0],
|
| 583 |
+
output_final_state=use_cache,
|
| 584 |
+
use_qk_l2norm_in_kernel=True,
|
| 585 |
+
cu_seqlens=cu_seqlens,
|
| 586 |
+
)
|
| 587 |
+
recurrent_state[0] = self.handle_recurrent_state(
|
| 588 |
+
recurrent_state[0],
|
| 589 |
+
recurrent_state_,
|
| 590 |
+
cu_seqlens,
|
| 591 |
+
cu_seqlen_all[0],
|
| 592 |
+
reverse_indices,
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
elif mode == 'fused_recurrent':
|
| 596 |
+
memories = self.prepare_recurrent_state(
|
| 597 |
+
recurrent_state[0],
|
| 598 |
+
cu_seqlens, cu_seqlen_all[0],
|
| 599 |
+
reverse_indices, batch_size
|
| 600 |
+
)
|
| 601 |
+
o, recurrent_state_ = fused_recurrent_gated_delta_rule(
|
| 602 |
+
q=cu_q,
|
| 603 |
+
k=cu_k,
|
| 604 |
+
v=cu_v,
|
| 605 |
+
g=cu_g,
|
| 606 |
+
beta=cu_beta,
|
| 607 |
+
initial_state=memories,
|
| 608 |
+
output_final_state=use_cache,
|
| 609 |
+
use_qk_l2norm_in_kernel=True,
|
| 610 |
+
cu_seqlens=cu_seqlens,
|
| 611 |
+
)
|
| 612 |
+
recurrent_state[0] = self.handle_recurrent_state(
|
| 613 |
+
recurrent_state[0],
|
| 614 |
+
recurrent_state_,
|
| 615 |
+
cu_seqlens,
|
| 616 |
+
cu_seqlen_all[0],
|
| 617 |
+
reverse_indices,
|
| 618 |
+
)
|
| 619 |
+
|
| 620 |
+
o = o.squeeze(0).contiguous()
|
| 621 |
+
o = pad_input(o, indices_q, batch_size*self.num_memories, max_len)
|
| 622 |
+
o = rearrange(o, '(e b) l h d -> e b l (h d)', b=batch_size)
|
| 623 |
+
o = reconstruct(o, indices=indices, sorted_indices=sorted_indices, batch_size=batch_size,
|
| 624 |
+
seq_len=seq_len, topk=self.topk, routing_weights=routing_weights, mask=mask)
|
| 625 |
+
o = rearrange(o, 'b l (h d) -> b l h d', h=self.num_heads)
|
| 626 |
+
|
| 627 |
+
if self.shared_mem:
|
| 628 |
+
shared_o = self.shared_o(shared_hidden_states, attention_mask, recurrent_state,
|
| 629 |
+
use_cache, conv_state_q, conv_state_k, conv_state_v)
|
| 630 |
+
o += shared_o
|
| 631 |
+
|
| 632 |
+
if past_key_values is not None:
|
| 633 |
+
past_key_values.update(
|
| 634 |
+
recurrent_state=recurrent_state,
|
| 635 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 636 |
+
layer_idx=self.layer_idx,
|
| 637 |
+
offset=q.shape[2]
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
if self.use_output_gate:
|
| 641 |
+
g = rearrange(self.g_proj(shared_hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
|
| 642 |
+
o = self.o_norm(o, g)
|
| 643 |
+
else:
|
| 644 |
+
o = self.o_norm(o)
|
| 645 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 646 |
+
o = self.o_proj(o)
|
| 647 |
+
|
| 648 |
+
if origin_cu_seqlens is not None:
|
| 649 |
+
indices, _, _ = get_unpad_data(attention_mask[:, -seq_len:])
|
| 650 |
+
o = index_first_axis(rearrange(o, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 651 |
+
|
| 652 |
+
return o, None, past_key_values, router_logits.view(-1, self.num_memories)
|
| 653 |
+
|
| 654 |
+
def shared_o(
|
| 655 |
+
self,
|
| 656 |
+
hidden_states: torch.Tensor,
|
| 657 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 658 |
+
recurrent_state=None,
|
| 659 |
+
use_cache: Optional[bool] = False,
|
| 660 |
+
conv_state_q=[None, None],
|
| 661 |
+
conv_state_k=[None, None],
|
| 662 |
+
conv_state_v=[None, None],
|
| 663 |
+
**kwargs
|
| 664 |
+
) -> torch.Tensor:
|
| 665 |
+
if attention_mask is not None:
|
| 666 |
+
assert len(attention_mask.shape) == 2, (
|
| 667 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 668 |
+
"for padding purposes (0 indicating padding). "
|
| 669 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 673 |
+
if self.training:
|
| 674 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 675 |
+
|
| 676 |
+
cu_seqlens = None
|
| 677 |
+
if attention_mask is not None:
|
| 678 |
+
batch_size, q_len = hidden_states.shape[0], hidden_states.shape[1]
|
| 679 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 680 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 681 |
+
|
| 682 |
+
if self.use_short_conv:
|
| 683 |
+
q, conv_state_q[1] = self.q_conv1d(
|
| 684 |
+
x=self.q_proj(hidden_states),
|
| 685 |
+
cache=conv_state_q[1],
|
| 686 |
+
output_final_state=use_cache,
|
| 687 |
+
cu_seqlens=cu_seqlens
|
| 688 |
+
)
|
| 689 |
+
k, conv_state_k[1] = self.k_conv1d(
|
| 690 |
+
x=self.shared_k(hidden_states),
|
| 691 |
+
cache=conv_state_k[1],
|
| 692 |
+
output_final_state=use_cache,
|
| 693 |
+
cu_seqlens=cu_seqlens
|
| 694 |
+
)
|
| 695 |
+
v, conv_state_v[1] = self.v_conv1d(
|
| 696 |
+
x=self.shared_v(hidden_states),
|
| 697 |
+
cache=conv_state_v[1],
|
| 698 |
+
output_final_state=use_cache,
|
| 699 |
+
cu_seqlens=cu_seqlens
|
| 700 |
+
)
|
| 701 |
+
else:
|
| 702 |
+
q = self.silu(self.q_proj(hidden_states))
|
| 703 |
+
k = self.silu(self.shared_k(hidden_states))
|
| 704 |
+
v = self.silu(self.shared_v(hidden_states))
|
| 705 |
+
|
| 706 |
+
q, k, v = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', h=self.num_heads), (q, k, v))
|
| 707 |
+
beta = self.shared_b(hidden_states).sigmoid()
|
| 708 |
+
g = -self.A_log.float().exp() * F.softplus(self.shared_a(hidden_states).float() + self.dt_bias)
|
| 709 |
+
|
| 710 |
+
if mode == 'chunk':
|
| 711 |
+
o, recurrent_state[-1] = chunk_gated_delta_rule(
|
| 712 |
+
q=q,
|
| 713 |
+
k=k,
|
| 714 |
+
v=v,
|
| 715 |
+
g=g,
|
| 716 |
+
beta=beta,
|
| 717 |
+
initial_state=recurrent_state[-1],
|
| 718 |
+
output_final_state=use_cache,
|
| 719 |
+
cu_seqlens=cu_seqlens,
|
| 720 |
+
use_qk_l2norm_in_kernel=True
|
| 721 |
+
)
|
| 722 |
+
elif mode == 'fused_recurrent':
|
| 723 |
+
o, recurrent_state[-1] = fused_recurrent_gated_delta_rule(
|
| 724 |
+
q=q,
|
| 725 |
+
k=k,
|
| 726 |
+
v=v,
|
| 727 |
+
g=g,
|
| 728 |
+
beta=beta,
|
| 729 |
+
initial_state=recurrent_state[-1],
|
| 730 |
+
output_final_state=use_cache,
|
| 731 |
+
cu_seqlens=cu_seqlens,
|
| 732 |
+
use_qk_l2norm_in_kernel=True
|
| 733 |
+
)
|
| 734 |
+
else:
|
| 735 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 736 |
+
|
| 737 |
+
if attention_mask is not None:
|
| 738 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 739 |
+
return o
|
| 740 |
+
|
| 741 |
+
def cu2pad(self, x, cu_seqlens):
|
| 742 |
+
batch_size = cu_seqlens.shape[0] - 1
|
| 743 |
+
max_len = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
|
| 744 |
+
indices = torch.tensor([], dtype=torch.long, device=x.device)
|
| 745 |
+
attention_mask = torch.ones((batch_size, max_len), dtype=torch.bool, device=x.device)
|
| 746 |
+
for i in range(batch_size):
|
| 747 |
+
seq_len = cu_seqlens[i+1] - cu_seqlens[i]
|
| 748 |
+
pad_len = max_len - seq_len
|
| 749 |
+
batch_indices = torch.arange(pad_len, max_len, device=x.device)
|
| 750 |
+
batch_indices = batch_indices + i * max_len
|
| 751 |
+
indices = torch.cat([indices, batch_indices])
|
| 752 |
+
attention_mask[i, :pad_len] = False
|
| 753 |
+
x = pad_input(x.squeeze(0), indices, batch_size, max_len)
|
| 754 |
+
return x, attention_mask
|
| 755 |
+
|
| 756 |
+
def pad_for_conv(self, cu_seqlens, cu_q, cu_k, cu_v):
|
| 757 |
+
lengths = cu_seqlens[1:] - cu_seqlens[:-1]
|
| 758 |
+
pad_lengths = torch.clamp(self.conv_size - lengths, min=0)
|
| 759 |
+
new_lengths = lengths + pad_lengths
|
| 760 |
+
new_cu_seqlens = torch.cat([
|
| 761 |
+
torch.tensor([0], device=cu_seqlens.device, dtype=cu_seqlens.dtype),
|
| 762 |
+
torch.cumsum(new_lengths, dim=0)
|
| 763 |
+
])
|
| 764 |
+
final_total_len = new_cu_seqlens[-1].item()
|
| 765 |
+
new_q = torch.zeros((1, final_total_len, cu_q.shape[-1]), dtype=cu_q.dtype, device=cu_q.device)
|
| 766 |
+
new_k = torch.zeros((1, final_total_len, cu_k.shape[-1]), dtype=cu_k.dtype, device=cu_k.device)
|
| 767 |
+
new_v = torch.zeros((1, final_total_len, cu_v.shape[-1]), dtype=cu_v.dtype, device=cu_v.device)
|
| 768 |
+
num_sequences = len(lengths)
|
| 769 |
+
for i in range(num_sequences):
|
| 770 |
+
src_start = cu_seqlens[i]
|
| 771 |
+
src_end = cu_seqlens[i+1]
|
| 772 |
+
dest_start = new_cu_seqlens[i] + pad_lengths[i]
|
| 773 |
+
dest_end = new_cu_seqlens[i+1]
|
| 774 |
+
new_q[:, dest_start:dest_end, ...] = cu_q[:, src_start:src_end, ...]
|
| 775 |
+
new_k[:, dest_start:dest_end, ...] = cu_k[:, src_start:src_end, ...]
|
| 776 |
+
new_v[:, dest_start:dest_end, ...] = cu_v[:, src_start:src_end, ...]
|
| 777 |
+
|
| 778 |
+
return new_cu_seqlens, new_q, new_k, new_v, pad_lengths
|
| 779 |
+
|
| 780 |
+
def unpad_after_conv(self, conv_cu_seqlens, cu_seqlens, cu_q, cu_k, cu_v, pad_lengths):
|
| 781 |
+
original_total_len = cu_seqlens[-1].item()
|
| 782 |
+
orig_q = torch.empty((1, original_total_len, cu_q.shape[-1]), dtype=cu_q.dtype, device=cu_q.device)
|
| 783 |
+
orig_k = torch.empty((1, original_total_len, cu_k.shape[-1]), dtype=cu_k.dtype, device=cu_k.device)
|
| 784 |
+
orig_v = torch.empty((1, original_total_len, cu_v.shape[-1]), dtype=cu_v.dtype, device=cu_v.device)
|
| 785 |
+
|
| 786 |
+
num_sequences = len(pad_lengths)
|
| 787 |
+
for i in range(num_sequences):
|
| 788 |
+
dest_start = cu_seqlens[i]
|
| 789 |
+
dest_end = cu_seqlens[i+1]
|
| 790 |
+
src_start = conv_cu_seqlens[i] + pad_lengths[i]
|
| 791 |
+
src_end = conv_cu_seqlens[i+1]
|
| 792 |
+
|
| 793 |
+
orig_q[:, dest_start:dest_end, ...] = cu_q[:, src_start:src_end, ...]
|
| 794 |
+
orig_k[:, dest_start:dest_end, ...] = cu_k[:, src_start:src_end, ...]
|
| 795 |
+
orig_v[:, dest_start:dest_end, ...] = cu_v[:, src_start:src_end, ...]
|
| 796 |
+
return orig_q, orig_k, orig_v
|
| 797 |
+
|
| 798 |
+
def prepare_recurrent_state(self, recurrent_state, cu_seqlens, cu_seqlen_all, reverse_indices, batch_size):
|
| 799 |
+
if recurrent_state is None:
|
| 800 |
+
return None
|
| 801 |
+
|
| 802 |
+
if cu_seqlens is None:
|
| 803 |
+
return recurrent_state
|
| 804 |
+
|
| 805 |
+
total_len = len(cu_seqlen_all)
|
| 806 |
+
if len(cu_seqlens) != total_len:
|
| 807 |
+
# select memories that are activated
|
| 808 |
+
memories = torch.zeros_like(recurrent_state[:self.topk*batch_size])
|
| 809 |
+
mem_id = 0
|
| 810 |
+
for i in range(total_len-1):
|
| 811 |
+
if cu_seqlen_all[i] != cu_seqlen_all[i+1]:
|
| 812 |
+
memories[mem_id] = recurrent_state[i]
|
| 813 |
+
mem_id += 1
|
| 814 |
+
assert mem_id == self.topk * batch_size, f"The number of memories {mem_id} is not correct."
|
| 815 |
+
else:
|
| 816 |
+
memories = recurrent_state
|
| 817 |
+
|
| 818 |
+
return memories
|
| 819 |
+
|
| 820 |
+
def handle_recurrent_state(self, recurrent_state, recurrent_state_new, cu_seqlens, cu_seqlen_all, reverse_indices):
|
| 821 |
+
if recurrent_state_new is None:
|
| 822 |
+
return None
|
| 823 |
+
if cu_seqlens is None:
|
| 824 |
+
return recurrent_state_new
|
| 825 |
+
if recurrent_state is None:
|
| 826 |
+
recurrent_state = torch.zeros_like(recurrent_state_new[reverse_indices[1:]-1])
|
| 827 |
+
total_len = len(cu_seqlen_all)
|
| 828 |
+
if len(cu_seqlens) != total_len:
|
| 829 |
+
for i in range(total_len-1):
|
| 830 |
+
if cu_seqlen_all[i] != cu_seqlen_all[i+1]:
|
| 831 |
+
recurrent_state[i] = recurrent_state_new[reverse_indices[i+1]-1]
|
| 832 |
+
else:
|
| 833 |
+
recurrent_state = recurrent_state_new
|
| 834 |
+
return recurrent_state
|
multiscale_retention.py
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from einops import rearrange, repeat
|
| 11 |
+
from transformers.activations import ACT2FN
|
| 12 |
+
|
| 13 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 14 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 15 |
+
from fla.modules.rotary import RotaryEmbedding
|
| 16 |
+
from fla.ops.retention import chunk_retention, fused_chunk_retention, fused_recurrent_retention, parallel_retention
|
| 17 |
+
from fla.ops.utils.index import prepare_lens_from_mask
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from transformers.processing_utils import Unpack
|
| 21 |
+
|
| 22 |
+
from fla.models.utils import Cache
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MultiScaleRetention(nn.Module):
|
| 26 |
+
r"""
|
| 27 |
+
The layer implementaion for [Retentive Network: A Successor to Transformer for Large Language Models](https://arxiv.org/pdf/2307.08621.pdf). # noqa
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
mode (str, Optional):
|
| 31 |
+
Which Retention kernel to use.
|
| 32 |
+
Currently available: `chunk`, `fused_recurrent`, `parallel`, and `fused_chunk`.
|
| 33 |
+
Default: `chunk`.
|
| 34 |
+
hidden_size (int, Optional):
|
| 35 |
+
The hidden size of the input. Default: 1024.
|
| 36 |
+
expand_k (float, Optional):
|
| 37 |
+
The expansion ratio for the key dim. Default: 1.0.
|
| 38 |
+
expand_v (float, Optional):
|
| 39 |
+
The expansion ratio for the value dim. Default: 2.0.
|
| 40 |
+
num_heads (int, Optional):
|
| 41 |
+
The number of heads. Default: 8.
|
| 42 |
+
num_kv_heads (int, Optional):
|
| 43 |
+
The number of key/value heads, used for MQA. Default: None.
|
| 44 |
+
feature_map (str, Optional):
|
| 45 |
+
Feature map function applied to queries/keys. Default: None.
|
| 46 |
+
use_short_conv (bool, Optional):
|
| 47 |
+
Whether to use short convolutions. Default: `False`.
|
| 48 |
+
conv_size (int, Optional):
|
| 49 |
+
The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
|
| 50 |
+
conv_bias (bool, Optional):
|
| 51 |
+
Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
|
| 52 |
+
use_output_gate (bool, Optional):
|
| 53 |
+
Whether to use output gate. Default: `True`.
|
| 54 |
+
gate_fn (str, Optional):
|
| 55 |
+
The activation function for the output gate. Default: `swish`.
|
| 56 |
+
elementwise_affine (bool, Optional):
|
| 57 |
+
If `True`, applies elementwise affine to LayerNorm with learnable parameters. Default: `True`.
|
| 58 |
+
norm_eps (float, Optional):
|
| 59 |
+
The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5.
|
| 60 |
+
fuse_norm (bool, Optional):
|
| 61 |
+
Whether to fuse the norm and the output gate for better memory footprint. Default: `True`.
|
| 62 |
+
layer_idx (int, Optional):
|
| 63 |
+
The index of the layer. Default: None.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def __init__(
|
| 67 |
+
self,
|
| 68 |
+
mode: str = 'chunk',
|
| 69 |
+
hidden_size: int = 1024,
|
| 70 |
+
expand_k: float = 1.0,
|
| 71 |
+
expand_v: float = 2.0,
|
| 72 |
+
num_heads: int = 8,
|
| 73 |
+
num_kv_heads: Optional[int] = None,
|
| 74 |
+
feature_map: Optional[str] = None,
|
| 75 |
+
use_short_conv: bool = False,
|
| 76 |
+
conv_size: int = 4,
|
| 77 |
+
conv_bias: bool = False,
|
| 78 |
+
use_output_gate: bool = True,
|
| 79 |
+
gate_fn: str = 'swish',
|
| 80 |
+
elementwise_affine: Optional[bool] = True,
|
| 81 |
+
norm_eps: float = 1e-5,
|
| 82 |
+
fuse_norm: bool = True,
|
| 83 |
+
layer_idx: int = None,
|
| 84 |
+
**kwargs
|
| 85 |
+
) -> MultiScaleRetention:
|
| 86 |
+
super().__init__()
|
| 87 |
+
|
| 88 |
+
self.mode = mode
|
| 89 |
+
self.hidden_size = hidden_size
|
| 90 |
+
self.expand_k = expand_k
|
| 91 |
+
self.expand_v = expand_v
|
| 92 |
+
self.num_heads = num_heads
|
| 93 |
+
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
| 94 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 95 |
+
self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None
|
| 96 |
+
|
| 97 |
+
self.use_short_conv = use_short_conv
|
| 98 |
+
self.conv_size = conv_size
|
| 99 |
+
self.conv_bias = conv_bias
|
| 100 |
+
self.use_output_gate = use_output_gate
|
| 101 |
+
|
| 102 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 103 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 104 |
+
self.key_dim_per_group = self.key_dim // self.num_kv_groups
|
| 105 |
+
self.value_dim_per_group = self.value_dim // self.num_kv_groups
|
| 106 |
+
self.layer_idx = layer_idx
|
| 107 |
+
|
| 108 |
+
assert mode in ['chunk', 'fused_chunk', 'parallel', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 109 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 110 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 111 |
+
|
| 112 |
+
self.head_k_dim = self.key_dim // num_heads
|
| 113 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 114 |
+
|
| 115 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 116 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
|
| 117 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
|
| 118 |
+
if self.use_output_gate:
|
| 119 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 120 |
+
|
| 121 |
+
if use_short_conv:
|
| 122 |
+
self.conv_size = conv_size
|
| 123 |
+
self.q_conv1d = ShortConvolution(
|
| 124 |
+
hidden_size=self.key_dim,
|
| 125 |
+
kernel_size=conv_size,
|
| 126 |
+
bias=conv_bias,
|
| 127 |
+
activation='silu'
|
| 128 |
+
)
|
| 129 |
+
self.k_conv1d = ShortConvolution(
|
| 130 |
+
hidden_size=self.key_dim_per_group,
|
| 131 |
+
kernel_size=conv_size,
|
| 132 |
+
bias=conv_bias,
|
| 133 |
+
activation='silu'
|
| 134 |
+
)
|
| 135 |
+
self.v_conv1d = ShortConvolution(
|
| 136 |
+
hidden_size=self.value_dim_per_group,
|
| 137 |
+
kernel_size=conv_size,
|
| 138 |
+
bias=conv_bias,
|
| 139 |
+
activation='silu'
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 143 |
+
|
| 144 |
+
if gate_fn == 'swish' and fuse_norm and use_output_gate:
|
| 145 |
+
self.g_norm_swish_gate = FusedRMSNormGated(
|
| 146 |
+
hidden_size=self.head_v_dim,
|
| 147 |
+
elementwise_affine=elementwise_affine,
|
| 148 |
+
eps=norm_eps
|
| 149 |
+
)
|
| 150 |
+
self.fuse_norm_and_gate = True
|
| 151 |
+
else:
|
| 152 |
+
self.fuse_norm_and_gate = False
|
| 153 |
+
self.g_norm = RMSNorm(
|
| 154 |
+
hidden_size=self.head_v_dim,
|
| 155 |
+
elementwise_affine=elementwise_affine,
|
| 156 |
+
eps=norm_eps
|
| 157 |
+
)
|
| 158 |
+
self.gate_fn = ACT2FN[gate_fn]
|
| 159 |
+
|
| 160 |
+
# TODO: fix this issue
|
| 161 |
+
# https://github.com/Dao-AILab/flash-attention/blob/main/flash_attn/ops/triton/rotary.py#L180
|
| 162 |
+
# Ideally, we would want to support arbitrary d_head_qk
|
| 163 |
+
assert self.head_k_dim <= 256, "head_k_dim must be less than or equal to 256"
|
| 164 |
+
self.rotary = RotaryEmbedding(dim=self.head_k_dim)
|
| 165 |
+
|
| 166 |
+
def forward(
|
| 167 |
+
self,
|
| 168 |
+
hidden_states: torch.Tensor,
|
| 169 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 170 |
+
past_key_values: Optional[Cache] = None,
|
| 171 |
+
use_cache: Optional[bool] = False,
|
| 172 |
+
output_attentions: Optional[bool] = False,
|
| 173 |
+
**kwargs: Unpack[Dict]
|
| 174 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 175 |
+
if attention_mask is not None:
|
| 176 |
+
assert len(attention_mask.shape) == 2, (
|
| 177 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 178 |
+
"for padding purposes (0 indicating padding). "
|
| 179 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 183 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 184 |
+
|
| 185 |
+
last_state = None
|
| 186 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 187 |
+
last_state = past_key_values[self.layer_idx]
|
| 188 |
+
|
| 189 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 190 |
+
if attention_mask is not None:
|
| 191 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 192 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 193 |
+
|
| 194 |
+
if self.use_short_conv:
|
| 195 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 196 |
+
if last_state is not None:
|
| 197 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 198 |
+
q, conv_state_q = self.q_conv1d(
|
| 199 |
+
x=self.q_proj(hidden_states),
|
| 200 |
+
cache=conv_state_q,
|
| 201 |
+
output_final_state=use_cache,
|
| 202 |
+
cu_seqlens=cu_seqlens
|
| 203 |
+
)
|
| 204 |
+
k, conv_state_k = self.k_conv1d(
|
| 205 |
+
x=self.k_proj(hidden_states),
|
| 206 |
+
cache=conv_state_k,
|
| 207 |
+
output_final_state=use_cache,
|
| 208 |
+
cu_seqlens=cu_seqlens
|
| 209 |
+
)
|
| 210 |
+
v, conv_state_v = self.v_conv1d(
|
| 211 |
+
x=self.v_proj(hidden_states),
|
| 212 |
+
cache=conv_state_v,
|
| 213 |
+
output_final_state=use_cache,
|
| 214 |
+
cu_seqlens=cu_seqlens
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
q = self.q_proj(hidden_states)
|
| 218 |
+
k = self.k_proj(hidden_states)
|
| 219 |
+
v = self.v_proj(hidden_states)
|
| 220 |
+
|
| 221 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 222 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_k_dim)
|
| 223 |
+
if self.feature_map_fn is not None:
|
| 224 |
+
q, k = map(self.feature_map_fn, (q, k))
|
| 225 |
+
|
| 226 |
+
seqlen_offset, max_seqlen = 0, q.shape[1]
|
| 227 |
+
if past_key_values is not None:
|
| 228 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 229 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 230 |
+
|
| 231 |
+
if attention_mask is not None and seqlen_offset > 0:
|
| 232 |
+
# to deliminate the offsets of padding tokens
|
| 233 |
+
seqlen_offset = prepare_lens_from_mask(attention_mask) - q_len
|
| 234 |
+
max_seqlen = q.shape[1] + seqlen_offset.max().item()
|
| 235 |
+
|
| 236 |
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 237 |
+
|
| 238 |
+
if self.num_kv_groups > 1:
|
| 239 |
+
k = repeat(k, '... h d -> ... (h g) d', g=self.num_kv_groups)
|
| 240 |
+
v = repeat(v, '... (h d) -> ... (h g) d', d=self.head_v_dim, g=self.num_kv_groups)
|
| 241 |
+
else:
|
| 242 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 243 |
+
|
| 244 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 245 |
+
if mode == 'chunk':
|
| 246 |
+
o, recurrent_state = chunk_retention(
|
| 247 |
+
q=q,
|
| 248 |
+
k=k,
|
| 249 |
+
v=v,
|
| 250 |
+
initial_state=recurrent_state,
|
| 251 |
+
output_final_state=use_cache,
|
| 252 |
+
cu_seqlens=cu_seqlens,
|
| 253 |
+
)
|
| 254 |
+
elif mode == 'fused_chunk':
|
| 255 |
+
o, recurrent_state = fused_chunk_retention(
|
| 256 |
+
q=q,
|
| 257 |
+
k=k,
|
| 258 |
+
v=v,
|
| 259 |
+
initial_state=recurrent_state,
|
| 260 |
+
output_final_state=use_cache,
|
| 261 |
+
cu_seqlens=cu_seqlens,
|
| 262 |
+
)
|
| 263 |
+
elif mode == 'parallel':
|
| 264 |
+
o, recurrent_state = parallel_retention(
|
| 265 |
+
q=q,
|
| 266 |
+
k=k,
|
| 267 |
+
v=v,
|
| 268 |
+
cu_seqlens=cu_seqlens,
|
| 269 |
+
)
|
| 270 |
+
elif mode == 'fused_recurrent':
|
| 271 |
+
o, recurrent_state = fused_recurrent_retention(
|
| 272 |
+
q=q,
|
| 273 |
+
k=k,
|
| 274 |
+
v=v,
|
| 275 |
+
initial_state=recurrent_state,
|
| 276 |
+
output_final_state=use_cache,
|
| 277 |
+
cu_seqlens=cu_seqlens,
|
| 278 |
+
)
|
| 279 |
+
else:
|
| 280 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 281 |
+
|
| 282 |
+
if past_key_values is not None:
|
| 283 |
+
past_key_values.update(
|
| 284 |
+
recurrent_state=recurrent_state,
|
| 285 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 286 |
+
layer_idx=self.layer_idx,
|
| 287 |
+
offset=q_len
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
if self.use_output_gate:
|
| 291 |
+
g = self.g_proj(hidden_states)
|
| 292 |
+
if self.fuse_norm_and_gate:
|
| 293 |
+
g = rearrange(g, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 294 |
+
o = self.g_norm_swish_gate(o, g)
|
| 295 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 296 |
+
else:
|
| 297 |
+
o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
|
| 298 |
+
o = o * self.gate_fn(g)
|
| 299 |
+
else:
|
| 300 |
+
o = rearrange(self.g_norm(o), '... h d -> ... (h d)')
|
| 301 |
+
o = self.o_proj(o)
|
| 302 |
+
if attention_mask is not None:
|
| 303 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 304 |
+
|
| 305 |
+
return o, None, past_key_values
|
past_gdn.py
ADDED
|
@@ -0,0 +1,1407 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
from einops import rearrange, repeat
|
| 10 |
+
from ..modules import FusedRMSNormSwishGate, RMSNorm
|
| 11 |
+
from fla.modules import ShortConvolution
|
| 12 |
+
import torch.nn.init as init
|
| 13 |
+
import math
|
| 14 |
+
from ..modules.l2norm import l2norm
|
| 15 |
+
from einops import rearrange
|
| 16 |
+
from fla.models.utils import Cache
|
| 17 |
+
from transformers.processing_utils import Unpack
|
| 18 |
+
import math
|
| 19 |
+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
|
| 20 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
|
| 21 |
+
# from ..modules import RotaryEmbedding
|
| 22 |
+
# from ..ops.gla import chunk_gla,fused_recurrent_gla
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def simple_norm(x):
|
| 26 |
+
return (F.normalize(x, dim=-1) * x.shape[-1] ** 0.5).to(x)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# @torch.jit.script
|
| 30 |
+
def elu_p1(x):
|
| 31 |
+
return (F.elu(x, 1., False) + 1.).to(x)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# @torch.jit.script
|
| 35 |
+
def sum_norm(x):
|
| 36 |
+
return (x / x.sum(-1, keepdim=True)).to(x)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# @torch.jit.script
|
| 40 |
+
def elu_norm(x):
|
| 41 |
+
dtype = x.dtype
|
| 42 |
+
x = F.elu(x, 1., False) + 1.
|
| 43 |
+
return (x / x.sum(-1, keepdim=True)).to(dtype)
|
| 44 |
+
|
| 45 |
+
from typing import Optional, Tuple, Union
|
| 46 |
+
|
| 47 |
+
import torch
|
| 48 |
+
import torch.nn as nn
|
| 49 |
+
import triton
|
| 50 |
+
import triton.language as tl
|
| 51 |
+
from einops import rearrange, repeat
|
| 52 |
+
|
| 53 |
+
from fla.ops.utils import prepare_chunk_indices
|
| 54 |
+
from fla.utils import get_multiprocessor_count, input_guard
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def rotate_half(x, interleaved=False):
|
| 58 |
+
if not interleaved:
|
| 59 |
+
x1, x2 = x.chunk(2, dim=-1)
|
| 60 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 61 |
+
else:
|
| 62 |
+
x1, x2 = x[..., ::2], x[..., 1::2]
|
| 63 |
+
return rearrange(torch.stack((-x2, x1), dim=-1), '... d two -> ... (d two)', two=2)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def rotary_embedding_ref(x, cos, sin, interleaved=False):
|
| 67 |
+
ro_dim = cos.shape[-1] * 2
|
| 68 |
+
assert ro_dim <= x.shape[-1]
|
| 69 |
+
cos = repeat(cos, '... d -> ... 1 (2 d)' if not interleaved else '... d -> ... 1 (d 2)')
|
| 70 |
+
sin = repeat(sin, '... d -> ... 1 (2 d)' if not interleaved else '... d -> ... 1 (d 2)')
|
| 71 |
+
return torch.cat([x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]], -1)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@triton.autotune(
|
| 75 |
+
configs=[
|
| 76 |
+
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
|
| 77 |
+
for num_warps in [2, 4, 8, 16, 32]
|
| 78 |
+
for num_stages in [2, 3, 4]
|
| 79 |
+
],
|
| 80 |
+
key=['B', 'H', 'D', 'INTERLEAVED'],
|
| 81 |
+
)
|
| 82 |
+
@triton.jit(do_not_specialize=['T'])
|
| 83 |
+
def rotary_embedding_kernel(
|
| 84 |
+
x,
|
| 85 |
+
cos,
|
| 86 |
+
sin,
|
| 87 |
+
y,
|
| 88 |
+
cu_seqlens,
|
| 89 |
+
chunk_indices,
|
| 90 |
+
seq_offsets,
|
| 91 |
+
T,
|
| 92 |
+
B: tl.constexpr,
|
| 93 |
+
H: tl.constexpr,
|
| 94 |
+
D: tl.constexpr,
|
| 95 |
+
R: tl.constexpr,
|
| 96 |
+
TR: tl.constexpr,
|
| 97 |
+
BT: tl.constexpr,
|
| 98 |
+
BD: tl.constexpr,
|
| 99 |
+
IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr,
|
| 100 |
+
IS_VARLEN: tl.constexpr,
|
| 101 |
+
INTERLEAVED: tl.constexpr,
|
| 102 |
+
CONJUGATE: tl.constexpr
|
| 103 |
+
):
|
| 104 |
+
i_t, i_b, i_h = tl.program_id(0), tl.program_id(1), tl.program_id(2)
|
| 105 |
+
|
| 106 |
+
if IS_VARLEN:
|
| 107 |
+
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
| 108 |
+
bos, eos = tl.load(cu_seqlens + i_n), tl.load(cu_seqlens + i_n + 1)
|
| 109 |
+
T = eos - bos
|
| 110 |
+
x = x + bos * H*D + i_h * D
|
| 111 |
+
y = y + bos * H*D + i_h * D
|
| 112 |
+
else:
|
| 113 |
+
i_n = i_b
|
| 114 |
+
x = x + i_n * T*H*D + i_h * D
|
| 115 |
+
y = y + i_n * T*H*D + i_h * D
|
| 116 |
+
|
| 117 |
+
if i_t * BT >= T:
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
o_t = i_t * BT + tl.arange(0, BT)
|
| 121 |
+
if not IS_SEQLEN_OFFSETS_TENSOR:
|
| 122 |
+
o_cs = o_t + seq_offsets
|
| 123 |
+
else:
|
| 124 |
+
o_cs = o_t + tl.load(seq_offsets + i_n)
|
| 125 |
+
|
| 126 |
+
if not INTERLEAVED:
|
| 127 |
+
# Load the 1st and 2nd halves of x, do calculation, then store to 1st and 2nd halves of out
|
| 128 |
+
o_r = tl.arange(0, BD // 2)
|
| 129 |
+
p_x = x + o_t[:, None] * H*D + o_r[None, :]
|
| 130 |
+
p_cos = cos + (o_cs[:, None] * R + o_r[None, :])
|
| 131 |
+
p_sin = sin + (o_cs[:, None] * R + o_r[None, :])
|
| 132 |
+
mask = (o_t[:, None] >= 0) & (o_t[:, None] < T) & (o_r[None, :] < R)
|
| 133 |
+
|
| 134 |
+
b_cos = tl.load(p_cos, mask=mask, other=1.0).to(tl.float32)
|
| 135 |
+
b_sin = tl.load(p_sin, mask=mask, other=0.0).to(tl.float32)
|
| 136 |
+
b_x0 = tl.load(p_x, mask=mask, other=0.0).to(tl.float32)
|
| 137 |
+
b_x1 = tl.load(p_x + R, mask=mask, other=0.0).to(tl.float32)
|
| 138 |
+
if CONJUGATE:
|
| 139 |
+
b_sin = -b_sin
|
| 140 |
+
b_o0 = b_x0 * b_cos - b_x1 * b_sin
|
| 141 |
+
b_o1 = b_x0 * b_sin + b_x1 * b_cos
|
| 142 |
+
# write back result
|
| 143 |
+
p_y = y + (o_t[:, None] * H*D + o_r[None, :])
|
| 144 |
+
tl.store(p_y, b_o0, mask=mask)
|
| 145 |
+
tl.store(p_y + R, b_o1, mask=mask)
|
| 146 |
+
else:
|
| 147 |
+
# We don't want to load x[0, 2, 4, ...] and x[1, 3, 5, ...] separately since both are slow.
|
| 148 |
+
# Instead, we load x0 = x[0, 1, 2, 3, ...] and x1 = x[1, 0, 3, 2, ...].
|
| 149 |
+
# Loading x0 will be fast but x1 will be slow.
|
| 150 |
+
# Then we load cos = cos[0, 0, 1, 1, ...] and sin = sin[0, 0, 1, 1, ...].
|
| 151 |
+
# Then we do the calculation and use tl.where to pick put the right outputs for the even
|
| 152 |
+
# and for the odd indices.
|
| 153 |
+
o_d = tl.arange(0, BD)
|
| 154 |
+
o_d_swap = o_d + ((o_d + 1) % 2) * 2 - 1 # 1, 0, 3, 2, 5, 4, ...
|
| 155 |
+
o_d_repeat = tl.arange(0, BD) // 2
|
| 156 |
+
p_x0 = x + o_t[:, None] * H*D + o_d[None, :]
|
| 157 |
+
p_x1 = x + o_t[:, None] * H*D + o_d_swap[None, :]
|
| 158 |
+
p_cos = cos + (o_cs[:, None] * R + o_d_repeat[None, :])
|
| 159 |
+
p_sin = sin + (o_cs[:, None] * R + o_d_repeat[None, :])
|
| 160 |
+
mask = (o_cs[:, None] >= 0) & (o_cs[:, None] < TR) & (o_d_repeat[None, :] < R)
|
| 161 |
+
|
| 162 |
+
b_cos = tl.load(p_cos, mask=mask, other=1.0).to(tl.float32)
|
| 163 |
+
b_sin = tl.load(p_sin, mask=mask, other=0.0).to(tl.float32)
|
| 164 |
+
b_x0 = tl.load(p_x0, mask=mask, other=0.0).to(tl.float32)
|
| 165 |
+
b_x1 = tl.load(p_x1, mask=mask, other=0.0).to(tl.float32)
|
| 166 |
+
if CONJUGATE:
|
| 167 |
+
b_sin = -b_sin
|
| 168 |
+
b_o0 = b_x0 * b_cos
|
| 169 |
+
b_o1 = b_x1 * b_sin
|
| 170 |
+
b_y = tl.where(o_d[None, :] % 2 == 0, b_o0 - b_o1, b_o0 + b_o1)
|
| 171 |
+
p_y = y + (o_t[:, None] * H*D + o_d[None, :])
|
| 172 |
+
tl.store(p_y, b_y, mask=mask)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def rotary_embedding_fwdbwd(
|
| 176 |
+
x: torch.Tensor,
|
| 177 |
+
cos: torch.Tensor,
|
| 178 |
+
sin: torch.Tensor,
|
| 179 |
+
seqlen_offsets: Union[int, torch.Tensor] = 0,
|
| 180 |
+
cu_seqlens: Optional[torch.Tensor] = None,
|
| 181 |
+
interleaved: bool = False,
|
| 182 |
+
inplace: bool = False,
|
| 183 |
+
conjugate: bool = False
|
| 184 |
+
) -> torch.Tensor:
|
| 185 |
+
"""
|
| 186 |
+
Args:
|
| 187 |
+
x: [B, T, H, D].
|
| 188 |
+
cos: [TR, R / 2]
|
| 189 |
+
sin: [TR, R / 2]
|
| 190 |
+
seqlen_offsets: integer or integer tensor of size [N]
|
| 191 |
+
cu_seqlens: [N + 1,] or None
|
| 192 |
+
|
| 193 |
+
Returns:
|
| 194 |
+
y: [B, T, H, D]
|
| 195 |
+
"""
|
| 196 |
+
is_varlen = cu_seqlens is not None
|
| 197 |
+
|
| 198 |
+
B, T, H, D = x.shape
|
| 199 |
+
N = B if not is_varlen else cu_seqlens.shape[0] - 1
|
| 200 |
+
TR, R = cos.shape
|
| 201 |
+
R2 = R * 2
|
| 202 |
+
|
| 203 |
+
assert D <= 256, "Only support D <= 256"
|
| 204 |
+
assert TR >= T, "TR must be >= T"
|
| 205 |
+
|
| 206 |
+
assert cos.dtype == sin.dtype, f"cos and sin must have the same dtype, got {cos.dtype} and {sin.dtype}"
|
| 207 |
+
assert x.dtype == cos.dtype, f"Input and cos/sin must have the same dtype, got {x.dtype} and {cos.dtype}"
|
| 208 |
+
|
| 209 |
+
if isinstance(seqlen_offsets, torch.Tensor):
|
| 210 |
+
assert seqlen_offsets.shape == (N,)
|
| 211 |
+
assert seqlen_offsets.dtype in [torch.int32, torch.int64]
|
| 212 |
+
else:
|
| 213 |
+
assert seqlen_offsets + T <= TR
|
| 214 |
+
|
| 215 |
+
y = torch.empty_like(x) if not inplace else x
|
| 216 |
+
if R2 < D and not inplace:
|
| 217 |
+
y[..., R2:].copy_(x[..., R2:])
|
| 218 |
+
|
| 219 |
+
BD = triton.next_power_of_2(R2)
|
| 220 |
+
BT = min(128, triton.next_power_of_2(triton.cdiv(T, get_multiprocessor_count(x.device.index))))
|
| 221 |
+
chunk_indices = prepare_chunk_indices(cu_seqlens, BT) if is_varlen else None
|
| 222 |
+
NT = len(chunk_indices) if is_varlen else triton.cdiv(T, BT)
|
| 223 |
+
|
| 224 |
+
grid = (NT, B, H)
|
| 225 |
+
rotary_embedding_kernel[grid](
|
| 226 |
+
x,
|
| 227 |
+
cos,
|
| 228 |
+
sin,
|
| 229 |
+
y,
|
| 230 |
+
cu_seqlens,
|
| 231 |
+
chunk_indices,
|
| 232 |
+
seqlen_offsets,
|
| 233 |
+
B=B,
|
| 234 |
+
T=T,
|
| 235 |
+
H=H,
|
| 236 |
+
D=D,
|
| 237 |
+
R=R,
|
| 238 |
+
TR=TR,
|
| 239 |
+
BT=BT,
|
| 240 |
+
BD=BD,
|
| 241 |
+
IS_SEQLEN_OFFSETS_TENSOR=isinstance(seqlen_offsets, torch.Tensor),
|
| 242 |
+
IS_VARLEN=is_varlen,
|
| 243 |
+
INTERLEAVED=interleaved,
|
| 244 |
+
CONJUGATE=conjugate
|
| 245 |
+
)
|
| 246 |
+
return y
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class RotaryEmbeddingFunction(torch.autograd.Function):
|
| 250 |
+
|
| 251 |
+
@staticmethod
|
| 252 |
+
@input_guard
|
| 253 |
+
def forward(
|
| 254 |
+
ctx,
|
| 255 |
+
x,
|
| 256 |
+
cos,
|
| 257 |
+
sin,
|
| 258 |
+
interleaved=False,
|
| 259 |
+
inplace=False,
|
| 260 |
+
seqlen_offsets: Union[int, torch.Tensor] = 0,
|
| 261 |
+
cu_seqlens: Optional[torch.Tensor] = None,
|
| 262 |
+
):
|
| 263 |
+
y = rotary_embedding_fwdbwd(
|
| 264 |
+
x,
|
| 265 |
+
cos,
|
| 266 |
+
sin,
|
| 267 |
+
seqlen_offsets=seqlen_offsets,
|
| 268 |
+
cu_seqlens=cu_seqlens,
|
| 269 |
+
interleaved=interleaved,
|
| 270 |
+
inplace=inplace,
|
| 271 |
+
)
|
| 272 |
+
if isinstance(seqlen_offsets, int):
|
| 273 |
+
# Can't save int with save_for_backward
|
| 274 |
+
ctx.save_for_backward(cos, sin, cu_seqlens)
|
| 275 |
+
ctx.seqlen_offsets = seqlen_offsets
|
| 276 |
+
else:
|
| 277 |
+
ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets)
|
| 278 |
+
ctx.seqlen_offsets = None
|
| 279 |
+
ctx.interleaved = interleaved
|
| 280 |
+
ctx.inplace = inplace
|
| 281 |
+
return y if not inplace else x
|
| 282 |
+
|
| 283 |
+
@staticmethod
|
| 284 |
+
@input_guard
|
| 285 |
+
def backward(ctx, do):
|
| 286 |
+
seqlen_offsets = ctx.seqlen_offsets
|
| 287 |
+
if seqlen_offsets is None:
|
| 288 |
+
cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors
|
| 289 |
+
else:
|
| 290 |
+
cos, sin, cu_seqlens = ctx.saved_tensors
|
| 291 |
+
# TD [2023-09-02]: For some reason Triton (2.0.0.post1) errors with
|
| 292 |
+
# "[CUDA]: invalid device context", and cloning makes it work. Idk why. Triton 2.1.0 works.
|
| 293 |
+
if not ctx.interleaved and not ctx.inplace:
|
| 294 |
+
do = do.clone()
|
| 295 |
+
dx = rotary_embedding_fwdbwd(
|
| 296 |
+
do,
|
| 297 |
+
cos,
|
| 298 |
+
sin,
|
| 299 |
+
seqlen_offsets=seqlen_offsets,
|
| 300 |
+
cu_seqlens=cu_seqlens,
|
| 301 |
+
interleaved=ctx.interleaved,
|
| 302 |
+
inplace=ctx.inplace,
|
| 303 |
+
conjugate=True,
|
| 304 |
+
)
|
| 305 |
+
return dx, None, None, None, None, None, None, None
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def rotary_embedding(
|
| 309 |
+
x,
|
| 310 |
+
cos,
|
| 311 |
+
sin,
|
| 312 |
+
interleaved=False,
|
| 313 |
+
inplace=False,
|
| 314 |
+
seqlen_offsets: Union[int, torch.Tensor] = 0,
|
| 315 |
+
cu_seqlens: Optional[torch.Tensor] = None
|
| 316 |
+
):
|
| 317 |
+
"""
|
| 318 |
+
Args:
|
| 319 |
+
x: [B, T, H, D]
|
| 320 |
+
cos, sin: [TR, R//2]
|
| 321 |
+
interleaved:
|
| 322 |
+
If True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style).
|
| 323 |
+
inplace:
|
| 324 |
+
If True, apply rotary embedding in-place.
|
| 325 |
+
seqlen_offsets: [N,] or int.
|
| 326 |
+
Each sequence in x is shifted by this amount.
|
| 327 |
+
Most commonly used in inference when we have KV cache.
|
| 328 |
+
cu_seqlens: [N + 1,] or None
|
| 329 |
+
|
| 330 |
+
Returns:
|
| 331 |
+
out: [B, T, H, D]
|
| 332 |
+
"""
|
| 333 |
+
return RotaryEmbeddingFunction.apply(
|
| 334 |
+
x,
|
| 335 |
+
cos,
|
| 336 |
+
sin,
|
| 337 |
+
interleaved,
|
| 338 |
+
inplace,
|
| 339 |
+
seqlen_offsets,
|
| 340 |
+
cu_seqlens
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class RotaryEmbedding(nn.Module):
|
| 345 |
+
"""
|
| 346 |
+
The rotary position embeddings from RoFormer_ (Su et. al).
|
| 347 |
+
A crucial insight from the method is that the query and keys are
|
| 348 |
+
transformed by rotation matrices which depend on the relative positions.
|
| 349 |
+
|
| 350 |
+
Other implementations are available in the Rotary Transformer repo_ and in
|
| 351 |
+
GPT-NeoX_, GPT-NeoX was an inspiration
|
| 352 |
+
|
| 353 |
+
.. _RoFormer: https://arxiv.org/abs/2104.09864
|
| 354 |
+
.. _repo: https://github.com/ZhuiyiTechnology/roformer
|
| 355 |
+
.. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox
|
| 356 |
+
|
| 357 |
+
If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554).
|
| 358 |
+
A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96
|
| 359 |
+
Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
def __init__(
|
| 363 |
+
self,
|
| 364 |
+
dim: int,
|
| 365 |
+
base: float = 10000.0,
|
| 366 |
+
scale_base: Optional[float] = None,
|
| 367 |
+
interleaved: bool = False,
|
| 368 |
+
pos_idx_in_fp32: bool = True,
|
| 369 |
+
device: Optional[torch.device] = None,
|
| 370 |
+
):
|
| 371 |
+
"""
|
| 372 |
+
interleaved:
|
| 373 |
+
If True, rotate pairs of even and odd dimensions (GPT-J style) instead of 1st half and 2nd half (GPT-NeoX style).
|
| 374 |
+
pos_idx_in_fp32:
|
| 375 |
+
If True, the position indices [0.0, ..., seqlen - 1] are in fp32, otherwise they might be in lower precision.
|
| 376 |
+
This option was added because previously (before 2023-07-02), when we construct
|
| 377 |
+
the position indices, we use the dtype of self.inv_freq.
|
| 378 |
+
In most cases this would be fp32, but if the model is trained in pure bf16 (not mixed precision), then
|
| 379 |
+
self.inv_freq would be bf16, and the position indices are also in bf16.
|
| 380 |
+
Because of the limited precision of bf16 (e.g. 1995.0 is rounded to 2000.0), the
|
| 381 |
+
embeddings for some positions will coincide.
|
| 382 |
+
To maintain compatibility with models previously trained in pure bf16, we add this option.
|
| 383 |
+
"""
|
| 384 |
+
super().__init__()
|
| 385 |
+
|
| 386 |
+
self.dim = dim
|
| 387 |
+
self.base = float(base)
|
| 388 |
+
self.scale_base = scale_base
|
| 389 |
+
self.interleaved = interleaved
|
| 390 |
+
self.pos_idx_in_fp32 = pos_idx_in_fp32
|
| 391 |
+
self.device = device
|
| 392 |
+
|
| 393 |
+
# Generate and save the inverse frequency buffer (non trainable)
|
| 394 |
+
self.register_buffer("inv_freq", torch.empty(-(dim // -2), dtype=torch.float32, device=device), persistent=False)
|
| 395 |
+
|
| 396 |
+
scale = None
|
| 397 |
+
if scale_base is not None:
|
| 398 |
+
scale = torch.empty(-(dim // -2), dtype=torch.float32, device=device)
|
| 399 |
+
self.register_buffer("scale", scale, persistent=False)
|
| 400 |
+
|
| 401 |
+
self._seq_len_cached = 0
|
| 402 |
+
self._cos_cached = None
|
| 403 |
+
self._sin_cached = None
|
| 404 |
+
self._cos_k_cached = None
|
| 405 |
+
self._sin_k_cached = None
|
| 406 |
+
|
| 407 |
+
self.reset_parameters()
|
| 408 |
+
|
| 409 |
+
def reset_parameters(self):
|
| 410 |
+
with torch.no_grad():
|
| 411 |
+
self.inv_freq.copy_(self._compute_inv_freq(device=self.inv_freq.device))
|
| 412 |
+
if self.scale_base is not None:
|
| 413 |
+
self.scale.copy_(self._compute_scale(device=self.scale.device))
|
| 414 |
+
|
| 415 |
+
def __repr__(self):
|
| 416 |
+
s = f"{self.__class__.__name__}("
|
| 417 |
+
s += f"dim={self.dim}, "
|
| 418 |
+
s += f"base={self.base}, "
|
| 419 |
+
s += f"interleaved={self.interleaved}, "
|
| 420 |
+
if self.scale_base is not None:
|
| 421 |
+
s += f"scale_base={self.scale_base}, "
|
| 422 |
+
s += f"pos_idx_in_fp32={self.pos_idx_in_fp32})"
|
| 423 |
+
return s
|
| 424 |
+
|
| 425 |
+
def _compute_inv_freq(self, device=None):
|
| 426 |
+
return 1.0 / (
|
| 427 |
+
self.base
|
| 428 |
+
** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim)
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
def _compute_scale(self, device=None):
|
| 432 |
+
return (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) + 0.4 * self.dim) / (1.4 * self.dim)
|
| 433 |
+
|
| 434 |
+
def _update_cos_sin_cache(self, seqlen, device=None, dtype=None):
|
| 435 |
+
# Reset the tables if the sequence length has changed,
|
| 436 |
+
# if we're on a new device (possibly due to tracing for instance),
|
| 437 |
+
# or if we're switching from inference mode to training
|
| 438 |
+
if (
|
| 439 |
+
seqlen > self._seq_len_cached
|
| 440 |
+
or self._cos_cached is None
|
| 441 |
+
or self._cos_cached.device != device
|
| 442 |
+
or self._cos_cached.dtype != dtype
|
| 443 |
+
or (self.training and self._cos_cached.is_inference())
|
| 444 |
+
):
|
| 445 |
+
self._seq_len_cached = seqlen
|
| 446 |
+
# We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16
|
| 447 |
+
# And the output of arange can be quite large, so bf16 would lose a lot of precision.
|
| 448 |
+
# However, for compatibility reason, we add an option to use the dtype of self.inv_freq.
|
| 449 |
+
if self.pos_idx_in_fp32:
|
| 450 |
+
t = torch.arange(seqlen, device=device, dtype=torch.float32)
|
| 451 |
+
# We want fp32 here as well since inv_freq will be multiplied with t, and the output
|
| 452 |
+
# will be large. Having it in bf16 will lose a lot of precision and cause the
|
| 453 |
+
# cos & sin output to change significantly.
|
| 454 |
+
# We want to recompute self.inv_freq if it was not loaded in fp32
|
| 455 |
+
if self.inv_freq.dtype != torch.float32:
|
| 456 |
+
inv_freq = self._compute_inv_freq(device=device)
|
| 457 |
+
else:
|
| 458 |
+
inv_freq = self.inv_freq
|
| 459 |
+
else:
|
| 460 |
+
t = torch.arange(seqlen, device=device, dtype=self.inv_freq.dtype)
|
| 461 |
+
inv_freq = self.inv_freq
|
| 462 |
+
# Don't do einsum, it converts fp32 to fp16 under AMP
|
| 463 |
+
# freqs = torch.einsum("i,j->ij", t, self.inv_freq)
|
| 464 |
+
freqs = torch.outer(t, inv_freq)
|
| 465 |
+
if self.scale is None:
|
| 466 |
+
self._cos_cached = torch.cos(freqs).to(dtype)
|
| 467 |
+
self._sin_cached = torch.sin(freqs).to(dtype)
|
| 468 |
+
else:
|
| 469 |
+
power = (
|
| 470 |
+
torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device)
|
| 471 |
+
- seqlen // 2
|
| 472 |
+
) / self.scale_base
|
| 473 |
+
scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1")
|
| 474 |
+
# We want the multiplication by scale to happen in fp32
|
| 475 |
+
self._cos_cached = (torch.cos(freqs) * scale).to(dtype)
|
| 476 |
+
self._sin_cached = (torch.sin(freqs) * scale).to(dtype)
|
| 477 |
+
self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype)
|
| 478 |
+
self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype)
|
| 479 |
+
|
| 480 |
+
def forward(
|
| 481 |
+
self,
|
| 482 |
+
q: torch.Tensor,
|
| 483 |
+
k: torch.Tensor,
|
| 484 |
+
seqlen_offset: Union[int, torch.Tensor] = 0,
|
| 485 |
+
cu_seqlens: Optional[torch.Tensor] = None,
|
| 486 |
+
max_seqlen: Optional[int] = None,
|
| 487 |
+
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
| 488 |
+
"""
|
| 489 |
+
q: [B, T, H, D]
|
| 490 |
+
k: [B, T, H, D]
|
| 491 |
+
seqlen_offset:
|
| 492 |
+
[N] or int.
|
| 493 |
+
Each sequence in x is shifted by this amount.
|
| 494 |
+
Most commonly used in inference when we have KV cache.
|
| 495 |
+
cu_seqlens: [N + 1] or None
|
| 496 |
+
max_seqlen: int
|
| 497 |
+
"""
|
| 498 |
+
if max_seqlen is not None:
|
| 499 |
+
self._update_cos_sin_cache(max_seqlen, device=q.device, dtype=q.dtype)
|
| 500 |
+
elif isinstance(seqlen_offset, int):
|
| 501 |
+
self._update_cos_sin_cache(q.shape[1] + seqlen_offset, device=q.device, dtype=q.dtype)
|
| 502 |
+
if self.scale is None:
|
| 503 |
+
q = rotary_embedding(
|
| 504 |
+
q,
|
| 505 |
+
self._cos_cached,
|
| 506 |
+
self._sin_cached,
|
| 507 |
+
interleaved=self.interleaved,
|
| 508 |
+
seqlen_offsets=seqlen_offset,
|
| 509 |
+
cu_seqlens=cu_seqlens,
|
| 510 |
+
)
|
| 511 |
+
k = rotary_embedding(
|
| 512 |
+
k,
|
| 513 |
+
self._cos_cached,
|
| 514 |
+
-self._sin_cached,
|
| 515 |
+
interleaved=self.interleaved,
|
| 516 |
+
seqlen_offsets=seqlen_offset,
|
| 517 |
+
cu_seqlens=cu_seqlens,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
else:
|
| 521 |
+
q = rotary_embedding(
|
| 522 |
+
q,
|
| 523 |
+
self._cos_cached,
|
| 524 |
+
self._sin_cached,
|
| 525 |
+
interleaved=self.interleaved,
|
| 526 |
+
seqlen_offsets=seqlen_offset,
|
| 527 |
+
cu_seqlens=cu_seqlens,
|
| 528 |
+
)
|
| 529 |
+
k = rotary_embedding(
|
| 530 |
+
k,
|
| 531 |
+
self._cos_k_cached,
|
| 532 |
+
-self._sin_k_cached,
|
| 533 |
+
interleaved=self.interleaved,
|
| 534 |
+
seqlen_offsets=seqlen_offset,
|
| 535 |
+
cu_seqlens=cu_seqlens,
|
| 536 |
+
)
|
| 537 |
+
return q, k
|
| 538 |
+
|
| 539 |
+
def stride_blhdtoblhrd(x,ratio:int,head_chunk_size,left=False):
|
| 540 |
+
assert x.dim() == 4 #blhd
|
| 541 |
+
batch_size, q_len, num_heads, head_qk_dim = x.shape
|
| 542 |
+
x_exp = []
|
| 543 |
+
for i in range(num_heads):
|
| 544 |
+
xi_exp = []
|
| 545 |
+
xi_exp.append(x[:,:,i:i+1,:])
|
| 546 |
+
for ratio_i in range(1,ratio):
|
| 547 |
+
pad = x.new_zeros((batch_size, head_chunk_size[i]*ratio_i, 1, head_qk_dim))###BL1D
|
| 548 |
+
xi_exp.append(torch.cat([x[:,:,i:i+1,:], pad], dim=1)[:,-q_len:,...])###BL1D
|
| 549 |
+
x_exp.append(torch.cat(xi_exp, dim=2).unsqueeze(2))###BL1D->BLRD->BL1RD
|
| 550 |
+
x_exp = torch.cat(x_exp, dim=2)###BL1RD->BLHRD
|
| 551 |
+
return x_exp
|
| 552 |
+
|
| 553 |
+
def stride_blhrdtoblhrd(x,ratio:int,head_chunk_size,left=True,inf=False):
|
| 554 |
+
assert x.dim() == 5 #blhrd
|
| 555 |
+
assert x.shape[-2] == ratio
|
| 556 |
+
batch_size, q_len, num_heads, _ , head_qk_dim = x.shape
|
| 557 |
+
x_exp = []
|
| 558 |
+
if inf:
|
| 559 |
+
for i in range(num_heads):
|
| 560 |
+
xi_exp = []
|
| 561 |
+
xi_exp.append(x[:,:,i:i+1,0,:])###BL1D
|
| 562 |
+
for ratio_i in range(1,ratio):
|
| 563 |
+
pad = x.new_full((batch_size, head_chunk_size[i]*ratio_i, 1, head_qk_dim), float('-inf'))###BL1D
|
| 564 |
+
xi_exp.append(torch.cat([pad, x[:,head_chunk_size[i]*ratio_i:,i:i+1,ratio_i,:]], dim=1)[:,:q_len,...])###BL1D
|
| 565 |
+
x_exp.append(torch.cat(xi_exp, dim=2).unsqueeze(2))###BL1D->BLRD->BL1RD
|
| 566 |
+
x_exp = torch.cat(x_exp, dim=2)###BL1RD->BLHRD
|
| 567 |
+
return x_exp
|
| 568 |
+
else:
|
| 569 |
+
for i in range(num_heads):
|
| 570 |
+
xi_exp = []
|
| 571 |
+
xi_exp.append(x[:,:,i:i+1,0,:])
|
| 572 |
+
for ratio_i in range(1,ratio):
|
| 573 |
+
pad = x.new_zeros((batch_size, head_chunk_size[i]*ratio_i, 1, head_qk_dim))
|
| 574 |
+
xi_exp.append(torch.cat([pad, x[:,head_chunk_size[i]*ratio_i:,i:i+1,ratio_i,:]], dim=1)[:,:q_len,...])
|
| 575 |
+
x_exp.append(torch.cat(xi_exp, dim=2).unsqueeze(2))###BL1D->BLRD->BL1RD
|
| 576 |
+
x_exp = torch.cat(x_exp, dim=2)###BL1RD->BLHRD
|
| 577 |
+
return x_exp
|
| 578 |
+
|
| 579 |
+
# def stride_blhdtoblhrd(x,ratio:int,head_chunk_size,left=False):
|
| 580 |
+
# assert x.dim() == 4 #blhd
|
| 581 |
+
# batch_size, q_len, num_heads, head_qk_dim = x.shape
|
| 582 |
+
# x_exp = []
|
| 583 |
+
# for i in range(num_heads):
|
| 584 |
+
# for ratio_i in range(ratio):
|
| 585 |
+
# pad = x.new_zeros((batch_size, head_chunk_size[i]*1, 1, head_qk_dim))
|
| 586 |
+
# x_exp.append(torch.cat([x[:,:,i:i+1,:], pad], dim=1)[:,head_chunk_size[i]*1:,...])
|
| 587 |
+
# x_exp = torch.cat(x_exp, dim=2)
|
| 588 |
+
# return x_exp
|
| 589 |
+
|
| 590 |
+
# def stride_blhrdtoblhrd(x,ratio:int,head_chunk_size,left=True,inf=False):
|
| 591 |
+
# assert x.dim() == 5 #blhrd
|
| 592 |
+
# assert x.shape[-2] == ratio
|
| 593 |
+
# batch_size, q_len, num_heads, _ , head_qk_dim = x.shape
|
| 594 |
+
# x_exp = []
|
| 595 |
+
# if inf:
|
| 596 |
+
# for i in range(num_heads):
|
| 597 |
+
# for ratio_i in range(ratio):
|
| 598 |
+
# pad = x.new_full((batch_size, head_chunk_size[i]*1, 1, head_qk_dim), float('-inf'))
|
| 599 |
+
# x_exp.append(torch.cat([pad, x[:,head_chunk_size[i]*1:,i:i+1,ratio_i,:]], dim=1)[:,:q_len,...])
|
| 600 |
+
# x_exp = torch.cat(x_exp, dim=2)
|
| 601 |
+
# return x_exp
|
| 602 |
+
# else:
|
| 603 |
+
# for i in range(num_heads):
|
| 604 |
+
# for ratio_i in range(ratio):
|
| 605 |
+
# pad = x.new_zeros((batch_size, head_chunk_size[i]*1, 1, head_qk_dim))
|
| 606 |
+
# x_exp.append(torch.cat([pad, x[:,head_chunk_size[i]*1:,i:i+1,ratio_i,:]], dim=1)[:,:q_len,...])
|
| 607 |
+
# x_exp = torch.cat(x_exp, dim=2)
|
| 608 |
+
# return x_exp
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
# from ..ops.gated_delta_rule import chunk_gated_delta_rule,fused_recurrent_gated_delta_rule
|
| 614 |
+
# class past_gdn(nn.Module):
|
| 615 |
+
# def __init__(
|
| 616 |
+
# self,
|
| 617 |
+
# d_model: int = None,
|
| 618 |
+
# hidden_size: int = 1024,
|
| 619 |
+
# expand_k: float = 1.0,
|
| 620 |
+
# expand_v: float = 1.0,
|
| 621 |
+
# num_heads: int = 4,
|
| 622 |
+
# mode: str = 'chunk',
|
| 623 |
+
# chunk_size: int = 64,
|
| 624 |
+
# use_beta: bool = True,
|
| 625 |
+
# use_gate: bool = False,
|
| 626 |
+
# use_output_norm: bool = True,
|
| 627 |
+
# use_elu: bool = False,
|
| 628 |
+
# use_short_conv: bool = True,
|
| 629 |
+
# conv_size: int = 4,
|
| 630 |
+
# conv_bias: bool = False,
|
| 631 |
+
# layer_idx: int = None,
|
| 632 |
+
# qk_activation: str = 'silu',
|
| 633 |
+
# qk_norm: str = 'l2',
|
| 634 |
+
# norm_first: bool = False,
|
| 635 |
+
# norm_eps: float = 1e-6,
|
| 636 |
+
# ratio :int = 2,
|
| 637 |
+
# topk : int = 1,
|
| 638 |
+
# **kwargs
|
| 639 |
+
# ) :
|
| 640 |
+
# super().__init__()
|
| 641 |
+
|
| 642 |
+
# self.mode = mode
|
| 643 |
+
# self.qk_activation = qk_activation
|
| 644 |
+
# self.qk_norm = qk_norm
|
| 645 |
+
|
| 646 |
+
# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 647 |
+
# assert self.qk_norm in ['l2', 'sum']
|
| 648 |
+
|
| 649 |
+
# if d_model is not None:
|
| 650 |
+
# hidden_size = d_model
|
| 651 |
+
# self.hidden_size = hidden_size
|
| 652 |
+
# self.expand_k = expand_k
|
| 653 |
+
# self.expand_v = expand_v
|
| 654 |
+
# self.num_heads = num_heads
|
| 655 |
+
# self.chunk_size = chunk_size
|
| 656 |
+
# self.use_gate = use_gate
|
| 657 |
+
# self.use_output_norm = use_output_norm
|
| 658 |
+
# self.use_short_conv = use_short_conv
|
| 659 |
+
# self.conv_size = conv_size
|
| 660 |
+
# self.conv_bias = conv_bias
|
| 661 |
+
|
| 662 |
+
# self.key_dim = int(hidden_size * expand_k)
|
| 663 |
+
# self.value_dim = int(hidden_size * expand_v)
|
| 664 |
+
# self.head_qk_dim = self.key_dim // num_heads
|
| 665 |
+
# self.head_v_dim = self.value_dim // num_heads
|
| 666 |
+
# self.norm_first = norm_first
|
| 667 |
+
# self.layer_idx = layer_idx
|
| 668 |
+
# self.top_k = topk
|
| 669 |
+
# self.silu = nn.SiLU()
|
| 670 |
+
# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 671 |
+
# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 672 |
+
# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 673 |
+
# if norm_first:
|
| 674 |
+
# self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 675 |
+
# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 676 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 677 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 678 |
+
# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 679 |
+
|
| 680 |
+
# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 681 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 682 |
+
# self.A_log._no_weight_decay = True
|
| 683 |
+
# # hard coded for now
|
| 684 |
+
# dt_min = 0.001
|
| 685 |
+
# dt_max = 0.1
|
| 686 |
+
# dt_init_floor = 1e-4
|
| 687 |
+
# dt = torch.exp(
|
| 688 |
+
# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 689 |
+
# + math.log(dt_min)
|
| 690 |
+
# )
|
| 691 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 692 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 693 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 694 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 695 |
+
# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 696 |
+
# # name.endswith("bias") in param_grouping.py
|
| 697 |
+
# self.dt_bias._no_weight_decay = True
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
# self.use_beta = use_beta
|
| 701 |
+
# self.use_elu = use_elu
|
| 702 |
+
# if self.use_beta:
|
| 703 |
+
# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 704 |
+
# if use_short_conv:
|
| 705 |
+
# self.conv_size = conv_size
|
| 706 |
+
# self.q_conv1d = ShortConvolution(self.key_dim,
|
| 707 |
+
# conv_size,
|
| 708 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 709 |
+
# self.k_conv1d = ShortConvolution(self.key_dim,
|
| 710 |
+
# conv_size,
|
| 711 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 712 |
+
# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 713 |
+
# self.add_dim = 16 ###相当于差值get 旋转,然而这里我们有一定的控制,实质得到的结果可能需要再给一个映射到1的系数
|
| 714 |
+
# if self.add_dim !=1:
|
| 715 |
+
# self.rotary = RotaryEmbedding(dim=self.add_dim, base=50000)
|
| 716 |
+
# self.vector_to_one = nn.Linear(self.add_dim, 1, bias=False)
|
| 717 |
+
# print('rotary')
|
| 718 |
+
# if use_gate:
|
| 719 |
+
# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 720 |
+
# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 721 |
+
# else:
|
| 722 |
+
# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 723 |
+
# self.rmsnorm = RMSNorm(self.head_v_dim, eps=norm_eps,elementwise_affine=False)
|
| 724 |
+
# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 725 |
+
# self.ratio = ratio
|
| 726 |
+
# self.top_k = topk
|
| 727 |
+
# print(self.ratio)
|
| 728 |
+
# print(self.top_k)
|
| 729 |
+
# ###64 128 256 512 for num_heads=4
|
| 730 |
+
# self.past_chunk_size = [64 for i in range(self.num_heads)]
|
| 731 |
+
# # self.past_chunk_size = [64*(2**i) for i in range(self.num_heads)] ###或许需要根据不同头调整past_chunk_size
|
| 732 |
+
# ###根据ratio看保留最近的几个chunk_state
|
| 733 |
+
|
| 734 |
+
# def _initialize_weights(self, module: nn.Module):
|
| 735 |
+
# if getattr(module, "_is_hf_initialized", False):
|
| 736 |
+
# return
|
| 737 |
+
# if isinstance(module, nn.Linear):
|
| 738 |
+
# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 739 |
+
# if module.bias is not None:
|
| 740 |
+
# nn.init.zeros_(module.bias)
|
| 741 |
+
# module._is_hf_initialized = True
|
| 742 |
+
|
| 743 |
+
# def forward(
|
| 744 |
+
# self,
|
| 745 |
+
# hidden_states: torch.Tensor,
|
| 746 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
| 747 |
+
# past_key_values: Optional[Cache] = None,
|
| 748 |
+
# use_cache: Optional[bool] = False,
|
| 749 |
+
# output_attentions: Optional[bool] = False,
|
| 750 |
+
# **kwargs
|
| 751 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 752 |
+
# # change to inference mode.
|
| 753 |
+
# if attention_mask is not None:
|
| 754 |
+
# assert len(attention_mask.shape) == 2, (
|
| 755 |
+
# "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 756 |
+
# "for padding purposes (0 indicating padding). "
|
| 757 |
+
# "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 758 |
+
# )
|
| 759 |
+
# batch_size, q_len, _ = hidden_states.shape
|
| 760 |
+
# # change to inference mode.
|
| 761 |
+
# mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 762 |
+
# if self.training:
|
| 763 |
+
# assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 764 |
+
|
| 765 |
+
# last_state = None
|
| 766 |
+
# if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 767 |
+
# last_state = past_key_values[self.layer_idx]
|
| 768 |
+
|
| 769 |
+
# cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 770 |
+
# if attention_mask is not None:
|
| 771 |
+
# indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 772 |
+
# hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 773 |
+
|
| 774 |
+
# if self.use_short_conv:
|
| 775 |
+
# conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 776 |
+
# if last_state is not None:
|
| 777 |
+
# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 778 |
+
# q = self.q_proj(hidden_states)
|
| 779 |
+
# k = self.k_proj(hidden_states)
|
| 780 |
+
# v = self.v_proj(hidden_states)
|
| 781 |
+
# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 782 |
+
# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 783 |
+
# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 784 |
+
# else:
|
| 785 |
+
# q = F.silu(self.q_proj(hidden_states))
|
| 786 |
+
# k = F.silu(self.k_proj(hidden_states))
|
| 787 |
+
# v = F.silu(self.v_proj(hidden_states))
|
| 788 |
+
|
| 789 |
+
# q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k))
|
| 790 |
+
# v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 791 |
+
# beta = self.b_proj(hidden_states).sigmoid()
|
| 792 |
+
# # if self.allow_neg_eigval:
|
| 793 |
+
# # beta = beta * 2.
|
| 794 |
+
|
| 795 |
+
# q = l2norm(q)
|
| 796 |
+
# k = l2norm(k)
|
| 797 |
+
# recurrent_state = None
|
| 798 |
+
# if last_state is not None:
|
| 799 |
+
# recurrent_state = last_state['recurrent_state']
|
| 800 |
+
# g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
# seqlen_offset, max_seqlen = 0, q_len
|
| 804 |
+
# if past_key_values is not None:
|
| 805 |
+
# seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 806 |
+
# max_seqlen = q.shape[1] + seqlen_offset
|
| 807 |
+
|
| 808 |
+
# v_add = torch.ones(batch_size, q_len,self.num_heads,self.add_dim,device=v.device,dtype=v.dtype)
|
| 809 |
+
# if self.add_dim !=1:
|
| 810 |
+
# v_add, _ = self.rotary(v_add,v_add, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 811 |
+
# v_expand = torch.cat([v, v_add], dim=-1)###B L H D+16
|
| 812 |
+
# ####################需要调整一下q,前部分mask掉
|
| 813 |
+
# q_exp = stride_blhdtoblhrd(q,self.ratio,self.past_chunk_size)
|
| 814 |
+
# # print(q_exp[0,:,0,0])####
|
| 815 |
+
# k_exp = rearrange(k.unsqueeze(-2).repeat(1,1,1,self.ratio,1),'b l h r d->b l (h r) d')###B L (HR) D
|
| 816 |
+
# v_exp = rearrange(v_expand.unsqueeze(-2).repeat(1,1,1,self.ratio,1),'b l h r d->b l (h r) d')###B L (HR) D
|
| 817 |
+
# beta_exp = rearrange(beta.unsqueeze(-1).repeat(1,1,1,self.ratio),'b l h r->b l (h r)')###B L (HR)
|
| 818 |
+
# g_exp = rearrange(g.unsqueeze(-1).repeat(1,1,1,self.ratio),'b l h r->b l (h r)')###B L (HR)
|
| 819 |
+
|
| 820 |
+
# # if self.num_v_heads > self.num_heads:
|
| 821 |
+
# # q, k = map(lambda x: repeat(x, '... h d -> ... (h g) d', g=self.num_v_heads // self.num_heads), (q, k))
|
| 822 |
+
# if mode == 'recurrent':
|
| 823 |
+
# o, recurrent_state = fused_recurrent_gated_delta_rule(
|
| 824 |
+
# q=q_exp,
|
| 825 |
+
# k=k_exp,
|
| 826 |
+
# v=v_exp,
|
| 827 |
+
# g=g_exp,
|
| 828 |
+
# beta=beta_exp,
|
| 829 |
+
# initial_state=recurrent_state,
|
| 830 |
+
# output_final_state=use_cache,
|
| 831 |
+
# cu_seqlens=cu_seqlens,
|
| 832 |
+
# use_qk_l2norm_in_kernel=False
|
| 833 |
+
# )
|
| 834 |
+
# else:
|
| 835 |
+
# o,recurrent_state = chunk_gated_delta_rule(
|
| 836 |
+
# q=q_exp,
|
| 837 |
+
# k=k_exp,
|
| 838 |
+
# v=v_exp,
|
| 839 |
+
# g=g_exp,
|
| 840 |
+
# beta=beta_exp,
|
| 841 |
+
# initial_state=recurrent_state,
|
| 842 |
+
# output_final_state=use_cache,
|
| 843 |
+
# cu_seqlens=cu_seqlens,
|
| 844 |
+
# use_qk_l2norm_in_kernel=False
|
| 845 |
+
# )
|
| 846 |
+
# if past_key_values is not None:
|
| 847 |
+
# past_key_values.update(
|
| 848 |
+
# recurrent_state=(recurrent_state),
|
| 849 |
+
# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 850 |
+
# layer_idx=self.layer_idx,
|
| 851 |
+
# offset=q_len
|
| 852 |
+
# )
|
| 853 |
+
# ####先考虑把序列重新拉出来
|
| 854 |
+
|
| 855 |
+
# represent_qk_sep = (o[...,-self.add_dim:])###BLHR16
|
| 856 |
+
# o_sep = o[...,:-self.add_dim]###BL(HR)D
|
| 857 |
+
# represent_qk_sep = rearrange(represent_qk_sep,'b l (h r) d->b l h r d',h=self.num_heads)
|
| 858 |
+
# o_sep = rearrange(o_sep,'b l (h r) d->b l h r d',h=self.num_heads)
|
| 859 |
+
# o_sep = stride_blhrdtoblhrd(o_sep,self.ratio,self.past_chunk_size,inf=False)
|
| 860 |
+
# o_sep = rearrange(o_sep,'b l (h r) d->b l h r d',h=self.num_heads)
|
| 861 |
+
# o_sep = self.rmsnorm(o_sep)##随意缩放一下,基本等价于L2norm,除了多了一个缩放稀疏,让每个state平权
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
# mask = stride_blhrdtoblhrd(represent_qk_sep,self.ratio,self.past_chunk_size,inf=True)[:,:,0,0]###BL
|
| 865 |
+
# mask = torch.isinf(mask)
|
| 866 |
+
|
| 867 |
+
# represent_qk_sep = stride_blhrdtoblhrd(represent_qk_sep,self.ratio,self.past_chunk_size,inf=False)
|
| 868 |
+
# _, represent_qk_sep = self.rotary(represent_qk_sep,represent_qk_sep, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 869 |
+
# represent_qk_sep = rearrange(represent_qk_sep,'b l (h r) d->b l h r d',h=self.num_heads)
|
| 870 |
+
# represent_qk_sep = self.vector_to_one(represent_qk_sep).squeeze()###B L H R
|
| 871 |
+
# ####根据mask 哪里是inf把represent qk也inf
|
| 872 |
+
# represent_qk_sep = represent_qk_sep.masked_fill(mask[:,:,None,None], float('-inf'))
|
| 873 |
+
|
| 874 |
+
# o = o_sep.sum(dim=-2)
|
| 875 |
+
# # softmax_qk = torch.softmax(represent_qk_sep,dim=-1)###BLH r
|
| 876 |
+
# # o = torch.einsum('b l h r d, b l h r ->b l h d',o_sep,softmax_qk)###B L H D
|
| 877 |
+
# # print(o)
|
| 878 |
+
# # o = rearrange(o,'b l (h r) d->b l h r d',h=self.num_heads)
|
| 879 |
+
# # o = stride_blhrdtoblhrd(o,self.ratio,self.past_chunk_size,inf=True)
|
| 880 |
+
# # o = rearrange(o,'b l (h r) d->b l h r d',h=self.num_heads)
|
| 881 |
+
# # print(o[0,:,0,0,0])####
|
| 882 |
+
# # assert 1==0
|
| 883 |
+
# # _, represent_qk_sep = self.rotary(represent_qk_sep,represent_qk_sep, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 884 |
+
# # represent_qk_sep = self.vector_to_one(represent_qk_sep).squeeze()###B L H R
|
| 885 |
+
# # softmax_qk = torch.softmax(represent_qk_sep,dim=-1)###BLH r
|
| 886 |
+
# # # print(o_sep.shape)
|
| 887 |
+
# # o_sep = self.rmsnorm(o_sep)##随意缩放一下,基本等价于L2norm,除了多了一个缩放稀疏,让每个state平权
|
| 888 |
+
# # o = torch.einsum('b l h r d, b l h r ->b l h d',o_sep,softmax_qk)###B L H D
|
| 889 |
+
# # if self.use_gate:
|
| 890 |
+
# # g = rearrange(self.g_proj(hidden_states), 'b l (h d) -> b l h d', h=self.num_heads)
|
| 891 |
+
# # o = self.o_norm(o, g)
|
| 892 |
+
# # else:
|
| 893 |
+
# o = self.o_norm(o)
|
| 894 |
+
# o = rearrange(o, 'b l h d -> b l (h d)')
|
| 895 |
+
# # print(o.shape)
|
| 896 |
+
# o = self.o_proj(o)
|
| 897 |
+
# if attention_mask is not None:
|
| 898 |
+
# o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 899 |
+
# return o, None, past_key_values,None
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
# #######################################这个版本的代码使用固定的scale,用于控制不同state的占比
|
| 903 |
+
# from ..ops.gated_delta_rule import chunk_gated_delta_rule,fused_recurrent_gated_delta_rule
|
| 904 |
+
# class past_gdn(nn.Module):
|
| 905 |
+
# def __init__(
|
| 906 |
+
# self,
|
| 907 |
+
# d_model: int = None,
|
| 908 |
+
# hidden_size: int = 1024,
|
| 909 |
+
# expand_k: float = 1.0,
|
| 910 |
+
# expand_v: float = 1.0,
|
| 911 |
+
# num_heads: int = 4,
|
| 912 |
+
# mode: str = 'chunk',
|
| 913 |
+
# chunk_size: int = 64,
|
| 914 |
+
# use_beta: bool = True,
|
| 915 |
+
# use_gate: bool = False,
|
| 916 |
+
# use_output_norm: bool = True,
|
| 917 |
+
# use_elu: bool = False,
|
| 918 |
+
# use_short_conv: bool = True,
|
| 919 |
+
# conv_size: int = 4,
|
| 920 |
+
# conv_bias: bool = False,
|
| 921 |
+
# layer_idx: int = None,
|
| 922 |
+
# qk_activation: str = 'silu',
|
| 923 |
+
# qk_norm: str = 'l2',
|
| 924 |
+
# norm_first: bool = False,
|
| 925 |
+
# norm_eps: float = 1e-6,
|
| 926 |
+
# ratio: int = 2,
|
| 927 |
+
# **kwargs
|
| 928 |
+
# ) :
|
| 929 |
+
# super().__init__()
|
| 930 |
+
|
| 931 |
+
# self.mode = mode
|
| 932 |
+
# self.qk_activation = qk_activation
|
| 933 |
+
# self.qk_norm = qk_norm
|
| 934 |
+
|
| 935 |
+
# assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 936 |
+
# assert self.qk_norm in ['l2', 'sum']
|
| 937 |
+
|
| 938 |
+
# if d_model is not None:
|
| 939 |
+
# hidden_size = d_model
|
| 940 |
+
# self.hidden_size = hidden_size
|
| 941 |
+
# self.expand_k = expand_k
|
| 942 |
+
# self.expand_v = expand_v
|
| 943 |
+
# self.num_heads = num_heads
|
| 944 |
+
# self.chunk_size = chunk_size
|
| 945 |
+
# self.use_gate = use_gate
|
| 946 |
+
# self.use_output_norm = use_output_norm
|
| 947 |
+
# self.use_short_conv = use_short_conv
|
| 948 |
+
# self.conv_size = conv_size
|
| 949 |
+
# self.conv_bias = conv_bias
|
| 950 |
+
|
| 951 |
+
# self.key_dim = int(hidden_size * expand_k)
|
| 952 |
+
# self.value_dim = int(hidden_size * expand_v)
|
| 953 |
+
# self.head_qk_dim = self.key_dim // num_heads
|
| 954 |
+
# self.head_v_dim = self.value_dim // num_heads
|
| 955 |
+
# self.norm_first = norm_first
|
| 956 |
+
# self.layer_idx = layer_idx
|
| 957 |
+
|
| 958 |
+
# self.silu = nn.SiLU()
|
| 959 |
+
# assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 960 |
+
# assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 961 |
+
# assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 962 |
+
# if norm_first:
|
| 963 |
+
# self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 964 |
+
# self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 965 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 966 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 967 |
+
# self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 968 |
+
|
| 969 |
+
# A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 970 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 971 |
+
# self.A_log._no_weight_decay = True
|
| 972 |
+
# # hard coded for now
|
| 973 |
+
# dt_min = 0.001
|
| 974 |
+
# dt_max = 0.1
|
| 975 |
+
# dt_init_floor = 1e-4
|
| 976 |
+
# dt = torch.exp(
|
| 977 |
+
# torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 978 |
+
# + math.log(dt_min)
|
| 979 |
+
# )
|
| 980 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 981 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 982 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 983 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 984 |
+
# # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 985 |
+
# # name.endswith("bias") in param_grouping.py
|
| 986 |
+
# self.dt_bias._no_weight_decay = True
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
# self.use_beta = use_beta
|
| 990 |
+
# self.use_elu = use_elu
|
| 991 |
+
# if self.use_beta:
|
| 992 |
+
# self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 993 |
+
# if use_short_conv:
|
| 994 |
+
# self.conv_size = conv_size
|
| 995 |
+
# self.q_conv1d = ShortConvolution(self.key_dim,
|
| 996 |
+
# conv_size,
|
| 997 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 998 |
+
# self.k_conv1d = ShortConvolution(self.key_dim,
|
| 999 |
+
# conv_size,
|
| 1000 |
+
# activation='silu' if qk_activation == 'silu' else None)
|
| 1001 |
+
# self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 1002 |
+
# if use_gate:
|
| 1003 |
+
# self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 1004 |
+
# self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 1005 |
+
# else:
|
| 1006 |
+
# self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 1007 |
+
# self.rmsnorm = RMSNorm(self.head_v_dim, eps=norm_eps,elementwise_affine=False)
|
| 1008 |
+
# self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 1009 |
+
# self.ratio = ratio
|
| 1010 |
+
# self.chunk_scale = nn.Parameter(torch.ones(self.num_heads,self.ratio))
|
| 1011 |
+
# self.past_chunk_size = [64*(2**i) for i in range(self.num_heads)]
|
| 1012 |
+
|
| 1013 |
+
# def _initialize_weights(self, module: nn.Module):
|
| 1014 |
+
# if getattr(module, "_is_hf_initialized", False):
|
| 1015 |
+
# return
|
| 1016 |
+
# if isinstance(module, nn.Linear):
|
| 1017 |
+
# nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 1018 |
+
# if module.bias is not None:
|
| 1019 |
+
# nn.init.zeros_(module.bias)
|
| 1020 |
+
# module._is_hf_initialized = True
|
| 1021 |
+
|
| 1022 |
+
# def forward(
|
| 1023 |
+
# self,
|
| 1024 |
+
# hidden_states: torch.Tensor,
|
| 1025 |
+
# attention_mask: Optional[torch.Tensor] = None,
|
| 1026 |
+
# past_key_values: Optional[Cache] = None,
|
| 1027 |
+
# use_cache: Optional[bool] = False,
|
| 1028 |
+
# output_attentions: Optional[bool] = False,
|
| 1029 |
+
# **kwargs
|
| 1030 |
+
# ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 1031 |
+
# # change to inference mode.
|
| 1032 |
+
# if attention_mask is not None:
|
| 1033 |
+
# assert len(attention_mask.shape) == 2, (
|
| 1034 |
+
# "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 1035 |
+
# "for padding purposes (0 indicating padding). "
|
| 1036 |
+
# "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 1037 |
+
# )
|
| 1038 |
+
# batch_size, q_len, _ = hidden_states.shape
|
| 1039 |
+
# # change to inference mode.
|
| 1040 |
+
# mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 1041 |
+
# if self.training:
|
| 1042 |
+
# assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 1043 |
+
|
| 1044 |
+
# last_state = None
|
| 1045 |
+
# if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 1046 |
+
# last_state = past_key_values[self.layer_idx]
|
| 1047 |
+
|
| 1048 |
+
# cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 1049 |
+
# if attention_mask is not None:
|
| 1050 |
+
# indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 1051 |
+
# hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 1052 |
+
|
| 1053 |
+
# if self.use_short_conv:
|
| 1054 |
+
# conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 1055 |
+
# if last_state is not None:
|
| 1056 |
+
# conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 1057 |
+
# q = self.q_proj(hidden_states)
|
| 1058 |
+
# k = self.k_proj(hidden_states)
|
| 1059 |
+
# v = self.v_proj(hidden_states)
|
| 1060 |
+
# q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1061 |
+
# k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1062 |
+
# v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1063 |
+
# else:
|
| 1064 |
+
# q = F.silu(self.q_proj(hidden_states))
|
| 1065 |
+
# k = F.silu(self.k_proj(hidden_states))
|
| 1066 |
+
# v = F.silu(self.v_proj(hidden_states))
|
| 1067 |
+
|
| 1068 |
+
# q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k))
|
| 1069 |
+
# v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 1070 |
+
# beta = self.b_proj(hidden_states).sigmoid()
|
| 1071 |
+
# # if self.allow_neg_eigval:
|
| 1072 |
+
# # beta = beta * 2.
|
| 1073 |
+
|
| 1074 |
+
# q = l2norm(q)
|
| 1075 |
+
# k = l2norm(k)
|
| 1076 |
+
# recurrent_state1,recurrent_state2 = None,None
|
| 1077 |
+
# if last_state is not None:
|
| 1078 |
+
# recurrent_state1,recurrent_state2 = last_state['recurrent_state']
|
| 1079 |
+
# g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
|
| 1080 |
+
|
| 1081 |
+
|
| 1082 |
+
# seqlen_offset, max_seqlen = 0, q_len
|
| 1083 |
+
# if past_key_values is not None:
|
| 1084 |
+
# seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 1085 |
+
# max_seqlen = q.shape[1] + seqlen_offset
|
| 1086 |
+
|
| 1087 |
+
# q1=[]
|
| 1088 |
+
# for i in range(self.num_heads):
|
| 1089 |
+
# q1.append(torch.cat([q[:,:,i:i+1,:],q.new_zeros(batch_size,self.past_chunk_size[i],1,self.head_qk_dim)], dim=1)[:,-q_len:,...])
|
| 1090 |
+
# q1 = torch.cat(q1, dim=2).contiguous()
|
| 1091 |
+
|
| 1092 |
+
# o1,recurrent_state1 = chunk_gated_delta_rule(
|
| 1093 |
+
# q=q,
|
| 1094 |
+
# k=k,
|
| 1095 |
+
# v=v,
|
| 1096 |
+
# g=g,
|
| 1097 |
+
# beta=beta,
|
| 1098 |
+
# initial_state=recurrent_state1,
|
| 1099 |
+
# output_final_state=use_cache,
|
| 1100 |
+
# cu_seqlens=cu_seqlens,
|
| 1101 |
+
# use_qk_l2norm_in_kernel=False
|
| 1102 |
+
# )
|
| 1103 |
+
# o2,recurrent_state2 = chunk_gated_delta_rule(
|
| 1104 |
+
# q=q1,
|
| 1105 |
+
# k=k,
|
| 1106 |
+
# v=v,
|
| 1107 |
+
# g=g,
|
| 1108 |
+
# beta=beta,
|
| 1109 |
+
# initial_state=recurrent_state2,
|
| 1110 |
+
# output_final_state=use_cache,
|
| 1111 |
+
# cu_seqlens=cu_seqlens,
|
| 1112 |
+
# use_qk_l2norm_in_kernel=False
|
| 1113 |
+
# )
|
| 1114 |
+
# if past_key_values is not None:
|
| 1115 |
+
# past_key_values.update(
|
| 1116 |
+
# recurrent_state=(recurrent_state1,recurrent_state2),
|
| 1117 |
+
# conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 1118 |
+
# layer_idx=self.layer_idx,
|
| 1119 |
+
# offset=q_len
|
| 1120 |
+
# )
|
| 1121 |
+
|
| 1122 |
+
# o2_new = []
|
| 1123 |
+
# for i in range(self.num_heads):
|
| 1124 |
+
# o2_new.append(torch.cat([o2.new_zeros(batch_size,self.past_chunk_size[i],1,self.head_v_dim),o2[:,:,i:i+1,:]], dim=1)[:,:q_len,...])
|
| 1125 |
+
# o2_new = torch.cat(o2_new, dim=2).contiguous()
|
| 1126 |
+
# o1 = self.rmsnorm(o1)#BLHD
|
| 1127 |
+
# o2_new = self.rmsnorm(o2_new)###BLHD###need
|
| 1128 |
+
# o = torch.stack([o1,o2_new], dim=-2)###BLHRD
|
| 1129 |
+
# o = torch.einsum('b l h r d, h r -> b l h d',o,self.chunk_scale)
|
| 1130 |
+
# o = self.o_norm(o)
|
| 1131 |
+
# o = rearrange(o, 'b l h d -> b l (h d)')
|
| 1132 |
+
# o = self.o_proj(o)
|
| 1133 |
+
# if attention_mask is not None:
|
| 1134 |
+
# o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 1135 |
+
# return o, None, past_key_values,None
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
from ..ops.gated_delta_rule import chunk_gated_delta_rule,fused_recurrent_gated_delta_rule
|
| 1139 |
+
class past_gdn(nn.Module):
|
| 1140 |
+
def __init__(
|
| 1141 |
+
self,
|
| 1142 |
+
d_model: int = None,
|
| 1143 |
+
hidden_size: int = 1024,
|
| 1144 |
+
expand_k: float = 1.0,
|
| 1145 |
+
expand_v: float = 1.0,
|
| 1146 |
+
num_heads: int = 4,
|
| 1147 |
+
mode: str = 'chunk',
|
| 1148 |
+
chunk_size: int = 64,
|
| 1149 |
+
use_beta: bool = True,
|
| 1150 |
+
use_gate: bool = False,
|
| 1151 |
+
use_output_norm: bool = True,
|
| 1152 |
+
use_elu: bool = False,
|
| 1153 |
+
use_short_conv: bool = True,
|
| 1154 |
+
conv_size: int = 4,
|
| 1155 |
+
conv_bias: bool = False,
|
| 1156 |
+
layer_idx: int = None,
|
| 1157 |
+
qk_activation: str = 'silu',
|
| 1158 |
+
qk_norm: str = 'l2',
|
| 1159 |
+
norm_first: bool = False,
|
| 1160 |
+
norm_eps: float = 1e-6,
|
| 1161 |
+
ratio: int = 2,
|
| 1162 |
+
**kwargs
|
| 1163 |
+
) :
|
| 1164 |
+
super().__init__()
|
| 1165 |
+
|
| 1166 |
+
self.mode = mode
|
| 1167 |
+
self.qk_activation = qk_activation
|
| 1168 |
+
self.qk_norm = qk_norm
|
| 1169 |
+
|
| 1170 |
+
assert self.qk_activation in ['silu', 'relu', 'elu', 'identity']
|
| 1171 |
+
assert self.qk_norm in ['l2', 'sum']
|
| 1172 |
+
|
| 1173 |
+
if d_model is not None:
|
| 1174 |
+
hidden_size = d_model
|
| 1175 |
+
self.hidden_size = hidden_size
|
| 1176 |
+
self.expand_k = expand_k
|
| 1177 |
+
self.expand_v = expand_v
|
| 1178 |
+
self.num_heads = num_heads
|
| 1179 |
+
self.chunk_size = chunk_size
|
| 1180 |
+
self.use_gate = use_gate
|
| 1181 |
+
self.use_output_norm = use_output_norm
|
| 1182 |
+
self.use_short_conv = use_short_conv
|
| 1183 |
+
self.conv_size = conv_size
|
| 1184 |
+
self.conv_bias = conv_bias
|
| 1185 |
+
|
| 1186 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 1187 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 1188 |
+
self.head_qk_dim = self.key_dim // num_heads
|
| 1189 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 1190 |
+
self.norm_first = norm_first
|
| 1191 |
+
self.layer_idx = layer_idx
|
| 1192 |
+
|
| 1193 |
+
self.silu = nn.SiLU()
|
| 1194 |
+
assert mode in ['chunk', 'fused_chunk', 'fused_recurrent'], f"Not suppoerted mode `{mode}`."
|
| 1195 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 1196 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 1197 |
+
if norm_first:
|
| 1198 |
+
self.norm = RMSNorm(self.hidden_size, eps=norm_eps)
|
| 1199 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 1200 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 1201 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 1202 |
+
self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 1203 |
+
|
| 1204 |
+
A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 1205 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 1206 |
+
self.A_log._no_weight_decay = True
|
| 1207 |
+
# hard coded for now
|
| 1208 |
+
dt_min = 0.001
|
| 1209 |
+
dt_max = 0.1
|
| 1210 |
+
dt_init_floor = 1e-4
|
| 1211 |
+
dt = torch.exp(
|
| 1212 |
+
torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 1213 |
+
+ math.log(dt_min)
|
| 1214 |
+
)
|
| 1215 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 1216 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 1217 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 1218 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 1219 |
+
# Just to be explicit. Without this we already don't put wd on dt_bias because of the check
|
| 1220 |
+
# name.endswith("bias") in param_grouping.py
|
| 1221 |
+
self.dt_bias._no_weight_decay = True
|
| 1222 |
+
|
| 1223 |
+
|
| 1224 |
+
self.use_beta = use_beta
|
| 1225 |
+
self.use_elu = use_elu
|
| 1226 |
+
if self.use_beta:
|
| 1227 |
+
self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
|
| 1228 |
+
if use_short_conv:
|
| 1229 |
+
self.conv_size = conv_size
|
| 1230 |
+
self.q_conv1d = ShortConvolution(self.key_dim,
|
| 1231 |
+
conv_size,
|
| 1232 |
+
activation='silu' if qk_activation == 'silu' else None)
|
| 1233 |
+
self.k_conv1d = ShortConvolution(self.key_dim,
|
| 1234 |
+
conv_size,
|
| 1235 |
+
activation='silu' if qk_activation == 'silu' else None)
|
| 1236 |
+
self.v_conv1d = ShortConvolution(self.value_dim, conv_size, activation='silu')
|
| 1237 |
+
if use_gate:
|
| 1238 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 1239 |
+
self.o_norm = FusedRMSNormSwishGate(self.head_v_dim, eps=norm_eps)
|
| 1240 |
+
else:
|
| 1241 |
+
self.o_norm = RMSNorm(self.head_v_dim, eps=norm_eps)
|
| 1242 |
+
self.rmsnorm = RMSNorm(self.head_v_dim, eps=norm_eps,elementwise_affine=False)
|
| 1243 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 1244 |
+
self.ratio = ratio
|
| 1245 |
+
self.chunk_scale = nn.Parameter(torch.ones(self.num_heads,self.ratio))
|
| 1246 |
+
self.past_chunk_size = [64*(2**i) for i in range(self.num_heads)]
|
| 1247 |
+
self.add_dim = 16 ###相当于差值get 旋转,然而这里我们有一定的控制,实质得到的结果可能需要再给一个映射到1的系数
|
| 1248 |
+
if self.add_dim !=1:
|
| 1249 |
+
self.rotary = RotaryEmbedding(dim=self.add_dim, base=50000)
|
| 1250 |
+
self.vector_to_one = nn.Linear(self.add_dim, 1, bias=False)
|
| 1251 |
+
print('rotary')
|
| 1252 |
+
|
| 1253 |
+
|
| 1254 |
+
def _initialize_weights(self, module: nn.Module):
|
| 1255 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 1256 |
+
return
|
| 1257 |
+
if isinstance(module, nn.Linear):
|
| 1258 |
+
nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 1259 |
+
if module.bias is not None:
|
| 1260 |
+
nn.init.zeros_(module.bias)
|
| 1261 |
+
module._is_hf_initialized = True
|
| 1262 |
+
|
| 1263 |
+
def forward(
|
| 1264 |
+
self,
|
| 1265 |
+
hidden_states: torch.Tensor,
|
| 1266 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1267 |
+
past_key_values: Optional[Cache] = None,
|
| 1268 |
+
use_cache: Optional[bool] = False,
|
| 1269 |
+
output_attentions: Optional[bool] = False,
|
| 1270 |
+
**kwargs
|
| 1271 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 1272 |
+
# change to inference mode.
|
| 1273 |
+
if attention_mask is not None:
|
| 1274 |
+
assert len(attention_mask.shape) == 2, (
|
| 1275 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 1276 |
+
"for padding purposes (0 indicating padding). "
|
| 1277 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 1278 |
+
)
|
| 1279 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 1280 |
+
# change to inference mode.
|
| 1281 |
+
mode = 'fused_recurrent' if q_len <= 64 else self.mode
|
| 1282 |
+
if self.training:
|
| 1283 |
+
assert mode == 'chunk', "Only chunk mode is supported in training."
|
| 1284 |
+
|
| 1285 |
+
last_state = None
|
| 1286 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 1287 |
+
last_state = past_key_values[self.layer_idx]
|
| 1288 |
+
|
| 1289 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 1290 |
+
if attention_mask is not None:
|
| 1291 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 1292 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 1293 |
+
|
| 1294 |
+
if self.use_short_conv:
|
| 1295 |
+
conv_state_q , conv_state_k , conv_state_v = None,None,None
|
| 1296 |
+
if last_state is not None:
|
| 1297 |
+
conv_state_q , conv_state_k , conv_state_v = last_state['conv_state']
|
| 1298 |
+
q = self.q_proj(hidden_states)
|
| 1299 |
+
k = self.k_proj(hidden_states)
|
| 1300 |
+
v = self.v_proj(hidden_states)
|
| 1301 |
+
q,conv_state_q = self.q_conv1d(q, cache= conv_state_q,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1302 |
+
k,conv_state_k = self.k_conv1d(k, cache= conv_state_k,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1303 |
+
v,conv_state_v = self.v_conv1d(v, cache= conv_state_v,output_final_state = use_cache,cu_seqlens =cu_seqlens)
|
| 1304 |
+
else:
|
| 1305 |
+
q = F.silu(self.q_proj(hidden_states))
|
| 1306 |
+
k = F.silu(self.k_proj(hidden_states))
|
| 1307 |
+
v = F.silu(self.v_proj(hidden_states))
|
| 1308 |
+
|
| 1309 |
+
seqlen_offset, max_seqlen = 0, q_len
|
| 1310 |
+
if past_key_values is not None:
|
| 1311 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 1312 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 1313 |
+
|
| 1314 |
+
q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_qk_dim), (q, k))
|
| 1315 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
|
| 1316 |
+
beta = self.b_proj(hidden_states).sigmoid()
|
| 1317 |
+
# if self.allow_neg_eigval:
|
| 1318 |
+
# beta = beta * 2.
|
| 1319 |
+
v_add = torch.ones(batch_size, q_len,self.num_heads,self.add_dim,device=v.device,dtype=v.dtype)
|
| 1320 |
+
if self.add_dim !=1:
|
| 1321 |
+
v_add, _ = self.rotary(v_add,v_add, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 1322 |
+
v = torch.cat([v, v_add], dim=-1)###B L H D+16
|
| 1323 |
+
|
| 1324 |
+
q = l2norm(q)
|
| 1325 |
+
k = l2norm(k)
|
| 1326 |
+
recurrent_state1,recurrent_state2 = None,None
|
| 1327 |
+
if last_state is not None:
|
| 1328 |
+
recurrent_state1,recurrent_state2 = last_state['recurrent_state']
|
| 1329 |
+
g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
# q1 = torch.cat([q,q.new_zeros(batch_size, 48, self.num_heads, self.head_qk_dim)], dim=1)[:,-q_len:,...]
|
| 1333 |
+
q1=[]
|
| 1334 |
+
for i in range(self.num_heads):
|
| 1335 |
+
q1.append(torch.cat([q[:,:,i:i+1,:],q.new_zeros(batch_size,self.past_chunk_size[i],1,self.head_qk_dim)], dim=1)[:,-q_len:,...])
|
| 1336 |
+
q1 = torch.cat(q1, dim=2).contiguous()
|
| 1337 |
+
|
| 1338 |
+
o1,recurrent_state1 = chunk_gated_delta_rule(
|
| 1339 |
+
q=q,
|
| 1340 |
+
k=k,
|
| 1341 |
+
v=v,
|
| 1342 |
+
g=g,
|
| 1343 |
+
beta=beta,
|
| 1344 |
+
initial_state=recurrent_state1,
|
| 1345 |
+
output_final_state=use_cache,
|
| 1346 |
+
cu_seqlens=cu_seqlens,
|
| 1347 |
+
use_qk_l2norm_in_kernel=False
|
| 1348 |
+
)
|
| 1349 |
+
o2,recurrent_state2 = chunk_gated_delta_rule(
|
| 1350 |
+
q=q1,
|
| 1351 |
+
k=k,
|
| 1352 |
+
v=v,
|
| 1353 |
+
g=g,
|
| 1354 |
+
beta=beta,
|
| 1355 |
+
initial_state=recurrent_state2,
|
| 1356 |
+
output_final_state=use_cache,
|
| 1357 |
+
cu_seqlens=cu_seqlens,
|
| 1358 |
+
use_qk_l2norm_in_kernel=False
|
| 1359 |
+
)
|
| 1360 |
+
if past_key_values is not None:
|
| 1361 |
+
past_key_values.update(
|
| 1362 |
+
recurrent_state=(recurrent_state1,recurrent_state2),
|
| 1363 |
+
conv_state=(conv_state_q,conv_state_k,conv_state_v) if self.use_short_conv else None,
|
| 1364 |
+
layer_idx=self.layer_idx,
|
| 1365 |
+
offset=q_len
|
| 1366 |
+
)
|
| 1367 |
+
a_range = 1/(torch.arange(q_len,device=o1.device,dtype=o1.dtype) + 1.0)###L
|
| 1368 |
+
o2_new = []
|
| 1369 |
+
a_o2_range = []
|
| 1370 |
+
for i in range(self.num_heads):
|
| 1371 |
+
o2_new.append(torch.cat([o2.new_zeros(batch_size,self.past_chunk_size[i],1,self.head_v_dim+self.add_dim),o2[:,:,i:i+1,:]], dim=1)[:,:q_len,...])
|
| 1372 |
+
a_o2_range.append(torch.cat([a_range.new_zeros((self.past_chunk_size[i])),a_range], dim=0)[:q_len])#qlen
|
| 1373 |
+
o2_new = torch.cat(o2_new, dim=2).contiguous()
|
| 1374 |
+
a_o2_range = torch.stack(a_o2_range, dim=-1).contiguous()##HL
|
| 1375 |
+
|
| 1376 |
+
#####占据比例有所差距,需要考虑除以什么去均衡嘛###B L H 16
|
| 1377 |
+
o1_sep = o1[...,-self.add_dim:]
|
| 1378 |
+
o2_new_sep = o2_new[...,-self.add_dim:]
|
| 1379 |
+
if self.add_dim !=1:
|
| 1380 |
+
_,o1_sep = self.rotary(o1_sep,o1_sep, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 1381 |
+
_,o2_new_sep = self.rotary(o2_new_sep,o2_new_sep, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 1382 |
+
o1_sep = self.vector_to_one(o1_sep).squeeze(-1)
|
| 1383 |
+
o2_new_sep = self.vector_to_one(o2_new_sep).squeeze(-1)###BLH
|
| 1384 |
+
o1_sep = o1_sep * a_range.unsqueeze(0).unsqueeze(-1)###L->BLH
|
| 1385 |
+
o2_new_sep = o2_new_sep * a_o2_range.unsqueeze(0)###LH->BLH
|
| 1386 |
+
else:
|
| 1387 |
+
o1_sep = o1_sep.squeeze(-1)####BLH
|
| 1388 |
+
o2_new_sep = o2_new_sep.squeeze(-1)####BLH
|
| 1389 |
+
o1_sep = o1_sep * a_range.unsqueeze(0).unsqueeze(-1)###L->BLH
|
| 1390 |
+
o2_new_sep = o2_new_sep * a_o2_range.unsqueeze(0)###LH->BLH
|
| 1391 |
+
|
| 1392 |
+
o1 = o1[...,:-self.add_dim]
|
| 1393 |
+
o2_new = o2_new[...,:-self.add_dim]
|
| 1394 |
+
|
| 1395 |
+
o1 = self.rmsnorm(o1)#BLHD
|
| 1396 |
+
o2_new = self.rmsnorm(o2_new)###BLHD###need
|
| 1397 |
+
o = torch.stack([o1,o2_new], dim=-2)###BLHRD
|
| 1398 |
+
sep = torch.stack([o1_sep,o2_new_sep], dim=-1)###BLHR
|
| 1399 |
+
sep = torch.softmax(sep, dim=-1)###BLHR
|
| 1400 |
+
o = torch.einsum('b l h r d, b l h r -> b l h d',o,sep)
|
| 1401 |
+
o = self.o_norm(o)
|
| 1402 |
+
o = rearrange(o, 'b l h d -> b l (h d)')
|
| 1403 |
+
o = self.o_proj(o)
|
| 1404 |
+
if attention_mask is not None:
|
| 1405 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 1406 |
+
return o, None, past_key_values,None
|
| 1407 |
+
|
path_attn.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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import torch.nn.functional as F
|
| 11 |
+
from einops import rearrange
|
| 12 |
+
from transformers.utils import logging
|
| 13 |
+
|
| 14 |
+
from fla.layers.utils import pad_input, unpad_input
|
| 15 |
+
from fla.modules import RMSNorm, ShortConvolution
|
| 16 |
+
from fla.modules.l2norm import l2_norm
|
| 17 |
+
from fla.ops.attn.decoding import attn_decoding_one_step
|
| 18 |
+
from fla.ops.path_attn.parallel import parallel_path_attn
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from fla.models.utils import Cache
|
| 22 |
+
|
| 23 |
+
logger = logging.get_logger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PaTHAttention(nn.Module):
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
hidden_size: int = 2048,
|
| 30 |
+
num_heads: int = 32,
|
| 31 |
+
num_kv_heads: Optional[int] = None,
|
| 32 |
+
use_forget_gate: bool = False,
|
| 33 |
+
use_qk_norm: bool = False,
|
| 34 |
+
layer_idx: int = None,
|
| 35 |
+
use_low_rank_w: bool = True,
|
| 36 |
+
use_w_shortconv: bool = True,
|
| 37 |
+
conv_size: int = 3,
|
| 38 |
+
conv_bias: bool = False,
|
| 39 |
+
):
|
| 40 |
+
super().__init__()
|
| 41 |
+
|
| 42 |
+
self.hidden_size = hidden_size
|
| 43 |
+
self.num_heads = num_heads
|
| 44 |
+
if num_kv_heads is None:
|
| 45 |
+
self.num_kv_heads = self.num_heads
|
| 46 |
+
else:
|
| 47 |
+
self.num_kv_heads = num_kv_heads
|
| 48 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 49 |
+
self.kv_dim = self.num_kv_heads * self.head_dim
|
| 50 |
+
|
| 51 |
+
self.layer_idx = layer_idx
|
| 52 |
+
|
| 53 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 54 |
+
self.k_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 55 |
+
self.v_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 56 |
+
|
| 57 |
+
# We use low-rank parameterization for the w_proj to reduce parameters in MHA settings.
|
| 58 |
+
if use_low_rank_w:
|
| 59 |
+
self.w_proj = nn.Sequential(
|
| 60 |
+
nn.Linear(self.hidden_size, 32, bias=False),
|
| 61 |
+
nn.Linear(32, self.kv_dim, bias=False)
|
| 62 |
+
)
|
| 63 |
+
# In MQA/GQA settings, key/value heads are shared, so we use a standard linear projection
|
| 64 |
+
# which doesn't introduce too many parameters
|
| 65 |
+
else:
|
| 66 |
+
self.w_proj = nn.Linear(self.hidden_size, self.kv_dim, bias=False)
|
| 67 |
+
|
| 68 |
+
# TODO: per head norm?
|
| 69 |
+
if use_qk_norm:
|
| 70 |
+
self.maybe_q_norm = RMSNorm(self.hidden_size)
|
| 71 |
+
self.maybe_k_norm = RMSNorm(self.kv_dim)
|
| 72 |
+
else:
|
| 73 |
+
self.maybe_q_norm = nn.Identity()
|
| 74 |
+
self.maybe_k_norm = nn.Identity()
|
| 75 |
+
|
| 76 |
+
if use_w_shortconv:
|
| 77 |
+
self.w_conv1d = ShortConvolution(hidden_size=self.kv_dim, kernel_size=conv_size, bias=conv_bias, activation='silu')
|
| 78 |
+
self.use_w_shortconv = use_w_shortconv
|
| 79 |
+
self.bt_proj = nn.Linear(self.hidden_size, self.num_kv_heads, bias=True)
|
| 80 |
+
self.use_forget_gate = use_forget_gate
|
| 81 |
+
if use_forget_gate:
|
| 82 |
+
self.g_proj = nn.Linear(self.hidden_size, self.num_heads, bias=True)
|
| 83 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 84 |
+
|
| 85 |
+
def forward(
|
| 86 |
+
self,
|
| 87 |
+
hidden_states: torch.Tensor,
|
| 88 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 89 |
+
past_key_values: Optional[Cache] = None,
|
| 90 |
+
output_attentions: bool = False,
|
| 91 |
+
use_cache: bool = False,
|
| 92 |
+
**kwargs,
|
| 93 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 94 |
+
if use_cache:
|
| 95 |
+
assert past_key_values is not None, "past_key_values must be provided when use_cache is True"
|
| 96 |
+
if attention_mask is not None:
|
| 97 |
+
assert len(attention_mask.shape) == 2, (
|
| 98 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 99 |
+
"for padding purposes (0 indicating padding). "
|
| 100 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 101 |
+
)
|
| 102 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 103 |
+
q = self.q_proj(hidden_states)
|
| 104 |
+
k = self.k_proj(hidden_states)
|
| 105 |
+
v = self.v_proj(hidden_states)
|
| 106 |
+
w = self.w_proj(hidden_states)
|
| 107 |
+
beta = self.bt_proj(hidden_states).sigmoid() * 2 # allowing negative eigenvalues
|
| 108 |
+
g = F.logsigmoid(self.g_proj(hidden_states).float()) if self.use_forget_gate else None
|
| 109 |
+
q, k = self.maybe_q_norm(q), self.maybe_k_norm(k)
|
| 110 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 111 |
+
assert not (cu_seqlens is not None and attention_mask is not None), (
|
| 112 |
+
"cu_seqlens should not be provided when attention_mask is not None"
|
| 113 |
+
)
|
| 114 |
+
# Training
|
| 115 |
+
if attention_mask is None:
|
| 116 |
+
assert use_cache is False, "use_cache should be False in training"
|
| 117 |
+
if self.use_w_shortconv:
|
| 118 |
+
w, _ = self.w_conv1d(w, cache=None, output_final_state=False, cu_seqlens=cu_seqlens)
|
| 119 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 120 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 121 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 122 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)####this 需要额外的分头,设定一个r的分块,d-》r*d//r
|
| 123 |
+
w = l2_norm(w)
|
| 124 |
+
o, _ = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g, cu_seqlens=cu_seqlens)####here
|
| 125 |
+
|
| 126 |
+
# Prefilling or decoding
|
| 127 |
+
else:
|
| 128 |
+
assert self.training is False, "attention mask is not supported in training. Please use variable length input."
|
| 129 |
+
try:
|
| 130 |
+
last_state = past_key_values[self.layer_idx]
|
| 131 |
+
except KeyError:
|
| 132 |
+
last_state = None
|
| 133 |
+
# Decoding
|
| 134 |
+
if last_state is not None:
|
| 135 |
+
if g is not None:
|
| 136 |
+
past_k, past_v, past_g = last_state['attn_state']
|
| 137 |
+
else:
|
| 138 |
+
past_k, past_v = last_state['attn_state']
|
| 139 |
+
w_conv_state = last_state['conv_state']
|
| 140 |
+
past_k = rearrange(past_k, '... (h d) -> ... h d', d=self.head_dim)
|
| 141 |
+
if self.use_w_shortconv:
|
| 142 |
+
w, w_conv_state = self.w_conv1d(w, cache=w_conv_state, output_final_state=use_cache, cu_seqlens=cu_seqlens)
|
| 143 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)
|
| 144 |
+
w = l2_norm(w)
|
| 145 |
+
|
| 146 |
+
@torch.compile
|
| 147 |
+
def rank_one_update(k, w, beta):
|
| 148 |
+
original_dtype = k.dtype
|
| 149 |
+
k = k.float()
|
| 150 |
+
w = w.float()
|
| 151 |
+
beta = beta.float()
|
| 152 |
+
k = k - beta[..., None].float() * (k * w).sum(-1, keepdim=True) * w
|
| 153 |
+
return k.to(original_dtype)
|
| 154 |
+
|
| 155 |
+
past_k = rank_one_update(past_k, w, beta)
|
| 156 |
+
past_k = rearrange(past_k, '... h d -> ... (h d)')
|
| 157 |
+
k = torch.cat([past_k, k], dim=1)
|
| 158 |
+
v = torch.cat([past_v, v], dim=1)
|
| 159 |
+
g = torch.cat([past_g, g], dim=1) if g is not None else None
|
| 160 |
+
past_key_values[self.layer_idx]['attn_state'] = (k, v, g) if g is not None else (k, v)
|
| 161 |
+
past_key_values.update(
|
| 162 |
+
conv_state=w_conv_state,
|
| 163 |
+
layer_idx=self.layer_idx,
|
| 164 |
+
offset=q_len
|
| 165 |
+
)
|
| 166 |
+
if g is not None:
|
| 167 |
+
q, (k, v, g), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 168 |
+
q, (k, v, g), attention_mask, q_len, keepdim=True)
|
| 169 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 170 |
+
else:
|
| 171 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 172 |
+
q, (k, v), attention_mask, q_len, keepdim=True)
|
| 173 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 174 |
+
_, cu_seqlens = cu_seqlens
|
| 175 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 176 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 177 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 178 |
+
assert max_seqlen_q == 1, "only support q_len == 1 for decoding"
|
| 179 |
+
o = attn_decoding_one_step(q, k, v, g, cu_seqlens=cu_seqlens, do_gate_scale=True) # reduced to fox's decoding
|
| 180 |
+
# Prefilling
|
| 181 |
+
else:
|
| 182 |
+
v_cache = v.clone()
|
| 183 |
+
g_cache = g.clone() if g is not None else None
|
| 184 |
+
if g is None:
|
| 185 |
+
q, (k, v, w, beta), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 186 |
+
q, (k, v, w, beta), attention_mask, q_len, keepdim=True)
|
| 187 |
+
else:
|
| 188 |
+
q, (k, v, w, beta, g), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 189 |
+
q, (k, v, w, beta, g), attention_mask, q_len, keepdim=True)
|
| 190 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 191 |
+
assert max_seqlen_q == max_seqlen_k, "max_seqlen_q should be equal to max_seqlen_k in prefilling"
|
| 192 |
+
_, cu_seqlens = cu_seqlens
|
| 193 |
+
if self.use_w_shortconv:
|
| 194 |
+
w, w_conv_state = self.w_conv1d(w, cache=None, output_final_state=use_cache, cu_seqlens=cu_seqlens)
|
| 195 |
+
else:
|
| 196 |
+
w_conv_state = None
|
| 197 |
+
q = rearrange(q, '... (h d) -> ... h d', d=self.head_dim)
|
| 198 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 199 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 200 |
+
w = rearrange(w, '... (h d) -> ... h d', d=self.head_dim)
|
| 201 |
+
w = l2_norm(w)
|
| 202 |
+
o, k_cache = parallel_path_attn(q=q, k=k, v=v, w=w, beta=beta, g=g,
|
| 203 |
+
cu_seqlens=cu_seqlens, use_cache=use_cache)
|
| 204 |
+
if use_cache:
|
| 205 |
+
k_cache = pad_input(k_cache.squeeze(0), indices_q, batch_size, q_len)
|
| 206 |
+
k_cache = rearrange(k_cache, '... h d -> ... (h d)')
|
| 207 |
+
past_key_values.update(
|
| 208 |
+
attn_state=(k_cache, v_cache, g_cache) if g_cache is not None else (k_cache, v_cache),
|
| 209 |
+
conv_state=w_conv_state,
|
| 210 |
+
layer_idx=self.layer_idx,
|
| 211 |
+
offset=q_len
|
| 212 |
+
)
|
| 213 |
+
o = pad_input(o.squeeze(0), indices_q, batch_size, q_len)
|
| 214 |
+
o = rearrange(o, '... h d -> ... (h d)')
|
| 215 |
+
o = self.o_proj(o)
|
| 216 |
+
return o, None, past_key_values
|
rodimus.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, Dict, Optional, Tuple, Union
|
| 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, repeat
|
| 14 |
+
from transformers.utils import logging
|
| 15 |
+
|
| 16 |
+
from fla.layers.utils import get_unpad_data, index_first_axis, pad_input, unpad_input
|
| 17 |
+
from fla.modules import RMSNorm, RotaryEmbedding, ShortConvolution
|
| 18 |
+
from fla.modules.layernorm_gated import RMSNormGated
|
| 19 |
+
from fla.ops.gla import chunk_gla, fused_chunk_gla, fused_recurrent_gla
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from transformers.processing_utils import Unpack
|
| 23 |
+
|
| 24 |
+
from fla.models.utils import Cache
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 28 |
+
except ImportError:
|
| 29 |
+
warnings.warn(
|
| 30 |
+
"Flash Attention is not installed. Please install it via `pip install flash-attn --no-build-isolation`",
|
| 31 |
+
category=ImportWarning
|
| 32 |
+
)
|
| 33 |
+
flash_attn_func = None
|
| 34 |
+
|
| 35 |
+
logger = logging.get_logger(__name__)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def align_multiple(value, multiple_size=8):
|
| 39 |
+
if value % multiple_size != 0:
|
| 40 |
+
value += multiple_size - (value % multiple_size)
|
| 41 |
+
return value
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def autocast_to_fp16(x):
|
| 45 |
+
if x.dtype not in {torch.float16, torch.bfloat16}:
|
| 46 |
+
return x.to(dtype=torch.bfloat16)
|
| 47 |
+
else:
|
| 48 |
+
return x
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class RodimusAttention(nn.Module):
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
block_type: str = 'rodimus',
|
| 55 |
+
mode: str = 'chunk',
|
| 56 |
+
hidden_size: int = 1024,
|
| 57 |
+
input_gate_low_rank: Optional[Union[float, str]] = 'auto',
|
| 58 |
+
expand_ratio: int = 64,
|
| 59 |
+
use_short_conv: bool = True,
|
| 60 |
+
conv_size: int = 4,
|
| 61 |
+
conv_bias: bool = True,
|
| 62 |
+
norm_eps: float = 1e-5,
|
| 63 |
+
k_norm_eps: Optional[float] = None,
|
| 64 |
+
residual_in_fp32: bool = True,
|
| 65 |
+
layer_idx: int = None
|
| 66 |
+
):
|
| 67 |
+
super().__init__()
|
| 68 |
+
|
| 69 |
+
self.block_type = block_type
|
| 70 |
+
self.mode = mode
|
| 71 |
+
self.hidden_size = hidden_size
|
| 72 |
+
self.d_inner = align_multiple(int(self.hidden_size * 2), 8)
|
| 73 |
+
|
| 74 |
+
self.expand_ratio = expand_ratio
|
| 75 |
+
self.input_gate_low_rank = max(self.hidden_size // 64, 16) if input_gate_low_rank == "auto" else input_gate_low_rank
|
| 76 |
+
|
| 77 |
+
self.use_short_conv = use_short_conv
|
| 78 |
+
self.conv_size = conv_size
|
| 79 |
+
self.conv_bias = conv_bias
|
| 80 |
+
|
| 81 |
+
self.norm_eps = norm_eps
|
| 82 |
+
self.k_norm_eps = k_norm_eps if k_norm_eps is not None else 1e-12
|
| 83 |
+
self.mem_size = expand_ratio
|
| 84 |
+
|
| 85 |
+
self.residual_in_fp32 = residual_in_fp32
|
| 86 |
+
self.layer_idx = layer_idx
|
| 87 |
+
|
| 88 |
+
assert mode in ['chunk', 'fused_recurrent', 'fused_chunk'], f"Not supported mode `{mode}`."
|
| 89 |
+
|
| 90 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.d_inner, bias=False)
|
| 91 |
+
self.up_proj = nn.Linear(self.hidden_size, self.d_inner, bias=False)
|
| 92 |
+
self.activation_norm = RMSNormGated(hidden_size=self.d_inner, eps=norm_eps, norm_before_gate=False)
|
| 93 |
+
self.down_proj = nn.Linear(self.d_inner, self.hidden_size, bias=False)
|
| 94 |
+
|
| 95 |
+
if use_short_conv:
|
| 96 |
+
self.short_conv = ShortConvolution(
|
| 97 |
+
hidden_size=self.d_inner,
|
| 98 |
+
kernel_size=conv_size,
|
| 99 |
+
bias=conv_bias,
|
| 100 |
+
activation='silu'
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
self.residual_weight = nn.Parameter(torch.ones(
|
| 104 |
+
(self.d_inner, ), dtype=torch.float32 if self.residual_in_fp32 else None), requires_grad=True)
|
| 105 |
+
|
| 106 |
+
self.k_proj = nn.Linear(self.d_inner, self.mem_size, bias=False)
|
| 107 |
+
self.q_proj = nn.Linear(self.d_inner, self.mem_size, bias=False)
|
| 108 |
+
|
| 109 |
+
self.g_gate_proj = nn.Linear(self.d_inner, self.mem_size, bias=True)
|
| 110 |
+
self.tau_gate_proj = nn.Linear(self.d_inner, self.mem_size, bias=True)
|
| 111 |
+
self.i_gate_proj = nn.Sequential(
|
| 112 |
+
nn.Linear(self.d_inner, self.input_gate_low_rank, bias=False),
|
| 113 |
+
nn.Linear(self.input_gate_low_rank, self.d_inner, bias=True),
|
| 114 |
+
nn.Sigmoid(),
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def forward(
|
| 118 |
+
self,
|
| 119 |
+
hidden_states: torch.Tensor,
|
| 120 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 121 |
+
past_key_values: Optional[Cache] = None,
|
| 122 |
+
use_cache: Optional[bool] = False,
|
| 123 |
+
output_attentions: Optional[bool] = False,
|
| 124 |
+
**kwargs: Unpack[Dict]
|
| 125 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 126 |
+
if attention_mask is not None:
|
| 127 |
+
assert len(attention_mask.shape) == 2, (
|
| 128 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 129 |
+
"for padding purposes (0 indicating padding). "
|
| 130 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 134 |
+
# mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 135 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] == 1 else self.mode
|
| 136 |
+
|
| 137 |
+
last_state = None
|
| 138 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 139 |
+
last_state = past_key_values[self.layer_idx]
|
| 140 |
+
|
| 141 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 142 |
+
if attention_mask is not None:
|
| 143 |
+
indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
|
| 144 |
+
hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
|
| 145 |
+
|
| 146 |
+
hidden_states, final_gate = self.up_proj(hidden_states), self.gate_proj(hidden_states)
|
| 147 |
+
|
| 148 |
+
if self.use_short_conv:
|
| 149 |
+
conv_state = None
|
| 150 |
+
if last_state is not None:
|
| 151 |
+
conv_state = last_state['conv_state']
|
| 152 |
+
shift_hidden_states, conv_state = self.short_conv(
|
| 153 |
+
x=hidden_states,
|
| 154 |
+
cache=conv_state,
|
| 155 |
+
output_final_state=use_cache,
|
| 156 |
+
cu_seqlens=cu_seqlens
|
| 157 |
+
)
|
| 158 |
+
else:
|
| 159 |
+
shift_hidden_states = hidden_states
|
| 160 |
+
|
| 161 |
+
q = self.q_proj(shift_hidden_states)
|
| 162 |
+
k = self.k_proj(shift_hidden_states)
|
| 163 |
+
v = self.i_gate_proj(hidden_states) * hidden_states
|
| 164 |
+
|
| 165 |
+
g_gate = F.linear(shift_hidden_states, self.g_gate_proj.weight) + self.g_gate_proj.bias.float()
|
| 166 |
+
tau_gate = F.linear(shift_hidden_states, self.tau_gate_proj.weight) + self.tau_gate_proj.bias.float()
|
| 167 |
+
|
| 168 |
+
g_gate = F.softplus(g_gate)
|
| 169 |
+
it_gate = g_gate
|
| 170 |
+
rt_gate_log = -g_gate
|
| 171 |
+
|
| 172 |
+
tau_gate = F.sigmoid(tau_gate)
|
| 173 |
+
it_gate = it_gate ** tau_gate
|
| 174 |
+
rt_gate_log = rt_gate_log * tau_gate
|
| 175 |
+
|
| 176 |
+
k = F.normalize(k.float(), dim=-1, eps=self.k_norm_eps) * it_gate
|
| 177 |
+
q, k, v, rt_gate_log = map(lambda x: x.unsqueeze(1).transpose(1, 2), (q, k, v, rt_gate_log))
|
| 178 |
+
|
| 179 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 180 |
+
if mode == 'fused_recurrent':
|
| 181 |
+
o, recurrent_state = fused_recurrent_gla(
|
| 182 |
+
q=q,
|
| 183 |
+
k=k,
|
| 184 |
+
v=v,
|
| 185 |
+
gk=rt_gate_log,
|
| 186 |
+
initial_state=recurrent_state,
|
| 187 |
+
output_final_state=use_cache,
|
| 188 |
+
cu_seqlens=cu_seqlens,
|
| 189 |
+
head_first=False,
|
| 190 |
+
)
|
| 191 |
+
elif mode == 'fused_chunk':
|
| 192 |
+
o, recurrent_state = fused_chunk_gla(
|
| 193 |
+
q=q,
|
| 194 |
+
k=k,
|
| 195 |
+
v=v,
|
| 196 |
+
g=rt_gate_log,
|
| 197 |
+
initial_state=recurrent_state,
|
| 198 |
+
output_final_state=use_cache,
|
| 199 |
+
head_first=False,
|
| 200 |
+
)
|
| 201 |
+
elif mode == 'chunk':
|
| 202 |
+
q, k, rt_gate_log = map(lambda x: x.to(v.dtype), (q, k, rt_gate_log))
|
| 203 |
+
o, recurrent_state = chunk_gla(
|
| 204 |
+
q=q,
|
| 205 |
+
k=k,
|
| 206 |
+
v=v,
|
| 207 |
+
g=rt_gate_log,
|
| 208 |
+
initial_state=recurrent_state,
|
| 209 |
+
output_final_state=use_cache,
|
| 210 |
+
cu_seqlens=cu_seqlens,
|
| 211 |
+
head_first=False,
|
| 212 |
+
)
|
| 213 |
+
else:
|
| 214 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 215 |
+
|
| 216 |
+
rodimus_caches = None
|
| 217 |
+
if past_key_values is not None:
|
| 218 |
+
if self.block_type == 'rodimus':
|
| 219 |
+
past_key_values.update(
|
| 220 |
+
recurrent_state=recurrent_state,
|
| 221 |
+
conv_state=conv_state if self.use_short_conv else None,
|
| 222 |
+
layer_idx=self.layer_idx,
|
| 223 |
+
offset=q_len
|
| 224 |
+
)
|
| 225 |
+
else:
|
| 226 |
+
rodimus_caches = (recurrent_state, conv_state if self.use_short_conv else None)
|
| 227 |
+
|
| 228 |
+
o = (o.transpose(1, 2).squeeze(1) + (shift_hidden_states.float()
|
| 229 |
+
if self.residual_in_fp32 else shift_hidden_states) * self.residual_weight).to(o.dtype)
|
| 230 |
+
|
| 231 |
+
o = self.activation_norm(o, final_gate)
|
| 232 |
+
o = self.down_proj(o)
|
| 233 |
+
|
| 234 |
+
if attention_mask is not None:
|
| 235 |
+
o = pad_input(o.squeeze(0), indices, batch_size, q_len)
|
| 236 |
+
|
| 237 |
+
if self.block_type == 'rodimus':
|
| 238 |
+
return o, None, past_key_values
|
| 239 |
+
else:
|
| 240 |
+
return o, None, (past_key_values, rodimus_caches)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class SlidingWindowSharedKeyAttention(nn.Module):
|
| 244 |
+
def __init__(
|
| 245 |
+
self,
|
| 246 |
+
hidden_size: int = 2048,
|
| 247 |
+
num_heads: int = 32,
|
| 248 |
+
qkv_bias: bool = False,
|
| 249 |
+
qk_norm: bool = False,
|
| 250 |
+
window_size: int = 2048,
|
| 251 |
+
rope_theta: Optional[float] = 10000.,
|
| 252 |
+
max_position_embeddings: Optional[int] = None,
|
| 253 |
+
layer_idx: int = None
|
| 254 |
+
):
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
self.hidden_size = hidden_size
|
| 258 |
+
self.num_heads = num_heads
|
| 259 |
+
self.head_dim = self.hidden_size // self.num_heads
|
| 260 |
+
self.qkv_bias = qkv_bias
|
| 261 |
+
self.qk_norm = qk_norm
|
| 262 |
+
|
| 263 |
+
self.window_size = window_size
|
| 264 |
+
self.rope_theta = rope_theta
|
| 265 |
+
self.max_position_embeddings = max_position_embeddings
|
| 266 |
+
self.layer_idx = layer_idx
|
| 267 |
+
|
| 268 |
+
self.q_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
|
| 269 |
+
self.k_proj = nn.Linear(self.hidden_size, self.head_dim, bias=self.qkv_bias)
|
| 270 |
+
self.v_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=self.qkv_bias)
|
| 271 |
+
self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=False)
|
| 272 |
+
|
| 273 |
+
if qk_norm:
|
| 274 |
+
self.q_norm = RMSNorm(self.head_dim)
|
| 275 |
+
self.k_norm = RMSNorm(self.head_dim)
|
| 276 |
+
|
| 277 |
+
self.rotary = RotaryEmbedding(dim=self.head_dim, base=self.rope_theta)
|
| 278 |
+
|
| 279 |
+
def forward(
|
| 280 |
+
self,
|
| 281 |
+
hidden_states: torch.Tensor,
|
| 282 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 283 |
+
past_key_values: Optional[Cache] = None,
|
| 284 |
+
output_attentions: bool = False,
|
| 285 |
+
use_cache: bool = False,
|
| 286 |
+
**kwargs,
|
| 287 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 288 |
+
rodimus_caches = kwargs.get('rodimus_caches', None)
|
| 289 |
+
|
| 290 |
+
if attention_mask is not None:
|
| 291 |
+
assert len(attention_mask.shape) == 2, (
|
| 292 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 293 |
+
"for padding purposes (0 indicating padding). "
|
| 294 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
batch_size, q_len, _ = hidden_states.size()
|
| 298 |
+
|
| 299 |
+
q = rearrange(self.q_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 300 |
+
k = rearrange(self.k_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 301 |
+
v = rearrange(self.v_proj(hidden_states), '... (h d) -> ... h d', d=self.head_dim)
|
| 302 |
+
|
| 303 |
+
if self.qk_norm:
|
| 304 |
+
q, k = self.q_norm(q), self.k_norm(k)
|
| 305 |
+
|
| 306 |
+
# equivalent to cu_seqlens in `flash_attn`
|
| 307 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 308 |
+
|
| 309 |
+
seqlen_offset, max_seqlen = 0, q.shape[1]
|
| 310 |
+
if past_key_values is not None:
|
| 311 |
+
seqlen_offset = past_key_values.get_seq_length(self.layer_idx)
|
| 312 |
+
max_seqlen = q.shape[1] + seqlen_offset
|
| 313 |
+
|
| 314 |
+
if attention_mask is not None:
|
| 315 |
+
# to deliminate the offsets of padding tokens
|
| 316 |
+
seqlen_offset = seqlen_offset + attention_mask.sum(-1) - attention_mask.shape[-1]
|
| 317 |
+
max_seqlen = q.shape[1] + max(seqlen_offset)
|
| 318 |
+
|
| 319 |
+
if self.max_position_embeddings is not None:
|
| 320 |
+
max_seqlen = max(max_seqlen, self.max_position_embeddings)
|
| 321 |
+
q, k = self.rotary(q, k, seqlen_offset=seqlen_offset, max_seqlen=max_seqlen, cu_seqlens=cu_seqlens)
|
| 322 |
+
|
| 323 |
+
if past_key_values is not None:
|
| 324 |
+
if rodimus_caches is not None:
|
| 325 |
+
recurrent_state, conv_state = rodimus_caches
|
| 326 |
+
else:
|
| 327 |
+
recurrent_state, conv_state = None, None
|
| 328 |
+
|
| 329 |
+
cache_has_content = past_key_values.get_seq_length(self.layer_idx) > 0
|
| 330 |
+
k_cached, v_cached = past_key_values.update(
|
| 331 |
+
recurrent_state=recurrent_state,
|
| 332 |
+
conv_state=conv_state,
|
| 333 |
+
attn_state=[k.flatten(-2, -1), v.flatten(-2, -1)],
|
| 334 |
+
layer_idx=self.layer_idx,
|
| 335 |
+
offset=q_len,
|
| 336 |
+
cache_kwargs=dict(window_size=self.window_size)
|
| 337 |
+
)['attn_state']
|
| 338 |
+
if cache_has_content:
|
| 339 |
+
k, v = k_cached, v_cached
|
| 340 |
+
k = rearrange(k, '... (h d) -> ... h d', d=self.head_dim)
|
| 341 |
+
v = rearrange(v, '... (h d) -> ... h d', d=self.head_dim)
|
| 342 |
+
|
| 343 |
+
if flash_attn_func is None:
|
| 344 |
+
raise ImportError("Please install Flash Attention via `pip install flash-attn --no-build-isolation` first")
|
| 345 |
+
|
| 346 |
+
q, k, v = map(autocast_to_fp16, (q, k, v))
|
| 347 |
+
k = repeat(k, "... h d -> ... (n h) d", n=self.num_heads)
|
| 348 |
+
# Contains at least one padding token in the sequence
|
| 349 |
+
if attention_mask is not None:
|
| 350 |
+
q, (k, v), indices_q, cu_seqlens, max_seq_lens = unpad_input(
|
| 351 |
+
q=q,
|
| 352 |
+
states=(k, v),
|
| 353 |
+
attention_mask=attention_mask[:, -max(self.window_size, q_len):],
|
| 354 |
+
q_len=q_len
|
| 355 |
+
)
|
| 356 |
+
cu_seqlens_q, cu_seqlens_k = cu_seqlens
|
| 357 |
+
max_seqlen_q, max_seqlen_k = max_seq_lens
|
| 358 |
+
o = flash_attn_varlen_func(
|
| 359 |
+
q, k, v,
|
| 360 |
+
cu_seqlens_q=cu_seqlens_q,
|
| 361 |
+
cu_seqlens_k=cu_seqlens_k,
|
| 362 |
+
max_seqlen_q=max_seqlen_q,
|
| 363 |
+
max_seqlen_k=max_seqlen_k,
|
| 364 |
+
causal=True,
|
| 365 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 366 |
+
)
|
| 367 |
+
o = pad_input(o, indices_q, batch_size, q_len)
|
| 368 |
+
elif cu_seqlens is not None:
|
| 369 |
+
o = flash_attn_varlen_func(
|
| 370 |
+
q.squeeze(0), k.squeeze(0), v.squeeze(0),
|
| 371 |
+
cu_seqlens_q=cu_seqlens,
|
| 372 |
+
cu_seqlens_k=cu_seqlens,
|
| 373 |
+
max_seqlen_q=max_seqlen,
|
| 374 |
+
max_seqlen_k=max_seqlen,
|
| 375 |
+
causal=True,
|
| 376 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 377 |
+
).unsqueeze(0)
|
| 378 |
+
else:
|
| 379 |
+
o = flash_attn_func(
|
| 380 |
+
q, k, v,
|
| 381 |
+
causal=True,
|
| 382 |
+
window_size=(-1, -1) if self.window_size is None else (self.window_size-1, 0)
|
| 383 |
+
)
|
| 384 |
+
o = o.reshape(batch_size, q_len, -1)
|
| 385 |
+
o = self.o_proj(o.to(dtype=self.o_proj.weight.dtype))
|
| 386 |
+
|
| 387 |
+
if not output_attentions:
|
| 388 |
+
attentions = None
|
| 389 |
+
|
| 390 |
+
return o, attentions, past_key_values
|
rwkv6.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# "Eagle and Finch: RWKV with Matrix-Valued States and Dynamic Recurrence"[https://arxiv.org/abs/2404.05892]
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import math
|
| 9 |
+
import warnings
|
| 10 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from einops import rearrange
|
| 15 |
+
|
| 16 |
+
from fla.modules import GroupNorm
|
| 17 |
+
from fla.modules.activations import ACT2FN
|
| 18 |
+
from fla.modules.token_shift import token_shift
|
| 19 |
+
from fla.ops.rwkv6 import chunk_rwkv6, fused_recurrent_rwkv6
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from fla.models.utils import Cache
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class RWKV6Attention(nn.Module):
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
mode: str = 'chunk',
|
| 30 |
+
hidden_size: int = 1024,
|
| 31 |
+
expand_k: float = 0.5,
|
| 32 |
+
expand_v: float = 1.0,
|
| 33 |
+
num_heads: int = 4,
|
| 34 |
+
gate_fn: str = 'swish',
|
| 35 |
+
proj_low_rank_dim: int = 32,
|
| 36 |
+
gate_low_rank_dim: int = 64,
|
| 37 |
+
fuse_norm: bool = True,
|
| 38 |
+
elementwise_affine: Optional[bool] = True,
|
| 39 |
+
norm_eps: float = 1e-5,
|
| 40 |
+
layer_idx: int = None,
|
| 41 |
+
**kwargs
|
| 42 |
+
) -> RWKV6Attention:
|
| 43 |
+
super().__init__()
|
| 44 |
+
|
| 45 |
+
self.mode = mode
|
| 46 |
+
self.hidden_size = hidden_size
|
| 47 |
+
self.expand_k = expand_k
|
| 48 |
+
self.expand_v = expand_v
|
| 49 |
+
self.num_heads = num_heads
|
| 50 |
+
self.proj_low_rank_dim = proj_low_rank_dim
|
| 51 |
+
self.gate_low_rank_dim = gate_low_rank_dim
|
| 52 |
+
|
| 53 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 54 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 55 |
+
self.layer_idx = layer_idx
|
| 56 |
+
|
| 57 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 58 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 59 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 60 |
+
|
| 61 |
+
self.head_k_dim = self.key_dim // num_heads
|
| 62 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 63 |
+
|
| 64 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
| 65 |
+
self.x_proj = nn.Sequential(
|
| 66 |
+
LerpLinear(hidden_size, proj_low_rank_dim * 5),
|
| 67 |
+
nn.Tanh(),
|
| 68 |
+
nn.Linear(proj_low_rank_dim * 5, hidden_size, bias=False)
|
| 69 |
+
)
|
| 70 |
+
self.x_bias = nn.Parameter(torch.zeros(5, hidden_size))
|
| 71 |
+
|
| 72 |
+
self.r_proj = DDLerpLinear(hidden_size, self.key_dim)
|
| 73 |
+
self.w_proj = DDLerpLinear(hidden_size, self.key_dim, low_rank_dim=gate_low_rank_dim)
|
| 74 |
+
self.k_proj = DDLerpLinear(hidden_size, self.key_dim)
|
| 75 |
+
self.v_proj = DDLerpLinear(hidden_size, self.value_dim)
|
| 76 |
+
self.g_proj = DDLerpLinear(hidden_size, self.value_dim)
|
| 77 |
+
self.bonus = nn.Parameter(torch.zeros(num_heads, self.head_k_dim))
|
| 78 |
+
|
| 79 |
+
# TODO: fuse GroupNorm and output gate
|
| 80 |
+
self.g_norm = GroupNorm(self.num_heads, self.value_dim, elementwise_affine=elementwise_affine, bias=True, eps=norm_eps)
|
| 81 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 82 |
+
self.gate_fn = ACT2FN[gate_fn]
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
from transformers.modeling_utils import _init_weights
|
| 86 |
+
except ImportError:
|
| 87 |
+
_init_weights = True
|
| 88 |
+
if _init_weights:
|
| 89 |
+
self.apply(self._initialize_weights)
|
| 90 |
+
|
| 91 |
+
warnings.warn(
|
| 92 |
+
"According to Bo, you are using a potentially buggy FLA implementation of RWKV. "
|
| 93 |
+
"If you plan to report any numbers based on this implementation, we strongly recommend "
|
| 94 |
+
"cross-checking with the official repo: https://github.com/BlinkDL/RWKV-LM. "
|
| 95 |
+
"Bo may disagree with results reported from this version."
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def _initialize_weights(self, module: nn.Module):
|
| 99 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 100 |
+
return
|
| 101 |
+
if isinstance(module, nn.Linear):
|
| 102 |
+
nn.init.xavier_uniform_(module.weight, gain=2 ** -2.5)
|
| 103 |
+
if module.bias is not None:
|
| 104 |
+
nn.init.zeros_(module.bias)
|
| 105 |
+
if isinstance(module, nn.Parameter):
|
| 106 |
+
nn.init.xavier_uniform_(module, gain=2 ** -2.5)
|
| 107 |
+
module._is_hf_initialized = True
|
| 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 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 117 |
+
**kwargs
|
| 118 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 119 |
+
if attention_mask is not None:
|
| 120 |
+
assert len(attention_mask.shape) == 2, (
|
| 121 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 122 |
+
"for padding purposes (0 indicating padding). "
|
| 123 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
batch_size, seq_len, hidden_size = hidden_states.shape
|
| 127 |
+
# launching the triton kernel for just one token will actually be slower
|
| 128 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 129 |
+
|
| 130 |
+
last_state = None
|
| 131 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 132 |
+
last_state = past_key_values[self.layer_idx]
|
| 133 |
+
|
| 134 |
+
if attention_mask is not None:
|
| 135 |
+
hidden_states = hidden_states.mul_(attention_mask[:, -hidden_states.shape[-2]:, None])
|
| 136 |
+
|
| 137 |
+
if hidden_states.shape[1] == 1 and last_state is not None:
|
| 138 |
+
shifted = last_state['conv_state'].unsqueeze(1)
|
| 139 |
+
delta = shifted - hidden_states
|
| 140 |
+
elif last_state is None:
|
| 141 |
+
delta = token_shift(hidden_states, cu_seqlens)
|
| 142 |
+
else:
|
| 143 |
+
shifted = self.time_shift(hidden_states)
|
| 144 |
+
shifted[:, 0] = last_state['conv_state']
|
| 145 |
+
delta = shifted - hidden_states
|
| 146 |
+
|
| 147 |
+
x = self.x_proj[0](hidden_states, delta, cu_seqlens).view(batch_size, seq_len, -1, self.proj_low_rank_dim)
|
| 148 |
+
x = torch.einsum('b t n r, h n r-> b t n h', self.x_proj[1](x), self.x_proj[2].weight.view(hidden_size, 5, -1))
|
| 149 |
+
|
| 150 |
+
r, w, k, v, g = x.add_(self.x_bias).unbind(-2)
|
| 151 |
+
r = self.r_proj(hidden_states, r, delta, cu_seqlens)
|
| 152 |
+
w = self.w_proj(hidden_states, w, delta, cu_seqlens)
|
| 153 |
+
k = self.k_proj(hidden_states, k, delta, cu_seqlens)
|
| 154 |
+
v = self.v_proj(hidden_states, v, delta, cu_seqlens)
|
| 155 |
+
g = self.g_proj(hidden_states, g, delta, cu_seqlens)
|
| 156 |
+
|
| 157 |
+
# dealing with left-padding
|
| 158 |
+
if attention_mask is not None:
|
| 159 |
+
v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
|
| 160 |
+
r, w, k = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', d=self.head_k_dim), (r, w, k))
|
| 161 |
+
v = rearrange(v, 'b t (h d) -> b t h d', d=self.head_v_dim)
|
| 162 |
+
w = -torch.exp(w)
|
| 163 |
+
u = self.bonus
|
| 164 |
+
|
| 165 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 166 |
+
|
| 167 |
+
if mode == 'fused_recurrent':
|
| 168 |
+
o, recurrent_state = fused_recurrent_rwkv6(
|
| 169 |
+
r=r,
|
| 170 |
+
k=k,
|
| 171 |
+
v=v,
|
| 172 |
+
w=w,
|
| 173 |
+
u=u,
|
| 174 |
+
scale=1.,
|
| 175 |
+
initial_state=recurrent_state,
|
| 176 |
+
output_final_state=use_cache,
|
| 177 |
+
cu_seqlens=cu_seqlens,
|
| 178 |
+
)
|
| 179 |
+
elif mode == 'chunk':
|
| 180 |
+
o, recurrent_state = chunk_rwkv6(
|
| 181 |
+
r=r,
|
| 182 |
+
k=k,
|
| 183 |
+
v=v,
|
| 184 |
+
w=w,
|
| 185 |
+
u=u,
|
| 186 |
+
scale=1.,
|
| 187 |
+
initial_state=recurrent_state,
|
| 188 |
+
output_final_state=use_cache,
|
| 189 |
+
cu_seqlens=cu_seqlens,
|
| 190 |
+
)
|
| 191 |
+
else:
|
| 192 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 193 |
+
|
| 194 |
+
if past_key_values is not None:
|
| 195 |
+
past_key_values.update(
|
| 196 |
+
recurrent_state=recurrent_state,
|
| 197 |
+
conv_state=hidden_states[:, -1],
|
| 198 |
+
layer_idx=self.layer_idx,
|
| 199 |
+
offset=r.shape[2]
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
o = self.g_norm(rearrange(o, '... h d -> ... (h d)')) * self.gate_fn(g)
|
| 203 |
+
o = self.o_proj(o)
|
| 204 |
+
|
| 205 |
+
return o, None, past_key_values
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class LoRA(nn.Module):
|
| 209 |
+
|
| 210 |
+
def __init__(
|
| 211 |
+
self,
|
| 212 |
+
input_dim: int,
|
| 213 |
+
output_dim: int,
|
| 214 |
+
low_rank_dim: int,
|
| 215 |
+
bias: Optional[bool] = True,
|
| 216 |
+
activation: Optional[str] = 'tanh'
|
| 217 |
+
):
|
| 218 |
+
super().__init__()
|
| 219 |
+
|
| 220 |
+
self.input_dim = input_dim
|
| 221 |
+
self.output_dim = output_dim
|
| 222 |
+
self.low_rank_dim = low_rank_dim
|
| 223 |
+
self.bias = bias
|
| 224 |
+
|
| 225 |
+
if activation is None:
|
| 226 |
+
self.activation = nn.Identity()
|
| 227 |
+
elif activation == 'sigmoid':
|
| 228 |
+
self.activation = nn.Sigmoid()
|
| 229 |
+
elif activation == 'tanh':
|
| 230 |
+
self.activation = nn.Tanh()
|
| 231 |
+
elif activation == 'relu':
|
| 232 |
+
self.activation = nn.ReLU()
|
| 233 |
+
else:
|
| 234 |
+
raise ValueError(f"Not supported activation `{activation}`.")
|
| 235 |
+
|
| 236 |
+
self.lora = nn.Sequential(
|
| 237 |
+
nn.Linear(input_dim, low_rank_dim, bias=False),
|
| 238 |
+
self.activation,
|
| 239 |
+
nn.Linear(low_rank_dim, output_dim, bias=bias)
|
| 240 |
+
)
|
| 241 |
+
try:
|
| 242 |
+
from transformers.modeling_utils import _init_weights
|
| 243 |
+
except ImportError:
|
| 244 |
+
_init_weights = True
|
| 245 |
+
if _init_weights:
|
| 246 |
+
self.apply(self._initialize_weights)
|
| 247 |
+
|
| 248 |
+
def __repr__(self) -> str:
|
| 249 |
+
s = f"{self.__class__.__name__}("
|
| 250 |
+
s += f"input_dim={self.input_dim}, low_rank_dim={self.low_rank_dim}, output_dim={self.output_dim}"
|
| 251 |
+
if not self.bias:
|
| 252 |
+
s += f", bias={self.bias}"
|
| 253 |
+
s += ")"
|
| 254 |
+
return s
|
| 255 |
+
|
| 256 |
+
def _initialize_weights(self, module: nn.Module):
|
| 257 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 258 |
+
return
|
| 259 |
+
|
| 260 |
+
# Initialize weights to zero as in original code
|
| 261 |
+
nn.init.zeros_(self.lora[0].weight)
|
| 262 |
+
original_dtype = self.lora[2].weight.dtype
|
| 263 |
+
shape = self.lora[2].weight.shape
|
| 264 |
+
# Convert to float32 for numerical stability in orthogonal init
|
| 265 |
+
weight_fp32 = self.lora[2].weight.float()
|
| 266 |
+
|
| 267 |
+
# Calculate gain based on dimensions
|
| 268 |
+
gain = math.sqrt(shape[1] / shape[0]) if shape[1] > shape[0] else 1
|
| 269 |
+
|
| 270 |
+
# Apply orthogonal initialization with scaling factor 0.1
|
| 271 |
+
nn.init.orthogonal_(weight_fp32, gain=gain * 0.1)
|
| 272 |
+
|
| 273 |
+
# Convert back to original dtype
|
| 274 |
+
self.lora[2].weight.data.copy_(weight_fp32.to(original_dtype))
|
| 275 |
+
# Set Lora[2] bias to zero
|
| 276 |
+
if self.lora[2].bias is not None:
|
| 277 |
+
nn.init.zeros_(self.lora[2].bias)
|
| 278 |
+
|
| 279 |
+
module._is_hf_initialized = True
|
| 280 |
+
|
| 281 |
+
def set_bias_value(self, value):
|
| 282 |
+
"""Set bias to a specific value (for v0, w0 etc.)"""
|
| 283 |
+
if self.bias and self.lora[2].bias is not None:
|
| 284 |
+
if isinstance(value, torch.Tensor):
|
| 285 |
+
# Handle tensor values
|
| 286 |
+
self.lora[2].bias.data.copy_(value.to(self.lora[2].bias.dtype))
|
| 287 |
+
else:
|
| 288 |
+
# Handle scalar values
|
| 289 |
+
nn.init.constant_(self.lora[2].bias, value)
|
| 290 |
+
|
| 291 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 292 |
+
return self.lora(x)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class LerpLinear(nn.Module):
|
| 296 |
+
|
| 297 |
+
def __init__(
|
| 298 |
+
self,
|
| 299 |
+
input_dim: int,
|
| 300 |
+
output_dim: int,
|
| 301 |
+
low_rank_dim: Optional[int] = None
|
| 302 |
+
):
|
| 303 |
+
super().__init__()
|
| 304 |
+
|
| 305 |
+
self.input_dim = input_dim
|
| 306 |
+
self.output_dim = output_dim
|
| 307 |
+
self.low_rank_dim = low_rank_dim
|
| 308 |
+
|
| 309 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
| 310 |
+
if low_rank_dim is None:
|
| 311 |
+
self.linear = nn.Linear(input_dim, output_dim, bias=False)
|
| 312 |
+
else:
|
| 313 |
+
self.linear = LoRA(input_dim, output_dim, low_rank_dim)
|
| 314 |
+
self.mu = nn.Parameter(torch.zeros(input_dim))
|
| 315 |
+
|
| 316 |
+
def __repr__(self) -> str:
|
| 317 |
+
s = f"{self.__class__.__name__}({self.input_dim}, {self.output_dim}"
|
| 318 |
+
if self.low_rank_dim is not None:
|
| 319 |
+
s += f", low_rank_dim={self.low_rank_dim}"
|
| 320 |
+
s += ")"
|
| 321 |
+
return s
|
| 322 |
+
|
| 323 |
+
def forward(self, x: torch.Tensor, delta: Optional[torch.Tensor] = None,
|
| 324 |
+
cu_seqlens: Optional[torch.LongTensor] = None) -> torch.Tensor:
|
| 325 |
+
if delta is None:
|
| 326 |
+
delta = token_shift(x, cu_seqlens)
|
| 327 |
+
return self.linear(x + delta * self.mu)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class DDLerpLinear(nn.Module):
|
| 331 |
+
|
| 332 |
+
def __init__(
|
| 333 |
+
self,
|
| 334 |
+
input_dim: int,
|
| 335 |
+
output_dim: int,
|
| 336 |
+
low_rank_dim: Optional[int] = None
|
| 337 |
+
):
|
| 338 |
+
super().__init__()
|
| 339 |
+
|
| 340 |
+
self.input_dim = input_dim
|
| 341 |
+
self.output_dim = output_dim
|
| 342 |
+
self.low_rank_dim = low_rank_dim
|
| 343 |
+
|
| 344 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
| 345 |
+
if low_rank_dim is None:
|
| 346 |
+
self.linear = nn.Linear(input_dim, output_dim, bias=False)
|
| 347 |
+
else:
|
| 348 |
+
self.linear = LoRA(input_dim, output_dim, low_rank_dim)
|
| 349 |
+
|
| 350 |
+
def __repr__(self) -> str:
|
| 351 |
+
s = f"{self.__class__.__name__}({self.input_dim}, {self.output_dim}"
|
| 352 |
+
if self.low_rank_dim is not None:
|
| 353 |
+
s += f", low_rank_dim={self.low_rank_dim}"
|
| 354 |
+
s += ")"
|
| 355 |
+
return s
|
| 356 |
+
|
| 357 |
+
def forward(self, x: torch.Tensor, mu: torch.Tensor,
|
| 358 |
+
delta: Optional[torch.Tensor] = None,
|
| 359 |
+
cu_seqlens: Optional[torch.LongTensor] = None) -> torch.Tensor:
|
| 360 |
+
if delta is None:
|
| 361 |
+
delta = token_shift(x, cu_seqlens)
|
| 362 |
+
return self.linear(x + delta * mu)
|
rwkv7.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from torch.nn import functional as F
|
| 13 |
+
|
| 14 |
+
from fla.layers.rwkv6 import LoRA
|
| 15 |
+
from fla.modules import GroupNorm
|
| 16 |
+
from fla.modules.l2norm import l2_norm
|
| 17 |
+
from fla.modules.token_shift import token_shift
|
| 18 |
+
from fla.ops.rwkv7 import chunk_rwkv7, fused_mul_recurrent_rwkv7
|
| 19 |
+
from fla.ops.rwkv7.fused_addcmul import fused_addcmul_rwkv7
|
| 20 |
+
from fla.ops.rwkv7.fused_k_update import fused_k_rwkv7
|
| 21 |
+
from fla.ops.rwkv7.gate_output_correction import gate_output_correction
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from fla.models.utils import Cache
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class RWKV7Attention(nn.Module):
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
mode: str = 'chunk',
|
| 32 |
+
hidden_size: int = 1024,
|
| 33 |
+
head_dim: Optional[int] = 64,
|
| 34 |
+
num_heads: Optional[int] = None,
|
| 35 |
+
decay_low_rank_dim: Optional[int] = None,
|
| 36 |
+
gate_low_rank_dim: Optional[int] = None,
|
| 37 |
+
a_low_rank_dim: Optional[int] = None,
|
| 38 |
+
v_low_rank_dim: Optional[int] = None,
|
| 39 |
+
elementwise_affine: Optional[bool] = True,
|
| 40 |
+
norm_eps: float = 1e-5,
|
| 41 |
+
layer_idx: int = None,
|
| 42 |
+
fuse_norm: bool = False,
|
| 43 |
+
value_dim: int = None,
|
| 44 |
+
num_hidden_layers: int = None,
|
| 45 |
+
**kwargs
|
| 46 |
+
) -> RWKV7Attention:
|
| 47 |
+
super().__init__()
|
| 48 |
+
|
| 49 |
+
self.mode = mode
|
| 50 |
+
assert mode in ['chunk', 'fused_recurrent'], f"Not supported mode `{mode}`."
|
| 51 |
+
self.hidden_size = hidden_size
|
| 52 |
+
|
| 53 |
+
self.key_dim = hidden_size
|
| 54 |
+
self.value_dim = value_dim if value_dim is not None else hidden_size
|
| 55 |
+
if head_dim is None and num_heads is None:
|
| 56 |
+
raise ValueError("Either `head_dim` or `num_heads` must be specified.")
|
| 57 |
+
elif head_dim is not None:
|
| 58 |
+
self.head_dim = head_dim
|
| 59 |
+
self.num_heads = int(hidden_size // head_dim)
|
| 60 |
+
elif num_heads is not None:
|
| 61 |
+
self.head_dim = int(hidden_size // num_heads)
|
| 62 |
+
self.num_heads = num_heads
|
| 63 |
+
self.head_v_dim = int(self.value_dim // self.num_heads)
|
| 64 |
+
|
| 65 |
+
# Increase lora dimension for headdim>64
|
| 66 |
+
factor = self.head_dim / 64
|
| 67 |
+
if decay_low_rank_dim is None:
|
| 68 |
+
decay_low_rank_dim = max(32, int(round((2.5 * (hidden_size**0.5)) * factor / 32) * 32))
|
| 69 |
+
self.decay_low_rank_dim = decay_low_rank_dim
|
| 70 |
+
else:
|
| 71 |
+
self.decay_low_rank_dim = decay_low_rank_dim
|
| 72 |
+
|
| 73 |
+
if gate_low_rank_dim is None:
|
| 74 |
+
gate_low_rank_dim = max(32, int(round((5 * (hidden_size**0.5)) / 32) * 32))
|
| 75 |
+
self.gate_low_rank_dim = gate_low_rank_dim
|
| 76 |
+
else:
|
| 77 |
+
self.gate_low_rank_dim = gate_low_rank_dim
|
| 78 |
+
|
| 79 |
+
if a_low_rank_dim is None:
|
| 80 |
+
a_low_rank_dim = max(32, int(round((2.5 * (hidden_size**0.5)) * factor / 32) * 32))
|
| 81 |
+
self.a_low_rank_dim = a_low_rank_dim
|
| 82 |
+
else:
|
| 83 |
+
self.a_low_rank_dim = a_low_rank_dim
|
| 84 |
+
|
| 85 |
+
if v_low_rank_dim is None:
|
| 86 |
+
v_low_rank_dim = max(32, int(round((1.7 * (hidden_size**0.5)) * factor / 32) * 32))
|
| 87 |
+
self.v_low_rank_dim = v_low_rank_dim
|
| 88 |
+
else:
|
| 89 |
+
self.v_low_rank_dim = v_low_rank_dim
|
| 90 |
+
|
| 91 |
+
self.layer_idx = layer_idx
|
| 92 |
+
self.num_hidden_layers = num_hidden_layers
|
| 93 |
+
self.fuse_norm = fuse_norm
|
| 94 |
+
|
| 95 |
+
self.time_shift = nn.ZeroPad2d((0, 0, 1, -1))
|
| 96 |
+
self.x_r = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 97 |
+
self.x_w = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 98 |
+
self.x_k = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 99 |
+
self.x_v = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 100 |
+
self.x_a = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 101 |
+
self.x_g = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 102 |
+
|
| 103 |
+
self.k_k = nn.Parameter(torch.zeros(self.key_dim))
|
| 104 |
+
self.k_a = nn.Parameter(torch.zeros(self.key_dim))
|
| 105 |
+
self.r_k = nn.Parameter(torch.zeros(self.num_heads, self.head_dim))
|
| 106 |
+
|
| 107 |
+
self.r_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 108 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 109 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 110 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 111 |
+
|
| 112 |
+
self.w_lora = LoRA(hidden_size, self.key_dim, low_rank_dim=decay_low_rank_dim, activation='tanh')
|
| 113 |
+
if self.layer_idx != 0:
|
| 114 |
+
self.v_lora = LoRA(hidden_size, self.value_dim, low_rank_dim=v_low_rank_dim, activation=None)
|
| 115 |
+
self.a_lora = LoRA(hidden_size, self.key_dim, low_rank_dim=a_low_rank_dim, activation=None)
|
| 116 |
+
self.g_lora = LoRA(hidden_size, self.value_dim, low_rank_dim=gate_low_rank_dim, activation='sigmoid', bias=False)
|
| 117 |
+
|
| 118 |
+
if self.fuse_norm:
|
| 119 |
+
self.g_norm = GroupNorm(
|
| 120 |
+
num_groups=self.num_heads,
|
| 121 |
+
hidden_size=self.value_dim,
|
| 122 |
+
elementwise_affine=elementwise_affine,
|
| 123 |
+
eps=self.head_dim*norm_eps,
|
| 124 |
+
bias=True,
|
| 125 |
+
)
|
| 126 |
+
else:
|
| 127 |
+
self.g_norm = nn.GroupNorm(
|
| 128 |
+
num_groups=self.num_heads,
|
| 129 |
+
num_channels=self.value_dim,
|
| 130 |
+
eps=self.head_dim*norm_eps,
|
| 131 |
+
affine=elementwise_affine
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
from transformers.modeling_utils import _init_weights
|
| 136 |
+
except ImportError:
|
| 137 |
+
_init_weights = True
|
| 138 |
+
if _init_weights:
|
| 139 |
+
self.apply(self._initialize_weights)
|
| 140 |
+
for name, module in self.named_modules():
|
| 141 |
+
module._in_rwkv_module = True
|
| 142 |
+
|
| 143 |
+
warnings.warn(
|
| 144 |
+
"According to Bo, you are using a potentially buggy FLA implementation of RWKV. "
|
| 145 |
+
"If you plan to report any numbers based on this implementation, we strongly recommend "
|
| 146 |
+
"cross-checking with the official repo: https://github.com/BlinkDL/RWKV-LM. "
|
| 147 |
+
"Bo may disagree with results reported from this version."
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
@torch.no_grad()
|
| 151 |
+
@torch.compiler.disable
|
| 152 |
+
def _initialize_weights(self, module: nn.Module):
|
| 153 |
+
if getattr(module, "_is_hf_initialized", False):
|
| 154 |
+
return
|
| 155 |
+
|
| 156 |
+
# Initialize only when we're processing the RWKV7Attention module itself
|
| 157 |
+
if isinstance(module, RWKV7Attention) and self.layer_idx is not None:
|
| 158 |
+
ratio_0_to_1 = self.layer_idx / (self.num_hidden_layers - 1) # 0 to 1
|
| 159 |
+
ratio_1_to_almost0 = 1.0 - (self.layer_idx / self.num_hidden_layers) # 1 to ~0
|
| 160 |
+
|
| 161 |
+
# Create position-based initialization tensor
|
| 162 |
+
ddd = torch.ones(1, 1, self.hidden_size, device=self.x_r.device)
|
| 163 |
+
www = torch.zeros(self.hidden_size, device=self.x_r.device)
|
| 164 |
+
zigzag = torch.zeros(self.hidden_size, device=self.x_r.device)
|
| 165 |
+
linear = torch.zeros(self.hidden_size, device=self.x_r.device)
|
| 166 |
+
for n in range(self.hidden_size):
|
| 167 |
+
linear[n] = n / (self.hidden_size-1) - 0.5
|
| 168 |
+
zigzag[n] = ((n % self.head_dim) - ((self.head_dim-1) / 2)) / ((self.head_dim-1) / 2)
|
| 169 |
+
zigzag[n] = zigzag[n] * abs(zigzag[n])
|
| 170 |
+
www[n] = -6 + 6 * (n / (self.hidden_size - 1)) ** (1 + 1 * ratio_0_to_1 ** 0.3)
|
| 171 |
+
ddd[0, 0, n] = n / self.hidden_size
|
| 172 |
+
|
| 173 |
+
# Initialize x_* parameters directly
|
| 174 |
+
self.x_r.data = (1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0)).to(self.x_r.dtype)
|
| 175 |
+
self.x_w.data = (1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0)).to(self.x_w.dtype)
|
| 176 |
+
self.x_k.data = (1.0 - torch.pow(ddd, 0.7 * ratio_1_to_almost0)).to(self.x_k.dtype)
|
| 177 |
+
self.x_v.data = (1.0 - torch.pow(ddd, 0.7 * ratio_1_to_almost0)).to(self.x_v.dtype)
|
| 178 |
+
self.x_a.data = (1.0 - torch.pow(ddd, 0.9 * ratio_1_to_almost0)).to(self.x_a.dtype)
|
| 179 |
+
self.x_g.data = (1.0 - torch.pow(ddd, 0.2 * ratio_1_to_almost0)).to(self.x_g.dtype)
|
| 180 |
+
|
| 181 |
+
# Initialize k_k, k_a, r_k
|
| 182 |
+
nn.init.constant_(self.k_a, 1.02)
|
| 183 |
+
nn.init.constant_(self.r_k, -0.04)
|
| 184 |
+
self.k_k.data.copy_((torch.zeros(self.hidden_size, device=self.k_k.device) +
|
| 185 |
+
0.71 - linear*0.1).to(self.k_k.dtype))
|
| 186 |
+
# Set specific bias values for LoRA modules
|
| 187 |
+
# 0.5 comes from F.softplus
|
| 188 |
+
self.w_lora.set_bias_value(www + 0.5 + zigzag*2.5)
|
| 189 |
+
self.a_lora.set_bias_value(-0.19 + zigzag*0.3 + linear*0.4)
|
| 190 |
+
|
| 191 |
+
# v0 initialization - ones (for non-first layers)
|
| 192 |
+
if self.layer_idx != 0:
|
| 193 |
+
self.v_lora._initialize_weights(self.v_lora)
|
| 194 |
+
self.v_lora.set_bias_value(0.73 - linear*0.4)
|
| 195 |
+
|
| 196 |
+
# Initialize GroupNorm
|
| 197 |
+
self.g_norm.weight.data[:] = ((self.layer_idx + 1) / self.num_hidden_layers) ** 0.7
|
| 198 |
+
|
| 199 |
+
# Initialize Linear projections
|
| 200 |
+
self._orthogonal_init(self.r_proj.weight)
|
| 201 |
+
self._orthogonal_init(self.k_proj.weight, gain=0.1)
|
| 202 |
+
self._orthogonal_init(self.v_proj.weight)
|
| 203 |
+
self.o_proj.weight.data.zero_()
|
| 204 |
+
|
| 205 |
+
# Clean up temporary tensors to free memory
|
| 206 |
+
del ddd, www, zigzag, linear
|
| 207 |
+
|
| 208 |
+
module._is_hf_initialized = True
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def _orthogonal_init(weight, gain=1.0):
|
| 212 |
+
oringinal_dtype = weight.dtype
|
| 213 |
+
weight = weight.float()
|
| 214 |
+
nn.init.orthogonal_(weight, gain=gain)
|
| 215 |
+
weight = weight.to(oringinal_dtype)
|
| 216 |
+
|
| 217 |
+
def forward(
|
| 218 |
+
self,
|
| 219 |
+
hidden_states: torch.Tensor,
|
| 220 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 221 |
+
past_key_values: Optional[Cache] = None,
|
| 222 |
+
use_cache: Optional[bool] = False,
|
| 223 |
+
output_attentions: Optional[bool] = False,
|
| 224 |
+
v_first: torch.Tensor = None,
|
| 225 |
+
cu_seqlens: Optional[torch.LongTensor] = None,
|
| 226 |
+
**kwargs
|
| 227 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 228 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 229 |
+
if attention_mask is not None:
|
| 230 |
+
assert len(attention_mask.shape) == 2, (
|
| 231 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 232 |
+
"for padding purposes (0 indicating padding). "
|
| 233 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 234 |
+
)
|
| 235 |
+
am = attention_mask.narrow(1, attention_mask.size(1) - seq_len, seq_len).unsqueeze(-1)
|
| 236 |
+
|
| 237 |
+
last_state = None
|
| 238 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 239 |
+
last_state = past_key_values[self.layer_idx]
|
| 240 |
+
|
| 241 |
+
if attention_mask is not None:
|
| 242 |
+
hidden_states = hidden_states.mul(am)
|
| 243 |
+
|
| 244 |
+
# delta [batch_size, seq_len, hidden_size]
|
| 245 |
+
# conv_cache [N, D]
|
| 246 |
+
if last_state is None:
|
| 247 |
+
conv_cache = None
|
| 248 |
+
recurrent_state = None
|
| 249 |
+
else:
|
| 250 |
+
conv_cache = last_state['conv_state']
|
| 251 |
+
recurrent_state = last_state['recurrent_state']
|
| 252 |
+
|
| 253 |
+
delta, conv_state = token_shift(
|
| 254 |
+
hidden_states, cu_seqlens, output_cache=True, cache=conv_cache
|
| 255 |
+
)
|
| 256 |
+
xr, xw, xk, xv, xa, xg = fused_addcmul_rwkv7(hidden_states, delta, self.x_r, self.x_w,
|
| 257 |
+
self.x_k, self.x_v, self.x_a, self.x_g)
|
| 258 |
+
|
| 259 |
+
r = self.r_proj(xr)
|
| 260 |
+
# Using bf16 for LoRA computation is numerically safe here because:
|
| 261 |
+
# 1. After sigmoid activation:
|
| 262 |
+
# - Max absolute error (vs float32): 0.003
|
| 263 |
+
# - Mean absolute error: 0.0004
|
| 264 |
+
# 2. Subsequent scaling by -0.6065 will further reduce relative error
|
| 265 |
+
# (error scales linearly with constant multiplication)
|
| 266 |
+
# 3. Final compounded error remains within acceptable bounds for bf16 precision
|
| 267 |
+
# Empirical observation confirms bf16 introduces no practical degradation
|
| 268 |
+
w = -0.6065306597126334 * self.w_lora(xw).sigmoid()
|
| 269 |
+
|
| 270 |
+
k = self.k_proj(xk)
|
| 271 |
+
v = self.v_proj(xv)
|
| 272 |
+
|
| 273 |
+
if self.layer_idx == 0:
|
| 274 |
+
v_first = v
|
| 275 |
+
else:
|
| 276 |
+
v = torch.lerp(v, v_first, self.v_lora(xv).sigmoid())
|
| 277 |
+
a = self.a_lora(xa).sigmoid()
|
| 278 |
+
g = self.g_lora(xg)
|
| 279 |
+
|
| 280 |
+
if self.fuse_norm:
|
| 281 |
+
kk = l2_norm(rearrange(k * self.k_k, 'b t (h d) -> b t h d', d=self.head_dim))
|
| 282 |
+
else:
|
| 283 |
+
kk = F.normalize(rearrange(k * self.k_k, 'b t (h d) -> b t h d', d=self.head_dim), dim=-1, p=2.0)
|
| 284 |
+
|
| 285 |
+
# Prefer addcmul over expanded form for numerical stability in bf16:
|
| 286 |
+
# 1. Fused Multiply-Add (FMA) in addcmul reduces intermediate rounding:
|
| 287 |
+
# - Single op vs original 3 ops (mul, sub, mul)
|
| 288 |
+
# - 1 less intermediate value storage (bf16 write->read overhead)
|
| 289 |
+
# 2. Mathematically equivalent to k*(1 + (a-1)*self.k_a)
|
| 290 |
+
# but with better precision preservation
|
| 291 |
+
# 3. Particularly crucial for bf16 where intermediate values easily lose precision
|
| 292 |
+
# 4. Pytorch method: k = k.addcmul(k * (a - 1), self.k_a)
|
| 293 |
+
k = fused_k_rwkv7(k, a, self.k_a)
|
| 294 |
+
|
| 295 |
+
# dealing with left-padding
|
| 296 |
+
if attention_mask is not None:
|
| 297 |
+
v = v * am
|
| 298 |
+
|
| 299 |
+
r, w, k, a = map(lambda x: rearrange(x, 'b t (h d) -> b t h d', d=self.head_dim), (r, w, k, a))
|
| 300 |
+
v = rearrange(v, 'b t (h d) -> b t h d', d=self.head_v_dim)
|
| 301 |
+
|
| 302 |
+
if self.training or seq_len >= 64:
|
| 303 |
+
# if training, use chunk mode no matter how short the sequence is
|
| 304 |
+
# launching the triton kernel for just one token will actually be slower
|
| 305 |
+
o, recurrent_state = chunk_rwkv7(
|
| 306 |
+
r=r,
|
| 307 |
+
w=w,
|
| 308 |
+
k=k,
|
| 309 |
+
v=v,
|
| 310 |
+
a=-kk,
|
| 311 |
+
b=kk * a,
|
| 312 |
+
scale=1.,
|
| 313 |
+
initial_state=recurrent_state,
|
| 314 |
+
output_final_state=use_cache,
|
| 315 |
+
cu_seqlens=cu_seqlens,
|
| 316 |
+
)
|
| 317 |
+
else:
|
| 318 |
+
o, recurrent_state = fused_mul_recurrent_rwkv7(
|
| 319 |
+
r=r,
|
| 320 |
+
w=w,
|
| 321 |
+
k=k,
|
| 322 |
+
v=v,
|
| 323 |
+
kk=kk,
|
| 324 |
+
a=a,
|
| 325 |
+
scale=1.,
|
| 326 |
+
initial_state=recurrent_state,
|
| 327 |
+
output_final_state=use_cache,
|
| 328 |
+
cu_seqlens=cu_seqlens,
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
if past_key_values is not None:
|
| 332 |
+
past_key_values.update(
|
| 333 |
+
recurrent_state=recurrent_state,
|
| 334 |
+
conv_state=conv_state,
|
| 335 |
+
layer_idx=self.layer_idx,
|
| 336 |
+
offset=r.shape[1]
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
if self.fuse_norm:
|
| 340 |
+
o = self.g_norm(rearrange(o, '... h d -> ... (h d)'))
|
| 341 |
+
else:
|
| 342 |
+
o = self.g_norm(rearrange(o, 'b t h d -> (b t) (h d)')).view(batch_size, seq_len, -1)
|
| 343 |
+
|
| 344 |
+
o = gate_output_correction(o, r, k, self.r_k, v, g)
|
| 345 |
+
o = self.o_proj(o)
|
| 346 |
+
|
| 347 |
+
return o, None, past_key_values, v_first
|
sig_tr_gka.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Trace Sigma-GKA layer.
|
| 2 |
+
|
| 3 |
+
Same block interface as ``SigmaGKANet`` (projections, short conv, beta, alpha,
|
| 4 |
+
polynomial coefficients, output norm). ``use_mamba_init`` selects the decay:
|
| 5 |
+
|
| 6 |
+
# Mamba / KDA
|
| 7 |
+
g = -exp(A_log) * softplus(f_proj(x) + dt_bias) # [B, T, H, D]
|
| 8 |
+
|
| 9 |
+
# GLA
|
| 10 |
+
g = logsigmoid(W2 W1 x) / gate_logit_normalizer # [B, T, H, D]
|
| 11 |
+
|
| 12 |
+
``g`` (value state) and ``gk`` (key-key state) share this gate. Both stay
|
| 13 |
+
non-positive.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
from typing import Optional, Sequence, Tuple
|
| 20 |
+
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn as nn
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from einops import rearrange, repeat
|
| 25 |
+
from torch import Tensor
|
| 26 |
+
|
| 27 |
+
from fla.models.utils import Cache
|
| 28 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 29 |
+
from ..modules.l2norm import l2norm
|
| 30 |
+
# from ..ops.phi_kkt_approx_gla_trace_c16.phi_kkt_solve_trace import (
|
| 31 |
+
# phi_kkt_decoding_one_step,
|
| 32 |
+
# phi_kkt_solve_gla,
|
| 33 |
+
# )
|
| 34 |
+
# from ..ops.phi_kkt_approx_gla_trace.phi_kkt_solve_trace import (
|
| 35 |
+
# phi_kkt_decoding_one_step,
|
| 36 |
+
# phi_kkt_solve_gla,
|
| 37 |
+
# )
|
| 38 |
+
from ..ops.phi_kkt_approx_gla_trace.phi_kkt_solve_trace import (
|
| 39 |
+
phi_kkt_decoding_one_step,
|
| 40 |
+
phi_kkt_solve_gla,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
class SigTrGKANet(nn.Module):
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
mode: str = "chunk",
|
| 47 |
+
hidden_size: int = 2048,
|
| 48 |
+
head_dim: int = 128,
|
| 49 |
+
num_heads: int = 8,
|
| 50 |
+
num_q_heads: Optional[int] = None,
|
| 51 |
+
num_k_heads: Optional[int] = None,
|
| 52 |
+
num_v_heads: Optional[int] = None,
|
| 53 |
+
use_short_conv: bool = True,
|
| 54 |
+
conv_size: int = 4,
|
| 55 |
+
conv_bias: bool = False,
|
| 56 |
+
use_output_gate: bool = False,
|
| 57 |
+
use_beta_gate: bool = True,
|
| 58 |
+
use_alpha_connection: bool = False,
|
| 59 |
+
use_v_conv: bool = True,
|
| 60 |
+
use_forgetting_gate: bool = True,
|
| 61 |
+
use_forgetting_gate_kk: bool = True,
|
| 62 |
+
gla_rescale: bool = True,
|
| 63 |
+
gate_logit_normalizer: float = 16.0,
|
| 64 |
+
gate_low_rank_dim: int = 16,
|
| 65 |
+
clamp_min: Optional[float] = None,
|
| 66 |
+
use_mamba_init: bool = False,
|
| 67 |
+
norm_eps: float = 1e-6,
|
| 68 |
+
layer_idx: Optional[int] = None,
|
| 69 |
+
chunk_size: int = 64,
|
| 70 |
+
learnable_abc: Sequence[float] = (1.0, -0.5, 0.375),
|
| 71 |
+
random_init_abc: bool = True,
|
| 72 |
+
abc_requires_grad: bool = True,
|
| 73 |
+
lambda_lower_bound: float = 0.25,
|
| 74 |
+
max_cg_step_training: int = 30,
|
| 75 |
+
max_cg_step_decoding: int = 30,
|
| 76 |
+
**kwargs,
|
| 77 |
+
) -> None:
|
| 78 |
+
super().__init__()
|
| 79 |
+
del lambda_lower_bound, max_cg_step_training, max_cg_step_decoding
|
| 80 |
+
|
| 81 |
+
self.mode = mode
|
| 82 |
+
self.hidden_size = hidden_size
|
| 83 |
+
self.head_dim = head_dim
|
| 84 |
+
self.num_heads = num_heads
|
| 85 |
+
self.num_q_heads = num_heads if num_q_heads is None else num_q_heads
|
| 86 |
+
self.num_k_heads = num_heads if num_k_heads is None else num_k_heads
|
| 87 |
+
self.num_v_heads = num_heads if num_v_heads is None else num_v_heads
|
| 88 |
+
self.expanded_num_heads = max(self.num_q_heads, self.num_k_heads, self.num_v_heads)
|
| 89 |
+
self.num_q_groups = self.expanded_num_heads // self.num_q_heads
|
| 90 |
+
self.num_k_groups = self.expanded_num_heads // self.num_k_heads
|
| 91 |
+
self.num_v_groups = self.expanded_num_heads // self.num_v_heads
|
| 92 |
+
if self.expanded_num_heads % self.num_q_heads:
|
| 93 |
+
raise ValueError("expanded heads must divide num_q_heads")
|
| 94 |
+
if self.expanded_num_heads % self.num_k_heads:
|
| 95 |
+
raise ValueError("expanded heads must divide num_k_heads")
|
| 96 |
+
if self.expanded_num_heads % self.num_v_heads:
|
| 97 |
+
raise ValueError("expanded heads must divide num_v_heads")
|
| 98 |
+
|
| 99 |
+
self.query_dim = self.num_q_heads * head_dim
|
| 100 |
+
self.key_dim = self.num_k_heads * head_dim
|
| 101 |
+
self.value_dim = self.num_v_heads * head_dim
|
| 102 |
+
self.expanded_dim = self.expanded_num_heads * head_dim
|
| 103 |
+
|
| 104 |
+
self.layer_idx = layer_idx
|
| 105 |
+
self.chunk_size = chunk_size
|
| 106 |
+
self.conv_size = conv_size
|
| 107 |
+
self.use_short_conv = use_short_conv
|
| 108 |
+
self.use_v_conv = use_v_conv
|
| 109 |
+
self.use_beta_gate = use_beta_gate
|
| 110 |
+
self.use_alpha_connection = use_alpha_connection
|
| 111 |
+
self.use_output_gate = use_output_gate
|
| 112 |
+
self.use_forgetting_gate = use_forgetting_gate
|
| 113 |
+
self.use_forgetting_gate_kk = use_forgetting_gate_kk
|
| 114 |
+
self.use_mamba_init = use_mamba_init
|
| 115 |
+
if layer_idx in (None, 0):
|
| 116 |
+
print("use_mamba_init:", use_mamba_init)
|
| 117 |
+
self.gate_logit_normalizer = gate_logit_normalizer
|
| 118 |
+
self.clamp_min = -5#clamp_min
|
| 119 |
+
self.gla_scale = head_dim ** -0.5 if gla_rescale else 1.0
|
| 120 |
+
|
| 121 |
+
self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False)
|
| 122 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 123 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 124 |
+
self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False)
|
| 125 |
+
|
| 126 |
+
if use_short_conv:
|
| 127 |
+
self.q_conv1d = ShortConvolution(self.query_dim, conv_size, bias=conv_bias, activation="silu")
|
| 128 |
+
self.k_conv1d = ShortConvolution(self.key_dim, conv_size, bias=conv_bias, activation="silu")
|
| 129 |
+
if use_v_conv:
|
| 130 |
+
self.v_conv1d = ShortConvolution(self.value_dim, conv_size, bias=conv_bias, activation="silu")
|
| 131 |
+
|
| 132 |
+
self.b_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True) if use_beta_gate else None
|
| 133 |
+
self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True) if use_alpha_connection else None
|
| 134 |
+
|
| 135 |
+
# One decay, shared by the value state (g) and the key-key state (gk).
|
| 136 |
+
if use_forgetting_gate or use_forgetting_gate_kk:
|
| 137 |
+
if use_mamba_init:
|
| 138 |
+
# Per expanded head and per key dim, matching KDA's [H, K].
|
| 139 |
+
self.gate_dim = self.expanded_num_heads * self.head_dim
|
| 140 |
+
self.f_proj = nn.Sequential(
|
| 141 |
+
nn.Linear(hidden_size, 16, bias=False),
|
| 142 |
+
nn.Linear(16, self.gate_dim, bias=False),
|
| 143 |
+
)
|
| 144 |
+
self.A_log = nn.Parameter(
|
| 145 |
+
torch.log(torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(1, 16))
|
| 146 |
+
)
|
| 147 |
+
self.A_log._no_weight_decay = True
|
| 148 |
+
dt = torch.exp(
|
| 149 |
+
torch.rand(self.gate_dim, dtype=torch.float32) * (math.log(0.1) - math.log(0.001))
|
| 150 |
+
+ math.log(0.001)
|
| 151 |
+
).clamp(min=1e-4)
|
| 152 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 153 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 154 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 155 |
+
self.dt_bias._no_weight_decay = True
|
| 156 |
+
else:
|
| 157 |
+
# GLA low-rank gate. Output is the key dim, then repeated across k groups.
|
| 158 |
+
self.gk_proj = nn.Sequential(
|
| 159 |
+
nn.Linear(hidden_size, gate_low_rank_dim, bias=False),
|
| 160 |
+
nn.Linear(gate_low_rank_dim, self.key_dim, bias=True),
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
coeff = torch.tensor(tuple(learnable_abc), dtype=torch.float32).reshape(-1)
|
| 164 |
+
n_coeff = int(coeff.numel())
|
| 165 |
+
if n_coeff not in (3, 4):
|
| 166 |
+
raise ValueError(f"learnable_abc must have 3 or 4 values, got {n_coeff}")
|
| 167 |
+
self.learnable_abc = nn.Parameter(
|
| 168 |
+
coeff.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous(),
|
| 169 |
+
requires_grad=abc_requires_grad,
|
| 170 |
+
)
|
| 171 |
+
if random_init_abc:
|
| 172 |
+
# a, c ~ U(0, 2); b, d ~ U(-2, 0). Same draw as SigmaGKANet.
|
| 173 |
+
signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32)
|
| 174 |
+
self.learnable_abc = nn.Parameter(
|
| 175 |
+
2 * (torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(),
|
| 176 |
+
requires_grad=abc_requires_grad,
|
| 177 |
+
)
|
| 178 |
+
print("random init abc")
|
| 179 |
+
print(self.learnable_abc)
|
| 180 |
+
print(self.learnable_abc.requires_grad)
|
| 181 |
+
else:
|
| 182 |
+
print("not random init abc")
|
| 183 |
+
print(self.learnable_abc)
|
| 184 |
+
print(self.learnable_abc.requires_grad)
|
| 185 |
+
self.learnable_abc._no_weight_decay = True
|
| 186 |
+
|
| 187 |
+
if use_output_gate:
|
| 188 |
+
self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False)
|
| 189 |
+
self.o_norm = FusedRMSNormGated(head_dim, eps=norm_eps)
|
| 190 |
+
else:
|
| 191 |
+
self.o_norm = RMSNorm(head_dim, eps=norm_eps)
|
| 192 |
+
|
| 193 |
+
def _heads(self, x: Tensor, n_heads: int) -> Tensor:
|
| 194 |
+
return rearrange(x, "... (h d) -> ... h d", h=n_heads)
|
| 195 |
+
|
| 196 |
+
def _repeat_heads(self, x: Tensor, groups: int) -> Tensor:
|
| 197 |
+
if groups == 1:
|
| 198 |
+
return x
|
| 199 |
+
return repeat(x, "... h d -> ... (h g) d", g=groups)
|
| 200 |
+
|
| 201 |
+
def _kda_decay(self, hidden_states: Tensor) -> Tensor:
|
| 202 |
+
"""Per-key-dim KDA decay, shape [B, T, H, D], values in (-inf, 0].
|
| 203 |
+
|
| 204 |
+
``g = -exp(A_log) * softplus(f_proj(x) + dt_bias)``, with ``A_log``
|
| 205 |
+
broadcast over the key dimension.
|
| 206 |
+
"""
|
| 207 |
+
gate = rearrange(self.f_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim)
|
| 208 |
+
gate = gate.float() + self.dt_bias.view(self.expanded_num_heads, self.head_dim)
|
| 209 |
+
gate = -self.A_log.float().exp().unsqueeze(-1) * F.softplus(gate)
|
| 210 |
+
if self.clamp_min is not None:
|
| 211 |
+
gate = gate.clamp_min(self.clamp_min)
|
| 212 |
+
return gate
|
| 213 |
+
|
| 214 |
+
def _gla_decay(self, hidden_states: Tensor) -> Tensor:
|
| 215 |
+
"""Per-dimension GLA decay, shape [B, T, H, D], values in (-inf, 0]."""
|
| 216 |
+
gate = self.gk_proj(hidden_states)
|
| 217 |
+
gate = self._repeat_heads(self._heads(gate, self.num_k_heads), self.num_k_groups)
|
| 218 |
+
gate = F.logsigmoid(gate) / self.gate_logit_normalizer
|
| 219 |
+
if self.clamp_min is not None:
|
| 220 |
+
gate = gate.clamp_min(self.clamp_min)
|
| 221 |
+
return gate
|
| 222 |
+
|
| 223 |
+
def forward(
|
| 224 |
+
self,
|
| 225 |
+
hidden_states: Tensor,
|
| 226 |
+
attention_mask: Optional[Tensor] = None,
|
| 227 |
+
past_key_values: Optional[Cache] = None,
|
| 228 |
+
use_cache: Optional[bool] = False,
|
| 229 |
+
output_attentions: Optional[bool] = False,
|
| 230 |
+
**kwargs,
|
| 231 |
+
) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]:
|
| 232 |
+
del output_attentions
|
| 233 |
+
if attention_mask is not None and not self.training:
|
| 234 |
+
raise NotImplementedError("sig_tr_gka does not support varlen attention_mask.")
|
| 235 |
+
|
| 236 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 237 |
+
del batch_size
|
| 238 |
+
cu_seqlens = kwargs.get("cu_seqlens", None)
|
| 239 |
+
|
| 240 |
+
last_state = None
|
| 241 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 242 |
+
last_state = past_key_values[self.layer_idx]
|
| 243 |
+
conv_state_q = conv_state_k = conv_state_v = None
|
| 244 |
+
if last_state is not None:
|
| 245 |
+
conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"]
|
| 246 |
+
|
| 247 |
+
if self.use_short_conv:
|
| 248 |
+
q, conv_state_q = self.q_conv1d(
|
| 249 |
+
x=self.q_proj(hidden_states), cache=conv_state_q,
|
| 250 |
+
output_final_state=use_cache, cu_seqlens=cu_seqlens,
|
| 251 |
+
)
|
| 252 |
+
k, conv_state_k = self.k_conv1d(
|
| 253 |
+
x=self.k_proj(hidden_states), cache=conv_state_k,
|
| 254 |
+
output_final_state=use_cache, cu_seqlens=cu_seqlens,
|
| 255 |
+
)
|
| 256 |
+
if self.use_v_conv:
|
| 257 |
+
v, conv_state_v = self.v_conv1d(
|
| 258 |
+
x=self.v_proj(hidden_states), cache=conv_state_v,
|
| 259 |
+
output_final_state=use_cache, cu_seqlens=cu_seqlens,
|
| 260 |
+
)
|
| 261 |
+
else:
|
| 262 |
+
v = self.v_proj(hidden_states)
|
| 263 |
+
else:
|
| 264 |
+
q = self.q_proj(hidden_states)
|
| 265 |
+
k = self.k_proj(hidden_states)
|
| 266 |
+
v = self.v_proj(hidden_states)
|
| 267 |
+
|
| 268 |
+
q = self._repeat_heads(self._heads(q, self.num_q_heads), self.num_q_groups)
|
| 269 |
+
k = self._repeat_heads(self._heads(k, self.num_k_heads), self.num_k_groups)
|
| 270 |
+
v = self._repeat_heads(self._heads(v, self.num_v_heads), self.num_v_groups)
|
| 271 |
+
q = l2norm(q)
|
| 272 |
+
k = l2norm(k)
|
| 273 |
+
# q = q / (torch.linalg.vector_norm(q, dim=-1, keepdim=True) + 1e-6)
|
| 274 |
+
# k = k / (torch.linalg.vector_norm(k, dim=-1, keepdim=True) + 1e-6)
|
| 275 |
+
|
| 276 |
+
if self.use_beta_gate:
|
| 277 |
+
beta = torch.sqrt(self.b_proj(hidden_states).sigmoid())
|
| 278 |
+
# k = (beta[..., None] + 1e-6) * k
|
| 279 |
+
# v = (beta[..., None] + 1e-6) * v
|
| 280 |
+
# k = beta[..., None] * k
|
| 281 |
+
# v = beta[..., None] * v
|
| 282 |
+
# Off by default: alpha = 1, so q_mix = x and q is not added back onto the polynomial query.
|
| 283 |
+
alpha = self.alpha_proj(hidden_states).sigmoid() if self.use_alpha_connection else torch.ones_like(q[..., 0])
|
| 284 |
+
|
| 285 |
+
if self.use_forgetting_gate or self.use_forgetting_gate_kk:
|
| 286 |
+
decay = self._kda_decay(hidden_states) if self.use_mamba_init else self._gla_decay(hidden_states)
|
| 287 |
+
else:
|
| 288 |
+
decay = None
|
| 289 |
+
g = decay if self.use_forgetting_gate else None
|
| 290 |
+
gk = decay if self.use_forgetting_gate_kk else None
|
| 291 |
+
|
| 292 |
+
coeff = self.learnable_abc.to(dtype=torch.float32)
|
| 293 |
+
if last_state is None:
|
| 294 |
+
o, h_kk, h_kv = phi_kkt_solve_gla(
|
| 295 |
+
q=q,
|
| 296 |
+
k=k,
|
| 297 |
+
v=v,
|
| 298 |
+
alpha=alpha,
|
| 299 |
+
g=g,
|
| 300 |
+
gk=gk,
|
| 301 |
+
gla_scale=self.gla_scale,
|
| 302 |
+
learnable_abc=coeff,
|
| 303 |
+
chunk_size=self.chunk_size,
|
| 304 |
+
output_final_state=past_key_values is not None,
|
| 305 |
+
layer_idx=self.layer_idx,
|
| 306 |
+
)
|
| 307 |
+
else:
|
| 308 |
+
last_h_kk, last_h_kv = last_state["recurrent_state"]
|
| 309 |
+
o, h_kk, h_kv = phi_kkt_decoding_one_step(
|
| 310 |
+
q=q,
|
| 311 |
+
k=k,
|
| 312 |
+
v=v,
|
| 313 |
+
alpha=alpha,
|
| 314 |
+
g=g,
|
| 315 |
+
gk=gk,
|
| 316 |
+
gla_scale=self.gla_scale,
|
| 317 |
+
learnable_abc=coeff,
|
| 318 |
+
prev_h_kk=last_h_kk,
|
| 319 |
+
prev_h_kv=last_h_kv,
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
if past_key_values is not None:
|
| 323 |
+
past_key_values.update(
|
| 324 |
+
recurrent_state=(h_kk, h_kv),
|
| 325 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 326 |
+
layer_idx=self.layer_idx,
|
| 327 |
+
offset=q_len,
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
if self.use_output_gate:
|
| 331 |
+
out_gate = rearrange(self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim)
|
| 332 |
+
o = self.o_norm(o, out_gate)
|
| 333 |
+
else:
|
| 334 |
+
o = self.o_norm(o)
|
| 335 |
+
o = self.o_proj(rearrange(o, "b t h d -> b t (h d)"))
|
| 336 |
+
return o, None, past_key_values
|
sigma_gka.py
ADDED
|
@@ -0,0 +1,1212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Sigma Gated KalmaNet (Sigma GKA) layer implementation with Grouped Query Attention (GQA) support.
|
| 3 |
+
|
| 4 |
+
This module implements the Sigma Gated KalmaNet layer from the paper:
|
| 5 |
+
"Sigma Gated KalmaNet: A Fading Memory Layer Through Test-Time Ridge Regression" (https://arxiv.org/abs/2511.21016).
|
| 6 |
+
|
| 7 |
+
Overview:
|
| 8 |
+
Sigma GKA is a state space model (SSM) that updates its state based on the entire history
|
| 9 |
+
of previously seen tokens, rather than just the current token. At each timestep t,
|
| 10 |
+
the optimal state S_t minimizes a ridge regression objective over all past tokens:
|
| 11 |
+
|
| 12 |
+
S_t = argmin_S { λ·||S||²_F + Σ(i=1 to t) η_i·||S·k_i - v_i||² }
|
| 13 |
+
|
| 14 |
+
where λ is the ridge regularization strength and η_i are exponentially decaying weights
|
| 15 |
+
controlled by forgetting gates. This has a closed-form solution:
|
| 16 |
+
|
| 17 |
+
S_t = U_t · (H_t + λI)^(-1)
|
| 18 |
+
|
| 19 |
+
where:
|
| 20 |
+
U_t = Σ(i=1 to t) η_i v_i k_i^T (cumulative value-key outer products)
|
| 21 |
+
H_t = Σ(i=1 to t) η_i k_i k_i^T (cumulative key-key covariance)
|
| 22 |
+
|
| 23 |
+
The output is computed as y_t = S_t · q_t, which reduces to solving the ridge
|
| 24 |
+
regression problem (H_t + λI)·x_t = q_t for x_t, then computing y_t = U_t · x_t.
|
| 25 |
+
This is solved numerically via the Chebyshev iteration algorithm.
|
| 26 |
+
|
| 27 |
+
The layer supports GQA-style head grouping where the number of key/value heads
|
| 28 |
+
can be different from the number of query heads. The hyperparameters in this module
|
| 29 |
+
are set so that we can initialize the module's weights from existing Attention layers.
|
| 30 |
+
|
| 31 |
+
Key Variables:
|
| 32 |
+
- head_dim: Head dimension (same for q/k/v)
|
| 33 |
+
- num_q_heads: Number of query heads
|
| 34 |
+
- num_k_heads: Number of key heads
|
| 35 |
+
- num_v_heads: Number of value heads
|
| 36 |
+
- expanded_num_heads: Maximum of num_q_heads, num_k_heads, num_v_heads
|
| 37 |
+
- num_q_groups: Repetition factor for Q heads, computed as expanded_num_heads // num_q_heads
|
| 38 |
+
- num_k_groups: Repetition factor for K heads, computed as expanded_num_heads // num_k_heads
|
| 39 |
+
- num_v_groups: Repetition factor for V heads, computed as expanded_num_heads // num_v_heads
|
| 40 |
+
- query_dim: Total query dimension, num_q_heads * head_dim
|
| 41 |
+
- key_dim: Total key dimension, num_k_heads * head_dim
|
| 42 |
+
- value_dim: Total value dimension, num_v_heads * head_dim
|
| 43 |
+
- expanded_dim: Expanded dimension, expanded_num_heads * head_dim
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
from __future__ import annotations
|
| 47 |
+
|
| 48 |
+
import math
|
| 49 |
+
from typing import TYPE_CHECKING, Any, Optional, Tuple
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
import torch.nn as nn
|
| 53 |
+
from einops import rearrange, repeat
|
| 54 |
+
from torch import Tensor
|
| 55 |
+
from torch.nn import functional as F
|
| 56 |
+
|
| 57 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 58 |
+
from fla.ops.simple_gla import chunk_simple_gla
|
| 59 |
+
from fla.models.utils import Cache
|
| 60 |
+
|
| 61 |
+
# from ..ops.chebyshev.chunk_dk_backward_gating_sp import compute_kk_final_with_gating
|
| 62 |
+
# from .sequence_parallel.gka_sp_utils import (
|
| 63 |
+
# state_passing_gka_p2p,
|
| 64 |
+
# recompute_with_initial_states,
|
| 65 |
+
# )
|
| 66 |
+
|
| 67 |
+
# from ..ops.chebyshev.gka_chebyshev_solve import (
|
| 68 |
+
# gka_chebyshev_gla,
|
| 69 |
+
# torch_decoding_one_step,
|
| 70 |
+
# )
|
| 71 |
+
from ..ops.phi_kkt_approx_gla.phi_kkt_solve import (
|
| 72 |
+
phi_kkt_solve_gla,
|
| 73 |
+
phi_kkt_decoding_one_step,
|
| 74 |
+
)
|
| 75 |
+
from torch.nn import Sigmoid
|
| 76 |
+
|
| 77 |
+
from typing import Any, Optional
|
| 78 |
+
|
| 79 |
+
import torch
|
| 80 |
+
import torch.nn as nn
|
| 81 |
+
import torch.nn.init as init
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class LinearLowRank(nn.Module):
|
| 85 |
+
"""
|
| 86 |
+
Low-rank linear layer that factorizes a linear projection into two smaller ones:
|
| 87 |
+
y = linearB(act_fn(linearA(x)))
|
| 88 |
+
|
| 89 |
+
where linearA projects from in_features to rank, and linearB projects from rank to out_features.
|
| 90 |
+
|
| 91 |
+
linearB is zero-initialized so that the module outputs zeros at init time. This makes it safe
|
| 92 |
+
to use as a residual branch (e.g. added on top of a repeat/expand) without perturbing the
|
| 93 |
+
pretrained signal at the start of training.
|
| 94 |
+
|
| 95 |
+
Note: linearB is marked with ``_is_hf_initialized = True`` to prevent transformers'
|
| 96 |
+
``post_init`` from overwriting the zero initialization with a random normal.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
in_features: Input dimension.
|
| 100 |
+
out_features: Output dimension.
|
| 101 |
+
rank: Bottleneck dimension between the two linear layers.
|
| 102 |
+
act_fn: Optional activation applied between linearA and linearB. Defaults to Identity.
|
| 103 |
+
bias: Whether to include bias terms in both linear layers. Defaults to False.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
in_features: int,
|
| 109 |
+
out_features: int,
|
| 110 |
+
rank: int,
|
| 111 |
+
act_fn: Optional[Any] = None,
|
| 112 |
+
bias: bool = False,
|
| 113 |
+
):
|
| 114 |
+
super().__init__()
|
| 115 |
+
self.linearA = nn.Linear(in_features, rank, bias=bias)
|
| 116 |
+
self.linearB = nn.Linear(rank, out_features, bias=bias)
|
| 117 |
+
|
| 118 |
+
self.in_features = in_features
|
| 119 |
+
self.out_features = out_features
|
| 120 |
+
self.rank = rank
|
| 121 |
+
self.bias = bias
|
| 122 |
+
self.act_fn = act_fn if act_fn is not None else nn.Identity()
|
| 123 |
+
|
| 124 |
+
# Initialize B weights and bias to zero
|
| 125 |
+
init.zeros_(self.linearB.weight)
|
| 126 |
+
if self.linearB.bias is not None:
|
| 127 |
+
init.zeros_(self.linearB.bias)
|
| 128 |
+
self.linearB._is_hf_initialized = (
|
| 129 |
+
True
|
| 130 |
+
) # prevent transformers' post_init from re-initializing
|
| 131 |
+
|
| 132 |
+
def forward(self, x: torch.Tensor):
|
| 133 |
+
return self.linearB(self.act_fn(self.linearA(x)))
|
| 134 |
+
###调整初始化
|
| 135 |
+
#####我们的目标是使用(-1/2)求逆
|
| 136 |
+
class SigmaGKANet(nn.Module):
|
| 137 |
+
"""
|
| 138 |
+
Sigma GKA layer with Chebyshev solver and GQA support.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
hidden_size: The hidden size of the input. Defaults to 2048.
|
| 142 |
+
head_dim: The dimension of each head. Assumes q/k/v have the same head dimension.
|
| 143 |
+
Defaults to 128.
|
| 144 |
+
num_q_heads: The number of query heads. Defaults to 16.
|
| 145 |
+
num_k_heads: The number of key heads for GQA. If None, defaults to num_q_heads.
|
| 146 |
+
Defaults to None.
|
| 147 |
+
num_v_heads: The number of value heads for GQA. If None, defaults to num_q_heads.
|
| 148 |
+
Defaults to None.
|
| 149 |
+
use_beta_gate: Whether to use beta gating mechanism. Defaults to True.
|
| 150 |
+
use_alpha_connection: Whether to use alpha connection for residual paths. Defaults to True.
|
| 151 |
+
use_v_conv: Whether to apply convolution to value vectors. Defaults to True.
|
| 152 |
+
use_forgetting_gate: Whether to use forgetting gate mechanism. Defaults to True.
|
| 153 |
+
use_forgetting_gate_kk: Whether to use forgetting gate for key-key interactions. Defaults to True.
|
| 154 |
+
gla_rescale: Whether to apply GLA-style rescaling. Defaults to True.
|
| 155 |
+
solver_type: Solver method. Currently, we only support "chebyshev". Defaults to "chebyshev".
|
| 156 |
+
bp_lambda: Whether to backpropagate through lambda parameters. Defaults to True.
|
| 157 |
+
num_iter: Number of iterations for iterative solvers. Defaults to 30.
|
| 158 |
+
ridge_strength: Regularization strength for ridge regression. Defaults to 0.02.
|
| 159 |
+
use_gate: Whether to use output gating mechanism. Defaults to True.
|
| 160 |
+
conv_size: Size of the convolution kernel. Defaults to 4.
|
| 161 |
+
layer_idx: The index of the layer. Used for caching during inference. Defaults to None.
|
| 162 |
+
norm_eps: The epsilon value for the normalization layer. Defaults to 1e-6.
|
| 163 |
+
chunk_size: Size of chunks for parallel processing in Triton kernels. Defaults to 64.
|
| 164 |
+
kv_proj_rank: Rank for low-rank KV projection to expand K/V heads. If None, uses
|
| 165 |
+
standard GQA repeat. Defaults to None.
|
| 166 |
+
kv_learnable_residual: Whether to use a learnable residual for the KV head expansion
|
| 167 |
+
instead of a fixed repeat. Only used when kv_proj_rank is set. Defaults to False.
|
| 168 |
+
learnable_abc: Initial polynomial coefficients. Length 3 (abc) uses
|
| 169 |
+
phi(H) ~ a I + b H/F + c H^2/F^2; length 4 (abcd) adds d H^3/F^3.
|
| 170 |
+
Stored as an ``nn.Parameter`` of shape [H, 3] or [H, 4].
|
| 171 |
+
Defaults to (1.0, -0.5, 0.375).
|
| 172 |
+
random_init_abc: If True, initialize per-head coefficients independently instead of
|
| 173 |
+
broadcasting ``learnable_abc`` to all heads. ``a, c`` are drawn from ``U(0, 1)``
|
| 174 |
+
(positive) and ``b, d`` from ``U(-1, 0)`` (negative). Defaults to False.
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
def __init__(
|
| 178 |
+
self,
|
| 179 |
+
hidden_size: int = 2048,
|
| 180 |
+
head_dim: int = 128,
|
| 181 |
+
num_heads: int = 8,
|
| 182 |
+
num_q_heads: Optional[int] = None,
|
| 183 |
+
num_k_heads: Optional[int] = None,
|
| 184 |
+
num_v_heads: Optional[int] = None,
|
| 185 |
+
use_beta_gate: bool = True,
|
| 186 |
+
use_alpha_connection: bool = True,
|
| 187 |
+
use_v_conv: bool = True,
|
| 188 |
+
use_forgetting_gate: bool = True,
|
| 189 |
+
use_forgetting_gate_kk: bool = True,
|
| 190 |
+
gla_rescale: bool = True,
|
| 191 |
+
# solver_type: str = "chebyshev",
|
| 192 |
+
bp_lambda: bool = True,
|
| 193 |
+
num_iter: int = 30,
|
| 194 |
+
ridge_strength: float = 0.02,
|
| 195 |
+
use_gate: bool = False,
|
| 196 |
+
conv_size: int = 4,
|
| 197 |
+
layer_idx: Optional[int] = None,
|
| 198 |
+
norm_eps: float = 1e-6,
|
| 199 |
+
chunk_size: int = 64,
|
| 200 |
+
kv_proj_rank: Optional[int] = None,
|
| 201 |
+
kv_learnable_residual: bool = False,
|
| 202 |
+
# learnable_abc: Tuple[float, ...] = (2.3424, -2.5663, 1.2652),
|
| 203 |
+
# learnable_abc: Tuple[float, ...] = (2.1111, -1.5556, 0.4444),
|
| 204 |
+
# learnable_abc: Tuple[float, ...] = (2.0, -2.0, 0.5,-0.125),
|
| 205 |
+
learnable_abc: Tuple[float, ...] = (1.0, -0.5, 0.375),
|
| 206 |
+
random_init_abc: bool = False,
|
| 207 |
+
abc_requires_grad: bool = False,
|
| 208 |
+
**kwargs,
|
| 209 |
+
) -> None:
|
| 210 |
+
super().__init__()
|
| 211 |
+
|
| 212 |
+
# assert solver_type == "chebyshev", f"Received {solver_type=}. Currently, Sigma GKA only supports 'chebyshev' solver."
|
| 213 |
+
|
| 214 |
+
self.hidden_size = hidden_size
|
| 215 |
+
|
| 216 |
+
self.use_gate = use_gate
|
| 217 |
+
self.conv_size = conv_size
|
| 218 |
+
self.sequence_parallel_group = None
|
| 219 |
+
self.chunk_size = chunk_size
|
| 220 |
+
|
| 221 |
+
self.head_dim = head_dim
|
| 222 |
+
self.num_heads = num_heads
|
| 223 |
+
self.num_q_heads = num_q_heads if num_q_heads is not None else num_heads
|
| 224 |
+
self.num_k_heads = num_k_heads if num_k_heads is not None else num_heads
|
| 225 |
+
self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
|
| 226 |
+
self.expanded_num_heads = max(
|
| 227 |
+
self.num_q_heads, self.num_k_heads, self.num_v_heads
|
| 228 |
+
)
|
| 229 |
+
self.num_q_groups = self.expanded_num_heads // self.num_q_heads
|
| 230 |
+
self.num_k_groups = self.expanded_num_heads // self.num_k_heads
|
| 231 |
+
self.num_v_groups = self.expanded_num_heads // self.num_v_heads
|
| 232 |
+
|
| 233 |
+
self.query_dim = self.num_q_heads * self.head_dim
|
| 234 |
+
self.key_dim = self.num_k_heads * self.head_dim
|
| 235 |
+
self.value_dim = self.num_v_heads * self.head_dim
|
| 236 |
+
self.expanded_dim = self.expanded_num_heads * self.head_dim
|
| 237 |
+
|
| 238 |
+
self.layer_idx = layer_idx
|
| 239 |
+
|
| 240 |
+
self.ridge_strength = ridge_strength
|
| 241 |
+
self.num_iter = num_iter
|
| 242 |
+
self.use_beta_gate = use_beta_gate
|
| 243 |
+
self.use_alpha_connection = use_alpha_connection
|
| 244 |
+
# self.solver_type = solver_type
|
| 245 |
+
self.bp_lambda = bp_lambda
|
| 246 |
+
self.use_v_conv = use_v_conv
|
| 247 |
+
self.use_forgetting_gate = use_forgetting_gate
|
| 248 |
+
self.use_forgetting_gate_kk = use_forgetting_gate_kk
|
| 249 |
+
|
| 250 |
+
if gla_rescale:
|
| 251 |
+
self.gla_scale = self.head_dim ** -0.5
|
| 252 |
+
else:
|
| 253 |
+
self.gla_scale = 1.0
|
| 254 |
+
|
| 255 |
+
# Projection layers
|
| 256 |
+
self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False)
|
| 257 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 258 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 259 |
+
|
| 260 |
+
self.a_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=False)
|
| 261 |
+
|
| 262 |
+
self.b_proj = (
|
| 263 |
+
nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
|
| 264 |
+
if self.use_beta_gate
|
| 265 |
+
else None
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
if self.use_alpha_connection:
|
| 269 |
+
self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
|
| 270 |
+
|
| 271 |
+
# Initialize A parameter (log scale)
|
| 272 |
+
A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 273 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 274 |
+
self.A_log._no_weight_decay = True
|
| 275 |
+
|
| 276 |
+
# Initialize dt bias parameter
|
| 277 |
+
dt_min = 0.001
|
| 278 |
+
dt_max = 0.1
|
| 279 |
+
dt_init_floor = 1e-4
|
| 280 |
+
dt = torch.exp(
|
| 281 |
+
torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 282 |
+
+ math.log(dt_min)
|
| 283 |
+
)
|
| 284 |
+
dt = torch.clamp(dt, min=dt_init_floor)
|
| 285 |
+
# Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 286 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 287 |
+
|
| 288 |
+
self.dt_bias = nn.Parameter(inv_dt)
|
| 289 |
+
self.dt_bias._no_weight_decay = True
|
| 290 |
+
|
| 291 |
+
# Per-head polynomial coefficients: [H, 3] abc or [H, 4] abcd
|
| 292 |
+
init_abc = torch.tensor(learnable_abc, dtype=torch.float32).reshape(-1)
|
| 293 |
+
n_coeff = int(init_abc.numel())
|
| 294 |
+
if n_coeff not in (3, 4):
|
| 295 |
+
raise ValueError(
|
| 296 |
+
f"learnable_abc must have 3 (abc) or 4 (abcd) coefficients, got {n_coeff}"
|
| 297 |
+
)
|
| 298 |
+
self.learnable_abc = nn.Parameter(
|
| 299 |
+
init_abc.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous(), requires_grad=abc_requires_grad
|
| 300 |
+
)
|
| 301 |
+
if random_init_abc:
|
| 302 |
+
# a, c ~ U(0, 1); b, d ~ U(-1, 0)
|
| 303 |
+
signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32)
|
| 304 |
+
self.learnable_abc = nn.Parameter(
|
| 305 |
+
2*(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
|
| 306 |
+
# (torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
|
| 307 |
+
# 2*(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32).contiguous())-1.0, requires_grad=abc_requires_grad
|
| 308 |
+
###make the abc to be in the range of [-1, 1]
|
| 309 |
+
)
|
| 310 |
+
print("random init abc")
|
| 311 |
+
print(self.learnable_abc)
|
| 312 |
+
print(self.learnable_abc.requires_grad)
|
| 313 |
+
else:
|
| 314 |
+
print("not random init abc")
|
| 315 |
+
print(self.learnable_abc)
|
| 316 |
+
print(self.learnable_abc.requires_grad)
|
| 317 |
+
self.learnable_abc._no_weight_decay = True
|
| 318 |
+
print('tanh')
|
| 319 |
+
|
| 320 |
+
# Short convolution layers
|
| 321 |
+
self.conv_size = conv_size
|
| 322 |
+
self.q_conv1d = ShortConvolution(
|
| 323 |
+
hidden_size=self.query_dim, kernel_size=conv_size, activation="silu"
|
| 324 |
+
)
|
| 325 |
+
self.k_conv1d = ShortConvolution(
|
| 326 |
+
hidden_size=self.key_dim, kernel_size=conv_size, activation="silu"
|
| 327 |
+
)
|
| 328 |
+
if self.use_v_conv:
|
| 329 |
+
self.v_conv1d = ShortConvolution(
|
| 330 |
+
hidden_size=self.value_dim, kernel_size=conv_size, activation="silu"
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
# Output gating and normalization
|
| 334 |
+
if use_gate:
|
| 335 |
+
self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False)
|
| 336 |
+
self.o_norm = FusedRMSNormGated(self.head_dim, eps=norm_eps)
|
| 337 |
+
else:
|
| 338 |
+
self.o_norm = RMSNorm(self.head_dim, eps=norm_eps)
|
| 339 |
+
self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False)
|
| 340 |
+
|
| 341 |
+
# Optional KV projection for GQA
|
| 342 |
+
self.kv_proj_rank = kv_proj_rank
|
| 343 |
+
self.kv_learnable_residual = kv_learnable_residual
|
| 344 |
+
if self.kv_proj_rank is not None:
|
| 345 |
+
act_fn = nn.SiLU()
|
| 346 |
+
self.proj_k = LinearLowRank(
|
| 347 |
+
in_features=self.key_dim,
|
| 348 |
+
out_features=self.expanded_num_heads * self.head_dim,
|
| 349 |
+
rank=self.kv_proj_rank,
|
| 350 |
+
act_fn=act_fn,
|
| 351 |
+
)
|
| 352 |
+
self.proj_v = LinearLowRank(
|
| 353 |
+
in_features=self.value_dim,
|
| 354 |
+
out_features=self.expanded_num_heads * self.head_dim,
|
| 355 |
+
rank=self.kv_proj_rank,
|
| 356 |
+
act_fn=act_fn,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
if self.kv_learnable_residual:
|
| 360 |
+
# Learnable mixing matrices initialized to mimic repeat_kv
|
| 361 |
+
eye_k = torch.eye(self.num_k_heads)
|
| 362 |
+
ones_k = torch.ones((self.num_k_groups, 1))
|
| 363 |
+
self.k_rep = nn.Parameter(
|
| 364 |
+
torch.kron(eye_k, ones_k)
|
| 365 |
+
) # [expanded_num_heads, num_k_heads]
|
| 366 |
+
|
| 367 |
+
eye_v = torch.eye(self.num_v_heads)
|
| 368 |
+
ones_v = torch.ones((self.num_v_groups, 1))
|
| 369 |
+
self.v_rep = nn.Parameter(
|
| 370 |
+
torch.kron(eye_v, ones_v)
|
| 371 |
+
) # [expanded_num_heads, num_v_heads]
|
| 372 |
+
|
| 373 |
+
def _expand_kv(self, k: Tensor, v: Tensor) -> Tuple[Tensor, Tensor]:
|
| 374 |
+
"""
|
| 375 |
+
Expand k and v from their native head counts to expanded_num_heads.
|
| 376 |
+
|
| 377 |
+
Three modes:
|
| 378 |
+
1. kv_proj_rank + kv_learnable_residual: learnable mixing residual + low-rank projection
|
| 379 |
+
2. kv_proj_rank without learnable residual: plain repeat residual + low-rank projection
|
| 380 |
+
3. No projection: simple repeat (or rearrange if groups == 1). This is the standard GQA repeat.
|
| 381 |
+
|
| 382 |
+
Args:
|
| 383 |
+
k: [B, L, Dk] raw key tensor (flat, not yet reshaped to heads)
|
| 384 |
+
v: [B, L, Dv] raw value tensor (flat, not yet reshaped to heads)
|
| 385 |
+
|
| 386 |
+
Returns:
|
| 387 |
+
k: [B, L, H, D] expanded keys
|
| 388 |
+
v: [B, L, H, D] expanded values
|
| 389 |
+
"""
|
| 390 |
+
if self.kv_proj_rank is not None and (
|
| 391 |
+
self.num_k_groups > 1 or self.num_v_groups > 1
|
| 392 |
+
):
|
| 393 |
+
# Build residual
|
| 394 |
+
if self.kv_learnable_residual:
|
| 395 |
+
k_heads = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
|
| 396 |
+
k_res = torch.einsum("eh,blhd->bled", self.k_rep, k_heads)
|
| 397 |
+
v_heads = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
|
| 398 |
+
v_res = torch.einsum("eh,blhd->bled", self.v_rep, v_heads)
|
| 399 |
+
else:
|
| 400 |
+
k_res = repeat(
|
| 401 |
+
rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads),
|
| 402 |
+
"... h d -> ... (h g) d",
|
| 403 |
+
g=self.num_k_groups,
|
| 404 |
+
)
|
| 405 |
+
v_res = repeat(
|
| 406 |
+
rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads),
|
| 407 |
+
"... h d -> ... (h g) d",
|
| 408 |
+
g=self.num_v_groups,
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
# Low-rank projection to expanded dim + add residual
|
| 412 |
+
k = (
|
| 413 |
+
rearrange(
|
| 414 |
+
self.proj_k(k), "... (h d) -> ... h d", h=self.expanded_num_heads
|
| 415 |
+
)
|
| 416 |
+
+ k_res
|
| 417 |
+
)
|
| 418 |
+
v = (
|
| 419 |
+
rearrange(
|
| 420 |
+
self.proj_v(v), "... (h d) -> ... h d", h=self.expanded_num_heads
|
| 421 |
+
)
|
| 422 |
+
+ v_res
|
| 423 |
+
)
|
| 424 |
+
else:
|
| 425 |
+
# Plain rearrange + repeat
|
| 426 |
+
k = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
|
| 427 |
+
v = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
|
| 428 |
+
if self.num_k_groups > 1:
|
| 429 |
+
k = repeat(k, "... h d -> ... (h g) d", g=self.num_k_groups)
|
| 430 |
+
if self.num_v_groups > 1:
|
| 431 |
+
v = repeat(v, "... h d -> ... (h g) d", g=self.num_v_groups)
|
| 432 |
+
|
| 433 |
+
return k, v
|
| 434 |
+
|
| 435 |
+
def forward(
|
| 436 |
+
self,
|
| 437 |
+
hidden_states: Tensor,
|
| 438 |
+
attention_mask: Optional[Tensor] = None,
|
| 439 |
+
past_key_values: Optional[Cache] = None,
|
| 440 |
+
use_cache: Optional[bool] = False,
|
| 441 |
+
output_attentions: Optional[bool] = False,
|
| 442 |
+
**kwargs,
|
| 443 |
+
) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]:
|
| 444 |
+
"""
|
| 445 |
+
Sigma GKA forward pass with optional caching.
|
| 446 |
+
|
| 447 |
+
NOTE: We use the following variables for tensor shape hints:
|
| 448 |
+
- B: Input batch size
|
| 449 |
+
- L: Sequence length (full sequence length before SP distribution)
|
| 450 |
+
- Dh: Hidden dimension (self.hidden_size)
|
| 451 |
+
- H: Expanded number of heads (self.expanded_num_heads)
|
| 452 |
+
- Hq: Number of query heads (self.num_q_heads)
|
| 453 |
+
- Hk: Number of key heads (self.num_k_heads)
|
| 454 |
+
- Hv: Number of value heads (self.num_v_heads)
|
| 455 |
+
- D: Head dimension (self.head_dim)
|
| 456 |
+
- Dq: Query dimension (self.query_dim)
|
| 457 |
+
- Dk: Key dimension (self.key_dim)
|
| 458 |
+
- Dv: Value dimension (self.value_dim)
|
| 459 |
+
- Dexp: Expanded dimension (self.expanded_dim)
|
| 460 |
+
- C: Convolution size (self.conv_size)
|
| 461 |
+
- SP: Sequence parallel size. 1 if not using sequence parallel
|
| 462 |
+
|
| 463 |
+
- B_sp: Batch size after SP reordering. B_sp = B*2 if self.sequence_parallel_group else B_sp = B
|
| 464 |
+
- L_sp: Sequence length after SP reordering. L_sp = L/(SP*2) + C-1 if self.sequence_parallel_group else L_sp = L/SP
|
| 465 |
+
- Lp: Sequence length after SP reordering and conv padding removal. Lp = L/(SP*2) if self.sequence_parallel_group else Lp = L/SP
|
| 466 |
+
|
| 467 |
+
Args:
|
| 468 |
+
hidden_states: Input tensor with shape [B, L/SP, Dh].
|
| 469 |
+
attention_mask: Optional 0-1 mask. Not used.
|
| 470 |
+
past_key_values: Optional cache containing conv_state and recurrent_state
|
| 471 |
+
for inference. When provided, performs incremental decoding.
|
| 472 |
+
use_cache: Whether to return updated cache states. Defaults to False.
|
| 473 |
+
output_attentions: Whether to return attention weights (not used). Defaults to False.
|
| 474 |
+
**kwargs: Additional keyword arguments, may include cu_seqlens for packed sequences.
|
| 475 |
+
|
| 476 |
+
Returns:
|
| 477 |
+
Tuple of (output, attention_weights, past_key_values) where:
|
| 478 |
+
- output: Output tensor with same shape as hidden_states [B, L, Dh]
|
| 479 |
+
- attention_weights: None (not computed for GKA)
|
| 480 |
+
- past_key_values: Updated cache (same as input if provided, else None)
|
| 481 |
+
"""
|
| 482 |
+
# During inference, if attention_mask is not None, throw an error
|
| 483 |
+
if attention_mask is not None and not self.training:
|
| 484 |
+
raise NotImplementedError(
|
| 485 |
+
"Sigma GKA kernels currently do not support varlen inputs."
|
| 486 |
+
)
|
| 487 |
+
|
| 488 |
+
batch_size, q_len, _ = hidden_states.shape
|
| 489 |
+
# print(hidden_states.dtype)
|
| 490 |
+
|
| 491 |
+
last_state = None
|
| 492 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 493 |
+
last_state = past_key_values[self.layer_idx]
|
| 494 |
+
|
| 495 |
+
cu_seqlens = kwargs.get("cu_seqlens", None)
|
| 496 |
+
|
| 497 |
+
# Apply P2P reordering to hidden_states first for custom zigzag SP
|
| 498 |
+
# if self.sequence_parallel_group is not None:
|
| 499 |
+
# assert (
|
| 500 |
+
# cu_seqlens is None
|
| 501 |
+
# ), "SP not implemented for cu_seqlens (variable length samples in a batch)."
|
| 502 |
+
# sp_size = torch.distributed.get_world_size(
|
| 503 |
+
# group=self.sequence_parallel_group
|
| 504 |
+
# )
|
| 505 |
+
# sp_rank = torch.distributed.get_rank(group=self.sequence_parallel_group)
|
| 506 |
+
|
| 507 |
+
# hidden_states = reorder_for_ssm_p2p(
|
| 508 |
+
# hidden_states,
|
| 509 |
+
# self.sequence_parallel_group,
|
| 510 |
+
# torch.cuda.Stream(),
|
| 511 |
+
# sp_size,
|
| 512 |
+
# sp_rank,
|
| 513 |
+
# self.conv_size,
|
| 514 |
+
# )
|
| 515 |
+
# # hidden_states: [B_sp, L_sp, Dh]
|
| 516 |
+
|
| 517 |
+
# Apply projections and convolutions
|
| 518 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 519 |
+
if last_state is not None:
|
| 520 |
+
conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"]
|
| 521 |
+
|
| 522 |
+
q, conv_state_q = self.q_conv1d(
|
| 523 |
+
x=self.q_proj(hidden_states),
|
| 524 |
+
cache=conv_state_q,
|
| 525 |
+
output_final_state=use_cache,
|
| 526 |
+
cu_seqlens=cu_seqlens,
|
| 527 |
+
)
|
| 528 |
+
# q: [B_sp, L_sp, Dq]
|
| 529 |
+
# conv_state_q: [B, Dq, C] or None
|
| 530 |
+
|
| 531 |
+
k, conv_state_k = self.k_conv1d(
|
| 532 |
+
x=self.k_proj(hidden_states),
|
| 533 |
+
cache=conv_state_k,
|
| 534 |
+
output_final_state=use_cache,
|
| 535 |
+
cu_seqlens=cu_seqlens,
|
| 536 |
+
)
|
| 537 |
+
# k: [B_sp, L_sp, Dk]
|
| 538 |
+
# conv_state_k: [B, Dk, C] or None
|
| 539 |
+
|
| 540 |
+
if self.use_v_conv:
|
| 541 |
+
v, conv_state_v = self.v_conv1d(
|
| 542 |
+
x=self.v_proj(hidden_states),
|
| 543 |
+
cache=conv_state_v,
|
| 544 |
+
output_final_state=use_cache,
|
| 545 |
+
cu_seqlens=cu_seqlens,
|
| 546 |
+
)
|
| 547 |
+
# v: [B_sp, L_sp, Dv]
|
| 548 |
+
# conv_state_v: [B, Dv, C] or None
|
| 549 |
+
else:
|
| 550 |
+
v = self.v_proj(hidden_states) # [B_sp, L_sp, Dv]
|
| 551 |
+
conv_state_v = None
|
| 552 |
+
|
| 553 |
+
# Remove padding for custom zigzag SP (first conv_size-1 tokens added by P2P)
|
| 554 |
+
# if self.sequence_parallel_group is not None:
|
| 555 |
+
# q = q[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dq]
|
| 556 |
+
# k = k[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dk]
|
| 557 |
+
# if self.use_v_conv:
|
| 558 |
+
# v = v[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dv]
|
| 559 |
+
# # Also remove padding from hidden_states so beta/alpha/g/gk match seq length
|
| 560 |
+
# hidden_states = hidden_states[
|
| 561 |
+
# :, self.conv_size - 1 :, :
|
| 562 |
+
# ].contiguous() # [B_sp, Lp, Dh]
|
| 563 |
+
|
| 564 |
+
# Reshape q to heads and expand k/v (handles projection + residual if configured)
|
| 565 |
+
q = rearrange(
|
| 566 |
+
q, "... (h d) -> ... h d", h=self.num_q_heads
|
| 567 |
+
) # [B_sp, Lp, Hq, D]
|
| 568 |
+
k, v = self._expand_kv(k, v) # [B_sp, Lp, H, D] each
|
| 569 |
+
|
| 570 |
+
# Apply GQA/head repeats for q to match expanded_num_heads
|
| 571 |
+
if self.num_q_groups > 1:
|
| 572 |
+
q = repeat(q, "... h d -> ... (h g) d", g=self.num_q_groups)
|
| 573 |
+
# q: [B_sp, Lp, H, D]
|
| 574 |
+
|
| 575 |
+
# Get recurrent state from cache
|
| 576 |
+
last_h_kk, last_h_kv = (
|
| 577 |
+
last_state["recurrent_state"] if last_state is not None else (None, None)
|
| 578 |
+
)
|
| 579 |
+
|
| 580 |
+
# Normalize queries and keys,question q k 需要norm嘛,没有明确感觉需要
|
| 581 |
+
qk_norm_eps = 1e-6
|
| 582 |
+
q = q / (
|
| 583 |
+
torch.linalg.vector_norm(q, dim=-1, keepdim=True).to(q) + qk_norm_eps
|
| 584 |
+
) # [B_sp, Lp, H, D]
|
| 585 |
+
k = k / (
|
| 586 |
+
torch.linalg.vector_norm(k, dim=-1, keepdim=True).to(k) + qk_norm_eps
|
| 587 |
+
) # [B_sp, Lp, H, D]
|
| 588 |
+
|
| 589 |
+
# Apply beta gating if enabled
|
| 590 |
+
if self.use_beta_gate:
|
| 591 |
+
beta = self.b_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 592 |
+
eps = 1e-6
|
| 593 |
+
k = ((beta[..., None] + eps) * k).to(k.dtype) # [B_sp, Lp, H, D]
|
| 594 |
+
v = ((beta[..., None] + eps) * v).to(v.dtype) # [B_sp, Lp, H, D]
|
| 595 |
+
|
| 596 |
+
# Compute alpha connection parameter
|
| 597 |
+
if self.use_alpha_connection:
|
| 598 |
+
alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 599 |
+
else:
|
| 600 |
+
alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H]
|
| 601 |
+
|
| 602 |
+
# Compute forgetting gate
|
| 603 |
+
if self.use_forgetting_gate:
|
| 604 |
+
g = -self.A_log.float().exp() * F.softplus(
|
| 605 |
+
self.a_proj(hidden_states).float() + self.dt_bias
|
| 606 |
+
) # [B_sp, Lp, H]
|
| 607 |
+
else:
|
| 608 |
+
g = None
|
| 609 |
+
|
| 610 |
+
gk = g if self.use_forgetting_gate_kk else None
|
| 611 |
+
|
| 612 |
+
# Backward kernels require sequence length to be divisible by chunk size
|
| 613 |
+
if gk is None and self.training:
|
| 614 |
+
seq_len = hidden_states.shape[1]
|
| 615 |
+
assert (
|
| 616 |
+
seq_len % self.chunk_size == 0
|
| 617 |
+
), f"Triton chunk size must divide the sequence length. Got seq_len={seq_len}, chunk_size={self.chunk_size}"
|
| 618 |
+
# sig_learnable_abc = (2*torch.sigmoid(self.learnable_abc)-1.0).to(torch.float32)
|
| 619 |
+
# sig_learnable_abc = torch.tanh(self.learnable_abc).to(torch.float32)
|
| 620 |
+
sig_learnable_abc = self.learnable_abc.to(torch.float32)
|
| 621 |
+
if last_state is None:
|
| 622 |
+
o, h_kk, h_kv = phi_kkt_solve_gla(
|
| 623 |
+
q=q,
|
| 624 |
+
k=k,
|
| 625 |
+
v=v,
|
| 626 |
+
alpha=alpha,###this alpha_connect
|
| 627 |
+
g=g,
|
| 628 |
+
gk=gk,
|
| 629 |
+
gla_scale=self.gla_scale,
|
| 630 |
+
learnable_abc=sig_learnable_abc.to(torch.float32),
|
| 631 |
+
chunk_size=self.chunk_size,
|
| 632 |
+
)
|
| 633 |
+
else:
|
| 634 |
+
o, h_kk, h_kv = phi_kkt_decoding_one_step(
|
| 635 |
+
q=q,
|
| 636 |
+
k=k,
|
| 637 |
+
v=v,
|
| 638 |
+
alpha=alpha,
|
| 639 |
+
g=g,
|
| 640 |
+
gk=gk,
|
| 641 |
+
gla_scale=self.gla_scale,
|
| 642 |
+
learnable_abc=sig_learnable_abc.to(torch.float32),
|
| 643 |
+
prev_h_kk=last_h_kk,
|
| 644 |
+
prev_h_kv=last_h_kv,
|
| 645 |
+
)
|
| 646 |
+
|
| 647 |
+
# Update cache
|
| 648 |
+
if past_key_values is not None:
|
| 649 |
+
past_key_values.update(
|
| 650 |
+
recurrent_state=(h_kk, h_kv),
|
| 651 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v),
|
| 652 |
+
layer_idx=self.layer_idx,
|
| 653 |
+
offset=q_len,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
# Apply output gating and normalization
|
| 657 |
+
if self.use_gate:
|
| 658 |
+
g = rearrange(
|
| 659 |
+
self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim
|
| 660 |
+
) # [B_sp, Lp, H, D]
|
| 661 |
+
o = self.o_norm(o, g) # [B_sp, Lp, H, D]
|
| 662 |
+
else:
|
| 663 |
+
o = self.o_norm(o) # [B_sp, Lp, H, D]
|
| 664 |
+
|
| 665 |
+
# Reshape and project output
|
| 666 |
+
o = rearrange(o, "b t h d -> b t (h d)") # [B_sp, Lp, Dexp]
|
| 667 |
+
o = self.o_proj(o) # [B_sp, Lp, Dh]
|
| 668 |
+
|
| 669 |
+
# Scatter sequence if using sequence parallel
|
| 670 |
+
# if self.sequence_parallel_group is not None:
|
| 671 |
+
# # Recombine zigzag chunks to contiguous
|
| 672 |
+
# bz, len_o, dim = o.shape
|
| 673 |
+
# if bz == 2:
|
| 674 |
+
# o = o.view(bz // 2, len_o * 2, dim)
|
| 675 |
+
# else:
|
| 676 |
+
# o = torch.cat([o[: bz // 2], o[bz // 2 :]], dim=1).contiguous()
|
| 677 |
+
# o: [B, L/SP, Dh]
|
| 678 |
+
|
| 679 |
+
return o, None, past_key_values
|
| 680 |
+
|
| 681 |
+
# #####我们的目标是使用(-1/2)求逆
|
| 682 |
+
# class SigmaGKANet(nn.Module):
|
| 683 |
+
# """
|
| 684 |
+
# Sigma GKA layer with Chebyshev solver and GQA support.
|
| 685 |
+
|
| 686 |
+
# Args:
|
| 687 |
+
# hidden_size: The hidden size of the input. Defaults to 2048.
|
| 688 |
+
# head_dim: The dimension of each head. Assumes q/k/v have the same head dimension.
|
| 689 |
+
# Defaults to 128.
|
| 690 |
+
# num_q_heads: The number of query heads. Defaults to 16.
|
| 691 |
+
# num_k_heads: The number of key heads for GQA. If None, defaults to num_q_heads.
|
| 692 |
+
# Defaults to None.
|
| 693 |
+
# num_v_heads: The number of value heads for GQA. If None, defaults to num_q_heads.
|
| 694 |
+
# Defaults to None.
|
| 695 |
+
# use_beta_gate: Whether to use beta gating mechanism. Defaults to True.
|
| 696 |
+
# use_alpha_connection: Whether to use alpha connection for residual paths. Defaults to True.
|
| 697 |
+
# use_v_conv: Whether to apply convolution to value vectors. Defaults to True.
|
| 698 |
+
# use_forgetting_gate: Whether to use forgetting gate mechanism. Defaults to True.
|
| 699 |
+
# use_forgetting_gate_kk: Whether to use forgetting gate for key-key interactions. Defaults to True.
|
| 700 |
+
# gla_rescale: Whether to apply GLA-style rescaling. Defaults to True.
|
| 701 |
+
# solver_type: Solver method. Currently, we only support "chebyshev". Defaults to "chebyshev".
|
| 702 |
+
# bp_lambda: Whether to backpropagate through lambda parameters. Defaults to True.
|
| 703 |
+
# num_iter: Number of iterations for iterative solvers. Defaults to 30.
|
| 704 |
+
# ridge_strength: Regularization strength for ridge regression. Defaults to 0.02.
|
| 705 |
+
# use_gate: Whether to use output gating mechanism. Defaults to True.
|
| 706 |
+
# conv_size: Size of the convolution kernel. Defaults to 4.
|
| 707 |
+
# layer_idx: The index of the layer. Used for caching during inference. Defaults to None.
|
| 708 |
+
# norm_eps: The epsilon value for the normalization layer. Defaults to 1e-6.
|
| 709 |
+
# chunk_size: Size of chunks for parallel processing in Triton kernels. Defaults to 64.
|
| 710 |
+
# kv_proj_rank: Rank for low-rank KV projection to expand K/V heads. If None, uses
|
| 711 |
+
# standard GQA repeat. Defaults to None.
|
| 712 |
+
# kv_learnable_residual: Whether to use a learnable residual for the KV head expansion
|
| 713 |
+
# instead of a fixed repeat. Only used when kv_proj_rank is set. Defaults to False.
|
| 714 |
+
# learnable_abc: Initial polynomial coefficients. Length 3 (abc) uses
|
| 715 |
+
# phi(H) ~ a I + b H/F + c H^2/F^2; length 4 (abcd) adds d H^3/F^3.
|
| 716 |
+
# Stored as an ``nn.Parameter`` of shape [H, 3] or [H, 4].
|
| 717 |
+
# Defaults to (1.0, -0.5, 0.375).
|
| 718 |
+
# random_init_abc: If True, initialize per-head coefficients independently instead of
|
| 719 |
+
# broadcasting ``learnable_abc`` to all heads. ``a, c`` are drawn from ``U(0, 1)``
|
| 720 |
+
# (positive) and ``b, d`` from ``U(-1, 0)`` (negative). Defaults to False.
|
| 721 |
+
# """
|
| 722 |
+
|
| 723 |
+
# def __init__(
|
| 724 |
+
# self,
|
| 725 |
+
# hidden_size: int = 2048,
|
| 726 |
+
# head_dim: int = 128,
|
| 727 |
+
# num_heads: int = 8,
|
| 728 |
+
# num_q_heads: Optional[int] = None,
|
| 729 |
+
# num_k_heads: Optional[int] = None,
|
| 730 |
+
# num_v_heads: Optional[int] = None,
|
| 731 |
+
# use_beta_gate: bool = True,
|
| 732 |
+
# use_alpha_connection: bool = True,
|
| 733 |
+
# use_v_conv: bool = True,
|
| 734 |
+
# use_forgetting_gate: bool = True,
|
| 735 |
+
# use_forgetting_gate_kk: bool = True,
|
| 736 |
+
# gla_rescale: bool = True,
|
| 737 |
+
# # solver_type: str = "chebyshev",
|
| 738 |
+
# bp_lambda: bool = True,
|
| 739 |
+
# num_iter: int = 30,
|
| 740 |
+
# ridge_strength: float = 0.02,
|
| 741 |
+
# use_gate: bool = False,
|
| 742 |
+
# conv_size: int = 4,
|
| 743 |
+
# layer_idx: Optional[int] = None,
|
| 744 |
+
# norm_eps: float = 1e-6,
|
| 745 |
+
# chunk_size: int = 64,
|
| 746 |
+
# kv_proj_rank: Optional[int] = None,
|
| 747 |
+
# kv_learnable_residual: bool = False,
|
| 748 |
+
# learnable_abc: Tuple[float, ...] = (2.3424, -2.5663, 1.2652),
|
| 749 |
+
# # learnable_abc: Tuple[float, ...] = (2.1111, -1.5556, 0.4444),
|
| 750 |
+
# # learnable_abc: Tuple[float, ...] = (2.0, -2.0, 0.5,-0.125),
|
| 751 |
+
# random_init_abc: bool = True,
|
| 752 |
+
# abc_requires_grad: bool = True,
|
| 753 |
+
# **kwargs,
|
| 754 |
+
# ) -> None:
|
| 755 |
+
# super().__init__()
|
| 756 |
+
|
| 757 |
+
# # assert solver_type == "chebyshev", f"Received {solver_type=}. Currently, Sigma GKA only supports 'chebyshev' solver."
|
| 758 |
+
|
| 759 |
+
# self.hidden_size = hidden_size
|
| 760 |
+
|
| 761 |
+
# self.use_gate = use_gate
|
| 762 |
+
# self.conv_size = conv_size
|
| 763 |
+
# self.sequence_parallel_group = None
|
| 764 |
+
# self.chunk_size = chunk_size
|
| 765 |
+
|
| 766 |
+
# self.head_dim = head_dim
|
| 767 |
+
# self.num_heads = num_heads
|
| 768 |
+
# self.num_q_heads = num_q_heads if num_q_heads is not None else num_heads
|
| 769 |
+
# self.num_k_heads = num_k_heads if num_k_heads is not None else num_heads
|
| 770 |
+
# self.num_v_heads = num_v_heads if num_v_heads is not None else num_heads
|
| 771 |
+
# self.expanded_num_heads = max(
|
| 772 |
+
# self.num_q_heads, self.num_k_heads, self.num_v_heads
|
| 773 |
+
# )
|
| 774 |
+
# self.num_q_groups = self.expanded_num_heads // self.num_q_heads
|
| 775 |
+
# self.num_k_groups = self.expanded_num_heads // self.num_k_heads
|
| 776 |
+
# self.num_v_groups = self.expanded_num_heads // self.num_v_heads
|
| 777 |
+
|
| 778 |
+
# self.query_dim = self.num_q_heads * self.head_dim
|
| 779 |
+
# self.key_dim = self.num_k_heads * self.head_dim
|
| 780 |
+
# self.value_dim = self.num_v_heads * self.head_dim
|
| 781 |
+
# self.expanded_dim = self.expanded_num_heads * self.head_dim
|
| 782 |
+
|
| 783 |
+
# self.layer_idx = layer_idx
|
| 784 |
+
|
| 785 |
+
# self.ridge_strength = ridge_strength
|
| 786 |
+
# self.num_iter = num_iter
|
| 787 |
+
# self.use_beta_gate = use_beta_gate
|
| 788 |
+
# self.use_alpha_connection = use_alpha_connection
|
| 789 |
+
# # self.solver_type = solver_type
|
| 790 |
+
# self.bp_lambda = bp_lambda
|
| 791 |
+
# self.use_v_conv = use_v_conv
|
| 792 |
+
# self.use_forgetting_gate = use_forgetting_gate
|
| 793 |
+
# self.use_forgetting_gate_kk = use_forgetting_gate_kk
|
| 794 |
+
|
| 795 |
+
# if gla_rescale:
|
| 796 |
+
# self.gla_scale = self.head_dim ** -0.5
|
| 797 |
+
# else:
|
| 798 |
+
# self.gla_scale = 1.0
|
| 799 |
+
|
| 800 |
+
# # Projection layers
|
| 801 |
+
# self.q_proj = nn.Linear(hidden_size, self.query_dim, bias=False)
|
| 802 |
+
# self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 803 |
+
# self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 804 |
+
|
| 805 |
+
# self.a_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=False)
|
| 806 |
+
|
| 807 |
+
# self.b_proj = (
|
| 808 |
+
# nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
|
| 809 |
+
# if self.use_beta_gate
|
| 810 |
+
# else None
|
| 811 |
+
# )
|
| 812 |
+
|
| 813 |
+
# if self.use_alpha_connection:
|
| 814 |
+
# self.alpha_proj = nn.Linear(hidden_size, self.expanded_num_heads, bias=True)
|
| 815 |
+
|
| 816 |
+
# # Initialize A parameter (log scale)
|
| 817 |
+
# A = torch.empty(self.expanded_num_heads, dtype=torch.float32).uniform_(0, 16)
|
| 818 |
+
# self.A_log = nn.Parameter(torch.log(A))
|
| 819 |
+
# self.A_log._no_weight_decay = True
|
| 820 |
+
|
| 821 |
+
# # Initialize dt bias parameter
|
| 822 |
+
# dt_min = 0.001
|
| 823 |
+
# dt_max = 0.1
|
| 824 |
+
# dt_init_floor = 1e-4
|
| 825 |
+
# dt = torch.exp(
|
| 826 |
+
# torch.rand(self.expanded_num_heads) * (math.log(dt_max) - math.log(dt_min))
|
| 827 |
+
# + math.log(dt_min)
|
| 828 |
+
# )
|
| 829 |
+
# dt = torch.clamp(dt, min=dt_init_floor)
|
| 830 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 831 |
+
# inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 832 |
+
|
| 833 |
+
# self.dt_bias = nn.Parameter(inv_dt)
|
| 834 |
+
# self.dt_bias._no_weight_decay = True
|
| 835 |
+
|
| 836 |
+
# # Per-head polynomial coefficients: [H, 3] abc or [H, 4] abcd
|
| 837 |
+
# init_abc = torch.tensor(learnable_abc, dtype=torch.float32).reshape(-1)
|
| 838 |
+
# n_coeff = int(init_abc.numel())
|
| 839 |
+
# if n_coeff not in (3, 4):
|
| 840 |
+
# raise ValueError(
|
| 841 |
+
# f"learnable_abc must have 3 (abc) or 4 (abcd) coefficients, got {n_coeff}"
|
| 842 |
+
# )
|
| 843 |
+
# self.learnable_abc = nn.Parameter(
|
| 844 |
+
# init_abc.unsqueeze(0).expand(self.expanded_num_heads, n_coeff).contiguous()
|
| 845 |
+
# )
|
| 846 |
+
# if random_init_abc:
|
| 847 |
+
# # a, c ~ U(0, 1); b, d ~ U(-1, 0)
|
| 848 |
+
# signs = torch.tensor([1.0, -1.0, 1.0, -1.0][:n_coeff], dtype=torch.float32)
|
| 849 |
+
# self.learnable_abc = nn.Parameter(
|
| 850 |
+
# # 2*(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
|
| 851 |
+
# # (torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32) * signs).contiguous(), requires_grad=abc_requires_grad
|
| 852 |
+
# 2*(torch.rand(self.expanded_num_heads, n_coeff, dtype=torch.float32).contiguous()-1.0), requires_grad=abc_requires_grad
|
| 853 |
+
# )
|
| 854 |
+
# print("random init abc")
|
| 855 |
+
# print(self.learnable_abc)
|
| 856 |
+
# print(self.learnable_abc.requires_grad)
|
| 857 |
+
# else:
|
| 858 |
+
# print("not random init abc")
|
| 859 |
+
# print(self.learnable_abc)
|
| 860 |
+
# print(self.learnable_abc.requires_grad)
|
| 861 |
+
# self.learnable_abc._no_weight_decay = True
|
| 862 |
+
|
| 863 |
+
# # Short convolution layers
|
| 864 |
+
# self.conv_size = conv_size
|
| 865 |
+
# self.q_conv1d = ShortConvolution(
|
| 866 |
+
# hidden_size=self.query_dim, kernel_size=conv_size, activation="silu"
|
| 867 |
+
# )
|
| 868 |
+
# self.k_conv1d = ShortConvolution(
|
| 869 |
+
# hidden_size=self.key_dim, kernel_size=conv_size, activation="silu"
|
| 870 |
+
# )
|
| 871 |
+
# if self.use_v_conv:
|
| 872 |
+
# self.v_conv1d = ShortConvolution(
|
| 873 |
+
# hidden_size=self.value_dim, kernel_size=conv_size, activation="silu"
|
| 874 |
+
# )
|
| 875 |
+
|
| 876 |
+
# # Output gating and normalization
|
| 877 |
+
# if use_gate:
|
| 878 |
+
# self.g_proj = nn.Linear(hidden_size, self.expanded_dim, bias=False)
|
| 879 |
+
# self.o_norm = FusedRMSNormGated(self.head_dim, eps=norm_eps)
|
| 880 |
+
# else:
|
| 881 |
+
# self.o_norm = RMSNorm(self.head_dim, eps=norm_eps)
|
| 882 |
+
# self.o_proj = nn.Linear(self.expanded_dim, hidden_size, bias=False)
|
| 883 |
+
|
| 884 |
+
# # Optional KV projection for GQA
|
| 885 |
+
# self.kv_proj_rank = kv_proj_rank
|
| 886 |
+
# self.kv_learnable_residual = kv_learnable_residual
|
| 887 |
+
# if self.kv_proj_rank is not None:
|
| 888 |
+
# act_fn = nn.SiLU()
|
| 889 |
+
# self.proj_k = LinearLowRank(
|
| 890 |
+
# in_features=self.key_dim,
|
| 891 |
+
# out_features=self.expanded_num_heads * self.head_dim,
|
| 892 |
+
# rank=self.kv_proj_rank,
|
| 893 |
+
# act_fn=act_fn,
|
| 894 |
+
# )
|
| 895 |
+
# self.proj_v = LinearLowRank(
|
| 896 |
+
# in_features=self.value_dim,
|
| 897 |
+
# out_features=self.expanded_num_heads * self.head_dim,
|
| 898 |
+
# rank=self.kv_proj_rank,
|
| 899 |
+
# act_fn=act_fn,
|
| 900 |
+
# )
|
| 901 |
+
|
| 902 |
+
# if self.kv_learnable_residual:
|
| 903 |
+
# # Learnable mixing matrices initialized to mimic repeat_kv
|
| 904 |
+
# eye_k = torch.eye(self.num_k_heads)
|
| 905 |
+
# ones_k = torch.ones((self.num_k_groups, 1))
|
| 906 |
+
# self.k_rep = nn.Parameter(
|
| 907 |
+
# torch.kron(eye_k, ones_k)
|
| 908 |
+
# ) # [expanded_num_heads, num_k_heads]
|
| 909 |
+
|
| 910 |
+
# eye_v = torch.eye(self.num_v_heads)
|
| 911 |
+
# ones_v = torch.ones((self.num_v_groups, 1))
|
| 912 |
+
# self.v_rep = nn.Parameter(
|
| 913 |
+
# torch.kron(eye_v, ones_v)
|
| 914 |
+
# ) # [expanded_num_heads, num_v_heads]
|
| 915 |
+
|
| 916 |
+
# def _expand_kv(self, k: Tensor, v: Tensor) -> Tuple[Tensor, Tensor]:
|
| 917 |
+
# """
|
| 918 |
+
# Expand k and v from their native head counts to expanded_num_heads.
|
| 919 |
+
|
| 920 |
+
# Three modes:
|
| 921 |
+
# 1. kv_proj_rank + kv_learnable_residual: learnable mixing residual + low-rank projection
|
| 922 |
+
# 2. kv_proj_rank without learnable residual: plain repeat residual + low-rank projection
|
| 923 |
+
# 3. No projection: simple repeat (or rearrange if groups == 1). This is the standard GQA repeat.
|
| 924 |
+
|
| 925 |
+
# Args:
|
| 926 |
+
# k: [B, L, Dk] raw key tensor (flat, not yet reshaped to heads)
|
| 927 |
+
# v: [B, L, Dv] raw value tensor (flat, not yet reshaped to heads)
|
| 928 |
+
|
| 929 |
+
# Returns:
|
| 930 |
+
# k: [B, L, H, D] expanded keys
|
| 931 |
+
# v: [B, L, H, D] expanded values
|
| 932 |
+
# """
|
| 933 |
+
# if self.kv_proj_rank is not None and (
|
| 934 |
+
# self.num_k_groups > 1 or self.num_v_groups > 1
|
| 935 |
+
# ):
|
| 936 |
+
# # Build residual
|
| 937 |
+
# if self.kv_learnable_residual:
|
| 938 |
+
# k_heads = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
|
| 939 |
+
# k_res = torch.einsum("eh,blhd->bled", self.k_rep, k_heads)
|
| 940 |
+
# v_heads = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
|
| 941 |
+
# v_res = torch.einsum("eh,blhd->bled", self.v_rep, v_heads)
|
| 942 |
+
# else:
|
| 943 |
+
# k_res = repeat(
|
| 944 |
+
# rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads),
|
| 945 |
+
# "... h d -> ... (h g) d",
|
| 946 |
+
# g=self.num_k_groups,
|
| 947 |
+
# )
|
| 948 |
+
# v_res = repeat(
|
| 949 |
+
# rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads),
|
| 950 |
+
# "... h d -> ... (h g) d",
|
| 951 |
+
# g=self.num_v_groups,
|
| 952 |
+
# )
|
| 953 |
+
|
| 954 |
+
# # Low-rank projection to expanded dim + add residual
|
| 955 |
+
# k = (
|
| 956 |
+
# rearrange(
|
| 957 |
+
# self.proj_k(k), "... (h d) -> ... h d", h=self.expanded_num_heads
|
| 958 |
+
# )
|
| 959 |
+
# + k_res
|
| 960 |
+
# )
|
| 961 |
+
# v = (
|
| 962 |
+
# rearrange(
|
| 963 |
+
# self.proj_v(v), "... (h d) -> ... h d", h=self.expanded_num_heads
|
| 964 |
+
# )
|
| 965 |
+
# + v_res
|
| 966 |
+
# )
|
| 967 |
+
# else:
|
| 968 |
+
# # Plain rearrange + repeat
|
| 969 |
+
# k = rearrange(k, "... (h d) -> ... h d", h=self.num_k_heads)
|
| 970 |
+
# v = rearrange(v, "... (h d) -> ... h d", h=self.num_v_heads)
|
| 971 |
+
# if self.num_k_groups > 1:
|
| 972 |
+
# k = repeat(k, "... h d -> ... (h g) d", g=self.num_k_groups)
|
| 973 |
+
# if self.num_v_groups > 1:
|
| 974 |
+
# v = repeat(v, "... h d -> ... (h g) d", g=self.num_v_groups)
|
| 975 |
+
|
| 976 |
+
# return k, v
|
| 977 |
+
|
| 978 |
+
# def forward(
|
| 979 |
+
# self,
|
| 980 |
+
# hidden_states: Tensor,
|
| 981 |
+
# attention_mask: Optional[Tensor] = None,
|
| 982 |
+
# past_key_values: Optional[Cache] = None,
|
| 983 |
+
# use_cache: Optional[bool] = False,
|
| 984 |
+
# output_attentions: Optional[bool] = False,
|
| 985 |
+
# **kwargs,
|
| 986 |
+
# ) -> Tuple[Tensor, Optional[Tensor], Optional[Cache]]:
|
| 987 |
+
# """
|
| 988 |
+
# Sigma GKA forward pass with optional caching.
|
| 989 |
+
|
| 990 |
+
# NOTE: We use the following variables for tensor shape hints:
|
| 991 |
+
# - B: Input batch size
|
| 992 |
+
# - L: Sequence length (full sequence length before SP distribution)
|
| 993 |
+
# - Dh: Hidden dimension (self.hidden_size)
|
| 994 |
+
# - H: Expanded number of heads (self.expanded_num_heads)
|
| 995 |
+
# - Hq: Number of query heads (self.num_q_heads)
|
| 996 |
+
# - Hk: Number of key heads (self.num_k_heads)
|
| 997 |
+
# - Hv: Number of value heads (self.num_v_heads)
|
| 998 |
+
# - D: Head dimension (self.head_dim)
|
| 999 |
+
# - Dq: Query dimension (self.query_dim)
|
| 1000 |
+
# - Dk: Key dimension (self.key_dim)
|
| 1001 |
+
# - Dv: Value dimension (self.value_dim)
|
| 1002 |
+
# - Dexp: Expanded dimension (self.expanded_dim)
|
| 1003 |
+
# - C: Convolution size (self.conv_size)
|
| 1004 |
+
# - SP: Sequence parallel size. 1 if not using sequence parallel
|
| 1005 |
+
|
| 1006 |
+
# - B_sp: Batch size after SP reordering. B_sp = B*2 if self.sequence_parallel_group else B_sp = B
|
| 1007 |
+
# - L_sp: Sequence length after SP reordering. L_sp = L/(SP*2) + C-1 if self.sequence_parallel_group else L_sp = L/SP
|
| 1008 |
+
# - Lp: Sequence length after SP reordering and conv padding removal. Lp = L/(SP*2) if self.sequence_parallel_group else Lp = L/SP
|
| 1009 |
+
|
| 1010 |
+
# Args:
|
| 1011 |
+
# hidden_states: Input tensor with shape [B, L/SP, Dh].
|
| 1012 |
+
# attention_mask: Optional 0-1 mask. Not used.
|
| 1013 |
+
# past_key_values: Optional cache containing conv_state and recurrent_state
|
| 1014 |
+
# for inference. When provided, performs incremental decoding.
|
| 1015 |
+
# use_cache: Whether to return updated cache states. Defaults to False.
|
| 1016 |
+
# output_attentions: Whether to return attention weights (not used). Defaults to False.
|
| 1017 |
+
# **kwargs: Additional keyword arguments, may include cu_seqlens for packed sequences.
|
| 1018 |
+
|
| 1019 |
+
# Returns:
|
| 1020 |
+
# Tuple of (output, attention_weights, past_key_values) where:
|
| 1021 |
+
# - output: Output tensor with same shape as hidden_states [B, L, Dh]
|
| 1022 |
+
# - attention_weights: None (not computed for GKA)
|
| 1023 |
+
# - past_key_values: Updated cache (same as input if provided, else None)
|
| 1024 |
+
# """
|
| 1025 |
+
# # During inference, if attention_mask is not None, throw an error
|
| 1026 |
+
# if attention_mask is not None and not self.training:
|
| 1027 |
+
# raise NotImplementedError(
|
| 1028 |
+
# "Sigma GKA kernels currently do not support varlen inputs."
|
| 1029 |
+
# )
|
| 1030 |
+
|
| 1031 |
+
# batch_size, q_len, _ = hidden_states.shape
|
| 1032 |
+
# # print(hidden_states.dtype)
|
| 1033 |
+
|
| 1034 |
+
# last_state = None
|
| 1035 |
+
# if past_key_values is not None:
|
| 1036 |
+
# last_state = past_key_values[self.layer_idx]
|
| 1037 |
+
|
| 1038 |
+
# cu_seqlens = kwargs.get("cu_seqlens", None)
|
| 1039 |
+
|
| 1040 |
+
# # Apply P2P reordering to hidden_states first for custom zigzag SP
|
| 1041 |
+
# # if self.sequence_parallel_group is not None:
|
| 1042 |
+
# # assert (
|
| 1043 |
+
# # cu_seqlens is None
|
| 1044 |
+
# # ), "SP not implemented for cu_seqlens (variable length samples in a batch)."
|
| 1045 |
+
# # sp_size = torch.distributed.get_world_size(
|
| 1046 |
+
# # group=self.sequence_parallel_group
|
| 1047 |
+
# # )
|
| 1048 |
+
# # sp_rank = torch.distributed.get_rank(group=self.sequence_parallel_group)
|
| 1049 |
+
|
| 1050 |
+
# # hidden_states = reorder_for_ssm_p2p(
|
| 1051 |
+
# # hidden_states,
|
| 1052 |
+
# # self.sequence_parallel_group,
|
| 1053 |
+
# # torch.cuda.Stream(),
|
| 1054 |
+
# # sp_size,
|
| 1055 |
+
# # sp_rank,
|
| 1056 |
+
# # self.conv_size,
|
| 1057 |
+
# # )
|
| 1058 |
+
# # # hidden_states: [B_sp, L_sp, Dh]
|
| 1059 |
+
|
| 1060 |
+
# # Apply projections and convolutions
|
| 1061 |
+
# conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 1062 |
+
# if last_state is not None:
|
| 1063 |
+
# conv_state_q, conv_state_k, conv_state_v = last_state["conv_state"]
|
| 1064 |
+
|
| 1065 |
+
# q, conv_state_q = self.q_conv1d(
|
| 1066 |
+
# x=self.q_proj(hidden_states),
|
| 1067 |
+
# cache=conv_state_q,
|
| 1068 |
+
# output_final_state=use_cache,
|
| 1069 |
+
# cu_seqlens=cu_seqlens,
|
| 1070 |
+
# )
|
| 1071 |
+
# # q: [B_sp, L_sp, Dq]
|
| 1072 |
+
# # conv_state_q: [B, Dq, C] or None
|
| 1073 |
+
|
| 1074 |
+
# k, conv_state_k = self.k_conv1d(
|
| 1075 |
+
# x=self.k_proj(hidden_states),
|
| 1076 |
+
# cache=conv_state_k,
|
| 1077 |
+
# output_final_state=use_cache,
|
| 1078 |
+
# cu_seqlens=cu_seqlens,
|
| 1079 |
+
# )
|
| 1080 |
+
# # k: [B_sp, L_sp, Dk]
|
| 1081 |
+
# # conv_state_k: [B, Dk, C] or None
|
| 1082 |
+
|
| 1083 |
+
# if self.use_v_conv:
|
| 1084 |
+
# v, conv_state_v = self.v_conv1d(
|
| 1085 |
+
# x=self.v_proj(hidden_states),
|
| 1086 |
+
# cache=conv_state_v,
|
| 1087 |
+
# output_final_state=use_cache,
|
| 1088 |
+
# cu_seqlens=cu_seqlens,
|
| 1089 |
+
# )
|
| 1090 |
+
# # v: [B_sp, L_sp, Dv]
|
| 1091 |
+
# # conv_state_v: [B, Dv, C] or None
|
| 1092 |
+
# else:
|
| 1093 |
+
# v = self.v_proj(hidden_states) # [B_sp, L_sp, Dv]
|
| 1094 |
+
# conv_state_v = None
|
| 1095 |
+
|
| 1096 |
+
# # Remove padding for custom zigzag SP (first conv_size-1 tokens added by P2P)
|
| 1097 |
+
# # if self.sequence_parallel_group is not None:
|
| 1098 |
+
# # q = q[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dq]
|
| 1099 |
+
# # k = k[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dk]
|
| 1100 |
+
# # if self.use_v_conv:
|
| 1101 |
+
# # v = v[:, self.conv_size - 1 :, :].contiguous() # [B_sp, Lp, Dv]
|
| 1102 |
+
# # # Also remove padding from hidden_states so beta/alpha/g/gk match seq length
|
| 1103 |
+
# # hidden_states = hidden_states[
|
| 1104 |
+
# # :, self.conv_size - 1 :, :
|
| 1105 |
+
# # ].contiguous() # [B_sp, Lp, Dh]
|
| 1106 |
+
|
| 1107 |
+
# # Reshape q to heads and expand k/v (handles projection + residual if configured)
|
| 1108 |
+
# q = rearrange(
|
| 1109 |
+
# q, "... (h d) -> ... h d", h=self.num_q_heads
|
| 1110 |
+
# ) # [B_sp, Lp, Hq, D]
|
| 1111 |
+
# k, v = self._expand_kv(k, v) # [B_sp, Lp, H, D] each
|
| 1112 |
+
|
| 1113 |
+
# # Apply GQA/head repeats for q to match expanded_num_heads
|
| 1114 |
+
# if self.num_q_groups > 1:
|
| 1115 |
+
# q = repeat(q, "... h d -> ... (h g) d", g=self.num_q_groups)
|
| 1116 |
+
# # q: [B_sp, Lp, H, D]
|
| 1117 |
+
|
| 1118 |
+
# # Get recurrent state from cache
|
| 1119 |
+
# last_h_kk, last_h_kv = (
|
| 1120 |
+
# last_state["recurrent_state"] if last_state is not None else (None, None)
|
| 1121 |
+
# )
|
| 1122 |
+
|
| 1123 |
+
# # Normalize queries and keys,question q k 需要norm嘛,没有明确感觉需要
|
| 1124 |
+
# qk_norm_eps = 1e-6
|
| 1125 |
+
# q = q / (
|
| 1126 |
+
# torch.linalg.vector_norm(q, dim=-1, keepdim=True).to(q) + qk_norm_eps
|
| 1127 |
+
# ) # [B_sp, Lp, H, D]
|
| 1128 |
+
# k = k / (
|
| 1129 |
+
# torch.linalg.vector_norm(k, dim=-1, keepdim=True).to(k) + qk_norm_eps
|
| 1130 |
+
# ) # [B_sp, Lp, H, D]
|
| 1131 |
+
|
| 1132 |
+
# # Apply beta gating if enabled
|
| 1133 |
+
# if self.use_beta_gate:
|
| 1134 |
+
# beta = self.b_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 1135 |
+
# eps = 1e-6
|
| 1136 |
+
# k = ((beta[..., None] + eps) * k).to(k.dtype) # [B_sp, Lp, H, D]
|
| 1137 |
+
# v = ((beta[..., None] + eps) * v).to(v.dtype) # [B_sp, Lp, H, D]
|
| 1138 |
+
|
| 1139 |
+
# # Compute alpha connection parameter
|
| 1140 |
+
# if self.use_alpha_connection:
|
| 1141 |
+
# alpha = self.alpha_proj(hidden_states).sigmoid() # [B_sp, Lp, H]
|
| 1142 |
+
# else:
|
| 1143 |
+
# alpha = torch.ones_like(q[..., 0]) # [B_sp, Lp, H]
|
| 1144 |
+
|
| 1145 |
+
# # Compute forgetting gate
|
| 1146 |
+
# if self.use_forgetting_gate:
|
| 1147 |
+
# g = -self.A_log.float().exp() * F.softplus(
|
| 1148 |
+
# self.a_proj(hidden_states).float() + self.dt_bias
|
| 1149 |
+
# ) # [B_sp, Lp, H]
|
| 1150 |
+
# else:
|
| 1151 |
+
# g = None
|
| 1152 |
+
|
| 1153 |
+
# gk = g if self.use_forgetting_gate_kk else None
|
| 1154 |
+
|
| 1155 |
+
# # Backward kernels require sequence length to be divisible by chunk size
|
| 1156 |
+
# if gk is None and self.training:
|
| 1157 |
+
# seq_len = hidden_states.shape[1]
|
| 1158 |
+
# assert (
|
| 1159 |
+
# seq_len % self.chunk_size == 0
|
| 1160 |
+
# ), f"Triton chunk size must divide the sequence length. Got seq_len={seq_len}, chunk_size={self.chunk_size}"
|
| 1161 |
+
# # sig_learnable_abc = (2*torch.sigmoid(self.learnable_abc)-1.0).to(torch.float32)
|
| 1162 |
+
# # sig_learnable_abc = torch.tanh(self.learnable_abc).to(torch.float32)
|
| 1163 |
+
# sig_learnable_abc = self.learnable_abc.to(torch.float32)
|
| 1164 |
+
# o, h_kk, h_kv = phi_kkt_solve_gla(
|
| 1165 |
+
# q=q,
|
| 1166 |
+
# k=k,
|
| 1167 |
+
# v=v,
|
| 1168 |
+
# alpha=alpha,###this alpha_connect
|
| 1169 |
+
# g=g,
|
| 1170 |
+
# gk=gk,
|
| 1171 |
+
# gla_scale=self.gla_scale,
|
| 1172 |
+
# learnable_abc=sig_learnable_abc.to(torch.float32),
|
| 1173 |
+
# chunk_size=self.chunk_size,
|
| 1174 |
+
# h0_kk=last_h_kk,
|
| 1175 |
+
# h0_kv=last_h_kv,
|
| 1176 |
+
# output_final_state=bool(use_cache),
|
| 1177 |
+
# )
|
| 1178 |
+
|
| 1179 |
+
# # Update cache
|
| 1180 |
+
# if past_key_values is not None:
|
| 1181 |
+
# past_key_values.update(
|
| 1182 |
+
# recurrent_state=(h_kk, h_kv),
|
| 1183 |
+
# conv_state=(conv_state_q, conv_state_k, conv_state_v),
|
| 1184 |
+
# layer_idx=self.layer_idx,
|
| 1185 |
+
# offset=q_len,
|
| 1186 |
+
# )
|
| 1187 |
+
|
| 1188 |
+
# # Apply output gating and normalization
|
| 1189 |
+
# if self.use_gate:
|
| 1190 |
+
# g = rearrange(
|
| 1191 |
+
# self.g_proj(hidden_states), "... (h d) -> ... h d", d=self.head_dim
|
| 1192 |
+
# ) # [B_sp, Lp, H, D]
|
| 1193 |
+
# o = self.o_norm(o, g) # [B_sp, Lp, H, D]
|
| 1194 |
+
# else:
|
| 1195 |
+
# o = self.o_norm(o) # [B_sp, Lp, H, D]
|
| 1196 |
+
|
| 1197 |
+
# # Reshape and project output
|
| 1198 |
+
# o = rearrange(o, "b t h d -> b t (h d)") # [B_sp, Lp, Dexp]
|
| 1199 |
+
# o = self.o_proj(o) # [B_sp, Lp, Dh]
|
| 1200 |
+
|
| 1201 |
+
# # Scatter sequence if using sequence parallel
|
| 1202 |
+
# # if self.sequence_parallel_group is not None:
|
| 1203 |
+
# # # Recombine zigzag chunks to contiguous
|
| 1204 |
+
# # bz, len_o, dim = o.shape
|
| 1205 |
+
# # if bz == 2:
|
| 1206 |
+
# # o = o.view(bz // 2, len_o * 2, dim)
|
| 1207 |
+
# # else:
|
| 1208 |
+
# # o = torch.cat([o[: bz // 2], o[bz // 2 :]], dim=1).contiguous()
|
| 1209 |
+
# # o: [B, L/SP, Dh]
|
| 1210 |
+
|
| 1211 |
+
# return o, None, past_key_values
|
| 1212 |
+
|
simple_gla.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
from einops import rearrange, repeat
|
| 12 |
+
|
| 13 |
+
from fla.modules import FusedRMSNormGated, RMSNorm, ShortConvolution
|
| 14 |
+
from fla.modules.activations import ACT2FN
|
| 15 |
+
from fla.ops.simple_gla import chunk_simple_gla, fused_recurrent_simple_gla
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from fla.models.utils import Cache
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SimpleGatedLinearAttention(nn.Module):
|
| 22 |
+
r"""
|
| 23 |
+
The layer implementaion for [Gated Linear Attention Transformers with Hardware-Efficient Training](https://arxiv.org/abs/2312.06635). # noqa
|
| 24 |
+
This layer calls the simplified GLA kernel in which the gating is head-wise instead of elementwise.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
mode (str, Optional):
|
| 28 |
+
Which GLA kernel to use.
|
| 29 |
+
Currently available: `chunk`.
|
| 30 |
+
Default: `chunk`.
|
| 31 |
+
hidden_size (int, Optional):
|
| 32 |
+
The hidden size of the input. Default: 1024.
|
| 33 |
+
expand_k (float, Optional):
|
| 34 |
+
The expansion ratio for the key dim. Default: 1.0.
|
| 35 |
+
expand_v (float, Optional):
|
| 36 |
+
The expansion ratio for the value dim. Default: 1.0.
|
| 37 |
+
num_heads (int, Optional):
|
| 38 |
+
The number of heads. Default: 4.
|
| 39 |
+
num_kv_heads (int, Optional):
|
| 40 |
+
The number of key/value heads, used for MQA. Default: None.
|
| 41 |
+
feature_map (str, Optional):
|
| 42 |
+
Feature map function applied to queries/keys. Default: None.
|
| 43 |
+
use_short_conv (bool, Optional):
|
| 44 |
+
Whether to use short convolutions. Default: `False`.
|
| 45 |
+
conv_size (int, Optional):
|
| 46 |
+
The kernel size of the short convolution, only used when `use_short_conv` is `True`. Default: 4.
|
| 47 |
+
conv_bias (bool, Optional):
|
| 48 |
+
Whether to use bias in the short convolution, only used when `use_short_conv` is `True`. Default: `False`.
|
| 49 |
+
gate_fn (str, Optional):
|
| 50 |
+
The activation function for the output gate. Default: `swish`.
|
| 51 |
+
elementwise_affine (bool, Optional):
|
| 52 |
+
If `True`, applies elementwise affine to LayerNorm with learnable parameters. Default: `True`.
|
| 53 |
+
norm_eps (float, Optional):
|
| 54 |
+
The epsilon value for the layernorm/rmsnorm layer. Default: 1e-5.
|
| 55 |
+
gate_logit_normalizer (int, Optional):
|
| 56 |
+
The normalizer for the gate logits, appied after `logsigmoid`. Default: 16.
|
| 57 |
+
fuse_norm (bool, Optional):
|
| 58 |
+
Whether to fuse the norm and the output gate for better memory footprint. Default: `True`.
|
| 59 |
+
layer_idx (int, Optional):
|
| 60 |
+
The index of the layer. Default: None.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
mode: str = 'chunk',
|
| 66 |
+
hidden_size: int = 1024,
|
| 67 |
+
expand_k: float = 1.,
|
| 68 |
+
expand_v: float = 1.,
|
| 69 |
+
num_heads: int = 4,
|
| 70 |
+
num_kv_heads: Optional[int] = None,
|
| 71 |
+
feature_map: Optional[str] = None,
|
| 72 |
+
use_short_conv: bool = True,
|
| 73 |
+
conv_size: int = 4,
|
| 74 |
+
conv_bias: bool = False,
|
| 75 |
+
gate_fn: str = 'swish',
|
| 76 |
+
elementwise_affine: Optional[bool] = True,
|
| 77 |
+
norm_eps: float = 1e-5,
|
| 78 |
+
gate_logit_normalizer: int = 16,
|
| 79 |
+
fuse_norm: bool = True,
|
| 80 |
+
layer_idx: int = None,
|
| 81 |
+
) -> SimpleGatedLinearAttention:
|
| 82 |
+
super().__init__()
|
| 83 |
+
|
| 84 |
+
self.mode = mode
|
| 85 |
+
self.hidden_size = hidden_size
|
| 86 |
+
self.expand_k = expand_k
|
| 87 |
+
self.expand_v = expand_v
|
| 88 |
+
self.num_heads = num_heads
|
| 89 |
+
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
| 90 |
+
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 91 |
+
self.feature_map_fn = ACT2FN[feature_map] if feature_map is not None else None
|
| 92 |
+
|
| 93 |
+
self.use_short_conv = use_short_conv
|
| 94 |
+
self.conv_size = conv_size
|
| 95 |
+
self.conv_bias = conv_bias
|
| 96 |
+
|
| 97 |
+
self.key_dim = int(hidden_size * expand_k)
|
| 98 |
+
self.value_dim = int(hidden_size * expand_v)
|
| 99 |
+
self.key_dim_per_group = self.key_dim // self.num_kv_groups
|
| 100 |
+
self.value_dim_per_group = self.value_dim // self.num_kv_groups
|
| 101 |
+
self.layer_idx = layer_idx
|
| 102 |
+
|
| 103 |
+
assert mode in ['chunk', "fused_recurrent"], f"Not supported mode `{mode}`."
|
| 104 |
+
assert self.key_dim % num_heads == 0, f"key dim must be divisible by num_heads of {num_heads}"
|
| 105 |
+
assert self.value_dim % num_heads == 0, f"value dim must be divisible by num_heads of {num_heads}"
|
| 106 |
+
|
| 107 |
+
self.head_k_dim = self.key_dim // num_heads
|
| 108 |
+
self.head_v_dim = self.value_dim // num_heads
|
| 109 |
+
|
| 110 |
+
self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
|
| 111 |
+
self.k_proj = nn.Linear(hidden_size, self.key_dim_per_group, bias=False)
|
| 112 |
+
self.v_proj = nn.Linear(hidden_size, self.value_dim_per_group, bias=False)
|
| 113 |
+
self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
|
| 114 |
+
|
| 115 |
+
if use_short_conv:
|
| 116 |
+
self.conv_size = conv_size
|
| 117 |
+
self.q_conv1d = ShortConvolution(
|
| 118 |
+
hidden_size=self.key_dim,
|
| 119 |
+
kernel_size=conv_size,
|
| 120 |
+
bias=conv_bias,
|
| 121 |
+
activation='silu',
|
| 122 |
+
)
|
| 123 |
+
self.k_conv1d = ShortConvolution(
|
| 124 |
+
hidden_size=self.key_dim_per_group,
|
| 125 |
+
kernel_size=conv_size,
|
| 126 |
+
bias=conv_bias,
|
| 127 |
+
activation='silu',
|
| 128 |
+
)
|
| 129 |
+
self.v_conv1d = ShortConvolution(
|
| 130 |
+
hidden_size=self.value_dim_per_group,
|
| 131 |
+
kernel_size=conv_size,
|
| 132 |
+
bias=conv_bias,
|
| 133 |
+
activation='silu',
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
self.gk_proj = nn.Linear(hidden_size, self.num_heads)
|
| 137 |
+
|
| 138 |
+
if gate_fn == 'swish' and fuse_norm:
|
| 139 |
+
self.g_norm_swish_gate = FusedRMSNormGated(
|
| 140 |
+
hidden_size=self.head_v_dim,
|
| 141 |
+
elementwise_affine=elementwise_affine,
|
| 142 |
+
eps=norm_eps
|
| 143 |
+
)
|
| 144 |
+
self.fuse_norm_and_gate = True
|
| 145 |
+
else:
|
| 146 |
+
self.fuse_norm_and_gate = False
|
| 147 |
+
self.g_norm = RMSNorm(
|
| 148 |
+
hidden_size=self.head_v_dim,
|
| 149 |
+
elementwise_affine=elementwise_affine,
|
| 150 |
+
eps=norm_eps
|
| 151 |
+
)
|
| 152 |
+
self.gate_fn = ACT2FN[gate_fn]
|
| 153 |
+
self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
|
| 154 |
+
|
| 155 |
+
self.gate_logit_normalizer = gate_logit_normalizer
|
| 156 |
+
|
| 157 |
+
def forward(
|
| 158 |
+
self,
|
| 159 |
+
hidden_states: torch.Tensor,
|
| 160 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 161 |
+
past_key_values: Optional[Cache] = None,
|
| 162 |
+
use_cache: Optional[bool] = False,
|
| 163 |
+
output_attentions: Optional[bool] = False,
|
| 164 |
+
**kwargs
|
| 165 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Cache]]:
|
| 166 |
+
if attention_mask is not None:
|
| 167 |
+
assert len(attention_mask.shape) == 2, (
|
| 168 |
+
"Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
|
| 169 |
+
"for padding purposes (0 indicating padding). "
|
| 170 |
+
"Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# launching the triton kernel for just one token will actually be slower
|
| 174 |
+
mode = 'fused_recurrent' if hidden_states.shape[1] <= 64 else self.mode
|
| 175 |
+
|
| 176 |
+
last_state = None
|
| 177 |
+
if past_key_values is not None and len(past_key_values) > self.layer_idx:
|
| 178 |
+
last_state = past_key_values[self.layer_idx]
|
| 179 |
+
|
| 180 |
+
cu_seqlens = kwargs.get('cu_seqlens', None)
|
| 181 |
+
if self.use_short_conv:
|
| 182 |
+
conv_state_q, conv_state_k, conv_state_v = None, None, None
|
| 183 |
+
if last_state is not None:
|
| 184 |
+
conv_state_q, conv_state_k, conv_state_v = last_state['conv_state']
|
| 185 |
+
conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
|
| 186 |
+
q, conv_state_q = self.q_conv1d(
|
| 187 |
+
x=self.q_proj(hidden_states),
|
| 188 |
+
mask=conv_mask,
|
| 189 |
+
cache=conv_state_q,
|
| 190 |
+
output_final_state=use_cache,
|
| 191 |
+
cu_seqlens=cu_seqlens
|
| 192 |
+
)
|
| 193 |
+
k, conv_state_k = self.k_conv1d(
|
| 194 |
+
x=self.k_proj(hidden_states),
|
| 195 |
+
mask=conv_mask,
|
| 196 |
+
cache=conv_state_k,
|
| 197 |
+
output_final_state=use_cache,
|
| 198 |
+
cu_seqlens=cu_seqlens
|
| 199 |
+
)
|
| 200 |
+
v, conv_state_v = self.v_conv1d(
|
| 201 |
+
x=self.v_proj(hidden_states),
|
| 202 |
+
mask=conv_mask,
|
| 203 |
+
cache=conv_state_v,
|
| 204 |
+
output_final_state=use_cache,
|
| 205 |
+
cu_seqlens=cu_seqlens
|
| 206 |
+
)
|
| 207 |
+
else:
|
| 208 |
+
q = self.q_proj(hidden_states)
|
| 209 |
+
k = self.k_proj(hidden_states)
|
| 210 |
+
v = self.v_proj(hidden_states)
|
| 211 |
+
gk = self.gk_proj(hidden_states)
|
| 212 |
+
|
| 213 |
+
if self.feature_map_fn is not None:
|
| 214 |
+
q, k = map(self.feature_map_fn, (q, k))
|
| 215 |
+
# dealing with left-padding
|
| 216 |
+
if attention_mask is not None:
|
| 217 |
+
v = v.mul_(attention_mask[:, -v.shape[-2]:, None])
|
| 218 |
+
q = rearrange(q, '... (h d) -> ... h d', h=self.num_heads)
|
| 219 |
+
if self.num_kv_groups > 1:
|
| 220 |
+
k, v = (repeat(x, '... (h d) -> ... (h g) d', h=self.num_kv_heads, g=self.num_kv_groups) for x in (k, v))
|
| 221 |
+
else:
|
| 222 |
+
k, v = (rearrange(x, '... (h d) -> ... h d', h=self.num_kv_heads) for x in (k, v))
|
| 223 |
+
gk = F.logsigmoid(gk) / self.gate_logit_normalizer
|
| 224 |
+
|
| 225 |
+
recurrent_state = last_state['recurrent_state'] if last_state is not None else None
|
| 226 |
+
if mode == 'chunk':
|
| 227 |
+
o, recurrent_state = chunk_simple_gla(
|
| 228 |
+
q=q,
|
| 229 |
+
k=k,
|
| 230 |
+
v=v,
|
| 231 |
+
g=gk,
|
| 232 |
+
initial_state=recurrent_state,
|
| 233 |
+
output_final_state=use_cache,
|
| 234 |
+
cu_seqlens=cu_seqlens,
|
| 235 |
+
)
|
| 236 |
+
elif mode == 'fused_recurrent':
|
| 237 |
+
o, recurrent_state = fused_recurrent_simple_gla(
|
| 238 |
+
q=q,
|
| 239 |
+
k=k,
|
| 240 |
+
v=v,
|
| 241 |
+
g=gk,
|
| 242 |
+
initial_state=recurrent_state,
|
| 243 |
+
output_final_state=use_cache,
|
| 244 |
+
cu_seqlens=cu_seqlens,
|
| 245 |
+
)
|
| 246 |
+
else:
|
| 247 |
+
raise NotImplementedError(f"Not supported mode `{mode}`.")
|
| 248 |
+
|
| 249 |
+
if past_key_values is not None:
|
| 250 |
+
past_key_values.update(
|
| 251 |
+
recurrent_state=recurrent_state,
|
| 252 |
+
conv_state=(conv_state_q, conv_state_k, conv_state_v) if self.use_short_conv else None,
|
| 253 |
+
layer_idx=self.layer_idx,
|
| 254 |
+
offset=q.shape[1]
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
g = self.g_proj(hidden_states)
|
| 258 |
+
if self.fuse_norm_and_gate:
|
| 259 |
+
g = rearrange(g, 'b t (h d) -> b t h d', h=self.num_heads)
|
| 260 |
+
o = self.g_norm_swish_gate(o, g)
|
| 261 |
+
o = rearrange(o, 'b t h d -> b t (h d)')
|
| 262 |
+
else:
|
| 263 |
+
o = rearrange(self.g_norm(o), 'b t h d -> b t (h d)')
|
| 264 |
+
o = o * self.gate_fn(g)
|
| 265 |
+
o = self.o_proj(o)
|
| 266 |
+
|
| 267 |
+
return o, None, past_key_values
|
| 268 |
+
|
| 269 |
+
def state_size(self, **kwargs) -> int:
|
| 270 |
+
state_size = self.key_dim * self.head_v_dim
|
| 271 |
+
for module in self.children():
|
| 272 |
+
if isinstance(module, ShortConvolution):
|
| 273 |
+
state_size += module.state_size
|
| 274 |
+
return state_size
|
utils.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
|
| 3 |
+
|
| 4 |
+
# Code is adapted from flash-attn.bert_padding.py
|
| 5 |
+
|
| 6 |
+
from typing import Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from einops import rearrange, repeat
|
| 10 |
+
|
| 11 |
+
from fla.ops.utils.index import prepare_cu_seqlens_from_mask, prepare_lens_from_mask
|
| 12 |
+
from fla.utils import tensor_cache
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class IndexFirstAxis(torch.autograd.Function):
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
def forward(ctx, x, indices):
|
| 19 |
+
ctx.save_for_backward(indices)
|
| 20 |
+
assert x.ndim >= 2
|
| 21 |
+
ctx.first_axis_dim, other_shape = x.shape[0], x.shape[1:]
|
| 22 |
+
second_dim = other_shape.numel()
|
| 23 |
+
# TD [2022-03-04] For some reason torch.gather is a bit faster than indexing.
|
| 24 |
+
# return x[indices]
|
| 25 |
+
return torch.gather(
|
| 26 |
+
rearrange(x, "b ... -> b (...)"), 0, repeat(indices, "z -> z d", d=second_dim)
|
| 27 |
+
).reshape(-1, *other_shape)
|
| 28 |
+
|
| 29 |
+
@staticmethod
|
| 30 |
+
def backward(ctx, do):
|
| 31 |
+
(indices,) = ctx.saved_tensors
|
| 32 |
+
assert do.ndim >= 2
|
| 33 |
+
other_shape = do.shape[1:]
|
| 34 |
+
do = rearrange(do, "b ... -> b (...)")
|
| 35 |
+
dx = torch.zeros(
|
| 36 |
+
[ctx.first_axis_dim, do.shape[1]],
|
| 37 |
+
device=do.device,
|
| 38 |
+
dtype=do.dtype,
|
| 39 |
+
)
|
| 40 |
+
# TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
|
| 41 |
+
# dx[indices] = do
|
| 42 |
+
dx.scatter_(0, repeat(indices, "z -> z d", d=do.shape[1]), do)
|
| 43 |
+
return dx.reshape(ctx.first_axis_dim, *other_shape), None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
index_first_axis = IndexFirstAxis.apply
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class IndexPutFirstAxis(torch.autograd.Function):
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def forward(ctx, x, indices, first_axis_dim):
|
| 53 |
+
ctx.save_for_backward(indices)
|
| 54 |
+
assert indices.ndim == 1
|
| 55 |
+
assert x.ndim >= 2
|
| 56 |
+
y = torch.zeros(first_axis_dim, *x.shape[1:], device=x.device, dtype=x.dtype)
|
| 57 |
+
# TODO [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
|
| 58 |
+
y[indices] = x
|
| 59 |
+
# y.scatter_(0, repeat(indices, 'z -> z d', d=x.shape[1]), x)
|
| 60 |
+
return y
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def backward(ctx, do):
|
| 64 |
+
(indices,) = ctx.saved_tensors
|
| 65 |
+
# TODO [2022-03-04] For some reason torch.gather is a bit faster than indexing.
|
| 66 |
+
dx = do[indices]
|
| 67 |
+
# dx = torch.gather(do, 0, repeat(indices, 'z -> z d', d=do.shape[1]))
|
| 68 |
+
return dx, None, None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
index_put_first_axis = IndexPutFirstAxis.apply
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@tensor_cache
|
| 75 |
+
def get_unpad_data(
|
| 76 |
+
attention_mask: torch.Tensor
|
| 77 |
+
) -> tuple[torch.Tensor, torch.Tensor, int]:
|
| 78 |
+
"""
|
| 79 |
+
Retrieves indexing data required to repad unpadded (ragged) tensors.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
attention_mask (`torch.Tensor`):
|
| 83 |
+
Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.
|
| 84 |
+
|
| 85 |
+
Return:
|
| 86 |
+
indices (`torch.Tensor`):
|
| 87 |
+
The indices of non-masked tokens from the flattened input sequence.
|
| 88 |
+
cu_seqlens (`torch.Tensor`):
|
| 89 |
+
The cumulative sequence lengths, used to index into ragged (unpadded) tensors.
|
| 90 |
+
`cu_seqlens` shape is [batch_size + 1].
|
| 91 |
+
max_seqlen_in_batch (`int`):
|
| 92 |
+
Maximum sequence length in batch.
|
| 93 |
+
"""
|
| 94 |
+
lens = prepare_lens_from_mask(attention_mask)
|
| 95 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
| 96 |
+
max_seqlen_in_batch = lens.max().item()
|
| 97 |
+
cu_seqlens = prepare_cu_seqlens_from_mask(attention_mask)
|
| 98 |
+
return indices, cu_seqlens, max_seqlen_in_batch
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def unpad_input(
|
| 102 |
+
q: torch.Tensor,
|
| 103 |
+
states: Tuple[torch.Tensor],
|
| 104 |
+
attention_mask: torch.Tensor,
|
| 105 |
+
q_len: int,
|
| 106 |
+
keepdim: bool = False,
|
| 107 |
+
):
|
| 108 |
+
"""
|
| 109 |
+
Unpads query, key, and values tensors, using a single dimension for all tokens
|
| 110 |
+
even though they belong to different batches.
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
Arguments:
|
| 114 |
+
q (`torch.Tensor`):
|
| 115 |
+
Query state with padding. Shape: [batch_size, q_len, ...].
|
| 116 |
+
states (`Tuple[torch.Tensor]`):
|
| 117 |
+
Attention state with padding. Shape: [batch_size, seq_len, ...].
|
| 118 |
+
attention_mask (`torch.Tensor`):
|
| 119 |
+
Boolean or int tensor of shape [batch_size, sequence_length], 1 means valid and 0 means not valid.
|
| 120 |
+
q_len (`int`):
|
| 121 |
+
Target length.
|
| 122 |
+
keepdim (`bool`):
|
| 123 |
+
Whether to keep the batch dimension. Default: `False`.
|
| 124 |
+
|
| 125 |
+
Return:
|
| 126 |
+
q (`torch.Tensor`):
|
| 127 |
+
Query state without padding.
|
| 128 |
+
Shape: [1, total_target_length, ...] if `keepdim=True` else [total_target_length, ...].
|
| 129 |
+
states (`Tuple[torch.Tensor]`):
|
| 130 |
+
Attention state without padding.
|
| 131 |
+
Shape: [1, total_source_length, ...] if `keepdim=True` else [total_source_length, ...].
|
| 132 |
+
indices_q (`torch.Tensor`):
|
| 133 |
+
The indices of non-masked tokens from the flattened input target sequence.
|
| 134 |
+
(cu_seqlens_q, cu_seqlens_k) (`Tuple[int]`):
|
| 135 |
+
The cumulative sequence lengths for the target (query) and source (key, value),
|
| 136 |
+
used to index into ragged (unpadded) tensors.
|
| 137 |
+
`cu_seqlens` shape is [batch_size + 1].
|
| 138 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`Tuple[int]`):
|
| 139 |
+
Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence
|
| 140 |
+
i.e. query, `max_seqlen_in_batch_k` for the source sequence i.e. key/value).
|
| 141 |
+
"""
|
| 142 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = get_unpad_data(attention_mask)
|
| 143 |
+
batch_size, seq_len, *_ = states[0].shape
|
| 144 |
+
|
| 145 |
+
state = tuple(
|
| 146 |
+
index_first_axis(rearrange(s, "b s ... -> (b s) ..."), indices_k)
|
| 147 |
+
for s in states
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
if q_len == seq_len:
|
| 151 |
+
q = index_first_axis(rearrange(q, "b s ... -> (b s) ..."), indices_k)
|
| 152 |
+
cu_seqlens_q = cu_seqlens_k
|
| 153 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
| 154 |
+
indices_q = indices_k
|
| 155 |
+
elif q_len == 1:
|
| 156 |
+
max_seqlen_in_batch_q = 1
|
| 157 |
+
cu_seqlens_q = torch.arange(batch_size + 1, dtype=torch.int32, device=q.device)
|
| 158 |
+
indices_q = cu_seqlens_q[:-1]
|
| 159 |
+
q = q.squeeze(1)
|
| 160 |
+
else:
|
| 161 |
+
raise NotImplementedError("We only support either q_len == k_len (prefilling) or q_len == 1 (decoding)")
|
| 162 |
+
|
| 163 |
+
if keepdim:
|
| 164 |
+
q = q.unsqueeze(0)
|
| 165 |
+
state = tuple(s.unsqueeze(0) for s in state)
|
| 166 |
+
|
| 167 |
+
return (
|
| 168 |
+
q,
|
| 169 |
+
state,
|
| 170 |
+
indices_q,
|
| 171 |
+
(cu_seqlens_q, cu_seqlens_k),
|
| 172 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def pad_input(
|
| 177 |
+
hidden_states: torch.Tensor,
|
| 178 |
+
indices: torch.LongTensor,
|
| 179 |
+
batch_size: int,
|
| 180 |
+
seq_len: int,
|
| 181 |
+
) -> torch.Tensor:
|
| 182 |
+
"""
|
| 183 |
+
Args:
|
| 184 |
+
hidden_states ([total_tokens, ...]):
|
| 185 |
+
where total_tokens denotes the number of tokens in selected in attention_mask.
|
| 186 |
+
indices ([total_tokens]):
|
| 187 |
+
the indices that represent the non-masked tokens of the original padded input sequence.
|
| 188 |
+
batch_size (int):
|
| 189 |
+
batch_size size for the padded sequence.
|
| 190 |
+
seq_len (int):
|
| 191 |
+
maximum sequence length for the padded sequence.
|
| 192 |
+
|
| 193 |
+
Return:
|
| 194 |
+
hidden_states of shape [batch_size, seq_len, ...]
|
| 195 |
+
"""
|
| 196 |
+
output = index_put_first_axis(hidden_states, indices, batch_size * seq_len)
|
| 197 |
+
return rearrange(output, "(b s) ... -> b s ...", b=batch_size)
|