math-skill 2.1.0 → 3.0.1

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 (244) hide show
  1. package/README.en-US.md +165 -198
  2. package/README.md +165 -198
  3. package/agents/math-critic.en.md +28 -26
  4. package/agents/math-critic.md +33 -33
  5. package/commands/ask.en.md +10 -0
  6. package/commands/ask.md +3 -10
  7. package/design-patterns/attention/equivariant-attention.en.md +72 -0
  8. package/design-patterns/attention/equivariant-attention.md +72 -0
  9. package/design-patterns/attention/geometry-aware-attention.en.md +73 -0
  10. package/design-patterns/attention/geometry-aware-attention.md +72 -0
  11. package/design-patterns/attention/information-bottleneck-attention.en.md +72 -0
  12. package/design-patterns/attention/information-bottleneck-attention.md +72 -0
  13. package/design-patterns/attention/projection-attention.en.md +68 -0
  14. package/design-patterns/attention/projection-attention.md +68 -0
  15. package/design-patterns/attention/spectral-attention.en.md +71 -0
  16. package/design-patterns/attention/spectral-attention.md +71 -0
  17. package/design-patterns/compression/leverage-score-selection.en.md +71 -0
  18. package/design-patterns/compression/leverage-score-selection.md +71 -0
  19. package/design-patterns/compression/low-rank-kv-cache.en.md +60 -0
  20. package/design-patterns/compression/low-rank-kv-cache.md +60 -0
  21. package/design-patterns/compression/spectral-token-pruning.en.md +61 -0
  22. package/design-patterns/compression/spectral-token-pruning.md +61 -0
  23. package/design-patterns/compression/topology-preserving-compression.en.md +64 -0
  24. package/design-patterns/compression/topology-preserving-compression.md +64 -0
  25. package/design-patterns/loss/constraint-penalty.en.md +67 -0
  26. package/design-patterns/loss/constraint-penalty.md +78 -0
  27. package/design-patterns/loss/contrastive-loss.en.md +59 -0
  28. package/design-patterns/loss/contrastive-loss.md +68 -0
  29. package/design-patterns/loss/information-bottleneck-loss.en.md +69 -0
  30. package/design-patterns/loss/information-bottleneck-loss.md +74 -0
  31. package/design-patterns/loss/orthogonality-loss.en.md +56 -0
  32. package/design-patterns/loss/orthogonality-loss.md +60 -0
  33. package/design-patterns/loss/variational-loss.en.md +61 -0
  34. package/design-patterns/loss/variational-loss.md +71 -0
  35. package/design-patterns/representation/equivariant-split.en.md +87 -0
  36. package/design-patterns/representation/equivariant-split.md +89 -0
  37. package/design-patterns/representation/manifold-representation.en.md +85 -0
  38. package/design-patterns/representation/manifold-representation.md +87 -0
  39. package/design-patterns/representation/shared-private-decomposition.en.md +84 -0
  40. package/design-patterns/representation/shared-private-decomposition.md +86 -0
  41. package/design-patterns/representation/subspace-alignment.en.md +90 -0
  42. package/design-patterns/representation/subspace-alignment.md +92 -0
  43. package/design-patterns/routing/graph-routing.en.md +79 -0
  44. package/design-patterns/routing/graph-routing.md +81 -0
  45. package/design-patterns/routing/moe-routing.en.md +85 -0
  46. package/design-patterns/routing/moe-routing.md +87 -0
  47. package/design-patterns/routing/optimal-transport-routing.en.md +68 -0
  48. package/design-patterns/routing/optimal-transport-routing.md +72 -0
  49. package/design-patterns/routing/spectral-clustering-routing.en.md +88 -0
  50. package/design-patterns/routing/spectral-clustering-routing.md +90 -0
  51. package/knowledge-base/differential-geometry/connection.en.md +51 -0
  52. package/knowledge-base/differential-geometry/connection.md +51 -0
  53. package/knowledge-base/differential-geometry/curvature.en.md +49 -0
  54. package/knowledge-base/differential-geometry/curvature.md +49 -0
  55. package/knowledge-base/differential-geometry/geodesic.en.md +51 -0
  56. package/knowledge-base/differential-geometry/geodesic.md +51 -0
  57. package/knowledge-base/differential-geometry/manifold.en.md +47 -0
  58. package/knowledge-base/differential-geometry/manifold.md +47 -0
  59. package/knowledge-base/differential-geometry/metric-tensor.en.md +50 -0
  60. package/knowledge-base/differential-geometry/metric-tensor.md +50 -0
  61. package/knowledge-base/differential-geometry/tangent-space.en.md +48 -0
  62. package/knowledge-base/differential-geometry/tangent-space.md +48 -0
  63. package/knowledge-base/information-geometry/fisher-metric.en.md +56 -0
  64. package/knowledge-base/information-geometry/fisher-metric.md +56 -0
  65. package/knowledge-base/information-geometry/natural-gradient.en.md +54 -0
  66. package/knowledge-base/information-geometry/natural-gradient.md +54 -0
  67. package/knowledge-base/lie-theory/equivariance.en.md +54 -0
  68. package/knowledge-base/lie-theory/equivariance.md +54 -0
  69. package/knowledge-base/lie-theory/group-action.en.md +51 -0
  70. package/knowledge-base/lie-theory/group-action.md +51 -0
  71. package/knowledge-base/lie-theory/lie-algebra.en.md +51 -0
  72. package/knowledge-base/lie-theory/lie-algebra.md +51 -0
  73. package/knowledge-base/lie-theory/lie-group.en.md +51 -0
  74. package/knowledge-base/lie-theory/lie-group.md +51 -0
  75. package/knowledge-base/lie-theory/representation.en.md +52 -0
  76. package/knowledge-base/lie-theory/representation.md +52 -0
  77. package/knowledge-base/matrix-analysis/low-rank-approximation.en.md +49 -0
  78. package/knowledge-base/matrix-analysis/low-rank-approximation.md +49 -0
  79. package/knowledge-base/matrix-analysis/matrix-perturbation.en.md +49 -0
  80. package/knowledge-base/matrix-analysis/matrix-perturbation.md +49 -0
  81. package/knowledge-base/matrix-analysis/positive-semidefinite.en.md +50 -0
  82. package/knowledge-base/matrix-analysis/positive-semidefinite.md +50 -0
  83. package/knowledge-base/matrix-analysis/projection.en.md +47 -0
  84. package/knowledge-base/matrix-analysis/projection.md +47 -0
  85. package/knowledge-base/matrix-analysis/spectral-decomposition.en.md +48 -0
  86. package/knowledge-base/matrix-analysis/spectral-decomposition.md +48 -0
  87. package/knowledge-base/optimization/constrained-optimization.en.md +53 -0
  88. package/knowledge-base/optimization/constrained-optimization.md +53 -0
  89. package/knowledge-base/optimization/convex-optimization.en.md +50 -0
  90. package/knowledge-base/optimization/convex-optimization.md +50 -0
  91. package/knowledge-base/optimization/lagrangian-duality.en.md +50 -0
  92. package/knowledge-base/optimization/lagrangian-duality.md +50 -0
  93. package/knowledge-base/optimization/proximal-method.en.md +52 -0
  94. package/knowledge-base/optimization/proximal-method.md +52 -0
  95. package/knowledge-base/optimization/riemannian-optimization.en.md +51 -0
  96. package/knowledge-base/optimization/riemannian-optimization.md +51 -0
  97. package/knowledge-base/overview.en.md +29 -218
  98. package/knowledge-base/overview.md +29 -220
  99. package/knowledge-base/probability/concentration-inequality.en.md +45 -0
  100. package/knowledge-base/probability/concentration-inequality.md +45 -0
  101. package/knowledge-base/probability/entropy.en.md +47 -0
  102. package/knowledge-base/probability/entropy.md +47 -0
  103. package/knowledge-base/probability/fisher-information.en.md +48 -0
  104. package/knowledge-base/probability/fisher-information.md +48 -0
  105. package/knowledge-base/probability/information-bottleneck.en.md +49 -0
  106. package/knowledge-base/probability/information-bottleneck.md +49 -0
  107. package/knowledge-base/probability/kl-divergence.en.md +51 -0
  108. package/knowledge-base/probability/kl-divergence.md +51 -0
  109. package/knowledge-base/topology/euler-characteristic.en.md +54 -0
  110. package/knowledge-base/topology/euler-characteristic.md +54 -0
  111. package/knowledge-base/topology/fundamental-group.en.md +52 -0
  112. package/knowledge-base/topology/fundamental-group.md +52 -0
  113. package/knowledge-base/topology/persistent-homology.en.md +54 -0
  114. package/knowledge-base/topology/persistent-homology.md +54 -0
  115. package/lenses/algorithmic.en.md +49 -0
  116. package/lenses/algorithmic.md +49 -0
  117. package/lenses/axiomatization.en.md +48 -0
  118. package/lenses/axiomatization.md +48 -0
  119. package/lenses/categorical.en.md +48 -0
  120. package/lenses/categorical.md +48 -0
  121. package/lenses/causal.en.md +49 -0
  122. package/lenses/causal.md +49 -0
  123. package/lenses/duality.en.md +47 -0
  124. package/lenses/duality.md +47 -0
  125. package/lenses/game.en.md +50 -0
  126. package/lenses/game.md +50 -0
  127. package/lenses/geometric.en.md +53 -0
  128. package/lenses/geometric.md +53 -0
  129. package/lenses/local-to-global.en.md +52 -0
  130. package/lenses/local-to-global.md +52 -0
  131. package/lenses/perturbation.en.md +51 -0
  132. package/lenses/perturbation.md +51 -0
  133. package/lenses/probabilistic.en.md +48 -0
  134. package/lenses/probabilistic.md +48 -0
  135. package/lenses/projection.en.md +50 -0
  136. package/lenses/projection.md +50 -0
  137. package/lenses/spectral.en.md +52 -0
  138. package/lenses/spectral.md +52 -0
  139. package/lenses/symmetry.en.md +49 -0
  140. package/lenses/symmetry.md +49 -0
  141. package/lenses/topological.en.md +48 -0
  142. package/lenses/topological.md +48 -0
  143. package/lenses/variational.en.md +48 -0
  144. package/lenses/variational.md +48 -0
  145. package/package.json +9 -3
  146. package/references/agentic-workflow.en.md +1 -1
  147. package/references/agentic-workflow.md +1 -1
  148. package/references/books/abstract-algebra.en.md +124 -0
  149. package/references/books/abstract-algebra.md +22 -22
  150. package/references/books/algebraic-geometry-rising-sea.en.md +171 -0
  151. package/references/books/algebraic-geometry-rising-sea.md +11 -11
  152. package/references/books/differential-geometry.en.md +140 -0
  153. package/references/books/differential-geometry.md +19 -19
  154. package/references/books/matrix-analysis.en.md +146 -0
  155. package/references/books/matrix-analysis.md +10 -10
  156. package/references/books/micro-lie-theory.en.md +116 -0
  157. package/references/books/micro-lie-theory.md +17 -17
  158. package/references/books/optimization-ml.en.md +163 -0
  159. package/references/books/optimization-ml.md +7 -8
  160. package/references/books/smooth-manifolds.en.md +105 -0
  161. package/references/books/smooth-manifolds.md +14 -14
  162. package/references/gpu-friendly-math.en.md +23 -10
  163. package/references/gpu-friendly-math.md +17 -4
  164. package/references/inspiration.en.md +1 -1
  165. package/references/inspiration.md +2 -2
  166. package/skills/math-research-activator/SKILL.en.md +195 -114
  167. package/skills/math-research-activator/SKILL.md +194 -119
  168. package/skills/math-research-activator/original-texts.en.md +9 -9
  169. package/skills/math-research-activator/original-texts.md +11 -11
  170. package/commands/abstraction.md +0 -11
  171. package/commands/algorithmic-thinking.md +0 -11
  172. package/commands/axiomatization.md +0 -11
  173. package/commands/causal-inference.md +0 -11
  174. package/commands/discrete-combinatorial.md +0 -11
  175. package/commands/game-theory.md +0 -11
  176. package/commands/induction-analogy.md +0 -11
  177. package/commands/information-theory.md +0 -11
  178. package/commands/logic-deduction.md +0 -11
  179. package/commands/modeling.md +0 -11
  180. package/commands/optimization.md +0 -11
  181. package/commands/probability-statistics.md +0 -11
  182. package/commands/symmetry-invariance.md +0 -11
  183. package/commands/topological-thinking.md +0 -11
  184. package/commands/transformation.md +0 -11
  185. package/skills/abstraction/SKILL.en.md +0 -117
  186. package/skills/abstraction/SKILL.md +0 -121
  187. package/skills/abstraction/original-texts.en.md +0 -163
  188. package/skills/abstraction/original-texts.md +0 -175
  189. package/skills/algorithmic-thinking/SKILL.en.md +0 -132
  190. package/skills/algorithmic-thinking/SKILL.md +0 -138
  191. package/skills/algorithmic-thinking/original-texts.en.md +0 -253
  192. package/skills/algorithmic-thinking/original-texts.md +0 -256
  193. package/skills/axiomatization/SKILL.en.md +0 -144
  194. package/skills/axiomatization/SKILL.md +0 -151
  195. package/skills/axiomatization/original-texts.en.md +0 -154
  196. package/skills/axiomatization/original-texts.md +0 -160
  197. package/skills/causal-inference/SKILL.en.md +0 -147
  198. package/skills/causal-inference/SKILL.md +0 -151
  199. package/skills/causal-inference/original-texts.en.md +0 -136
  200. package/skills/causal-inference/original-texts.md +0 -167
  201. package/skills/discrete-combinatorial/SKILL.en.md +0 -124
  202. package/skills/discrete-combinatorial/SKILL.md +0 -131
  203. package/skills/discrete-combinatorial/original-texts.en.md +0 -184
  204. package/skills/discrete-combinatorial/original-texts.md +0 -185
  205. package/skills/game-theory/SKILL.en.md +0 -117
  206. package/skills/game-theory/SKILL.md +0 -123
  207. package/skills/game-theory/original-texts.en.md +0 -131
  208. package/skills/game-theory/original-texts.md +0 -131
  209. package/skills/induction-analogy/SKILL.en.md +0 -145
  210. package/skills/induction-analogy/SKILL.md +0 -152
  211. package/skills/induction-analogy/original-texts.en.md +0 -140
  212. package/skills/induction-analogy/original-texts.md +0 -154
  213. package/skills/information-theory/SKILL.en.md +0 -134
  214. package/skills/information-theory/SKILL.md +0 -140
  215. package/skills/information-theory/original-texts.en.md +0 -127
  216. package/skills/information-theory/original-texts.md +0 -127
  217. package/skills/logic-deduction/SKILL.en.md +0 -130
  218. package/skills/logic-deduction/SKILL.md +0 -135
  219. package/skills/logic-deduction/original-texts.en.md +0 -160
  220. package/skills/logic-deduction/original-texts.md +0 -173
  221. package/skills/modeling/SKILL.en.md +0 -135
  222. package/skills/modeling/SKILL.md +0 -139
  223. package/skills/modeling/original-texts.en.md +0 -162
  224. package/skills/modeling/original-texts.md +0 -165
  225. package/skills/optimization/SKILL.en.md +0 -129
  226. package/skills/optimization/SKILL.md +0 -135
  227. package/skills/optimization/original-texts.en.md +0 -167
  228. package/skills/optimization/original-texts.md +0 -168
  229. package/skills/probability-statistics/SKILL.en.md +0 -146
  230. package/skills/probability-statistics/SKILL.md +0 -151
  231. package/skills/probability-statistics/original-texts.en.md +0 -191
  232. package/skills/probability-statistics/original-texts.md +0 -193
  233. package/skills/symmetry-invariance/SKILL.en.md +0 -135
  234. package/skills/symmetry-invariance/SKILL.md +0 -139
  235. package/skills/symmetry-invariance/original-texts.en.md +0 -206
  236. package/skills/symmetry-invariance/original-texts.md +0 -221
  237. package/skills/topological-thinking/SKILL.en.md +0 -124
  238. package/skills/topological-thinking/SKILL.md +0 -128
  239. package/skills/topological-thinking/original-texts.en.md +0 -134
  240. package/skills/topological-thinking/original-texts.md +0 -164
  241. package/skills/transformation/SKILL.en.md +0 -120
  242. package/skills/transformation/SKILL.md +0 -124
  243. package/skills/transformation/original-texts.en.md +0 -204
  244. package/skills/transformation/original-texts.md +0 -216
@@ -0,0 +1,72 @@
1
+ # 几何感知注意力 / Geometry-Aware Attention
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当 token/key 之间存在**已知的几何关系**(空间距离、流形测地距、层级结构、时序间隔)时,标准注意力的位置无关内积无法利用这些结构信息。几何感知注意力将**几何先验直接注入注意力权重计算**,使模型天然尊重底空间的度量结构。典型场景:3D 场景理解、分子构象、时序预测、层级文本结构(段落-句子-词)、知识图谱。
6
+
7
+ ## 数学思想来源
8
+ - 透镜:[symmetry(对称透镜 — 度量不变性), duality(对偶透镜 — 坐标系无关表达)]
9
+ - 知识:[`../../knowledge-base/information-geometry/fisher-metric.md`(分布空间的几何度量), `../../knowledge-base/probability/concentration-inequality.md`(几何约束下的浓度行为)]
10
+
11
+ ## 需要的数学知识
12
+ - **度量空间与距离函数**:欧氏距离、测地距、树距离、Wasserstein 距离
13
+ - **RBF / 核方法**:$k(x, y) = \exp(-d(x,y)^2 / 2\sigma^2)$,距离→相似度的转换
14
+ - **位置编码的几何解释**:RoPE = 旋转群 $SO(2)$ 的作用(相对距离编码为旋转角度差);ALiBi = 指数衰减的距离偏置
15
+
16
+ ## AI 模块形式
17
+
18
+ **核心思路**:在注意力分数中显式引入几何距离项,使远距离 token 的注意力天然衰减:
19
+
20
+ $$\text{GeoAttn}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d}} + \text{GeoBias}(i, j)\right) V$$
21
+
22
+ **方案 A:距离偏置注意力(通用度量空间)**:
23
+ ```python
24
+ # d_ij 为 token i 和 j 之间的几何距离(预计算或在线计算)
25
+ # 可学习距离偏置函数
26
+ distance_bias = MLP(d_ij) # 或简单的 -α * d_ij
27
+ scores = (Q @ K.T) / sqrt(d) + distance_bias
28
+ attn = softmax(scores) @ V
29
+ ```
30
+
31
+ **方案 B:相对位置编码(RoPE / ALiBi 的几何推广)**:
32
+ ```python
33
+ # 推广 RoPE:位置 → 群元素 g_i,相对位置 → g_i g_j^{-1}
34
+ # 可学习任意度量空间上的相对位置偏置
35
+ def geo_attention(Q, K, V, positions):
36
+ rel_pos = pairwise_difference(positions) # (n, n, coord_dim)
37
+ geo_bias = geo_encoder(rel_pos) # (n, n) 可学习映射
38
+ scores = (Q @ K.T) / sqrt(d) + geo_bias
39
+ return softmax(scores) @ V
40
+ ```
41
+
42
+ **方案 C:流形感知注意力(非欧空间)**:
43
+ ```python
44
+ # token 位于非欧流形(双曲空间、球面)时,用测地距替代欧氏距
45
+ def manifold_attention(Q, K, V, manifold):
46
+ geodist = manifold.geodesic_distance_matrix(positions) # (n, n)
47
+ geo_kernel = exp(-geodist^2 / (2 * sigma^2)) # RBF 核
48
+ scores = (Q @ K.T) / sqrt(d) + log(geo_kernel + eps)
49
+ return softmax(scores) @ V
50
+ ```
51
+
52
+ ## 可实现结构
53
+ - **RoPE 扩展**:从 $SO(2)$ 旋转到更高维旋转群 $SO(2k)$,编码多维位置信息(2D 图像 patch、3D voxel)
54
+ - **层级位置偏置**:树结构中用 LCA(最近公共祖先)深度作为距离,适合文档/代码的层级建模
55
+ - **分子构象注意力**:3D 原子坐标 → 距离矩阵 → 几何偏置,用于分子 GNN 和蛋白质结构预测
56
+
57
+ ## GPU 可行性
58
+ - **D1[v]**:距离矩阵和偏置矩阵均为稠密张量,逐元素运算
59
+ - **D2[v]**:主体 $Q K^T$ 为标准 GEMM;几何偏置为加法,不阻断 GEMM
60
+ - **D3[~]**:成对距离矩阵 $O(n^2)$ 构建和存储;但可用分块计算 + online softmax 避免物化完整矩阵
61
+ - **D4[~]**:$n \times n$ 距离矩阵占用显存;可分块/流式计算(与 FlashAttention 兼容)
62
+ - **D5[v]**:距离计算和偏置加法在 bf16 下稳定;RBF 的 exp 需注意上溢(clamp 距离)
63
+ - **D6[v]**:距离计算和注意力可流水线并行,成对距离可分块并行
64
+ - **D7[v]**:远距离偏置趋于 $-\infty$(softmax 后趋零),天然诱导结构化稀疏(局部注意力窗口)
65
+ - **D8[v]**:几何偏置可融入 FlashAttention 的 online softmax 循环中(加在 $QK^T$ 之后、softmax 之前)
66
+
67
+ ## 论文表述方式
68
+ "我们提出几何感知注意力,通过在注意力分数中显式注入可学习的几何距离偏置项,使模型天然尊重输入空间的度量结构,在不增加参数量的情况下将远距离 token 的注意力指数衰减,同时保持与 FlashAttention 的兼容性。"
69
+
70
+ ## 风险
71
+ - **几何先验与数据冲突**:若几何距离与语义相关性不一致(如文本中远距离但语义相关的 token),强几何偏置会伤害模型表达。需让偏置可学习且可被内容注意力覆盖。
72
+ - **距离计算的非可微性**:某些距离(图最短路径、树 LCA 深度)不可微或计算复杂。需使用可微松弛(softmin 替代 min)或预计算距离矩阵。
@@ -0,0 +1,72 @@
1
+ # Information Bottleneck Attention
2
+ > **Rigor disclaimer**: Claims about complexity, memory, FlashAttention fusion, Tensor Core, and KV-Cache compression are marked as [v] verified / [~] retrofittable (needs validation) / [x] infeasible. Unmarked claims are theoretically possible but require engineering validation.
3
+
4
+ ## Applicable Problems
5
+ When the attention mechanism needs to **selectively transmit useful information while suppressing redundant/noisy information**, information bottleneck theory can guide the learning of attention weights -- maximizing the mutual information $I(Z;Y)$ of the attention distribution with respect to the target $Y$, while minimizing the mutual information $I(X;Z)$ with respect to the input $X$. Typical scenarios include: long-document summarization (filtering large numbers of irrelevant tokens), multimodal alignment (cross-modal noise suppression), and interpretability (attention weights as visualization of information flow).
6
+
7
+ ## Mathematical Inspiration
8
+ - Lenses: [categorical (information-theoretic framework unifying attention design), variational (constrained variational and Lagrangian duality)]
9
+ - Knowledge: [`../../knowledge-base/probability/information-bottleneck.md` (IB objective and variational lower bound), `../../knowledge-base/probability/kl-divergence.md` (implementation of KL regularization), `../../knowledge-base/probability/entropy.md` (mutual information estimation)]
10
+
11
+ ## Required Mathematical Knowledge
12
+ - **Information Bottleneck Objective**: $\min I(X;Z) - \beta I(Z;Y)$, balancing compression and prediction
13
+ - **Variational Information Bottleneck (VIB)**: Replacing intractable mutual information with variational lower bounds
14
+ - **Correspondence Between Mutual Information and Attention**: Softmax attention weights $\alpha_{ij}$ can be interpreted as information channel allocations from key $j$ to query $i$
15
+
16
+ ## AI Module Form
17
+
18
+ **Core Idea**: Treat attention as an information bottleneck -- attention weights determine "how much information flows from values to output," while KL regularization constrains the information throughput.
19
+
20
+ **Scheme A: KL-Regularized Attention (Simplest IB Attention)**:
21
+ ```python
22
+ # KL divergence between attention distribution q(z|x) and uniform prior as IB regularizer
23
+ scores = (Q @ K.T) / sqrt(d)
24
+ attn = softmax(scores)
25
+ uniform_prior = ones_like(attn) / n
26
+ kl_reg = (attn * (log(attn + eps) - log(uniform_prior))).sum(dim=-1).mean()
27
+ loss = task_loss + beta * kl_reg
28
+ output = attn @ V
29
+ ```
30
+
31
+ **Scheme B: Variational Information Bottleneck Attention (VIB-Attention)**:
32
+ ```python
33
+ # Introduce stochastic bottleneck Z ~ q(Z|attention) to limit information throughput
34
+ scores = (Q @ K.T) / sqrt(d)
35
+ attn = softmax(scores)
36
+ mu_z, log_var_z = attn, linear(attn) # mean and learnable variance
37
+ z = softmax(mu_z + exp(0.5 * log_var_z) * randn_like(mu_z)) # reparameterization + softmax
38
+ kl = 0.5 * (mu_z^2 + exp(log_var_z) - log_var_z - 1).sum(-1).mean() # KL vs prior
39
+ output = z @ V
40
+ loss = task_loss + beta * kl
41
+ ```
42
+
43
+ **Scheme C: Mutual Information Maximization Attention (DIM Style)**:
44
+ ```python
45
+ # Directly maximize I(Z;Y) via InfoNCE, with KL constraining I(X;Z)
46
+ Z = softmax((Q @ K.T) / sqrt(d)) @ V
47
+ info_nce = infonce_loss(Z, target_embedding, negatives, tau=0.1)
48
+ kl_bottleneck = estimate_kl(X, Z) # MINE/NWJ estimator
49
+ loss = -info_nce + beta * kl_bottleneck
50
+ ```
51
+
52
+ ## Implementable Architectures
53
+ - **IB-Sparse Attention**: KL regularization serves as a soft constraint on attention sparsity -- larger KL relative to uniform prior leads to more concentrated attention, yielding implicit Top-K selection
54
+ - **IB Interpretation of Dropout**: Dropout is a form of stochastic information bottleneck -- randomly blocking information channels forces the model to learn robust representations. The dropout rate corresponds to the $\beta$ parameter
55
+ - **Multi-Head Information Allocation**: Different heads learn different information bottlenecks (different $\beta$); some heads transmit global information, others only local information
56
+
57
+ ## GPU Feasibility
58
+ - **D1**: KL regularization involves element-wise operations; VIB reparameterization sampling is element-wise
59
+ - **D2**: The main body $QK^T$ and $attn \cdot V$ are standard GEMM; regularization introduces no new GEMM operations
60
+ - **D3**: KL regularization is $O(n)$ per token, adding no asymptotic complexity
61
+ - **D4**: VIB requires additional $\mu_z$ and $\log\sigma_z$, approximately doubling attention weight memory
62
+ - **D5**: log/exp in KL computations are stable under bf16 (standard log-softmax tricks)
63
+ - **D6**: Regularization can be computed in parallel with forward propagation, introducing no serial dependencies
64
+ - **D7**: KL regularization implicitly induces attention sparsity, amenable to block-sparse acceleration
65
+ - **D8**: KL can be fused into the softmax kernel (FusedSoftmaxKL)
66
+
67
+ ## Paper Phrasing
68
+ "We propose information bottleneck attention, which models attention as an information bottleneck variational problem. By maximizing the mutual information between output and target while minimizing redundant information transmission from the input, it achieves theoretically optimal information selection and demonstrates enhanced sparsity and interpretability in experiments."
69
+
70
+ ## Risks
71
+ - **High Variance of Mutual Information Estimators**: The MINE/NWJ/InfoNCE estimators in Scheme C exhibit high variance in high-dimensional spaces, potentially causing training instability. It is recommended to first validate the basic effect of IB attention with Scheme A (KL regularization) before attempting the full IB objective.
72
+ - **Difficulty of $\beta$ Tuning**: $\beta$ controls the compression-prediction trade-off, and the optimal $\beta$ varies significantly across tasks. Too small a $\beta$ degenerates to standard attention; too large a $\beta$ causes underfitting. Adaptive $\beta$ scheduling or information plane monitoring is recommended.
@@ -0,0 +1,72 @@
1
+ # 信息瓶颈注意力 / Information Bottleneck Attention
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当注意力机制需要**选择性传递有用信息、抑制冗余/噪声信息**时,用信息瓶颈理论指导注意力权重的学习——使注意力分布最大化关于目标 $Y$ 的互信息 $I(Z;Y)$,同时最小化关于输入 $X$ 的互信息 $I(X;Z)$。典型场景:长文档摘要(大量无关 token 需被过滤)、多模态对齐(跨模态噪声抑制)、可解释性(注意力权重作为信息流的可视化)。
6
+
7
+ ## 数学思想来源
8
+ - 透镜:[categorical(范畴化透镜 — 信息论框架统一注意力设计), variational(变分透镜 — 约束优化与拉格朗日对偶)]
9
+ - 知识:[`../../knowledge-base/probability/information-bottleneck.md`(IB 目标函数与变分下界), `../../knowledge-base/probability/kl-divergence.md`(KL 正则项的实现), `../../knowledge-base/probability/entropy.md`(互信息估计)]
10
+
11
+ ## 需要的数学知识
12
+ - **信息瓶颈 IB 目标**:$\min I(X;Z) - \beta I(Z;Y)$,压缩-预测权衡
13
+ - **变分信息瓶颈 VIB**:用变分下界替代难以估计的互信息
14
+ - **互信息与注意力的对应**:softmax 注意力权重 $\alpha_{ij}$ 可解释为从 key $j$ 到 query $i$ 的信息信道分配
15
+
16
+ ## AI 模块形式
17
+
18
+ **核心思路**:将注意力视为信息瓶颈——注意力权重决定"让多少信息从 value 流向输出",同时用 KL 正则约束信息量不过大。
19
+
20
+ **方案 A:KL 正则化注意力(最简 IB 注意力)**:
21
+ ```python
22
+ # 注意力分布 q(z|x) 与均匀先验的 KL 散度作为 IB 正则
23
+ scores = (Q @ K.T) / sqrt(d)
24
+ attn = softmax(scores)
25
+ uniform_prior = ones_like(attn) / n
26
+ kl_reg = (attn * (log(attn + eps) - log(uniform_prior))).sum(dim=-1).mean()
27
+ loss = task_loss + beta * kl_reg
28
+ output = attn @ V
29
+ ```
30
+
31
+ **方案 B:变分信息瓶颈注意力(VIB-Attention)**:
32
+ ```python
33
+ # 引入随机瓶颈 Z ~ q(Z|attention),限制信息通过量
34
+ scores = (Q @ K.T) / sqrt(d)
35
+ attn = softmax(scores)
36
+ mu_z, log_var_z = attn, linear(attn) # 均值与可学习方差
37
+ z = softmax(mu_z + exp(0.5 * log_var_z) * randn_like(mu_z)) # 重参数化 + softmax
38
+ kl = 0.5 * (mu_z^2 + exp(log_var_z) - log_var_z - 1).sum(-1).mean() # KL vs 先验
39
+ output = z @ V
40
+ loss = task_loss + beta * kl
41
+ ```
42
+
43
+ **方案 C:互信息最大化注意力(DIM 风格)**:
44
+ ```python
45
+ # 用 InfoNCE 直接最大化 I(Z;Y),配合 KL 约束 I(X;Z)
46
+ Z = softmax((Q @ K.T) / sqrt(d)) @ V
47
+ info_nce = infonce_loss(Z, target_embedding, negatives, tau=0.1)
48
+ kl_bottleneck = estimate_kl(X, Z) # MINE/NWJ 估计器
49
+ loss = -info_nce + beta * kl_bottleneck
50
+ ```
51
+
52
+ ## 可实现结构
53
+ - **IB-Sparse Attention**:将 KL 正则化为注意力稀疏性的软约束——KL 对均匀先越大 → 注意力越集中 → 隐式 Top-K 选择
54
+ - **Dropout 的 IB 解释**:Dropout 是一种随机信息瓶颈——随机阻断部分信息通道,迫使模型学习鲁棒表示。Dropout rate 对应 $\beta$ 参数
55
+ - **Multi-Head 信息分配**:不同 head 学习不同的信息瓶颈(不同 $\beta$),有的 head 传递全局信息,有的只传递局部信息
56
+
57
+ ## GPU 可行性
58
+ - **D1[v]**:KL 正则项为逐元素运算,VIB 重参数化采样为逐元素
59
+ - **D2[v]**:主体 $QK^T$ 和 $attn \cdot V$ 为标准 GEMM,正则项不引入新 GEMM
60
+ - **D3[v]**:KL 正则 $O(n)$ 逐 token,不增加渐近复杂度
61
+ - **D4[~]**:VIB 需额外 $\mu_z$ 和 $\log\sigma_z$,约 2x 注意力权重显存
62
+ - **D5[v]**:KL 中 log/exp 在 bf16 下稳定(标准 log-softmax 技巧)
63
+ - **D6[v]**:正则项可与前向传播并行,不引入串行依赖
64
+ - **D7[v]**:KL 正则隐式诱导注意力稀疏性,可利用 block-sparse 加速
65
+ - **D8[v]**:KL 可融入 softmax kernel(FusedSoftmaxKL)
66
+
67
+ ## 论文表述方式
68
+ "我们提出信息瓶颈注意力机制,通过将注意力建模为信息瓶颈优化问题,在最大化输出与目标的互信息的同时最小化输入信息的冗余传递,实现理论上最优的信息选择,并在实验中展现出更强的稀疏性和可解释性。"
69
+
70
+ ## 风险
71
+ - **互信息估计的方差问题**:方案 C 中的 MINE/NWJ/InfoNCE 估计器在高维空间中方差大,可能导致训练不稳定。建议先用方案 A(KL 正则)验证 IB 注意力的基本效果,再尝试完整 IB 目标。
72
+ - **$\beta$ 调参困难**:$\beta$ 控制压缩-预测权衡,不同任务最优 $\beta$ 差异大。$\beta$ 过小退化为标准注意力,$\beta$ 过大导致欠拟合。建议自适应 $\beta$ 调度或信息平面监控。
@@ -0,0 +1,68 @@
1
+ # Projection Attention
2
+ > **Rigor disclaimer**: Claims about complexity, memory, FlashAttention fusion, Tensor Core, and KV-Cache compression are marked as [v] verified / [~] retrofittable (needs validation) / [x] infeasible. Unmarked claims are theoretically possible but require engineering validation.
3
+
4
+ ## Applicable Problems
5
+ When the token/key space dimensionality is too high, the standard attention $Q K^T$ inner product tends to become uniform in high-dimensional spaces ("attention collapse"). In such cases, key/query vectors must first be projected onto a **subspace with superior geometric structure** before computing attention. Typical scenarios include: KV-Cache compression for long-context LLMs, attention sparsification in high-dimensional embedding spaces, and attention alignment of heterogeneous features in multimodal fusion.
6
+
7
+ ## Mathematical Inspiration
8
+ - Lenses: [projection, spectral, probabilistic]
9
+ - Knowledge: [`../../knowledge-base/probability/concentration-inequality.md` (high-dimensional concentration inequalities provide theoretical explanation for attention collapse), `../../knowledge-base/probability/entropy.md` (entropy of attention distributions as a quality metric)]
10
+
11
+ ## Required Mathematical Knowledge
12
+ - **Johnson-Lindenstrauss Lemma**: High-dimensional point sets can be projected onto an $O(\log n / \epsilon^2)$-dimensional subspace while approximately preserving distances
13
+ - **Random Projections and Subspace Embeddings**: Sparse projection matrices (e.g., CountSketch, SRHT) approximately preserve inner products
14
+ - **SVD / PCA Truncation**: Optimal low-rank subspace projection that maximizes retained variance
15
+
16
+ ## AI Module Form
17
+
18
+ **Core Idea**: Project $Q, K \in \mathbb{R}^{n \times d}$ onto an $r$-dimensional subspace ($r \ll d$) before computing attention:
19
+
20
+ $$\text{ProjAttn}(Q, K, V) = \text{softmax}\left(\frac{Q P_Q (K P_K)^T}{\sqrt{r}}\right) V$$
21
+
22
+ where $P_Q, P_K \in \mathbb{R}^{d \times r}$ are projection matrices.
23
+
24
+ **Three Projection Strategies**:
25
+
26
+ 1. **Learnable Projection** ($P$ as trainable parameters):
27
+ ```
28
+ P_Q = Linear(d, r, bias=False) # r << d
29
+ P_K = Linear(d, r, bias=False)
30
+ scores = (Q @ P_Q) @ (K @ P_K).T / sqrt(r)
31
+ attn = softmax(scores) @ V
32
+ ```
33
+
34
+ 2. **Random Fixed Projection** (guaranteed by the JL Lemma):
35
+ ```
36
+ P = random_gaussian(d, r) / sqrt(r) # fixed, not trained
37
+ scores = (Q @ P) @ (K @ P).T / sqrt(r)
38
+ ```
39
+
40
+ 3. **Data-Adaptive Projection** (online PCA):
41
+ ```
42
+ # Maintain running covariance of K, take top-r eigenvectors
43
+ C = running_mean(K^T @ K) # d x d
44
+ eigenvecs = top_r_eigenvectors(C) # d x r
45
+ scores = (Q @ eigenvecs) @ (K @ eigenvecs).T / sqrt(r)
46
+ ```
47
+
48
+ ## Implementable Architectures
49
+ - **Multi-Head Projection**: Each head uses a different $P_h \in \mathbb{R}^{d_h \times r}$, with total computation $O(n \cdot d \cdot r + n^2 \cdot r)$. When $r \ll d$, this saves the $O(n^2 d)$ cost of $Q K^T$
50
+ - **Key-cache Compression**: The projected $K' = K P_K \in \mathbb{R}^{n \times r}$ replaces the original $K$ in storage, reducing Key-cache memory by about $d/r$. Full KV-Cache compression requires a separate V compression/reconstruction mechanism
51
+ - **Hierarchical Projection**: Shallow layers use small $r$ (coarse filtering), while deep layers use large $r$ (fine ranking)
52
+
53
+ ## GPU Feasibility
54
+ - **D1**: Projection = matrix multiplication, attention = matrix multiplication chain; entirely tensor operations
55
+ - **D2**: $Q P_Q$ and $K P_K$ are both standard GEMM operations, fully utilizing Tensor Cores
56
+ - **D3**: Projection cost $O(ndr)$ is far below attention cost $O(n^2 d)$, and after projection $r \ll d$ reduces attention to $O(n^2 r)$
57
+ - **D4**: Key-cache compressed by $d/r$; V-cache must be handled separately
58
+ - **D5**: Projection matrices are orthogonal or near-orthogonal, yielding numerical stability; bf16 is acceptable
59
+ - **D6**: Projection can be pipelined with attention; Multi-Head is naturally parallel across heads
60
+ - **D7**: Projection matrices are inherently dense; sparse projections (CountSketch) may introduce gather/scatter operations
61
+ - **D8[~] Retrofittable, needs kernel-level validation**: Projection may be integrated into a FlashAttention-style kernel, but requires kernel-level verification
62
+
63
+ ## Paper Phrasing
64
+ "We decompose attention computation into two steps -- low-dimensional subspace projection and projected-space attention -- achieving a $d/r$-fold Key-cache compression (full KV-Cache compression requires separate V compression/reconstruction) while preserving attention quality and guaranteeing Johnson-Lindenstrauss distance preservation."
65
+
66
+ ## Risks
67
+ - **Projection Direction Degeneracy**: Learnable projections may collapse onto a few directions (deterioration of the condition number of $P^T P$), causing attention distributions to degenerate. Orthogonal regularization $\|P^T P - I\|_F^2$ is required.
68
+ - **Irreversible Information Loss**: Projection discards $(d-r)$ dimensions of information; if the task relies on features in these dimensions, performance will degrade. It is recommended to combine with residual connections (weighted combination of original attention and projected attention).
@@ -0,0 +1,68 @@
1
+ # 投影注意力 / Projection Attention
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当输入的 token/key 空间维度过高,标准注意力的 $Q K^T$ 内积在高维空间中趋于均匀("注意力坍缩")时,需要先将 key/query 投影到一个**几何结构更优的子空间**再做注意力计算。典型场景:长上下文 LLM 的 KV-Cache 压缩、高维嵌入空间的注意力稀疏化、多模态融合中异构特征的注意力对齐。
6
+
7
+ ## 数学思想来源
8
+ - 透镜:[projection(投影与分解), spectral(谱分解), probabilistic(概率)]
9
+ - 知识:[`../../knowledge-base/probability/concentration-inequality.md`(高维浓度不等式 → 注意力坍缩的理论解释), `../../knowledge-base/probability/entropy.md`(注意力分布的熵作为质量指标)]
10
+
11
+ ## 需要的数学知识
12
+ - **Johnson-Lindenstrauss 引理**:高维点集可投影到 $O(\log n / \epsilon^2)$ 维子空间而近似保持距离
13
+ - **随机投影与子空间嵌入**:稀疏投影矩阵(如 CountSketch、SRHT)近似保持内积
14
+ - **SVD / PCA 截断**:最优低秩子空间投影,最大化保留方差
15
+
16
+ ## AI 模块形式
17
+
18
+ **核心思路**:将 $Q, K \in \mathbb{R}^{n \times d}$ 先投影到 $r$ 维子空间($r \ll d$),再计算注意力:
19
+
20
+ $$\text{ProjAttn}(Q, K, V) = \text{softmax}\left(\frac{Q P_Q (K P_K)^T}{\sqrt{r}}\right) V$$
21
+
22
+ 其中 $P_Q, P_K \in \mathbb{R}^{d \times r}$ 为投影矩阵。
23
+
24
+ **三种投影策略**:
25
+
26
+ 1. **可学习投影**($P$ 为训练参数):
27
+ ```
28
+ P_Q = Linear(d, r, bias=False) # r << d
29
+ P_K = Linear(d, r, bias=False)
30
+ scores = (Q @ P_Q) @ (K @ P_K).T / sqrt(r)
31
+ attn = softmax(scores) @ V
32
+ ```
33
+
34
+ 2. **随机固定投影**(JL 引理保证):
35
+ ```
36
+ P = random_gaussian(d, r) / sqrt(r) # 固定不训练
37
+ scores = (Q @ P) @ (K @ P).T / sqrt(r)
38
+ ```
39
+
40
+ 3. **数据自适应投影**(在线 PCA):
41
+ ```
42
+ # 维护 K 的 running covariance,取 top-r 特征向量
43
+ C = running_mean(K^T @ K) # d x d
44
+ eigenvecs = top_r_eigenvectors(C) # d x r
45
+ scores = (Q @ eigenvecs) @ (K @ eigenvecs).T / sqrt(r)
46
+ ```
47
+
48
+ ## 可实现结构
49
+ - **Multi-Head 投影**:每个 head 使用不同的 $P_h \in \mathbb{R}^{d_h \times r}$,总计算量 $O(n \cdot d \cdot r + n^2 \cdot r)$,当 $r \ll d$ 时节省 $Q K^T$ 的 $O(n^2 d)$ 开销
50
+ - **KV-Cache 压缩**:投影后的 $K' = K P_K \in \mathbb{R}^{n \times r}$ 替代原始 $K$ 存储,Key 部分显存节省约 $d/r$ 倍(完整 KV-Cache 压缩需额外设计 V 的压缩/重构机制)
51
+ - **分层投影**:浅层用小 $r$(粗筛),深层用大 $r$(精排)
52
+
53
+ ## GPU 可行性
54
+ - **D1[v]**:投影 = 矩阵乘,注意力 = 矩阵乘链,全程张量运算
55
+ - **D2[v]**:$Q P_Q$ 和 $K P_K$ 均为标准 GEMM,吃满 Tensor Core
56
+ - **D3[v]**:投影 $O(ndr)$ 远低于注意力 $O(n^2 d)$,且投影后 $r \ll d$ 使注意力 $O(n^2 r)$
57
+ - **D4[v]**:Key-cache 压缩 $d/r$ 倍(V-cache 需独立处理),直接降低显存峰值
58
+ - **D5[v]**:投影矩阵正交/近正交时数值稳定,bf16 可接受
59
+ - **D6[v]**:投影可与注意力流水线并行,Multi-Head 天然跨头并行
60
+ - **D7[~]**:投影矩阵本身稠密;若用稀疏投影(CountSketch),可能引入 gather/scatter
61
+ - **D8[~]可改造需验证**:投影可融入 FlashAttention 的 online softmax 循环中
62
+
63
+ ## 论文表述方式
64
+ "我们将注意力计算分解为低维子空间投影与投影空间注意力两步,在保持注意力质量的同时将 Key-cache 压缩 $d/r$ 倍(V-cache 需独立处理),并保证 Johnson-Lindenstrauss 距离保持性。"
65
+
66
+ ## 风险
67
+ - **投影方向退化**:可学习投影可能坍缩到少数方向($P^T P$ 条件数恶化),导致注意力分布退化。需加正交正则化 $\|P^T P - I\|_F^2$。
68
+ - **信息丢失不可逆**:投影丢弃了 $(d-r)$ 维信息,若任务恰需这些维度的特征则性能下降。建议配合残差连接(原始注意力 + 投影注意力的加权组合)。
@@ -0,0 +1,71 @@
1
+ # Spectral Attention
2
+ > **Rigor disclaimer**: Claims about complexity, memory, FlashAttention fusion, Tensor Core, and KV-Cache compression are marked as [v] verified / [~] retrofittable (needs validation) / [x] infeasible. Unmarked claims are theoretically possible but require engineering validation.
3
+
4
+ ## Applicable Problems
5
+ When the input signal exhibits **frequency-domain/spectral structure** (periodicity, cyclic symmetry, graph structure), computing attention in the spectral domain rather than the spatial domain can dramatically reduce complexity while exploiting the signal's intrinsic structure. Typical scenarios include: time series forecasting (periodic signals), graph neural networks (graph Laplacian spectral decomposition), positional encoding (frequency-domain interpretation of RoPE/ALiBi), and $O(n \log n)$ acceleration of long-sequence attention.
6
+
7
+ ## Mathematical Inspiration
8
+ - Lenses: [duality (frequency-domain transform), symmetry (cyclic/translation invariance)]
9
+ - Knowledge: [`../../knowledge-base/probability/entropy.md` (spectral entropy for measuring signal complexity), `../../knowledge-base/probability/concentration-inequality.md` (frequency-domain concentration inequalities)]
10
+
11
+ ## Required Mathematical Knowledge
12
+ - **Discrete Fourier Transform (DFT/FFT)**: $O(n \log n)$ frequency-domain transform and the cyclic convolution theorem
13
+ - **Graph Laplacian Spectral Decomposition**: $L = U \Lambda U^T$, where $U$ is the graph Fourier basis
14
+ - **Irreducible Representations of the Cyclic Group $\mathbb{Z}_n$**: The DFT matrix is precisely the representation matrix of the cyclic group (see `references/books/abstract-algebra.md` Ch.4, Ch.11)
15
+
16
+ ## AI Module Form
17
+
18
+ **Core Idea**: Transform attention from the spatial-domain $Q K^T$ into diagonal/sparse operations in the spectral domain:
19
+
20
+ **Scheme A: FFT-Accelerated Attention (Time Series)**:
21
+ ```python
22
+ # Express cyclic convolution as element-wise multiplication in the frequency domain
23
+ Q_hat = fft(Q, dim=seq) # (n, d) -> (n, d) frequency domain
24
+ K_hat = fft(K, dim=seq)
25
+ # Attention ~ frequency-domain filtering: independent weighting per frequency component
26
+ attn_hat = Q_hat * conj(K_hat) # element-wise multiply = cyclic convolution
27
+ attn = ifft(attn_hat, dim=seq)
28
+ # Complexity: O(n log n * d) vs. standard O(n^2 * d)
29
+ ```
30
+
31
+ **Scheme B: Graph Spectral Attention (GNN)**:
32
+ ```python
33
+ # Precompute graph Laplacian spectral decomposition L = U Lambda U^T (offline)
34
+ U = eigenvectors(L) # (n, k), take top-k low-frequency eigenvectors
35
+ # Spectral-domain attention: compute in the low-frequency subspace
36
+ Q_spec = U^T @ Q # (k, d) project to spectral domain
37
+ K_spec = U^T @ K
38
+ scores = (Q_spec @ W_q) @ (K_spec @ W_k).T / sqrt(d)
39
+ attn_spec = softmax(scores) @ (U^T @ V)
40
+ output = U @ attn_spec # back-project to spatial domain
41
+ ```
42
+
43
+ **Scheme C: Frequency-Adaptive Attention Weights**:
44
+ ```python
45
+ freq_weights = learnable_parameter(num_freq_bands) # learnable spectral weights
46
+ Q_hat, K_hat = fft(Q), fft(K)
47
+ scores_freq = freq_weights.unsqueeze(-1) * (Q_hat * conj(K_hat))
48
+ attn = ifft(scores_freq)
49
+ ```
50
+
51
+ ## Implementable Architectures
52
+ - **Spectral Transformer**: Replace $O(n^2)$ attention with FFT, suitable for periodic sequence data (meteorological, financial, audio)
53
+ - **Graph Spectral Attention**: Leverage the first $k$ eigenvectors of the graph Laplacian for low-dimensional attention, suitable for large-scale graphs ($n > 10^5$)
54
+ - **Frequency-Aware Positional Encoding**: The essence of RoPE is the unitary representation of the cyclic group $\mathbb{Z}$ (see Abstract Algebra Ch.4), generalizable to other groups
55
+
56
+ ## GPU Feasibility
57
+ - **D1**: FFT and matrix multiplication are both standard tensor operations
58
+ - **D2**: Spectral projection $U^T Q$ is a standard GEMM; although FFT is not GEMM, highly optimized cuFFT implementations are available
59
+ - **D3**: FFT attention $O(n \log n \cdot d)$, far superior to $O(n^2 d)$
60
+ - **D4**: Frequency-domain representation introduces no extra dimensions; spectral projection can reduce to $k \ll n$ dimensions
61
+ - **D5**: Complex-valued FFT suffers precision loss under fp16; fp32 or real-valued FFT (RFFT) is required
62
+ - **D6**: FFT can be parallelized across batch/head; cuFFT supports multi-stream execution
63
+ - **D7**: High-frequency components can be truncated in the spectral domain (structured sparsity), retaining only top-k frequencies
64
+ - **D8**: Fusing FFT with attention requires custom kernels; no ready-made fusion exists in standard libraries
65
+
66
+ ## Paper Phrasing
67
+ "We propose a spectral-domain attention mechanism that transforms attention computation into the Fourier/Laplacian spectral domain, leveraging the cyclic convolution theorem to reduce sequence attention complexity from $O(n^2)$ to $O(n \log n)$ while preserving the ability to model dependencies at multiple scales through frequency-adaptive weights."
68
+
69
+ ## Risks
70
+ - **Violation of Periodicity Assumption**: FFT implicitly assumes periodic boundary conditions, causing spectral leakage for non-periodic signals such as natural language. Windowing functions or zero-padding are needed.
71
+ - **Graph Laplacian Precomputation Cost**: Eigendecomposition $O(n^3)$ is infeasible for large-scale graphs, requiring approximations (Nystrom/Lanczos), and dynamic graphs necessitate recomputation.
@@ -0,0 +1,71 @@
1
+ # 谱注意力 / Spectral Attention
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当输入信号具有**频域/谱结构**(周期性、循环对称性、图结构)时,在谱域而非空域计算注意力可大幅降低复杂度并利用信号的内在结构。典型场景:时间序列预测(周期性信号)、图神经网络(图 Laplacian 谱分解)、位置编码(RoPE/ALiBi 的频率解释)、长序列注意力的 $O(n \log n)$ 加速。
6
+
7
+ ## 数学思想来源
8
+ - 透镜:[duality(对偶透镜 — 频域变换), symmetry(对称透镜 — 循环/平移不变性)]
9
+ - 知识:[`../../knowledge-base/probability/entropy.md`(谱熵度量信号复杂度), `../../knowledge-base/probability/concentration-inequality.md`(频域浓度不等式)]
10
+
11
+ ## 需要的数学知识
12
+ - **离散傅里叶变换 DFT / FFT**:$O(n \log n)$ 频域变换,循环卷积定理
13
+ - **图 Laplacian 谱分解**:$L = U \Lambda U^T$,$U$ 为图 Fourier 基
14
+ - **循环群 $\mathbb{Z}_n$ 的不可约表示**:DFT 矩阵即循环群的表示矩阵(参见 `references/books/abstract-algebra.md` Ch.4, Ch.11)
15
+
16
+ ## AI 模块形式
17
+
18
+ **核心思路**:将注意力从空域的 $Q K^T$ 转换到谱域的对角/稀疏运算:
19
+
20
+ **方案 A:FFT 加速注意力(时间序列)**:
21
+ ```python
22
+ # 将循环卷积写成谱域逐元素乘
23
+ Q_hat = fft(Q, dim=seq) # (n, d) -> (n, d) 频域
24
+ K_hat = fft(K, dim=seq)
25
+ # 注意力 ≈ 频域滤波:每个频率分量独立加权
26
+ attn_hat = Q_hat * conj(K_hat) # 逐元素乘 = 循环卷积
27
+ attn = ifft(attn_hat, dim=seq)
28
+ # 复杂度:O(n log n * d) vs 标准 O(n^2 * d)
29
+ ```
30
+
31
+ **方案 B:图谱注意力(GNN)**:
32
+ ```python
33
+ # 预计算图 Laplacian 谱分解 L = U Λ U^T(离线)
34
+ U = eigenvectors(L) # (n, k), 取 top-k 低频特征向量
35
+ # 谱域注意力:在低频子空间中计算
36
+ Q_spec = U^T @ Q # (k, d) 投影到谱域
37
+ K_spec = U^T @ K
38
+ scores = (Q_spec @ W_q) @ (K_spec @ W_k).T / sqrt(d)
39
+ attn_spec = softmax(scores) @ (U^T @ V)
40
+ output = U @ attn_spec # 反投影回空域
41
+ ```
42
+
43
+ **方案 C:频率自适应注意力权重**:
44
+ ```python
45
+ freq_weights = learnable_parameter(num_freq_bands) # 可学习频谱权重
46
+ Q_hat, K_hat = fft(Q), fft(K)
47
+ scores_freq = freq_weights.unsqueeze(-1) * (Q_hat * conj(K_hat))
48
+ attn = ifft(scores_freq)
49
+ ```
50
+
51
+ ## 可实现结构
52
+ - **Spectral Transformer**:用 FFT 替代 $O(n^2)$ 注意力,适合周期性序列数据(气象、金融、音频)
53
+ - **Graph Spectral Attention**:利用图 Laplacian 的前 $k$ 个特征向量做低维注意力,适合大规模图($n > 10^5$)
54
+ - **频率感知位置编码**:RoPE 的本质即循环群 $\mathbb{Z}$ 的酉表示(参见抽象代数 Ch.4),可推广到其他群
55
+
56
+ ## GPU 可行性
57
+ - **D1[v]**:FFT 和矩阵乘均为标准张量运算
58
+ - **D2[v]**:谱投影 $U^T Q$ 为标准 GEMM;FFT 虽非 GEMM 但有高度优化的 cuFFT 实现
59
+ - **D3[v]**:FFT 注意力 $O(n \log n \cdot d)$,远优于 $O(n^2 d)$
60
+ - **D4[v]**:频域表示不增加额外维度,谱投影可降低到 $k \ll n$ 维
61
+ - **D5[~]**:复数 FFT 在 fp16 下精度损失,需 fp32 或使用实数 FFT (RFFT)
62
+ - **D6[v]**:FFT 可跨 batch/head 并行,cuFFT 支持多流
63
+ - **D7[v]**:谱域中高频分量可截断(结构化稀疏),只保留 top-k 频率
64
+ - **D8[~]**:FFT 与 attention 融合需自定义 kernel,标准库无现成融合
65
+
66
+ ## 论文表述方式
67
+ "我们提出谱域注意力机制,通过将注意力计算转换到 Fourier/Laplacian 谱域,利用循环卷积定理将序列注意力复杂度从 $O(n^2)$ 降至 $O(n \log n)$,同时通过频率自适应权重保留对不同尺度依赖关系的建模能力。"
68
+
69
+ ## 风险
70
+ - **非周期性假设违反**:FFT 隐式假设周期性边界条件,对自然语言等非周期信号产生谱泄漏,需加窗函数或零填充。
71
+ - **图 Laplacian 预计算成本**:大规模图的特征分解 $O(n^3)$ 不可行,需近似(Nyström/Lanczos),且动态图需重算。
@@ -0,0 +1,71 @@
1
+ # Leverage Score Selection
2
+ > **Rigor disclaimer**: Claims about complexity, memory, FlashAttention fusion, Tensor Core, and KV-Cache compression are marked as [v] verified / [~] retrofittable (needs validation) / [x] infeasible. Unmarked claims are theoretically possible but require engineering validation.
3
+
4
+ ## Target Problem
5
+ Use when selecting the most representative rows / columns / tokens from a large-scale matrix while guaranteeing the precision of downstream linear algebra operations: KV-Cache token selection, data coreset construction, Nystrom landmark sampling, distributed gradient compression. Core objective: **sample based on statistical leverage scores derived from subspace projections, with probabilistic guarantees of approximating full-computation accuracy**.
6
+
7
+ ## Mathematical Foundations
8
+ - Lenses: lenses/spectral.md (leverage scores = projection energy of row vectors onto the principal subspace), lenses/probabilistic.md (probabilistic sampling and concentration inequality guarantees), lenses/algorithmic.md (complexity--accuracy trade-offs of randomized algorithms)
9
+ - Knowledge: knowledge-base/matrix-analysis/low-rank-approximation.md (randomized SVD, nuclear norm), knowledge-base/matrix-analysis/projection.md (diagonal entries of the projection matrix = leverage scores), knowledge-base/probability/concentration-inequality.md (Bernstein matrix concentration bound)
10
+
11
+ ## Required Mathematical Background
12
+ - **Statistical Leverage Scores**: $\ell_i = \|(V_k V_k^T)_i\|^2 = (V_k V_k^T)_{ii}$, the projection energy of the $i$-th row onto the rank-$k$ subspace; $\sum_i \ell_i = k$
13
+ - **Leverage Score Sampling Guarantee**: sampling $s = O(k \log k / \epsilon^2)$ rows with probabilities $p_i = \ell_i / k$ yields a $(1+\epsilon)$ approximation to full least squares (Drineas--Mahoney)
14
+ - **Bernstein Matrix Bound**: after sampling, $\|\hat{A}^T \hat{A} - A^T A\|_2 \leq \epsilon \|A\|_F^2$ with probability $\geq 1-\delta$
15
+ - **Fast Approximation**: $\tilde{\ell}_i = \|(A\Omega)_i\|^2$ ($\Omega$ random Gaussian), avoids full SVD, $O(Ndk)$
16
+ - **DPP Extension**: Determinantal Point Process $P(S) \propto \det(L_S)$ adds a diversity guarantee on top of leverage scores
17
+
18
+ ## AI Module Specification
19
+ ```
20
+ Module: LeverageScoreSelector
21
+ Input: A ∈ R^{N×d} Parameters: sample size s << N, rank parameter k
22
+
23
+ Method 1 - Random projection leverage scores (online / large-scale):
24
+ Omega = randn(d, k+p) // random matrix, p=5 oversampling
25
+ Q = qr(A @ Omega)[0] // N×(k+p), GEMM + QR
26
+ leverage = sum(Q ** 2, dim=1) // N-dim, row-wise sum of squares
27
+ indices = topk(leverage, s) // deterministic top-s selection
28
+ A_selected = A[indices]
29
+
30
+ Method 2 - Exact leverage scores (offline / small matrices):
31
+ U_k = svd(A)[:k][0] // truncated SVD left singular vectors
32
+ leverage = sum(U_k ** 2, dim=1) // exact rank-k leverage scores
33
+ probs = leverage / leverage.sum()
34
+ indices = multinomial_sample(N, s, probs) // probabilistic sampling + reweighting
35
+ weights = 1 / sqrt(s * probs[indices])
36
+
37
+ Method 3 - KV-Cache sliding-window eviction:
38
+ Every M steps update Q = qr(K_cache @ Omega)[0]
39
+ leverage = sum(Q ** 2, dim=1)
40
+ Evict tokens with lowest leverage (least contribution to the subspace)
41
+
42
+ Method 4 - DPP greedy diverse selection:
43
+ scores = leverage.clone(); L = A @ A^T // PSD kernel matrix
44
+ for _ in range(s):
45
+ idx = argmax(scores); selected.append(idx)
46
+ scores -= α * |L[:, idx]| // penalize neighbors of already selected tokens
47
+ ```
48
+
49
+ ## Implementable Architectures
50
+ - **Random projection leverage layer**: 1 GEMM + 1 QR yields approximate leverage scores in $O(Ndk)$
51
+ - **KV-Cache eviction policy**: evict by leverage score ranking, with stronger theoretical guarantees than attention-score-based eviction
52
+ - **Coreset constructor**: leverage score sampling + importance reweighting, ensuring empirical risk approximates the full-data risk
53
+ - **DPP greedy extension**: leverage scores + exclusion penalty, balancing importance and diversity
54
+
55
+ ## GPU Feasibility
56
+ - Tensorization / GEMM: $A\Omega$ is a GEMM; QR via cuSOLVER; leverage scores = elementwise row-wise sum of squares
57
+ - Complexity: $O(Ndk)$ is far superior to $O(Nd^2)$ full SVD; top-s selection in $O(N \log s)$
58
+ - Memory: $\Omega$ is only $d \times k$ (KB-scale); $Q$ is the same size as $A$ but can be computed in batches
59
+ - Low precision: QR recommended in fp32 (small matrix with $k+p$ columns, negligible overhead); leverage scores can be cast back to bf16
60
+ - Parallelism: the $A\Omega$ GEMM is highly parallelizable; top-s can use parallel radix sort
61
+ - Operator fusion: $A\Omega$ + QR + row-norm² can be fused to avoid materializing intermediate matrices
62
+
63
+ ## Paper-Worthy Formulation
64
+ "We adopt statistical leverage scores as the importance metric for token selection: approximating rank-$k$ subspace leverage scores via random projection in $O(Ndk)$, with the Drineas--Mahoney theory guaranteeing that $O(k \log k / \epsilon^2)$ samples suffice for a $(1+\epsilon)$ approximation of the full subspace."
65
+
66
+ ## Risks
67
+ - **Rank parameter $k$ selection**: leverage scores depend on the rank-$k$ subspace; an incorrect $k$ leads to biased sampling -- the effective rank must be diagnosed first
68
+ - **Sampling variance**: probabilistic sampling introduces variance; low-probability rows occasionally selected produce large weight noise -- deterministic top-s can be used as an alternative
69
+ - **Leverage scores vs. semantic importance mismatch**: the metric measures subspace contribution, which does not necessarily reflect semantics; it can be combined with attention scores via weighted fusion
70
+ - **DPP greedy suboptimality**: exact DPP sampling is $O(N^3)$; the greedy approximation may miss the globally optimal subset
71
+ - **Stale scores under dynamic data**: in streaming scenarios leverage scores drift as data evolves, requiring periodic recomputation or incremental updates