fla-core 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. fla/__init__.py +4 -0
  2. fla/modules/__init__.py +33 -0
  3. fla/modules/activations.py +548 -0
  4. fla/modules/convolution.py +1143 -0
  5. fla/modules/feature_map.py +300 -0
  6. fla/modules/fused_bitlinear.py +632 -0
  7. fla/modules/fused_cross_entropy.py +419 -0
  8. fla/modules/fused_kl_div.py +324 -0
  9. fla/modules/fused_linear_cross_entropy.py +620 -0
  10. fla/modules/fused_norm_gate.py +1253 -0
  11. fla/modules/grpo.py +411 -0
  12. fla/modules/l2norm.py +285 -0
  13. fla/modules/l2warp.py +38 -0
  14. fla/modules/layernorm.py +1433 -0
  15. fla/modules/layernorm_gated.py +528 -0
  16. fla/modules/mlp.py +132 -0
  17. fla/modules/parallel.py +42 -0
  18. fla/modules/rotary.py +500 -0
  19. fla/modules/token_shift.py +543 -0
  20. fla/ops/__init__.py +53 -0
  21. fla/ops/abc/__init__.py +7 -0
  22. fla/ops/abc/chunk.py +1117 -0
  23. fla/ops/abc/naive.py +96 -0
  24. fla/ops/attn/__init__.py +7 -0
  25. fla/ops/attn/decoding.py +182 -0
  26. fla/ops/attn/parallel.py +730 -0
  27. fla/ops/based/__init__.py +9 -0
  28. fla/ops/based/fused_chunk.py +373 -0
  29. fla/ops/based/naive.py +72 -0
  30. fla/ops/based/parallel.py +408 -0
  31. fla/ops/comba/__init__.py +7 -0
  32. fla/ops/comba/chunk.py +342 -0
  33. fla/ops/comba/fused_recurrent.py +332 -0
  34. fla/ops/comba/utils.py +172 -0
  35. fla/ops/comba/wy_fast.py +423 -0
  36. fla/ops/common/__init__.py +1 -0
  37. fla/ops/common/chunk_delta_h.py +527 -0
  38. fla/ops/common/chunk_h.py +384 -0
  39. fla/ops/common/chunk_h_parallel.py +551 -0
  40. fla/ops/common/chunk_h_split.py +596 -0
  41. fla/ops/common/chunk_o.py +681 -0
  42. fla/ops/common/chunk_scaled_dot_kkt.py +305 -0
  43. fla/ops/common/fused_chunk.py +629 -0
  44. fla/ops/common/fused_recurrent.py +567 -0
  45. fla/ops/delta_rule/__init__.py +11 -0
  46. fla/ops/delta_rule/chunk.py +311 -0
  47. fla/ops/delta_rule/fused_chunk.py +6 -0
  48. fla/ops/delta_rule/fused_recurrent.py +535 -0
  49. fla/ops/delta_rule/naive.py +120 -0
  50. fla/ops/delta_rule/parallel.py +403 -0
  51. fla/ops/delta_rule/wy_fast.py +294 -0
  52. fla/ops/forgetting_attn/__init__.py +7 -0
  53. fla/ops/forgetting_attn/parallel.py +64 -0
  54. fla/ops/gated_delta_product/__init__.py +5 -0
  55. fla/ops/gated_delta_product/chunk.py +305 -0
  56. fla/ops/gated_delta_product/chunk_deltaproduct_h.py +502 -0
  57. fla/ops/gated_delta_product/chunk_deltaproduct_o.py +154 -0
  58. fla/ops/gated_delta_product/chunk_ref.py +68 -0
  59. fla/ops/gated_delta_product/naive.py +36 -0
  60. fla/ops/gated_delta_rule/__init__.py +7 -0
  61. fla/ops/gated_delta_rule/chunk.py +340 -0
  62. fla/ops/gated_delta_rule/fused_recurrent.py +351 -0
  63. fla/ops/gated_delta_rule/wy_fast.py +296 -0
  64. fla/ops/generalized_delta_rule/__init__.py +9 -0
  65. fla/ops/generalized_delta_rule/dplr/__init__.py +7 -0
  66. fla/ops/generalized_delta_rule/dplr/chunk.py +362 -0
  67. fla/ops/generalized_delta_rule/dplr/chunk_A_bwd.py +367 -0
  68. fla/ops/generalized_delta_rule/dplr/chunk_A_fwd.py +198 -0
  69. fla/ops/generalized_delta_rule/dplr/chunk_h_bwd.py +175 -0
  70. fla/ops/generalized_delta_rule/dplr/chunk_h_fwd.py +175 -0
  71. fla/ops/generalized_delta_rule/dplr/chunk_o_bwd.py +430 -0
  72. fla/ops/generalized_delta_rule/dplr/chunk_o_fwd.py +125 -0
  73. fla/ops/generalized_delta_rule/dplr/fused_recurrent.py +268 -0
  74. fla/ops/generalized_delta_rule/dplr/naive.py +96 -0
  75. fla/ops/generalized_delta_rule/dplr/wy_fast_bwd.py +164 -0
  76. fla/ops/generalized_delta_rule/dplr/wy_fast_fwd.py +284 -0
  77. fla/ops/generalized_delta_rule/iplr/__init__.py +7 -0
  78. fla/ops/generalized_delta_rule/iplr/chunk.py +492 -0
  79. fla/ops/generalized_delta_rule/iplr/fused_recurrent.py +452 -0
  80. fla/ops/generalized_delta_rule/iplr/naive.py +69 -0
  81. fla/ops/generalized_delta_rule/iplr/wy_fast.py +300 -0
  82. fla/ops/gla/__init__.py +11 -0
  83. fla/ops/gla/chunk.py +1298 -0
  84. fla/ops/gla/fused_chunk.py +642 -0
  85. fla/ops/gla/fused_recurrent.py +111 -0
  86. fla/ops/gla/naive.py +41 -0
  87. fla/ops/gsa/__init__.py +9 -0
  88. fla/ops/gsa/chunk.py +1133 -0
  89. fla/ops/gsa/fused_recurrent.py +536 -0
  90. fla/ops/gsa/naive.py +69 -0
  91. fla/ops/hgrn/__init__.py +9 -0
  92. fla/ops/hgrn/chunk.py +282 -0
  93. fla/ops/hgrn/fused_recurrent.py +308 -0
  94. fla/ops/hgrn/naive.py +63 -0
  95. fla/ops/lightning_attn/__init__.py +9 -0
  96. fla/ops/lightning_attn/chunk.py +84 -0
  97. fla/ops/lightning_attn/fused_recurrent.py +84 -0
  98. fla/ops/linear_attn/__init__.py +11 -0
  99. fla/ops/linear_attn/chunk.py +76 -0
  100. fla/ops/linear_attn/fused_chunk.py +61 -0
  101. fla/ops/linear_attn/fused_recurrent.py +35 -0
  102. fla/ops/linear_attn/naive.py +64 -0
  103. fla/ops/linear_attn/utils.py +10 -0
  104. fla/ops/log_linear_attn/__init__.py +7 -0
  105. fla/ops/log_linear_attn/chunk.py +1904 -0
  106. fla/ops/log_linear_attn/naive.py +50 -0
  107. fla/ops/mesa_net/__init__.py +5 -0
  108. fla/ops/mesa_net/chunk.py +371 -0
  109. fla/ops/mesa_net/chunk_cg_solver_bwd.py +162 -0
  110. fla/ops/mesa_net/chunk_cg_solver_fwd.py +186 -0
  111. fla/ops/mesa_net/chunk_h_fwd.py +170 -0
  112. fla/ops/mesa_net/chunk_h_kk_intra_bwd.py +191 -0
  113. fla/ops/mesa_net/chunk_h_kv_intra_bwd.py +209 -0
  114. fla/ops/mesa_net/chunk_h_kv_intra_bwd_separate.py +300 -0
  115. fla/ops/mesa_net/decoding_one_step.py +175 -0
  116. fla/ops/mesa_net/naive.py +131 -0
  117. fla/ops/nsa/__init__.py +9 -0
  118. fla/ops/nsa/compression.py +536 -0
  119. fla/ops/nsa/naive.py +103 -0
  120. fla/ops/nsa/parallel.py +879 -0
  121. fla/ops/nsa/utils.py +92 -0
  122. fla/ops/path_attn/__init__.py +7 -0
  123. fla/ops/path_attn/cumprod_householder_bwd.py +140 -0
  124. fla/ops/path_attn/cumprod_householder_fwd.py +119 -0
  125. fla/ops/path_attn/intra_chunk_preprocess_bwd.py +140 -0
  126. fla/ops/path_attn/intra_chunk_preprocess_bwd_prepare.py +208 -0
  127. fla/ops/path_attn/intra_chunk_preprocess_fwd.py +168 -0
  128. fla/ops/path_attn/parallel.py +270 -0
  129. fla/ops/path_attn/parallel_path_bwd_inter_dkv.py +189 -0
  130. fla/ops/path_attn/parallel_path_bwd_inter_dqh.py +200 -0
  131. fla/ops/path_attn/parallel_path_bwd_intra.py +172 -0
  132. fla/ops/path_attn/parallel_path_fwd.py +195 -0
  133. fla/ops/path_attn/prepare_k_cache.py +74 -0
  134. fla/ops/path_attn/transform_q.py +108 -0
  135. fla/ops/rebased/__init__.py +7 -0
  136. fla/ops/rebased/naive.py +27 -0
  137. fla/ops/rebased/parallel.py +464 -0
  138. fla/ops/retention/__init__.py +13 -0
  139. fla/ops/retention/chunk.py +77 -0
  140. fla/ops/retention/fused_chunk.py +78 -0
  141. fla/ops/retention/fused_recurrent.py +33 -0
  142. fla/ops/retention/naive.py +15 -0
  143. fla/ops/retention/parallel.py +71 -0
  144. fla/ops/rwkv4/__init__.py +7 -0
  145. fla/ops/rwkv4/fused_recurrent.py +472 -0
  146. fla/ops/rwkv6/__init__.py +9 -0
  147. fla/ops/rwkv6/chunk.py +1300 -0
  148. fla/ops/rwkv6/chunk_naive.py +43 -0
  149. fla/ops/rwkv6/fused_recurrent.py +673 -0
  150. fla/ops/rwkv6/recurrent_naive.py +103 -0
  151. fla/ops/rwkv7/__init__.py +10 -0
  152. fla/ops/rwkv7/channel_mixing.py +323 -0
  153. fla/ops/rwkv7/chunk.py +78 -0
  154. fla/ops/rwkv7/fused_addcmul.py +293 -0
  155. fla/ops/rwkv7/fused_k_update.py +346 -0
  156. fla/ops/rwkv7/fused_recurrent.py +334 -0
  157. fla/ops/rwkv7/gate_output_correction.py +244 -0
  158. fla/ops/simple_gla/__init__.py +13 -0
  159. fla/ops/simple_gla/chunk.py +303 -0
  160. fla/ops/simple_gla/fused_chunk.py +108 -0
  161. fla/ops/simple_gla/fused_recurrent.py +112 -0
  162. fla/ops/simple_gla/naive.py +114 -0
  163. fla/ops/simple_gla/parallel.py +722 -0
  164. fla/ops/titans/__init__.py +7 -0
  165. fla/ops/titans/log_impl.py +153 -0
  166. fla/ops/titans/naive.py +375 -0
  167. fla/ops/ttt/__init__.py +9 -0
  168. fla/ops/ttt/chunk.py +1441 -0
  169. fla/ops/ttt/fused_chunk.py +831 -0
  170. fla/ops/ttt/naive.py +126 -0
  171. fla/ops/utils/__init__.py +58 -0
  172. fla/ops/utils/constant.py +6 -0
  173. fla/ops/utils/cumsum.py +465 -0
  174. fla/ops/utils/index.py +133 -0
  175. fla/ops/utils/logcumsumexp.py +52 -0
  176. fla/ops/utils/logsumexp.py +80 -0
  177. fla/ops/utils/matmul.py +245 -0
  178. fla/ops/utils/op.py +62 -0
  179. fla/ops/utils/pack.py +208 -0
  180. fla/ops/utils/pooling.py +207 -0
  181. fla/ops/utils/softmax.py +106 -0
  182. fla/ops/utils/solve_tril.py +381 -0
  183. fla/utils.py +462 -0
  184. fla_core-0.3.2.dist-info/METADATA +575 -0
  185. fla_core-0.3.2.dist-info/RECORD +188 -0
  186. fla_core-0.3.2.dist-info/WHEEL +5 -0
  187. fla_core-0.3.2.dist-info/licenses/LICENSE +21 -0
  188. fla_core-0.3.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,7 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .naive import chunk_titans_linear
4
+
5
+ __all__ = [
6
+ 'chunk_titans_linear'
7
+ ]
@@ -0,0 +1,153 @@
1
+ import torch
2
+
3
+
4
+ def cal_n_log(log_theta, log_eta, seq_len):
5
+ """
6
+ calculate n_{i,j} in log space
7
+ log(n_{i,j}) = log(θ_j) + sum_{k=j+1}^i log(η_k)
8
+ """
9
+ # create log(n)
10
+ log_n = torch.zeros(*log_theta.shape, seq_len, dtype=log_eta.dtype).to(
11
+ log_eta.device
12
+ ) # [batch_size, num_heads, seq_len, seq_len]
13
+ for i in range(seq_len):
14
+ for j in range(i + 1):
15
+ if i == j:
16
+ log_n[..., j, i] = log_theta[..., j]
17
+ else:
18
+ log_n[..., j, i] = log_theta[..., j] + torch.sum(
19
+ log_eta[..., j + 1: i + 1], dim=-1
20
+ )
21
+
22
+ return log_n
23
+
24
+
25
+ def cal_f_log(log_beta, seq_len, log_m):
26
+ """
27
+ cal_f_log(log_beta, seq_len, log_m) -> f
28
+ log(f_t) = log(sum_{i=1}^t exp(sum_{k=i+1}^t log(1-α_k) + sum_{k=1}^i log(η_k)))
29
+ """
30
+ # create f
31
+ # f = torch.zeros_like(log_beta)
32
+ # for t in range(seq_len):
33
+ # for i in range(t + 1):
34
+ # f[..., t] += torch.exp(log_beta[..., t] - log_beta[..., i] + log_m[..., i])
35
+ log_f = torch.zeros_like(log_beta)
36
+ for t in range(seq_len):
37
+ a_i = log_beta[..., t: t + 1] - log_beta[..., : t + 1] + log_m[..., : t + 1]
38
+ log_f[..., t] = torch.logsumexp(a_i, dim=-1)
39
+ f = torch.exp(log_f)
40
+
41
+ # this version overflow and even slower
42
+ # t_indices = torch.arange(seq_len, device=log_beta.device)
43
+ # i_indices = torch.arange(seq_len, device=log_beta.device)
44
+ #
45
+ # mask = i_indices.unsqueeze(0) <= t_indices.unsqueeze(1)
46
+ # log_beta_t = log_beta.unsqueeze(-1) # [..., seq_len, 1]
47
+ # log_beta_i = log_beta.unsqueeze(-2) # [..., 1, seq_len]
48
+ # log_m_i = log_m.unsqueeze(-2)
49
+ # a_i = log_beta_t - log_beta_i + log_m_i
50
+ # masked_a_i = torch.where(mask, a_i, torch.tensor(-float('inf'), device=a_i.device, dtype=a_i.dtype))
51
+ # log_f = torch.logsumexp(masked_a_i, dim=-1) # [..., seq_len]
52
+ #
53
+ # f = torch.exp(log_f)
54
+ return f
55
+
56
+
57
+ def cal_G_log(log_beta, log_n, seq_len):
58
+ """
59
+ calculate G_{i,j}
60
+ log(G_{i,j}) = log(sum_{k=j}^i exp(log(β_i/β_k) + log(n_{k,j})))
61
+ """
62
+ # G = torch.zeros(*log_beta.shape[:-1], seq_len, seq_len, device = log_beta.device)
63
+ # # Fill in the lower triangular part
64
+ # for i in range(seq_len): # row
65
+ # for j in range(i + 1): # column
66
+ # # Sum from k=j to i
67
+ # for k in range(j, i + 1):
68
+ # G[..., i, j] += torch.exp(log_beta[..., i] - log_beta[..., k] + log_n[..., j, k])
69
+
70
+ log_G = torch.full(
71
+ (*log_beta.shape[:-1], seq_len, seq_len), float("-inf"), device=log_beta.device
72
+ )
73
+ # fill in the lower triangular part
74
+ for i in range(seq_len): # row
75
+ for j in range(i + 1): # column
76
+ terms = (
77
+ log_beta[..., i: i + 1]
78
+ - log_beta[..., j: i + 1]
79
+ + log_n[..., j: j + 1, j: i + 1].squeeze(-2)
80
+ )
81
+ # use logsumexp to avoid overflow
82
+ log_G[..., i, j] = torch.logsumexp(terms, dim=-1)
83
+
84
+ G = torch.exp(log_G)
85
+ return G
86
+
87
+
88
+ def _combine_params_log(log_theta, log_alpha_complement, log_eta, seq_len):
89
+ """
90
+ Update rule for Titans in log space
91
+
92
+ Parameters:
93
+ - log_theta: log(θ)
94
+ - log_alpha_complement: log(1-α)
95
+ - log_eta: log(η)
96
+ - seq_len: sequence length
97
+
98
+ Returns:
99
+ - log_beta, beta_T, log_f, f_T, log_g, log_G, m_T, n_T
100
+ """
101
+ # calculate log(β_t) = sum_{k=1}^t log(1-α_k)
102
+ log_beta = torch.cumsum(log_alpha_complement, dim=-1)
103
+
104
+ # get β_T
105
+ beta_T = torch.exp(log_beta[..., -1])
106
+
107
+ # calculate log(m_i) = sum_{k=1}^i log(η_k)
108
+ log_m = torch.cumsum(log_eta, dim=-1)
109
+ m_T = torch.exp(log_m[..., -1])
110
+
111
+ # cal log(n_{i,j})
112
+ log_n = cal_n_log(log_theta, log_eta, seq_len)
113
+ n_T = torch.exp(log_n[..., -1])
114
+
115
+ # cal log(f_t)
116
+ f = cal_f_log(log_beta, seq_len, log_m)
117
+ f_T = f[..., -1]
118
+
119
+ # cal log(G_{i,j})
120
+ G = cal_G_log(log_beta, log_n, seq_len)
121
+ # get log(g_j) = log(G_{T,j})
122
+ g = G[..., -1, :]
123
+
124
+ return log_beta, beta_T, f, f_T, g, G, m_T, n_T
125
+
126
+
127
+ def combine_params_log(theta, alpha, eta, seq_len):
128
+ """
129
+ log space Titians
130
+
131
+ Parameters:
132
+ - theta: θ
133
+ - alpha: α
134
+ - eta: η
135
+ - seq_len: sequence length
136
+
137
+ Returns:
138
+ - beta, beta_T, f, f_T, g, G, m_T, n_T
139
+ """
140
+ # convert to log space
141
+ log_theta = torch.log(theta.squeeze(-1))
142
+ log_alpha_complement = torch.log(1 - alpha.squeeze(-1))
143
+ log_eta = torch.log(eta.squeeze(-1))
144
+
145
+ # combine params in log space
146
+ log_beta, beta_T, f, f_T, g, G, m_T, n_T = _combine_params_log(
147
+ log_theta, log_alpha_complement, log_eta, seq_len
148
+ )
149
+
150
+ # convert back to normal space
151
+ beta = torch.exp(log_beta)
152
+
153
+ return beta, beta_T, f, f_T, g, G, m_T, n_T
@@ -0,0 +1,375 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+
6
+ from fla.ops.titans.log_impl import combine_params_log
7
+
8
+
9
+ def cal_n(theta, eta, seq_len):
10
+ n = torch.zeros(*theta.shape, seq_len, dtype=theta.dtype).to(
11
+ theta.device
12
+ ) # [batch_size, num_heads, seq_len, seq_len]
13
+
14
+ # 1. deal with diagonal elements
15
+ indices = torch.arange(seq_len, device=theta.device)
16
+ n[..., indices, indices] = theta[..., indices]
17
+
18
+ # 2. Create a cumulative product matrix
19
+ # First create a mask to mark the positions where eta needs to be multiplied
20
+ mask = torch.triu(torch.ones(seq_len, seq_len), diagonal=1).to(theta.device)
21
+ # Convert mask to boolean type
22
+ mask = mask.bool()
23
+ # Expand eta to match the target shape
24
+ eta_expanded = eta.unsqueeze(-2).expand(*theta.shape[:-1], seq_len, seq_len)
25
+ # Create a matrix filled with 1s for cumulative product
26
+ cumulative = torch.ones_like(eta_expanded)
27
+ cumulative = torch.where(mask, eta_expanded, cumulative)
28
+ # Calculate the cumulative product
29
+ cumulative_prod = torch.cumprod(cumulative, dim=-1)
30
+
31
+ # 3. Calculate non-diagonal elements
32
+ # Create an expanded version of theta
33
+ theta_expanded = theta.unsqueeze(-1).expand(*theta.shape[:-1], seq_len, seq_len)
34
+ # Create a mask to keep only the upper triangular part (excluding the diagonal)
35
+ upper_triangular = torch.triu(torch.ones_like(n), diagonal=1).bool()
36
+ # Combine theta and cumulative product
37
+ n = torch.where(upper_triangular, theta_expanded * cumulative_prod, n)
38
+ return n
39
+
40
+
41
+ def cal_f(beta, seq_len, m):
42
+ a = torch.tril(beta.to(torch.float32).unsqueeze(-1).expand(*beta.shape, seq_len), 0)
43
+ ratio = (m.to(torch.float32) / beta.to(torch.float32)).unsqueeze(-1)
44
+ f = torch.matmul(a, ratio).squeeze(-1)
45
+ return f.to(beta.dtype)
46
+
47
+
48
+ def cal_G(beta, n, seq_len):
49
+ i_indices = torch.arange(seq_len, device=beta.device)
50
+ j_indices = torch.arange(seq_len, device=beta.device)
51
+ k_indices = torch.arange(seq_len, device=beta.device)
52
+ beta_ratio = beta[..., :, None] / beta[..., None, :] # [..., i, k]
53
+
54
+ # create mask
55
+ k_mask = (k_indices[None, None, :] >= j_indices[None, :, None]) & (
56
+ k_indices[None, None, :] <= i_indices[:, None, None]
57
+ )
58
+
59
+ # use mask to filter out invalid values
60
+ masked_beta_ratio = beta_ratio[..., :, None, :] * k_mask # [..., i, j, k]
61
+ masked_n = n[..., None, :, :] * k_mask # [..., i, j, k]
62
+ # calculate G
63
+ G = torch.sum(masked_beta_ratio * masked_n, dim=-1) # [..., i, j]
64
+ return G
65
+
66
+
67
+ def combine_params(theta, alpha, eta, seq_len):
68
+ theta = theta.squeeze(-1)
69
+ eta = eta.squeeze(-1)
70
+ alpha = alpha.squeeze(-1)
71
+ beta = torch.cumprod(1 - alpha, dim=-1) # β_t = ∏(1 - α_t) in titans paper
72
+ beta_T = beta[..., -1] # β_T
73
+ # Calculate m_i = ∏(k=1 to i) η_k
74
+ m = torch.cumprod(eta, dim=-1) # [batch_size, num_heads, seq_len]
75
+ m_T = m[..., -1] # m_T
76
+ # Calculate n_{i,j}
77
+ # We need to calculate ∏(k=j+1 to i) η_k for each i,j pair
78
+ # # this may be optimized
79
+ # n = torch.zeros(*theta.shape, seq_len, dtype = theta.dtype).to(
80
+ # theta.device) # [batch_size, num_heads, seq_len, seq_len]
81
+ # for i in range(seq_len):
82
+ # for j in range(i + 1):
83
+ # if i == j:
84
+ # n[..., j, i] = theta[..., j]
85
+ # else:
86
+ # # Calculate product of eta from j+1 to i
87
+ # eta_product = torch.prod(eta[..., j + 1:i + 1], dim = -1)
88
+ # n[..., j, i] = theta[..., j] * eta_product
89
+
90
+ n = cal_n(theta, eta, seq_len)
91
+ n_T = n[..., -1] # [batch_size, num_heads, seq_len]
92
+ # Calculate f_t = ∑(i=1 to t) (β_t/β_i) m_i
93
+ # f = torch.zeros_like(theta)
94
+ # for t in range(seq_len):
95
+ # for i in range(t + 1):
96
+ # f[..., t] += (beta[..., t] / beta[..., i]) * m[..., i]
97
+ f = cal_f(beta, seq_len, m)
98
+ f_T = f[..., -1] # [batch_size, num_heads, seq_len]
99
+ # Calculate g_j = ∑(i=j to t) (β_t/β_i) n_{i,j}
100
+ # g = torch.zeros_like(theta) # [batch_size, num_heads, seq_len]
101
+ # for j in range(seq_len):
102
+ # for i in range(j, seq_len):
103
+ # g[..., j] += (beta[..., -1] / beta[..., i]) * n[..., j, i]
104
+ # G = torch.zeros(*beta.shape[:-1], seq_len, seq_len, device = beta.device)
105
+ # # Fill in the lower triangular part
106
+ # for i in range(seq_len): # row
107
+ # for j in range(i + 1): # column
108
+ # # Sum from k=j to i
109
+ # for k in range(j, i + 1):
110
+ # G[..., i, j] += (beta[..., i] / beta[..., k]) * n[..., j, k]
111
+ G = cal_G(beta, n, seq_len)
112
+ g = G[:, :, -1, :] # [batch_size, num_heads, seq_len]
113
+ # g2, G2 = compute_g_and_G(beta, n, seq_len)
114
+ return beta, beta_T, f, f_T, g, G, m_T, n_T
115
+
116
+
117
+ def titans_linear(
118
+ q, k, v, w, b, theta, alpha, eta, eps, chunk_size, initial_state, output_final_state
119
+ ):
120
+ """
121
+ Implementation of Titans Linear function based on the update rules:
122
+ M_t = (1 - alpha_t) * M_{t-1} + S_t
123
+ S_t = eta_t * S_{t-1} - theta_t * nabla_l(M_{t-1}; x_t)
124
+
125
+ Args:
126
+ q: Query tensor
127
+ k: Key tensor
128
+ v: Value tensor
129
+ w: Weight tensor
130
+ b: Bias tensor
131
+ theta: Learning rate tensor
132
+ alpha: Momentum decay tensor
133
+ eta: Step size tensor
134
+ eps: Epsilon for numerical stability
135
+ initial_state: Initial state M_0
136
+ output_final_state: Whether to output the final state
137
+
138
+ Returns:
139
+ Tuple of (output tensor, final state)
140
+ """
141
+ B, H, T, D = q.shape
142
+ device = q.device
143
+ w = w.reshape(H, 1, D).to(torch.float32)
144
+ b = b.reshape(H, 1, D).to(torch.float32)
145
+ # Initialize states
146
+ if initial_state is None:
147
+ M_prev = torch.zeros(B, H, D, D, device=device)
148
+ else:
149
+ M_prev = initial_state
150
+ M_prev_nabla = M_prev.clone()
151
+ S_prev = torch.zeros_like(M_prev)
152
+ outputs = []
153
+
154
+ # Process sequence step by step
155
+ for t in range(T):
156
+ # Get current step inputs
157
+ q_t = q[:, :, t: t + 1, :] # (batch_size, num_heads, 1, dim)
158
+ k_t = k[:, :, t: t + 1, :] # (batch_size, num_heads, 1, dim)
159
+ v_t = v[:, :, t: t + 1, :] # (batch_size, num_heads, 1, dim)
160
+ theta_t = theta[:, :, t: t + 1, :] # (batch_size, num_heads, 1, dim)
161
+ alpha_t = alpha[:, :, t: t + 1, :] # (batch_size, num_heads, 1, dim)
162
+ eta_t = eta[:, :, t: t + 1, :] # (batch_size, num_heads, 1, dim)
163
+
164
+ # Compute gradient
165
+ km = k_t @ M_prev_nabla # (batch_size, num_heads, 1, dim)
166
+ reconstruction_target = v_t - k_t
167
+ mean = km.mean(-1, keepdim=True)
168
+ var = km.var(-1, unbiased=False, keepdim=True).to(torch.float32)
169
+ rstd = torch.sqrt(var + eps).to(torch.float32)
170
+ km_hat = (km - mean) / rstd
171
+
172
+ grad = w * km_hat + b - reconstruction_target
173
+ grad = grad * w
174
+ # v_new = (D * grad - grad.sum(-1, keepdim = True) - km_hat * (grad * km_hat).sum(-1, keepdim = True)) / (
175
+ # rstd * D)
176
+ v_new = D * grad - grad.sum(-1, keepdim=True) / (rstd * D)
177
+ proj_term = km_hat * (grad * km_hat).sum(-1, keepdim=True) / (rstd * D)
178
+ v_new = v_new - proj_term
179
+ # v_new = grad
180
+
181
+ # Update S_t
182
+ S_t = eta_t * S_prev - 2 * theta_t * k_t.transpose(-2, -1) @ v_new
183
+
184
+ # Update M_t
185
+ M_t = (1 - alpha_t) * M_prev + S_t
186
+
187
+ # Store output
188
+ output_t = q_t @ M_t # (batch_size, num_heads, seq_len, dim)
189
+ mean = output_t.mean(dim=-1, keepdim=True)
190
+ var = output_t.var(dim=-1, unbiased=False, keepdim=True).to(torch.float32)
191
+ rstd = torch.sqrt(var + eps).to(torch.float32)
192
+ output_t = output_t + (output_t - mean) / rstd * w + b
193
+ outputs.append(output_t)
194
+
195
+ # Update states for next step
196
+ if (t + 1) % chunk_size == 0:
197
+ M_prev_nabla = M_t.clone()
198
+ M_prev = M_t
199
+ S_prev = S_t
200
+
201
+ # Stack outputs along sequence dimension
202
+ output = torch.stack(outputs, dim=-2).squeeze(
203
+ -3
204
+ ) # (batch_size, num_heads, seq_len, dim)
205
+
206
+ if output_final_state:
207
+ return output, M_prev
208
+ return output, None
209
+
210
+
211
+ def chunk_titans_linear(
212
+ q, k, v, w, b, theta, alpha, eta, eps, chunk_size, initial_state, output_final_state
213
+ ):
214
+ B, H, T, D = q.shape
215
+ num_batch = T // chunk_size
216
+ # [num_batch, B, num_heads, mini_batch_size, head_dim]
217
+ _q = q.reshape(B, H, num_batch, chunk_size, D).permute(2, 0, 1, 3, 4)
218
+ _k = k.reshape(B, H, num_batch, chunk_size, D).permute(2, 0, 1, 3, 4)
219
+ _v = v.reshape(B, H, num_batch, chunk_size, D).permute(2, 0, 1, 3, 4)
220
+ # [num_batch, B, num_heads, mini_batch_size, 1]
221
+ _eta = eta.reshape(B, H, num_batch, chunk_size, 1).permute(2, 0, 1, 3, 4)
222
+ _theta = theta.reshape(B, H, num_batch, chunk_size, 1).permute(2, 0, 1, 3, 4)
223
+ _alpha = alpha.reshape(B, H, num_batch, chunk_size, 1).permute(2, 0, 1, 3, 4)
224
+ # [H, 1, D]
225
+ w = w.reshape(H, 1, D).to(torch.float32)
226
+ b = b.reshape(H, 1, D).to(torch.float32)
227
+ # [num_heads, 1, head_dim]
228
+ if initial_state is None:
229
+ M_prev = torch.zeros((B, H, D, D), device=v.device, dtype=v.dtype).to(
230
+ torch.float32
231
+ )
232
+ else:
233
+ M_prev = initial_state
234
+
235
+ S_prev = torch.zeros_like(M_prev)
236
+
237
+ # [num_batch, B, num_heads, mini_batch_size, head_dim]
238
+ o = torch.empty_like(_v)
239
+
240
+ for i in range(num_batch):
241
+ q_i, k_i, v_i, eta_i, theta_i, alpha_i = [
242
+ x[i] for x in [_q, _k, _v, _eta, _theta, _alpha]
243
+ ]
244
+
245
+ # beta, beta_T, f, f_T, g, G, m_T, n = combine_params(theta_i, alpha_i, eta_i, chunk_size)
246
+ beta, beta_T, f, f_T, g, G, m_T, n = combine_params_log(
247
+ theta_i, alpha_i, eta_i, chunk_size
248
+ )
249
+
250
+ m_T = m_T.unsqueeze(-1).unsqueeze(-1)
251
+ beta_T = beta_T.unsqueeze(-1).unsqueeze(-1)
252
+ f_T = f_T.unsqueeze(-1).unsqueeze(-1)
253
+ g_diag = torch.diag_embed(g).to(q_i.dtype)
254
+ n = torch.diag_embed(n).to(q_i.dtype)
255
+ beta = torch.diag_embed(beta).to(q_i.dtype)
256
+ f = torch.diag_embed(f).to(q_i.dtype)
257
+ km = k_i @ M_prev
258
+ reconstruction_target = v_i - k_i
259
+
260
+ mean = km.mean(-1, True)
261
+ var = km.var(-1, unbiased=False, keepdim=True).to(torch.float32)
262
+ rstd = torch.sqrt(var + eps).to(torch.float32)
263
+ km_hat = (km - mean) / rstd
264
+
265
+ grad = w * km_hat + b - reconstruction_target
266
+ grad *= w
267
+ v_new = D * grad - grad.sum(-1, keepdim=True) / (rstd * D)
268
+ proj_term = km_hat * (grad * km_hat).sum(-1, keepdim=True) / (rstd * D)
269
+ v_new = v_new - proj_term
270
+ # v_new = (D * grad - grad.sum(-1, True))
271
+ # print(f"Projection term stats: min={torch.abs(beta_T).min()}")
272
+
273
+ # v_new = grad
274
+
275
+ Attn = torch.tril(q_i @ k_i.transpose(-2, -1)) * G
276
+
277
+ # o_i
278
+ output_t = beta @ q_i @ M_prev + f @ q_i @ S_prev - 2 * Attn @ v_new
279
+
280
+ M_t = (
281
+ beta_T * M_prev
282
+ + f_T * S_prev
283
+ - 2 * (g_diag @ k_i).transpose(-1, -2) @ v_new
284
+ )
285
+ # cal S_T from S_0
286
+ S_t = m_T * S_prev - 2 * (n @ k_i).transpose(-1, -2) @ v_new
287
+ # layer norm with residuals
288
+ mean = output_t.mean(dim=-1, keepdim=True)
289
+ var = output_t.var(dim=-1, unbiased=False, keepdim=True).to(torch.float32)
290
+ rstd = torch.sqrt(var + eps).to(torch.float32)
291
+ output_t = output_t + (output_t - mean) / rstd * w + b
292
+ o[i] = output_t
293
+ S_prev = S_t
294
+ M_prev = M_t
295
+
296
+ # [B, num_mini_batch, mini_batch_size, num_heads, head_dim]
297
+ o = o.permute(1, 2, 0, 3, 4).reshape(B, H, T, D)
298
+ M_prev = M_prev if output_final_state else None
299
+ return o, M_prev
300
+
301
+
302
+ # most of the code is copied from ttt
303
+ def chunk_titans_linear_ref(
304
+ q: torch.Tensor,
305
+ k: torch.Tensor,
306
+ v: torch.Tensor,
307
+ w: torch.Tensor,
308
+ b: torch.Tensor,
309
+ theta: torch.Tensor,
310
+ alpha: torch.Tensor,
311
+ eta: torch.Tensor,
312
+ eps: float = 1e-6,
313
+ chunk_size: int = 16, # chunk size
314
+ initial_state: torch.Tensor = None,
315
+ output_final_state: bool = False,
316
+ head_first: bool = False,
317
+ use_chunk: bool = True,
318
+ ):
319
+ assert q.dtype == k.dtype == v.dtype
320
+ assert k.shape[-1] == v.shape[-1], "DK must equal to DV."
321
+ if not head_first:
322
+ q = q.transpose(1, 2)
323
+ k = k.transpose(1, 2)
324
+ v = v.transpose(1, 2)
325
+ eta = eta.transpose(1, 2)
326
+ alpha = alpha.transpose(1, 2)
327
+ theta = theta.transpose(1, 2)
328
+ seq_len = q.shape[-2]
329
+ pad_len = (chunk_size - (seq_len % chunk_size)) % chunk_size
330
+ if pad_len > 0:
331
+ q = F.pad(q, (0, 0, 0, pad_len))
332
+ k = F.pad(k, (0, 0, 0, pad_len))
333
+ v = F.pad(v, (0, 0, 0, pad_len))
334
+ theta = F.pad(theta, (0, 0, 0, pad_len))
335
+ alpha = F.pad(alpha, (0, 0, 0, pad_len))
336
+ eta = F.pad(eta, (0, 0, 0, pad_len))
337
+ theta[:, :, -1, :] = theta[:, :, -(pad_len + 1), :]
338
+ alpha[:, :, -1, :] = alpha[:, :, -(pad_len + 1), :]
339
+ eta[:, :, -1, :] = eta[:, :, -(pad_len + 1), :]
340
+ assert q.shape[-2] % chunk_size == 0, "Sequence length should be a multiple of BT."
341
+ q, k, v, w, b = map(lambda x: x.to(torch.float32), [q, k, v, w, b])
342
+ if use_chunk:
343
+ o, final_state = chunk_titans_linear(
344
+ q,
345
+ k,
346
+ v,
347
+ w,
348
+ b,
349
+ theta,
350
+ alpha,
351
+ eta,
352
+ eps,
353
+ chunk_size,
354
+ initial_state,
355
+ output_final_state,
356
+ )
357
+ else:
358
+ o, final_state = titans_linear(
359
+ q,
360
+ k,
361
+ v,
362
+ w,
363
+ b,
364
+ theta,
365
+ alpha,
366
+ eta,
367
+ eps,
368
+ chunk_size,
369
+ initial_state,
370
+ output_final_state,
371
+ )
372
+ o = o[:, :, :seq_len, :]
373
+ if not head_first:
374
+ o = o.transpose(1, 2)
375
+ return o, final_state
@@ -0,0 +1,9 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ from .chunk import chunk_ttt_linear
4
+ from .fused_chunk import fused_chunk_ttt_linear
5
+
6
+ __all__ = [
7
+ 'fused_chunk_ttt_linear',
8
+ 'chunk_ttt_linear'
9
+ ]