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,71 @@
1
+ # Leverage Score Selection(杠杆分数选择)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当需要从大规模矩阵中选取最有代表性的行/列/token,且需保证下游线性代数运算精度时使用:KV-Cache token 选择、数据 coreset 构建、Nyström landmark 采样、分布式梯度压缩。核心诉求:**基于子空间投影的统计杠杆分数做采样,以概率保证逼近全量计算精度**。
6
+
7
+ ## 数学思想来源
8
+ - 透镜:lenses/spectral.md(杠杆分数 = 行向量在主子空间上的投影能量)、lenses/probabilistic.md(概率采样与浓度不等式保证)、lenses/algorithmic.md(随机化算法的复杂度与精度权衡)
9
+ - 知识:knowledge-base/matrix-analysis/low-rank-approximation.md(随机化 SVD、核范数)、knowledge-base/matrix-analysis/projection.md(投影矩阵对角元 = 杠杆分数)、knowledge-base/probability/concentration-inequality.md(Bernstein 矩阵浓度界)
10
+
11
+ ## 需要的数学知识
12
+ - **统计杠杆分数**:$\ell_i = \|(V_k V_k^T)_i\|^2 = (V_k V_k^T)_{ii}$,第 $i$ 行在 rank-$k$ 子空间的投影能量;$\sum_i \ell_i = k$
13
+ - **杠杆分数采样保证**:以 $p_i = \ell_i / k$ 采样 $s = O(k \log k / \epsilon^2)$ 行,$(1+\epsilon)$ 近似全量最小二乘(Drineas-Mahoney)
14
+ - **Bernstein 矩阵界**:采样后 $\|\hat{A}^T \hat{A} - A^T A\|_2 \leq \epsilon \|A\|_F^2$,概率 $\geq 1-\delta$
15
+ - **快速近似**:$\tilde{\ell}_i = \|(A\Omega)_i\|^2$($\Omega$ 随机高斯),避免完整 SVD,$O(Ndk)$
16
+ - **DPP 扩展**:行列式点过程 $P(S) \propto \det(L_S)$ 在杠杆分数基础上增加多样性保证
17
+
18
+ ## AI 模块形式
19
+ ```
20
+ 模块:LeverageScoreSelector
21
+ 输入:A ∈ R^{N×d} 参数:采样数 s << N,秩参数 k
22
+
23
+ 方法1 - 随机投影杠杆分数(在线/大规模):
24
+ Omega = randn(d, k+p) // 随机矩阵,p=5 过采样
25
+ Q = qr(A @ Omega)[0] // N×(k+p),GEMM + QR
26
+ leverage = sum(Q ** 2, dim=1) // N 维,逐行平方和
27
+ indices = topk(leverage, s) // 确定性选 top-s
28
+ A_selected = A[indices]
29
+
30
+ 方法2 - 精确杠杆分数(离线/小矩阵):
31
+ U_k = svd(A)[:k][0] // 截断 SVD 左奇异向量
32
+ leverage = sum(U_k ** 2, dim=1) // 精确 rank-k 杠杆分数
33
+ probs = leverage / leverage.sum()
34
+ indices = multinomial_sample(N, s, probs) // 概率采样 + 重加权
35
+ weights = 1 / sqrt(s * probs[indices])
36
+
37
+ 方法3 - KV-Cache 滑动窗口驱逐:
38
+ 每 M 步更新 Q = qr(K_cache @ Omega)[0]
39
+ leverage = sum(Q ** 2, dim=1)
40
+ 驱逐 leverage 最低的 token(对子空间贡献最小)
41
+
42
+ 方法4 - DPP 贪心多样化选择:
43
+ scores = leverage.clone(); L = A @ A^T // PSD 核矩阵
44
+ for _ in range(s):
45
+ idx = argmax(scores); selected.append(idx)
46
+ scores -= α * |L[:, idx]| // 惩罚已选 token 的邻居
47
+ ```
48
+
49
+ ## 可实现结构
50
+ - **随机投影杠杆层**:1 次 GEMM + 1 次 QR 即得近似杠杆分数,$O(Ndk)$
51
+ - **KV-Cache 驱逐策略**:按杠杆分数排序驱逐,比 attention score 驱逐更有理论保证
52
+ - **Coreset 构建器**:杠杆分数采样 + 重要性重加权,保证经验风险逼近全量
53
+ - **DPP 贪心扩展**:杠杆分数 + 互斥惩罚,兼顾重要性与多样性
54
+
55
+ ## GPU 可行性
56
+ - 张量化/GEMM:$A\Omega$ 为 GEMM;QR 有 cuSOLVER;杠杆分数 = elementwise 逐行平方和
57
+ - 复杂度:$O(Ndk)$ 远优于 $O(Nd^2)$ 完整 SVD;top-s 选择 $O(N \log s)$
58
+ - 显存:$\Omega$ 仅 $d \times k$(KB 级);$Q$ 与 $A$ 同尺寸但可分批计算
59
+ - 低精度:QR 建议 fp32(小矩阵 $k+p$ 列,开销可忽略);杠杆分数可回 bf16
60
+ - 并行:$A\Omega$ 的 GEMM 高度并行;top-s 可用 radix sort 并行
61
+ - 算子融合:$A\Omega$ + QR + row-norm² 可融合避免物化中间矩阵
62
+
63
+ ## 论文表述方式
64
+ "采用统计杠杆分数作为 token 选择的重要性度量:通过随机投影在 $O(Ndk)$ 内近似 rank-$k$ 子空间杠杆分数,Drineas-Mahoney 理论保证 $O(k \log k / \epsilon^2)$ 次采样即可 $(1+\epsilon)$ 近似全量子空间。"
65
+
66
+ ## 风险
67
+ - **秩参数 $k$ 选择**:杠杆分数依赖 rank-$k$ 子空间,$k$ 选错导致采样偏差;需先诊断有效秩
68
+ - **采样方差**:概率采样引入方差,低概率行偶尔被选中产生大权重噪声;可改用确定性 top-s
69
+ - **杠杆分数 vs. 语义重要性不一致**:度量的是子空间贡献,不一定反映语义;可与 attention score 加权融合
70
+ - **DPP 贪心次优**:精确 DPP 采样 $O(N^3)$,贪心近似可能漏掉全局最优子集
71
+ - **动态数据过时**:streaming 场景下杠杆分数随数据漂移,需定期重算或增量更新
@@ -0,0 +1,60 @@
1
+ # Low-Rank KV-Cache
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 KV-Cache memory consumption becomes the bottleneck during LLM inference: long-context inference ($L > 8K$), multi-turn conversation accumulation, edge deployment, speculative decoding / beam search. Core objective: **compress the KV-Cache from $O(Ld)$ to $O(kd)$ with $k \ll L$, under controlled information loss**.
6
+
7
+ ## Mathematical Foundations
8
+ - Lenses: lenses/spectral.md (spectral component identification and truncation), lenses/variational.md (Pareto trade-off between compression ratio and reconstruction error), lenses/duality.md (nuclear norm--spectral norm duality)
9
+ - Knowledge: knowledge-base/matrix-analysis/low-rank-approximation.md (Eckart--Young optimal approximation, randomized SVD), knowledge-base/matrix-analysis/projection.md (orthogonal projection onto principal subspace), knowledge-base/matrix-analysis/matrix-perturbation.md (Weyl perturbation bound)
10
+
11
+ ## Required Mathematical Background
12
+ - **Eckart--Young--Mirsky Theorem**: $A_k = U_k \Sigma_k V_k^H$, $\|A - A_k\|_F = \sqrt{\sum_{i>k} \sigma_i^2}$; truncated SVD = optimal rank-$k$ approximation
13
+ - **Randomized SVD**: $Y = A\Omega$ ($\Omega$ random Gaussian), $Y = QR$, $B = Q^H A$, perform SVD on $B$; complexity $O(Ldk)$, dominated by matrix multiplications
14
+ - **Weyl Perturbation Bound**: $\|A - A_k\|_2 = \sigma_{k+1}$; maximum deviation of attention scores after compression $\leq \sigma_{k+1}$
15
+ - **Effective Rank**: $r_{\text{eff}}(K) = \|K\|_F^2 / \|K\|_2^2$, guides adaptive selection of $k$
16
+
17
+ ## AI Module Specification
18
+ ```
19
+ Module: LowRankKVCompressor
20
+ Input: K ∈ R^{L×d}, V ∈ R^{L×d} Parameters: target rank k << L, update frequency M
21
+
22
+ Method 1 - Offline periodic compression (most practical):
23
+ Omega = randn(d, k+p) // random projection, p=5 oversampling
24
+ Q_k = qr(K @ Omega)[0] // L×(k+p) orthonormal basis (GEMM + QR)
25
+ B_k = Q_k^T @ K // (k+p)×d small matrix GEMM
26
+ U_r, S_r, Vt_r = svd(B_k) // small matrix SVD
27
+ K_comp = S_r[:k] * Vt_r[:k, :] // k×d compressed Key
28
+ // Attention: softmax(Q @ K_comp^T / √d) @ V_comp, sequence dimension L → k
29
+
30
+ Method 2 - Streaming incremental compression (low latency):
31
+ Maintain basis (U_basis ∈ R^{k×d}), on new token arrival:
32
+ residual p = k_new - U_basis^T @ (U_basis @ k_new)
33
+ if ‖p‖ > τ: brand_update + truncate_to_rank(k) // expand basis
34
+ else: coeff = U_basis @ k_new // project onto existing basis
35
+
36
+ Method 3 - Layer-wise adaptive: allocate per-layer, per-head k based on effective rank r_eff[l,h]
37
+ ```
38
+
39
+ ## Implementable Architectures
40
+ - **Periodic compression layer**: trigger randomized SVD every $M=64$ steps, $L \times d \to k \times d$
41
+ - **Double buffering**: compressed basis + recent $w$ raw tokens, balancing accuracy and compression ratio
42
+ - **Shared basis**: multi-head sharing of the Key column-space basis, each head stores only coefficients
43
+ - **Quantized basis**: further INT8/FP8 quantization after compression, achieving dual compression
44
+
45
+ ## GPU Feasibility
46
+ - Tensorization / GEMM: randomized SVD = 3 GEMMs + 1 small SVD, maps perfectly onto Tensor Cores
47
+ - Complexity: $O(Ldk)$ is far superior to $O(Ld^2)$ full SVD; overhead negligible for $k \sim 256$
48
+ - Memory: KV-Cache reduced from $O(Ld)$ to $O(kd)$; $k/L \sim 1/16$ yields 16x compression
49
+ - Low precision: SVD recommended in fp32 (acceptable for small matrices); compressed KV can be stored back in bf16
50
+ - Parallelism: compression across layers / heads is fully independent; incremental update $O(kd)$ with very low latency
51
+ - Operator fusion: $K\Omega$ + QR can be partially fused; the QK^T dimension in attention is already reduced
52
+
53
+ ## Paper-Worthy Formulation
54
+ "Building on the Eckart--Young--Mirsky theorem, we employ randomized SVD to project the KV-Cache onto the optimal rank-$k$ subspace, achieving $L/k$-fold memory compression at $O(Ldk)$ complexity, with the Weyl perturbation bound guaranteeing that attention score deviations do not exceed $\sigma_{k+1}$."
55
+
56
+ ## Risks
57
+ - **Improper rank selection**: $k$ too small causes $\sigma_{k+1}$ to be non-negligible, degrading long-range recall; singular value decay curves must be monitored
58
+ - **Incremental SVD error accumulation**: repeated Brand updates drift away from the true SVD, requiring periodic re-compression for correction
59
+ - **Positional encoding distortion**: RoPE is coupled with Keys, and compression may disrupt relative positional information; separate handling or re-injection is needed
60
+ - **Double-buffer seam**: attention score scales differ between the compressed region and the raw region, requiring unified normalization
@@ -0,0 +1,60 @@
1
+ # Low-Rank KV-Cache(低秩 KV 缓存压缩)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当 LLM 推理的 KV-Cache 显存占用成为瓶颈时使用:长上下文推理($L > 8K$)、多轮对话累积、边缘部署、投机解码/束搜索。核心诉求:**以可控信息损失将 KV-Cache 从 $O(Ld)$ 压缩到 $O(kd)$,$k \ll L$**。
6
+
7
+ ## 数学思想来源
8
+ - 透镜:lenses/spectral.md(谱分量识别与截断)、lenses/variational.md(压缩率与重构误差的帕累托取舍)、lenses/duality.md(核范数-谱范数对偶)
9
+ - 知识:knowledge-base/matrix-analysis/low-rank-approximation.md(Eckart-Young 最优逼近、随机化 SVD)、knowledge-base/matrix-analysis/projection.md(正交投影到主子空间)、knowledge-base/matrix-analysis/matrix-perturbation.md(Weyl 扰动界)
10
+
11
+ ## 需要的数学知识
12
+ - **Eckart-Young-Mirsky 定理**:$A_k = U_k \Sigma_k V_k^H$,$\|A - A_k\|_F = \sqrt{\sum_{i>k} \sigma_i^2}$,截断 SVD = 最优秩-$k$ 逼近
13
+ - **随机化 SVD**:$Y = A\Omega$($\Omega$ 随机高斯),$Y = QR$,$B = Q^H A$,对 $B$ 做 SVD;复杂度 $O(Ldk)$,核心全是 matmul
14
+ - **Weyl 扰动界**:$\|A - A_k\|_2 = \sigma_{k+1}$,压缩后 attention score 最大偏差 $\leq \sigma_{k+1}$
15
+ - **有效秩**:$r_{\text{eff}}(K) = \|K\|_F^2 / \|K\|_2^2$,指导 $k$ 的自适应选取
16
+
17
+ ## AI 模块形式
18
+ ```
19
+ 模块:LowRankKVCompressor
20
+ 输入:K ∈ R^{L×d}, V ∈ R^{L×d} 参数:目标秩 k << L,更新频率 M
21
+
22
+ 方法1 - 离线周期压缩(最实用):
23
+ Omega = randn(d, k+p) // 随机投影,p=5 过采样
24
+ Q_k = qr(K @ Omega)[0] // L×(k+p) 正交基底(GEMM + QR)
25
+ B_k = Q_k^T @ K // (k+p)×d 小矩阵 GEMM
26
+ U_r, S_r, Vt_r = svd(B_k) // 小矩阵 SVD
27
+ K_comp = S_r[:k] * Vt_r[:k, :] // k×d 压缩 Key
28
+ // Attention: softmax(Q @ K_comp^T / √d) @ V_comp,序列维度 L → k
29
+
30
+ 方法2 - 流式增量压缩(低延迟):
31
+ 维护基底 (U_basis ∈ R^{k×d}),新 token 到来:
32
+ 残差 p = k_new - U_basis^T @ (U_basis @ k_new)
33
+ if ‖p‖ > τ: brand_update + truncate_to_rank(k) // 扩展基底
34
+ else: coeff = U_basis @ k_new // 投影到现有基底
35
+
36
+ 方法3 - 分层自适应:按有效秩 r_eff[l,h] 分配各层各头的 k
37
+ ```
38
+
39
+ ## 可实现结构
40
+ - **周期压缩层**:每 M=64 步触发随机化 SVD,$L \times d \to k \times d$
41
+ - **双缓冲**:压缩基底 + 近期 $w$ 个原始 token,兼顾精度与压缩率
42
+ - **共享基底**:多头共享 Key 列空间基底,各头只存系数
43
+ - **量化基底**:压缩后进一步 INT8/FP8 量化,双重压缩
44
+
45
+ ## GPU 可行性
46
+ - 张量化/GEMM:随机化 SVD = 3 次 GEMM + 1 次小 SVD,完美映射 Tensor Core
47
+ - 复杂度:$O(Ldk)$ 远优于 $O(Ld^2)$ 完整 SVD;$k \sim 256$ 时开销可忽略
48
+ - 显存:KV-Cache 从 $O(Ld)$ 到 $O(kd)$,$k/L \sim 1/16$ 可达 16x 压缩
49
+ - 低精度:SVD 建议 fp32(小矩阵可接受);压缩后 KV 可回 bf16 存储
50
+ - 并行:多层/多头压缩完全独立;增量更新 $O(kd)$ 极低延迟
51
+ - 算子融合:$K\Omega$ + QR 可部分融合;attention 的 QK^T 维度已缩小
52
+
53
+ ## 论文表述方式
54
+ "基于 Eckart-Young-Mirsky 定理,采用随机化 SVD 将 KV-Cache 投影到最优秩-$k$ 子空间,以 $O(Ldk)$ 复杂度实现 $L/k$ 倍显存压缩,Weyl 扰动界保证 attention score 偏差不超过 $\sigma_{k+1}$。"
55
+
56
+ ## 风险
57
+ - **秩选取不当**:$k$ 过小导致 $\sigma_{k+1}$ 不可忽略,长距离 recall 下降;需监控奇异值衰减曲线
58
+ - **增量 SVD 误差累积**:Brand 更新多次后偏离真实 SVD,需定期重压缩校正
59
+ - **位置编码失真**:RoPE 与 Key 耦合,压缩可能破坏相对位置;需单独处理或重新注入
60
+ - **双缓冲接缝**:压缩区与原始区的 attention score 尺度不一致,需统一归一化
@@ -0,0 +1,61 @@
1
+ # Spectral Token Pruning
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 pruning must be based on the structural importance of tokens (rather than raw attention scores alone): KV-Cache eviction, long-document summarization, inference acceleration (reducing $O(L^2)$), multimodal vision token compression. Core objective: **quantify the structural importance of each token via spectral methods, achieving pruning with minimal information loss**.
6
+
7
+ ## Mathematical Foundations
8
+ - Lenses: lenses/spectral.md (identifying dominant spectral components, discarding redundant ones), lenses/algorithmic.md (complexity classification and approximation algorithms), lenses/perturbation.md (pruning = sparse perturbation, Weyl bound for spectral drift estimation)
9
+ - Knowledge: knowledge-base/matrix-analysis/spectral-decomposition.md (spectral radius, eigenvector centrality), knowledge-base/matrix-analysis/matrix-perturbation.md (Geršgorin discs, perturbation bounds), knowledge-base/matrix-analysis/positive-semidefinite.md (Gram matrix PSD structure)
10
+
11
+ ## Required Mathematical Background
12
+ - **Eigenvector Centrality**: the principal eigenvector of the attention matrix $A$ satisfies $Ax = \lambda_1 x$; component $x_i$ quantifies the global influence of token $i$ (Perron--Frobenius guarantees non-negativity)
13
+ - **Spectral Gap**: $\Delta = \lambda_1 - \lambda_2$ governs the rate of information diffusion; large $\Delta \Rightarrow$ a few tokens dominate $\Rightarrow$ safe to prune
14
+ - **Fiedler Vector**: the second-smallest eigenvector of the Laplacian $L_{\text{sym}}$ yields the optimal bipartition; small magnitude = partition boundary = important
15
+ - **Weyl Perturbation Bound**: pruning = removing rows/columns = rank-1 perturbation $E$, $|\lambda_i(A) - \lambda_i(A_{\text{pruned}})| \leq \|E\|_2$
16
+
17
+ ## AI Module Specification
18
+ ```
19
+ Module: SpectralTokenPruner
20
+ Input: K ∈ R^{L×d} Parameters: retention ratio ρ ∈ (0,1]
21
+
22
+ Method 1 - Spectral centrality pruning (power iteration):
23
+ A = softmax(K @ K^T / √d) // L×L similarity graph
24
+ v = ones(L) / √L
25
+ for t in range(5): v = A @ v; v = v / ‖v‖ // power iteration O(L²·T)
26
+ indices = topk(v, ceil(ρ * L)) // retain tokens with highest centrality
27
+
28
+ Method 2 - Geršgorin cheap pruning (zero iterations):
29
+ A = softmax(K @ K^T / √d)
30
+ gersh_score = |diag(A)| + sum(|A|, dim=1) // disc upper bound, O(L²) elementwise
31
+ indices = topk(gersh_score, ceil(ρ * L))
32
+
33
+ Method 3 - Differentiable spectral pruning (end-to-end):
34
+ v = power_iteration(A, T=5)
35
+ gate = sigmoid(v @ W_gate / τ) // soft gating, τ annealing
36
+ K_gated = gate * K // per-token scaling
37
+ L_sparse = ‖gate‖_1 / L // sparsity regularization
38
+ ```
39
+
40
+ ## Implementable Architectures
41
+ - **Power iteration centrality**: 5-step matvec to estimate the principal eigenvector, $O(L^2 \cdot 5)$, suitable for moderate-length sequences
42
+ - **Sampling approximation**: for $L > 4096$, sample $m$ anchor points and construct an $m \times m$ submatrix for spectral analysis
43
+ - **Multi-head fusion**: average the attention graphs across different heads before performing spectral analysis
44
+ - **Progressive pruning**: incrementally increase the pruning ratio across layers (light pruning in shallow layers, heavy pruning in deep layers)
45
+
46
+ ## GPU Feasibility
47
+ - Tensorization / GEMM: $A = KK^T$ is a GEMM; power iteration is a chain of matvecs; Geršgorin is elementwise
48
+ - Complexity: power iteration $O(L^2 T)$, $T \leq 10$; Geršgorin $O(L^2)$ elementwise, zero iterations
49
+ - Memory: the $L \times L$ similarity matrix exceeds 256 MB for $L > 8K$, requiring chunking or sampling
50
+ - Low precision: power iteration is stable in bf16 (normalization prevents overflow); Geršgorin is purely elementwise with no precision concerns
51
+ - Parallelism: spectral analysis across heads / layers is independently parallel; matvec is highly parallelizable
52
+ - Operator fusion: $KK^T$ + row-sum + topk can be fused into a single kernel
53
+
54
+ ## Paper-Worthy Formulation
55
+ "We cast token pruning as spectral sparsification of a directed graph: leveraging the Perron--Frobenius principal eigenvector of the attention matrix to quantify global centrality, with the Weyl perturbation bound guaranteeing that post-pruning spectral drift does not exceed the $\ell_2$ norm of the removed tokens, while Geršgorin discs provide an $O(L^2)$ inexpensive alternative."
56
+
57
+ ## Risks
58
+ - **$L \times L$ matrix memory bottleneck**: for long sequences the similarity matrix itself may exceed available memory, necessitating sampling or chunking
59
+ - **Slow power iteration convergence**: when $\lambda_1 / \lambda_2 \approx 1$, $O(1/\Delta)$ iterations are required, reducing efficiency
60
+ - **Semantics $\neq$ spectral importance**: certain tokens (e.g., punctuation) have low spectral centrality yet are semantically critical; purely spectral methods may prune them erroneously
61
+ - **Hard pruning is non-differentiable**: top-k blocks gradients; end-to-end training requires softmax relaxation or Gumbel-topk
@@ -0,0 +1,61 @@
1
+ # Spectral Token Pruning(谱 Token 剪枝)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当需要基于 token 的结构性重要性(而非单纯 attention score)进行剪枝时使用:KV-Cache 驱逐、长文档摘要、推理加速(降低 $O(L^2)$)、多模态视觉 token 压缩。核心诉求:**用谱方法量化每个 token 的结构性重要性,实现信息损失最小的剪枝**。
6
+
7
+ ## 数学思想来源
8
+ - 透镜:lenses/spectral.md(识别主导谱分量、丢弃冗余分量)、lenses/algorithmic.md(复杂度分类与近似算法)、lenses/perturbation.md(剪枝 = 稀疏扰动,Weyl 界估谱漂移)
9
+ - 知识:knowledge-base/matrix-analysis/spectral-decomposition.md(谱半径、特征向量中心性)、knowledge-base/matrix-analysis/matrix-perturbation.md(Geršgorin 圆盘、扰动界)、knowledge-base/matrix-analysis/positive-semidefinite.md(Gram 矩阵 PSD 结构)
10
+
11
+ ## 需要的数学知识
12
+ - **特征向量中心性**:attention 矩阵 $A$ 的主特征向量 $Ax = \lambda_1 x$,分量 $x_i$ 量化 token $i$ 的全局影响力(Perron-Frobenius 保证非负)
13
+ - **谱间隙**:$\Delta = \lambda_1 - \lambda_2$ 决定信息扩散速度,$\Delta$ 大 $\Rightarrow$ 少数 token 主导 $\Rightarrow$ 安全剪枝
14
+ - **Fiedler 向量**:Laplacian $L_{\text{sym}}$ 的第二小特征向量给出最优二分割,幅值小 = 分割边界 = 重要
15
+ - **Weyl 扰动界**:剪枝 = 删除行/列 = 秩-1 扰动 $E$,$|\lambda_i(A) - \lambda_i(A_{\text{pruned}})| \leq \|E\|_2$
16
+
17
+ ## AI 模块形式
18
+ ```
19
+ 模块:SpectralTokenPruner
20
+ 输入:K ∈ R^{L×d} 参数:保留比例 ρ ∈ (0,1]
21
+
22
+ 方法1 - 谱中心性剪枝(幂迭代):
23
+ A = softmax(K @ K^T / √d) // L×L 相似度图
24
+ v = ones(L) / √L
25
+ for t in range(5): v = A @ v; v = v / ‖v‖ // 幂迭代 O(L²·T)
26
+ indices = topk(v, ceil(ρ * L)) // 保留中心性最高的 token
27
+
28
+ 方法2 - Geršgorin 廉价剪枝(零迭代):
29
+ A = softmax(K @ K^T / √d)
30
+ gersh_score = |diag(A)| + sum(|A|, dim=1) // 圆盘上界,O(L²) elementwise
31
+ indices = topk(gersh_score, ceil(ρ * L))
32
+
33
+ 方法3 - 可微谱剪枝(端到端):
34
+ v = power_iteration(A, T=5)
35
+ gate = sigmoid(v @ W_gate / τ) // 软门控,τ 退火
36
+ K_gated = gate * K // 逐 token 缩放
37
+ L_sparse = ‖gate‖_1 / L // 稀疏正则
38
+ ```
39
+
40
+ ## 可实现结构
41
+ - **幂迭代中心性**:5 步 matvec 估计主特征向量,$O(L^2 \cdot 5)$,适合中等序列
42
+ - **采样近似**:$L > 4096$ 时采样 $m$ 个锚点,构造 $m \times m$ 子矩阵做谱分析
43
+ - **多头融合**:不同头的 attention 图取平均后再做谱分析
44
+ - **渐进式剪枝**:逐层递增剪枝比例(浅层少剪、深层多剪)
45
+
46
+ ## GPU 可行性
47
+ - 张量化/GEMM:$A = KK^T$ 为 GEMM;幂迭代为 matvec 链;Geršgorin 为 elementwise
48
+ - 复杂度:幂迭代 $O(L^2 T)$,$T \leq 10$;Geršgorin $O(L^2)$ elementwise,零迭代
49
+ - 显存:$L \times L$ 相似度矩阵在 $L > 8K$ 时超 256MB,需分块或采样
50
+ - 低精度:幂迭代在 bf16 下稳定(归一化防溢出);Geršgorin 纯 elementwise 无精度问题
51
+ - 并行:多头/多层谱分析独立并行;matvec 高度并行
52
+ - 算子融合:$KK^T$ + row-sum + topk 可融合为单一 kernel
53
+
54
+ ## 论文表述方式
55
+ "将 token 剪枝建模为有向图的谱稀疏化:利用 attention 矩阵的 Perron-Frobenius 主特征向量量化全局中心性,Weyl 扰动界保证剪枝后谱漂移不超过被移除 token 的 $\ell_2$ 范数,Geršgorin 圆盘提供 $O(L^2)$ 廉价替代。"
56
+
57
+ ## 风险
58
+ - **$L \times L$ 矩阵显存瓶颈**:长序列下相似度矩阵本身可能超出显存,必须采样或分块
59
+ - **幂迭代收敛慢**:$\lambda_1 / \lambda_2 \approx 1$ 时需 $O(1/\Delta)$ 步,效率下降
60
+ - **语义 ≠ 谱重要性**:某些 token(如标点)谱中心性低但语义关键,纯谱方法可能误剪
61
+ - **硬剪枝不可微**:top-k 阻断梯度,端到端训练需 softmax 松弛或 Gumbel-topk
@@ -0,0 +1,64 @@
1
+ # Topology-Preserving Compression
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 compressing representations while homologically preserving the intrinsic topological structure of the data (connected components, loops, cavities): latent-space compression (a toroidal manifold must not collapse into a line segment), knowledge distillation (student--teacher homological equivalence), 3D mesh simplification (genus invariance), KV-Cache semantic preservation (cluster structure must not collapse). Core objective: **compress dimensions or counts while ensuring that changes in the persistence diagram of persistent homology remain controlled**.
6
+
7
+ ## Mathematical Foundations
8
+ - Lenses: lenses/topological.md (topological invariants -- connected components and hole counts are invariant under continuous deformation), lenses/spectral.md (Gauss--Bonnet linking curvature and Euler characteristic), lenses/variational.md (constrained variational of compression ratio vs. topological fidelity)
9
+ - Knowledge: knowledge-base/topology/persistent-homology.md (persistent homology, Vietoris--Rips filtration, bottleneck distance), knowledge-base/topology/euler-characteristic.md (Euler characteristic for rapid topological diagnostics), knowledge-base/matrix-analysis/matrix-perturbation.md (Davis--Kahan subspace perturbation bound)
10
+
11
+ ## Required Mathematical Background
12
+ - **Stability Theorem of Persistent Homology**: $d_B(D(X), D(Y)) \leq d_{GH}(X, Y)$; the Hausdorff distance bounds the change in persistence diagrams
13
+ - **Euler Characteristic Curve**: $\chi(\epsilon) = \sum_k (-1)^k \beta_k(\epsilon)$, richer in information than a single $\chi$, computable in $O(N^2)$
14
+ - **Mapping Cylinder Isomorphism**: if $f: X \to Y$ is an $\epsilon$-isometry, then $f_*$ induces an isomorphism on features with persistence intervals $> 2\epsilon$
15
+ - **Landmark Approximation**: build a witness complex on $m$ landmarks, $O(m^3)$ replacing $O(N^3)$
16
+
17
+ ## AI Module Specification
18
+ ```
19
+ Module: TopologyPreservingCompressor
20
+ Input: X ∈ R^{N×d} Parameters: topological weight λ_topo, target dimension r < d
21
+
22
+ Method 1 - Euler curve matching (most practical, differentiable):
23
+ Z = encoder(X) // R^{N×r}
24
+ D_orig = cdist(X, X); D_comp = cdist(Z, Z) // N×N distance matrices
25
+ chi_orig = euler_curve(D_orig, eps_grid) // |eps_grid|-dimensional vector
26
+ chi_comp = euler_curve(D_comp, eps_grid)
27
+ L_topo = ‖chi_orig - chi_comp‖_2² // topological matching loss (differentiable)
28
+ L_total = L_recon + λ_topo · L_topo
29
+
30
+ Method 2 - Persistent homology regularization (exact but expensive):
31
+ D_orig = persistent_homology(X, max_dim=1) // H_0 + H_1 barcode
32
+ D_comp = persistent_homology(Z, max_dim=1)
33
+ // differentiable surrogate: persistence landscape/image
34
+ L_topo = ‖landscape(D_orig) - landscape(D_comp)‖_2²
35
+
36
+ Method 3 - Topology monitoring + adaptive compression ratio (at inference time):
37
+ Z = compress(X, ratio=ρ)
38
+ if count_components(Z, τ) < 0.8 * count_components(X, τ):
39
+ ρ *= 1.2; Z = compress(X, ratio=ρ) // topological collapse → reduce compression ratio
40
+ ```
41
+
42
+ ## Implementable Architectures
43
+ - **Euler curve matching layer**: $\chi(\epsilon)$ requires only a distance matrix + threshold counting; the $\epsilon$ sweep is parallelizable
44
+ - **Landmark sampler**: FPS (Farthest Point Sampling) in $O(Nm)$, guaranteeing coverage
45
+ - **Topology-aware distillation**: the persistence image discrepancy between teacher and student representations serves as an auxiliary distillation objective
46
+ - **Topological diagnostics dashboard**: real-time plotting of $\beta_0(\epsilon), \beta_1(\epsilon)$ curves during training
47
+
48
+ ## GPU Feasibility
49
+ - Tensorization / GEMM: the distance matrix `cdist` is GEMM-dominated; $\chi(\epsilon)$ involves threshold counting + cumulative sum
50
+ - Complexity: full persistent homology $O(N^3)$ is infeasible; Euler curve $O(N^2 |\epsilon|)$ is feasible; Landmark $O(m^3)$
51
+ - Memory: the $N \times N$ distance matrix requires chunking or landmark reduction for $N > 8K$
52
+ - Low precision: distance computation is stable in bf16 (positive-number addition); $\chi$ involves integer arithmetic with no precision concerns
53
+ - Parallelism: each threshold in the $\epsilon$ sweep is independently parallel; landmark selection can be batch-parallelized
54
+ - Operator fusion: cdist + threshold + count can be fused to avoid materializing the large distance matrix
55
+
56
+ ## Paper-Worthy Formulation
57
+ "Grounded in the Bottleneck stability theorem of persistent homology, we achieve $O(N^2)$-complexity topology-preserving regularization via Euler characteristic curve matching, ensuring that post-compression deviations in Betti numbers over persistence intervals are controlled by the Hausdorff distance."
58
+
59
+ ## Risks
60
+ - **Persistent homology computational bottleneck**: exact boundary matrix reduction is highly serial ($O(N^3)$), necessitating reliance on Euler curve or landmark approximations
61
+ - **Information loss in the Euler curve**: $\chi = \sum(-1)^k \beta_k$ collapses multi-order Betti numbers into a single scalar; distinct topologies may share the same $\chi$
62
+ - **Topology $\neq$ semantics**: topological preservation does not imply semantic preservation -- two semantically distinct spaces may be topologically isomorphic
63
+ - **Scale parameter sensitivity**: the $\epsilon$ range for the filtration must be set manually and varies significantly across datasets
64
+ - **Landmark sampling bias**: FPS may produce non-uniform coverage in high-dimensional spaces, leading to biased topological estimates
@@ -0,0 +1,64 @@
1
+ # Topology-Preserving Compression(拓扑保持压缩)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当压缩表示时需要同构保持数据的本质拓扑结构(连通性、环、空腔)时使用:隐空间压缩(环形流形不能压成线段)、知识蒸馏(学生-教师同调等价)、3D 网格简化(genus 不变)、KV-Cache 语义保持(聚类结构不坍缩)。核心诉求:**压缩维度或数量,保证持续同调的 persistence diagram 变化可控**。
6
+
7
+ ## 数学思想来源
8
+ - 透镜:lenses/topological.md(拓扑不变量——连通性、洞数在连续变形下不变)、lenses/spectral.md(Gauss-Bonnet 连接曲率与欧拉示性数)、lenses/variational.md(压缩率 vs. 拓扑保真度的约束优化)
9
+ - 知识:knowledge-base/topology/persistent-homology.md(持续同调、Vietoris-Rips 滤流、Bottleneck 距离)、knowledge-base/topology/euler-characteristic.md(欧拉示性数快速拓扑诊断)、knowledge-base/matrix-analysis/matrix-perturbation.md(Davis-Kahan 子空间扰动界)
10
+
11
+ ## 需要的数学知识
12
+ - **持续同调稳定性定理**:$d_B(D(X), D(Y)) \leq d_{GH}(X, Y)$,Hausdorff 距离界定 persistence diagram 变化
13
+ - **欧拉示性数曲线**:$\chi(\epsilon) = \sum_k (-1)^k \beta_k(\epsilon)$,比单一 $\chi$ 信息更丰富,计算 $O(N^2)$
14
+ - **映射柱同构**:若 $f: X \to Y$ 是 $\epsilon$-等距,则 $f_*$ 在持续区间 $> 2\epsilon$ 的特征上同构
15
+ - **Landmark 近似**:用 witness complex 在 $m$ 个 landmark 上构建,$O(m^3)$ 替代 $O(N^3)$
16
+
17
+ ## AI 模块形式
18
+ ```
19
+ 模块:TopologyPreservingCompressor
20
+ 输入:X ∈ R^{N×d} 参数:拓扑权重 λ_topo,目标维度 r < d
21
+
22
+ 方法1 - Euler curve 匹配(最实用,可微):
23
+ Z = encoder(X) // R^{N×r}
24
+ D_orig = cdist(X, X); D_comp = cdist(Z, Z) // N×N 距离矩阵
25
+ chi_orig = euler_curve(D_orig, eps_grid) // |eps_grid| 维向量
26
+ chi_comp = euler_curve(D_comp, eps_grid)
27
+ L_topo = ‖chi_orig - chi_comp‖_2² // 拓扑匹配损失(可微)
28
+ L_total = L_recon + λ_topo · L_topo
29
+
30
+ 方法2 - 持续同调正则(精确但昂贵):
31
+ D_orig = persistent_homology(X, max_dim=1) // H_0 + H_1 barcode
32
+ D_comp = persistent_homology(Z, max_dim=1)
33
+ // 可微代理:persistence landscape/image
34
+ L_topo = ‖landscape(D_orig) - landscape(D_comp)‖_2²
35
+
36
+ 方法3 - 拓扑监控 + 自适应压缩率(推理时):
37
+ Z = compress(X, ratio=ρ)
38
+ if count_components(Z, τ) < 0.8 * count_components(X, τ):
39
+ ρ *= 1.2; Z = compress(X, ratio=ρ) // 拓扑坍缩 → 降低压缩比
40
+ ```
41
+
42
+ ## 可实现结构
43
+ - **Euler curve 匹配层**:$\chi(\epsilon)$ 只需距离矩阵 + 阈值计数,$\epsilon$ 扫描可并行
44
+ - **Landmark 采样器**:FPS(最远点采样)$O(Nm)$,保证覆盖
45
+ - **拓扑感知蒸馏**:教师-学生表示的 persistence image 差异作为附加蒸馏目标
46
+ - **拓扑诊断仪表板**:训练中实时绘制 $\beta_0(\epsilon), \beta_1(\epsilon)$ 曲线
47
+
48
+ ## GPU 可行性
49
+ - 张量化/GEMM:距离矩阵 `cdist` 核心为 GEMM;$\chi(\epsilon)$ 为阈值计数 + 累积和
50
+ - 复杂度:完整持续同调 $O(N^3)$ 不可行;Euler curve $O(N^2 |\epsilon|)$ 可行;Landmark $O(m^3)$
51
+ - 显存:$N \times N$ 距离矩阵在 $N > 8K$ 时需分块或 Landmark 降维
52
+ - 低精度:距离计算在 bf16 下稳定(正数加法);$\chi$ 为整数运算无精度问题
53
+ - 并行:$\epsilon$ 扫描的每个阈值独立并行;Landmark 选择可批并行
54
+ - 算子融合:cdist + threshold + count 可融合避免物化大距离矩阵
55
+
56
+ ## 论文表述方式
57
+ "以持续同调的 Bottleneck 稳定性定理为理论基础,通过 Euler characteristic curve 匹配实现 $O(N^2)$ 复杂度的拓扑保真正则化,保证压缩后 Betti 数在持续区间上的偏差受 Hausdorff 距离控制。"
58
+
59
+ ## 风险
60
+ - **持续同调计算瓶颈**:精确边界矩阵约化高度串行($O(N^3)$),必须依赖 Euler curve 或 Landmark 近似
61
+ - **Euler curve 信息退化**:$\chi = \sum(-1)^k \beta_k$ 将多阶 Betti 数压成单值,不同拓扑可共享同一 $\chi$
62
+ - **拓扑 ≠ 语义**:拓扑保持不等于语义保持——两个语义不同的空间可能拓扑同构
63
+ - **尺度参数敏感**:滤流的 $\epsilon$ 范围需手动设定,不同数据集差异大
64
+ - **Landmark 采样偏差**:FPS 在高维空间中可能不均匀,导致拓扑估计偏差
@@ -0,0 +1,67 @@
1
+ # Constraint Penalty
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 design involves hard constraints (e.g., probability simplex, orthogonality, capacity limits, load balancing) but end-to-end training is required. Typical scenarios: (1) MoE routing probabilities must lie on the $K$-simplex with load balancing; (2) Expert activation count is constrained (top-k); (3) Subspace projection matrices must satisfy orthogonality $W^T W = I$; (4) Feature norms are bounded $\|z\| \leq R$. Core objective: **transform mathematical constraints into differentiable penalty terms integrated into gradient-based variational**.
6
+
7
+ ## Mathematical Inspiration
8
+ - Lenses: lenses/variational.md (constrained variational, Lagrangian duality, KKT conditions), lenses/geometric.md (manifold projection)
9
+ - Knowledge: knowledge-base/optimization/lagrangian-duality.md (augmented Lagrangian method, penalty function method), knowledge-base/matrix-analysis/projection.md (projection operators, constraint sets)
10
+
11
+ ## Required Mathematical Knowledge
12
+ - **Penalty Function Method**: $\min f(x)$ s.t. $g(x)=0 \to \min f(x) + \rho/2 \cdot \|g(x)\|^2$ -- $\rho$ is gradually increased (exterior point method), driving constraint violation $\|g(x)\| \to 0$
13
+ - **Augmented Lagrangian Method**: $\min f(x) + \lambda^T g(x) + \rho/2 \cdot \|g(x)\|^2$ -- introduces dual variable $\lambda$, alternating between updating $\lambda \leftarrow \lambda + \rho \cdot g(x)$ and optimizing $x$; converges better than pure penalty methods
14
+ - **Projected Gradient Method**: $x_{k+1} = \text{Proj}_C(x_k - \alpha \nabla f(x_k))$ -- for simple constraint sets $C$ (e.g., simplex, sphere), closed-form projection formulas exist
15
+ - **Barrier Function Method**: $\min f(x) - \mu \sum \log(-g_i(x))$ for inequality constraints $g_i(x) \leq 0$ -- as $\mu \to 0$, approaches the constrained optimum
16
+
17
+ ## AI Module Form
18
+ ```
19
+ Module: ConstraintPenalty
20
+ Input: constraint violations g(x) in R^m (equality constraints), h(x) in R^p (inequality constraints)
21
+
22
+ Method 1 - Adaptive Penalty Function (most commonly used):
23
+ L_penalty = Sum_i rho_i/2 * g_i(x)^2 + Sum_j rho_j/2 * max(0, h_j(x))^2
24
+ // rho updated dynamically: each epoch rho_i *= gamma (gamma=2~10) until constraints are satisfied
25
+ // Different constraints can have different rho values, adapted to violation severity
26
+
27
+ Method 2 - Augmented Lagrangian Method (ALM):
28
+ L_ALM = lambda^T * g(x) + rho/2 * ||g(x)||^2
29
+ // lambda is a learnable parameter (nn.Parameter), updated via gradient ascent:
30
+ lambda.data += rho * g(x).detach() // dual ascent step
31
+ // Converges faster than pure penalty, avoids rho -> infinity
32
+
33
+ Method 3 - Softmax Projection onto Simplex (load balancing special case):
34
+ p = softmax(logits / tau) // project onto Delta^{K-1}
35
+ L_balance = ||p - 1/K||^2 // uniformity penalty
36
+ // Or Switch Transformer auxiliary loss:
37
+ L_aux = K * Sum_k f_k * P_k // f_k = allocation fraction, P_k = average probability
38
+
39
+ Method 4 - Orthogonal Constraint Projection:
40
+ W_proj = W * (W^T W)^{-1/2} // project onto Stiefel manifold via matrix square root inverse
41
+ // Or parameterize via Cayley transform: W = (I-A)(I+A)^{-1} * W_0, A is skew-symmetric
42
+ ```
43
+
44
+ ## Implementable Architectures
45
+ - **Loss Wrapper**: ConstraintLoss(base_loss, constraints, rho_schedule) -- forward computes base_loss + Sum constraint.penalty()
46
+ - **Dual Variable Management**: nn.Parameter stores lambda; negative learning rate set in the optimizer to achieve gradient ascent
47
+ - **Warm-up Strategy**: Optimize only base_loss for the first $N$ steps, then progressively activate constraint penalties
48
+ - **Constraint Monitoring**: Record $\|g(x)\|$ at each step for visualization and adaptive rho adjustment
49
+
50
+ ## GPU Feasibility
51
+ - **Tensorization**: Constraint violations are vector/matrix operations; penalty terms are element-wise squared sums
52
+ - **GEMM-mappability**: Load balancing $f_k$, $P_k$ computation uses softmax + reduce_sum; orthogonal constraint uses matmul
53
+ - **Complexity**: Penalty computation is $O(m)$ or $O(m^2)$, far smaller than the main network forward pass; negligible
54
+ - **Memory & KV-Cache**: Only additional storage for lambda ($m$ dimensions) and rho ($m$ dimensions); minimal overhead
55
+ - **Low Precision Stability**: Penalty terms are squaring operations, safe under fp16; ALM lambda updates are recommended in fp32 to avoid accumulated errors
56
+ - **Parallelism & Communication**: Constraints are independently computable and parallelizable; on multiple GPUs, lambda updates require all-reduce of $g(x)$
57
+ - **Sparse Structure**: $\max(0, h(x))^2$ has zero gradient when constraints are satisfied, naturally sparse activation
58
+ - **Operator Fusion**: Constraint computation + weighted summation + merging with base_loss can be fused into a single kernel
59
+
60
+ ## Paper Phrasing
61
+ "We employ the augmented Lagrangian method to convert hard constraints $g(x)=0$ into differentiable penalty terms $\lambda^T g(x) + \rho/2 \|g(x)\|^2$. Through alternating dual ascent updates of $\lambda$, constraint satisfaction is guaranteed to converge at rate $O(1/\rho)$ without requiring $\rho \to \infty$, reducing constraint violations by 3x compared to pure penalty methods in experiments."
62
+
63
+ ## Risks
64
+ - Excessively fast rho growth leads to ill-conditioned variational landscapes (deteriorating condition numbers), causing gradient vanishing or explosion
65
+ - ALM lambda update frequency and step size require tuning; too fast causes oscillation, too slow impedes convergence
66
+ - When multiple constraints coexist, the relative ratios of their rho values influence the variational trajectory
67
+ - Projection operations (e.g., matrix square root inverse) are computationally expensive and numerically unstable
@@ -0,0 +1,78 @@
1
+ # Constraint Penalty(约束惩罚损失)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「[v] 已验证 / [~] 可改造需验证 / [x] 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当设计中有硬约束(如概率单纯形、正交性、容量限制、负载均衡)但需要端到端训练时使用。
6
+ 典型场景:(1) MoE 路由概率必须在 K-simplex 上且负载均衡;(2) 专家激活数量受限(top-k);
7
+ (3) 子空间投影矩阵必须满足正交性 W^TW = I;(4) 特征范数有界 ‖z‖ ≤ R。
8
+ 核心诉求:**将数学约束转化为可微惩罚项,融入梯度优化流程**。
9
+
10
+ ## 数学思想来源
11
+ - 透镜:lenses/variational.md(约束优化、拉格朗日对偶、KKT 条件)、lenses/geometric.md(流形投影)
12
+ - 知识:knowledge-base/optimization/lagrangian-duality.md(增广拉格朗日法、惩罚函数法)、
13
+ knowledge-base/matrix-analysis/projection.md(投影算子、约束集)
14
+
15
+ ## 需要的数学知识
16
+ - **罚函数法**:min f(x) s.t. g(x)=0 → min f(x) + ρ/2 · ‖g(x)‖²
17
+ ρ 逐步增大(外点法),约束违反量 ‖g(x)‖ → 0
18
+ - **增广拉格朗日法**:min f(x) + λ^T g(x) + ρ/2 · ‖g(x)‖²
19
+ 引入对偶变量 λ,交替更新 λ ← λ + ρ·g(x) 和优化 x,比纯罚函数收敛更好
20
+ - **投影梯度法**:x_{k+1} = Proj_C(x_k - α∇f(x_k))
21
+ 对简单约束集 C(如 simplex、球面)有闭合投影公式
22
+ - **屏障函数法**:min f(x) - μ Σ log(-g_i(x)) 对不等式约束 g_i(x) ≤ 0
23
+ μ → 0 时逼近约束最优解
24
+
25
+ ## AI 模块形式
26
+ ```
27
+ 模块:ConstraintPenalty
28
+ 输入:约束违反量 g(x) ∈ R^m(等式约束),h(x) ∈ R^p(不等式约束)
29
+
30
+ 方法1 - 自适应罚函数(最常用):
31
+ L_penalty = Σ_i ρ_i/2 · g_i(x)² + Σ_j ρ_j/2 · max(0, h_j(x))²
32
+ // ρ 动态更新:每个 epoch ρ_i *= γ(γ=2~10)直到约束满足
33
+ // 不同约束可有不同的 ρ,按违反程度自适应
34
+
35
+ 方法2 - 增广拉格朗日(ALM):
36
+ L_ALM = λ^T · g(x) + ρ/2 · ‖g(x)‖²
37
+ // λ 为可学习参数(nn.Parameter),通过梯度上升更新:
38
+ λ.data += ρ * g(x).detach() // 对偶上升步
39
+ // 比纯罚函数收敛快,避免 ρ → ∞
40
+
41
+ 方法3 - Softmax 投影到单纯形(负载均衡特例):
42
+ p = softmax(logits / τ) // 投影到 Δ^{K-1}
43
+ L_balance = ‖p - 1/K‖² // 均匀性惩罚
44
+ // 或 Switch Transformer 的辅助损失:
45
+ L_aux = K · Σ_k f_k · P_k // f_k = 分配比例, P_k = 平均概率
46
+
47
+ 方法4 - 正交约束投影:
48
+ W_proj = W · (W^T W)^{-1/2} // 通过矩阵平方根反投影到 Stiefel 流形
49
+ // 或用 Cayley 变换参数化:W = (I-A)(I+A)^{-1} · W_0, A 为反对称矩阵
50
+ ```
51
+
52
+ ## 可实现结构
53
+ - **Loss Wrapper**:ConstraintLoss(base_loss, constraints, ρ_schedule)
54
+ forward 时计算 base_loss + Σ constraint.penalty()
55
+ - **对偶变量管理**:nn.Parameter 存储 λ,optimizer 中为 λ 设置负学习率实现梯度上升
56
+ - **warm-up 策略**:前 N 步只优化 base_loss,之后逐步激活约束惩罚
57
+ - **约束监控**:每 step 记录 ‖g(x)‖ 用于可视化和自适应 ρ 调整
58
+
59
+ ## GPU 可行性
60
+ - **张量化**:约束违反量为向量/矩阵运算,罚项为 element-wise 平方和
61
+ - **GEMM 可映射**:负载均衡的 f_k, P_k 计算为 softmax + reduce_sum;正交约束为 matmul
62
+ - **复杂度**:罚项计算 O(m) 或 O(m²),远小于主网络前向,可忽略
63
+ - **显存与 KV-Cache**:仅额外存储 λ (m 维) 和 ρ (m 维),极小开销
64
+ - **低精度稳定**:罚项为平方运算,fp16 安全;ALM 的 λ 更新建议 fp32 避免累积误差
65
+ - **并行与通信**:各约束独立计算,可并行;多 GPU 时 λ 更新需 all-reduce g(x)
66
+ - **稀疏结构**:max(0, h(x))² 在约束满足时梯度为零,天然稀疏激活
67
+ - **算子融合**:constraint 计算 + 加权求和 + 与 base_loss 合并可融合为单 kernel
68
+
69
+ ## 论文表述方式
70
+ "采用增广拉格朗日法将硬约束 g(x)=0 转化为可微惩罚项 λ^Tg(x) + ρ/2‖g(x)‖²,
71
+ 通过对偶变量 λ 的交替上升更新,在无需 ρ→∞ 的条件下保证约束满足度以 O(1/ρ) 收敛,
72
+ 相比纯罚函数法在实验中减少 3× 的约束违反。"
73
+
74
+ ## 风险
75
+ - ρ 增大过快导致优化 landscape 病态(条件数恶化),梯度消失或爆炸
76
+ - ALM 的 λ 更新频率和步长需调参,更新过快震荡、过慢收敛
77
+ - 多个约束同时存在时 ρ 的相对比例影响优化路径
78
+ - 投影操作(如矩阵平方根逆)计算代价高且数值不稳定