math-skill 2.1.0 → 3.0.0

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 (234) hide show
  1. package/README.en-US.md +159 -200
  2. package/README.md +159 -200
  3. package/agents/math-critic.en.md +2 -2
  4. package/agents/math-critic.md +8 -8
  5. package/commands/ask.md +3 -10
  6. package/design-patterns/attention/equivariant-attention.en.md +72 -0
  7. package/design-patterns/attention/equivariant-attention.md +72 -0
  8. package/design-patterns/attention/geometry-aware-attention.en.md +73 -0
  9. package/design-patterns/attention/geometry-aware-attention.md +72 -0
  10. package/design-patterns/attention/information-bottleneck-attention.en.md +72 -0
  11. package/design-patterns/attention/information-bottleneck-attention.md +72 -0
  12. package/design-patterns/attention/projection-attention.en.md +68 -0
  13. package/design-patterns/attention/projection-attention.md +68 -0
  14. package/design-patterns/attention/spectral-attention.en.md +71 -0
  15. package/design-patterns/attention/spectral-attention.md +71 -0
  16. package/design-patterns/compression/leverage-score-selection.en.md +71 -0
  17. package/design-patterns/compression/leverage-score-selection.md +71 -0
  18. package/design-patterns/compression/low-rank-kv-cache.en.md +60 -0
  19. package/design-patterns/compression/low-rank-kv-cache.md +60 -0
  20. package/design-patterns/compression/spectral-token-pruning.en.md +61 -0
  21. package/design-patterns/compression/spectral-token-pruning.md +61 -0
  22. package/design-patterns/compression/topology-preserving-compression.en.md +64 -0
  23. package/design-patterns/compression/topology-preserving-compression.md +64 -0
  24. package/design-patterns/loss/constraint-penalty.en.md +67 -0
  25. package/design-patterns/loss/constraint-penalty.md +78 -0
  26. package/design-patterns/loss/contrastive-loss.en.md +59 -0
  27. package/design-patterns/loss/contrastive-loss.md +68 -0
  28. package/design-patterns/loss/information-bottleneck-loss.en.md +69 -0
  29. package/design-patterns/loss/information-bottleneck-loss.md +74 -0
  30. package/design-patterns/loss/orthogonality-loss.en.md +56 -0
  31. package/design-patterns/loss/orthogonality-loss.md +60 -0
  32. package/design-patterns/loss/variational-loss.en.md +61 -0
  33. package/design-patterns/loss/variational-loss.md +71 -0
  34. package/design-patterns/representation/equivariant-split.en.md +87 -0
  35. package/design-patterns/representation/equivariant-split.md +89 -0
  36. package/design-patterns/representation/manifold-representation.en.md +85 -0
  37. package/design-patterns/representation/manifold-representation.md +87 -0
  38. package/design-patterns/representation/shared-private-decomposition.en.md +84 -0
  39. package/design-patterns/representation/shared-private-decomposition.md +86 -0
  40. package/design-patterns/representation/subspace-alignment.en.md +90 -0
  41. package/design-patterns/representation/subspace-alignment.md +92 -0
  42. package/design-patterns/routing/graph-routing.en.md +79 -0
  43. package/design-patterns/routing/graph-routing.md +81 -0
  44. package/design-patterns/routing/moe-routing.en.md +85 -0
  45. package/design-patterns/routing/moe-routing.md +87 -0
  46. package/design-patterns/routing/optimal-transport-routing.en.md +68 -0
  47. package/design-patterns/routing/optimal-transport-routing.md +72 -0
  48. package/design-patterns/routing/spectral-clustering-routing.en.md +88 -0
  49. package/design-patterns/routing/spectral-clustering-routing.md +90 -0
  50. package/knowledge-base/differential-geometry/connection.en.md +51 -0
  51. package/knowledge-base/differential-geometry/connection.md +51 -0
  52. package/knowledge-base/differential-geometry/curvature.en.md +49 -0
  53. package/knowledge-base/differential-geometry/curvature.md +49 -0
  54. package/knowledge-base/differential-geometry/geodesic.en.md +51 -0
  55. package/knowledge-base/differential-geometry/geodesic.md +51 -0
  56. package/knowledge-base/differential-geometry/manifold.en.md +47 -0
  57. package/knowledge-base/differential-geometry/manifold.md +47 -0
  58. package/knowledge-base/differential-geometry/metric-tensor.en.md +50 -0
  59. package/knowledge-base/differential-geometry/metric-tensor.md +50 -0
  60. package/knowledge-base/differential-geometry/tangent-space.en.md +48 -0
  61. package/knowledge-base/differential-geometry/tangent-space.md +48 -0
  62. package/knowledge-base/information-geometry/fisher-metric.en.md +56 -0
  63. package/knowledge-base/information-geometry/fisher-metric.md +56 -0
  64. package/knowledge-base/information-geometry/natural-gradient.en.md +54 -0
  65. package/knowledge-base/information-geometry/natural-gradient.md +54 -0
  66. package/knowledge-base/lie-theory/equivariance.en.md +54 -0
  67. package/knowledge-base/lie-theory/equivariance.md +54 -0
  68. package/knowledge-base/lie-theory/group-action.en.md +51 -0
  69. package/knowledge-base/lie-theory/group-action.md +51 -0
  70. package/knowledge-base/lie-theory/lie-algebra.en.md +51 -0
  71. package/knowledge-base/lie-theory/lie-algebra.md +51 -0
  72. package/knowledge-base/lie-theory/lie-group.en.md +51 -0
  73. package/knowledge-base/lie-theory/lie-group.md +51 -0
  74. package/knowledge-base/lie-theory/representation.en.md +52 -0
  75. package/knowledge-base/lie-theory/representation.md +52 -0
  76. package/knowledge-base/matrix-analysis/low-rank-approximation.en.md +49 -0
  77. package/knowledge-base/matrix-analysis/low-rank-approximation.md +49 -0
  78. package/knowledge-base/matrix-analysis/matrix-perturbation.en.md +49 -0
  79. package/knowledge-base/matrix-analysis/matrix-perturbation.md +49 -0
  80. package/knowledge-base/matrix-analysis/positive-semidefinite.en.md +50 -0
  81. package/knowledge-base/matrix-analysis/positive-semidefinite.md +50 -0
  82. package/knowledge-base/matrix-analysis/projection.en.md +47 -0
  83. package/knowledge-base/matrix-analysis/projection.md +47 -0
  84. package/knowledge-base/matrix-analysis/spectral-decomposition.en.md +48 -0
  85. package/knowledge-base/matrix-analysis/spectral-decomposition.md +48 -0
  86. package/knowledge-base/optimization/constrained-optimization.en.md +53 -0
  87. package/knowledge-base/optimization/constrained-optimization.md +53 -0
  88. package/knowledge-base/optimization/convex-optimization.en.md +50 -0
  89. package/knowledge-base/optimization/convex-optimization.md +50 -0
  90. package/knowledge-base/optimization/lagrangian-duality.en.md +50 -0
  91. package/knowledge-base/optimization/lagrangian-duality.md +50 -0
  92. package/knowledge-base/optimization/proximal-method.en.md +52 -0
  93. package/knowledge-base/optimization/proximal-method.md +52 -0
  94. package/knowledge-base/optimization/riemannian-optimization.en.md +51 -0
  95. package/knowledge-base/optimization/riemannian-optimization.md +51 -0
  96. package/knowledge-base/overview.en.md +29 -218
  97. package/knowledge-base/overview.md +29 -220
  98. package/knowledge-base/probability/concentration-inequality.en.md +45 -0
  99. package/knowledge-base/probability/concentration-inequality.md +45 -0
  100. package/knowledge-base/probability/entropy.en.md +47 -0
  101. package/knowledge-base/probability/entropy.md +47 -0
  102. package/knowledge-base/probability/fisher-information.en.md +48 -0
  103. package/knowledge-base/probability/fisher-information.md +48 -0
  104. package/knowledge-base/probability/information-bottleneck.en.md +49 -0
  105. package/knowledge-base/probability/information-bottleneck.md +49 -0
  106. package/knowledge-base/probability/kl-divergence.en.md +51 -0
  107. package/knowledge-base/probability/kl-divergence.md +51 -0
  108. package/knowledge-base/topology/euler-characteristic.en.md +54 -0
  109. package/knowledge-base/topology/euler-characteristic.md +54 -0
  110. package/knowledge-base/topology/fundamental-group.en.md +52 -0
  111. package/knowledge-base/topology/fundamental-group.md +52 -0
  112. package/knowledge-base/topology/persistent-homology.en.md +54 -0
  113. package/knowledge-base/topology/persistent-homology.md +54 -0
  114. package/lenses/algorithmic.en.md +49 -0
  115. package/lenses/algorithmic.md +49 -0
  116. package/lenses/axiomatization.en.md +48 -0
  117. package/lenses/axiomatization.md +48 -0
  118. package/lenses/categorical.en.md +48 -0
  119. package/lenses/categorical.md +48 -0
  120. package/lenses/causal.en.md +49 -0
  121. package/lenses/causal.md +49 -0
  122. package/lenses/duality.en.md +47 -0
  123. package/lenses/duality.md +47 -0
  124. package/lenses/game.en.md +50 -0
  125. package/lenses/game.md +50 -0
  126. package/lenses/geometric.en.md +53 -0
  127. package/lenses/geometric.md +53 -0
  128. package/lenses/local-to-global.en.md +52 -0
  129. package/lenses/local-to-global.md +52 -0
  130. package/lenses/perturbation.en.md +51 -0
  131. package/lenses/perturbation.md +51 -0
  132. package/lenses/probabilistic.en.md +48 -0
  133. package/lenses/probabilistic.md +48 -0
  134. package/lenses/projection.en.md +50 -0
  135. package/lenses/projection.md +50 -0
  136. package/lenses/spectral.en.md +52 -0
  137. package/lenses/spectral.md +52 -0
  138. package/lenses/symmetry.en.md +49 -0
  139. package/lenses/symmetry.md +49 -0
  140. package/lenses/topological.en.md +48 -0
  141. package/lenses/topological.md +48 -0
  142. package/lenses/variational.en.md +48 -0
  143. package/lenses/variational.md +48 -0
  144. package/package.json +9 -3
  145. package/references/books/abstract-algebra.md +5 -5
  146. package/references/books/algebraic-geometry-rising-sea.md +5 -5
  147. package/references/books/differential-geometry.md +3 -3
  148. package/references/books/matrix-analysis.md +4 -4
  149. package/references/books/micro-lie-theory.md +3 -3
  150. package/references/books/optimization-ml.md +1 -1
  151. package/references/books/smooth-manifolds.md +3 -3
  152. package/references/gpu-friendly-math.en.md +8 -8
  153. package/references/gpu-friendly-math.md +2 -2
  154. package/references/inspiration.en.md +1 -1
  155. package/references/inspiration.md +2 -2
  156. package/skills/math-research-activator/SKILL.en.md +161 -106
  157. package/skills/math-research-activator/SKILL.md +162 -110
  158. package/skills/math-research-activator/original-texts.en.md +9 -9
  159. package/skills/math-research-activator/original-texts.md +11 -11
  160. package/commands/abstraction.md +0 -11
  161. package/commands/algorithmic-thinking.md +0 -11
  162. package/commands/axiomatization.md +0 -11
  163. package/commands/causal-inference.md +0 -11
  164. package/commands/discrete-combinatorial.md +0 -11
  165. package/commands/game-theory.md +0 -11
  166. package/commands/induction-analogy.md +0 -11
  167. package/commands/information-theory.md +0 -11
  168. package/commands/logic-deduction.md +0 -11
  169. package/commands/modeling.md +0 -11
  170. package/commands/optimization.md +0 -11
  171. package/commands/probability-statistics.md +0 -11
  172. package/commands/symmetry-invariance.md +0 -11
  173. package/commands/topological-thinking.md +0 -11
  174. package/commands/transformation.md +0 -11
  175. package/skills/abstraction/SKILL.en.md +0 -117
  176. package/skills/abstraction/SKILL.md +0 -121
  177. package/skills/abstraction/original-texts.en.md +0 -163
  178. package/skills/abstraction/original-texts.md +0 -175
  179. package/skills/algorithmic-thinking/SKILL.en.md +0 -132
  180. package/skills/algorithmic-thinking/SKILL.md +0 -138
  181. package/skills/algorithmic-thinking/original-texts.en.md +0 -253
  182. package/skills/algorithmic-thinking/original-texts.md +0 -256
  183. package/skills/axiomatization/SKILL.en.md +0 -144
  184. package/skills/axiomatization/SKILL.md +0 -151
  185. package/skills/axiomatization/original-texts.en.md +0 -154
  186. package/skills/axiomatization/original-texts.md +0 -160
  187. package/skills/causal-inference/SKILL.en.md +0 -147
  188. package/skills/causal-inference/SKILL.md +0 -151
  189. package/skills/causal-inference/original-texts.en.md +0 -136
  190. package/skills/causal-inference/original-texts.md +0 -167
  191. package/skills/discrete-combinatorial/SKILL.en.md +0 -124
  192. package/skills/discrete-combinatorial/SKILL.md +0 -131
  193. package/skills/discrete-combinatorial/original-texts.en.md +0 -184
  194. package/skills/discrete-combinatorial/original-texts.md +0 -185
  195. package/skills/game-theory/SKILL.en.md +0 -117
  196. package/skills/game-theory/SKILL.md +0 -123
  197. package/skills/game-theory/original-texts.en.md +0 -131
  198. package/skills/game-theory/original-texts.md +0 -131
  199. package/skills/induction-analogy/SKILL.en.md +0 -145
  200. package/skills/induction-analogy/SKILL.md +0 -152
  201. package/skills/induction-analogy/original-texts.en.md +0 -140
  202. package/skills/induction-analogy/original-texts.md +0 -154
  203. package/skills/information-theory/SKILL.en.md +0 -134
  204. package/skills/information-theory/SKILL.md +0 -140
  205. package/skills/information-theory/original-texts.en.md +0 -127
  206. package/skills/information-theory/original-texts.md +0 -127
  207. package/skills/logic-deduction/SKILL.en.md +0 -130
  208. package/skills/logic-deduction/SKILL.md +0 -135
  209. package/skills/logic-deduction/original-texts.en.md +0 -160
  210. package/skills/logic-deduction/original-texts.md +0 -173
  211. package/skills/modeling/SKILL.en.md +0 -135
  212. package/skills/modeling/SKILL.md +0 -139
  213. package/skills/modeling/original-texts.en.md +0 -162
  214. package/skills/modeling/original-texts.md +0 -165
  215. package/skills/optimization/SKILL.en.md +0 -129
  216. package/skills/optimization/SKILL.md +0 -135
  217. package/skills/optimization/original-texts.en.md +0 -167
  218. package/skills/optimization/original-texts.md +0 -168
  219. package/skills/probability-statistics/SKILL.en.md +0 -146
  220. package/skills/probability-statistics/SKILL.md +0 -151
  221. package/skills/probability-statistics/original-texts.en.md +0 -191
  222. package/skills/probability-statistics/original-texts.md +0 -193
  223. package/skills/symmetry-invariance/SKILL.en.md +0 -135
  224. package/skills/symmetry-invariance/SKILL.md +0 -139
  225. package/skills/symmetry-invariance/original-texts.en.md +0 -206
  226. package/skills/symmetry-invariance/original-texts.md +0 -221
  227. package/skills/topological-thinking/SKILL.en.md +0 -124
  228. package/skills/topological-thinking/SKILL.md +0 -128
  229. package/skills/topological-thinking/original-texts.en.md +0 -134
  230. package/skills/topological-thinking/original-texts.md +0 -164
  231. package/skills/transformation/SKILL.en.md +0 -120
  232. package/skills/transformation/SKILL.md +0 -124
  233. package/skills/transformation/original-texts.en.md +0 -204
  234. package/skills/transformation/original-texts.md +0 -216
@@ -0,0 +1,64 @@
1
+ # Topology-Preserving Compression(拓扑保持压缩)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
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 ✅ verified / ⚠️ retrofittable (needs validation) / ❌ 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 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
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
+ - 投影操作(如矩阵平方根逆)计算代价高且数值不稳定
@@ -0,0 +1,59 @@
1
+ # Contrastive Loss
2
+ > **Rigor disclaimer**: Claims about complexity, memory, FlashAttention fusion, Tensor Core, and KV-Cache compression are marked as ✅ verified / ⚠️ retrofittable (needs validation) / ❌ infeasible. Unmarked claims are theoretically possible but require engineering validation.
3
+
4
+ ## Applicable Problems
5
+ When the model needs to learn "what is similar to what and what is different from what." Typical scenarios: (1) Different augmented views of the same input should be pulled closer (positive pairs), while different inputs should be pushed apart (negative pairs); (2) Shared representations should capture cross-task commonalities, while Private representations should distinguish task-specific features; (3) In the expert embedding space, similar inputs should be routed to the same expert. Core objective: **learn relative relationships rather than absolute values**.
6
+
7
+ ## Mathematical Inspiration
8
+ - Lenses: lenses/geometric.md (metric spaces and distance functions), lenses/probabilistic.md (mutual information maximization)
9
+ - Knowledge: knowledge-base/probability/entropy.md (conditional distributions and likelihood), knowledge-base/differential-geometry/manifold.md (geodesics and curvature)
10
+
11
+ ## Required Mathematical Knowledge
12
+ - **InfoNCE Loss**: $L = -\log[\exp(\text{sim}(q,k^+)/\tau) / \sum_j \exp(\text{sim}(q,k_j)/\tau)]$ -- essentially a lower-bound estimate of mutual information in contrastive learning; $\tau$ is the temperature parameter controlling distribution sharpness
13
+ - **Margin-Based Metric Learning**: Triplet Loss $= \max(0, d(a,p) - d(a,n) + \text{margin})$ -- explicitly widens the distance gap between positive and negative pairs in metric space
14
+ - **NT-Xent (Normalized Temperature-scaled Cross Entropy)**: Softmax contrastive loss on the unit sphere $S^{d-1}$, with normalization eliminating scale effects
15
+ - **Debiased Contrastive Learning**: Corrects for false negatives in negative samples, using prior $\tau^+$ to estimate the true negative sample distribution
16
+
17
+ ## AI Module Form
18
+ ```
19
+ Module: ContrastiveLoss
20
+ Input: anchors z_a in R^{B x d}, positives z_p in R^{B x d}, negative pool z_n in R^{N x d}
21
+
22
+ Core formula (InfoNCE + temperature scaling):
23
+ sim(q, k) = q^T k / (||q|| * ||k||) // cosine similarity
24
+ logits_i = [sim(z_a_i, z_p_i)] (+) [sim(z_a_i, z_n_j)]_{j=1}^N // concatenation
25
+ L_contrast = -1/B * Sum_i log( exp(logits_i[0]/tau) / Sum_j exp(logits_i[j]/tau) )
26
+
27
+ Queue mechanism (MoCo style):
28
+ z_n = FIFO_queue.enqueue(z_p.detach()) // negative sample queue, capacity N >> B
29
+ // Queue stores encodings from historical batches, increasing negative count without additional memory
30
+
31
+ Hard Negative Mining:
32
+ top-k indices = argsort(sim(z_a, z_n), descending=True)[:k]
33
+ z_n_hard = z_n[top-k indices] // retain only the k hardest negatives
34
+ ```
35
+
36
+ ## Implementable Architectures
37
+ - **Dual-Tower Encoder + Projection Head**: encoder -> projection_head (2-layer MLP) -> normalize -> loss
38
+ - **Negative Sample Queue**: Maintain a FIFO queue of momentum encoder outputs, capacity N=65536
39
+ - **Symmetric Loss**: $L = L(a \to p) + L(p \to a)$, swapping positive/negative roles for enhanced training stability
40
+ - **Multi-Granularity Contrast**: Apply contrastive objectives simultaneously at token-level, sequence-level, and expert-level
41
+
42
+ ## GPU Feasibility
43
+ - **Tensorization**: Similarity computation is $z_a @ z_n^T$ -- standard GEMM $(B \times d) @ (d \times N) = B \times N$
44
+ - **GEMM-mappability**: Core computation is 1-2 matrix multiplications, perfectly mapped to cuBLAS
45
+ - **Complexity**: $O(B \cdot N \cdot d)$ computation + $O(B \cdot N)$ storage for the logits matrix; approximately 64MB when B=256, N=65536
46
+ - **Memory & KV-Cache**: Negative sample queue occupies $N \cdot d \cdot 4$ bytes, approximately 65536 * 256 * 4 = 64MB, fixed overhead
47
+ - **Low Precision Stability**: Cosine similarity + softmax under fp16 requires caution for exp overflow; use log-sum-exp trick
48
+ - **Parallelism & Communication**: On multiple GPUs, use all-gather to collect negatives from other GPUs to enlarge $N$ (MoCo v3 strategy)
49
+ - **Sparse Structure**: After hard negative mining, only $k \ll N$ negatives are retained, effectively sparsifying the logits
50
+ - **Operator Fusion**: L2-norm -> matmul -> scale -> log-softmax -> nll_loss can be fused
51
+
52
+ ## Paper Phrasing
53
+ "We employ temperature-scaled InfoNCE contrastive loss with a momentum encoder maintaining a negative sample queue of N=65536, maximizing the lower bound of positive-pair mutual information on the unit sphere. Theoretical analysis shows this lower bound converges at rate $O(1/\sqrt{N})$."
54
+
55
+ ## Risks
56
+ - Too small $\tau$ causes training instability (excessively large gradients); too large $\tau$ makes all samples indistinguishable (degenerates to uniform distribution)
57
+ - Stale encodings in the negative sample queue introduce representation bias
58
+ - False negative problem: unsupervised negative sampling may select samples that are semantically similar but differently labeled
59
+ - When $B$ is too small, the positive/negative pair imbalance within the batch must be compensated by the queue
@@ -0,0 +1,68 @@
1
+ # Contrastive Loss(对比损失)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当需要让模型学会"什么和什么相似、什么和什么不同"时使用。典型场景:
6
+ (1) 同一输入的不同增强视图应拉近(正对),不同输入应推远(负对);
7
+ (2) Shared 表示应包含跨任务共性,Private 表示应区分任务特异性;
8
+ (3) 专家嵌入空间中相似输入应路由到同一专家。核心诉求:**学习相对关系而非绝对值**。
9
+
10
+ ## 数学思想来源
11
+ - 透镜:lenses/geometric.md(度量空间与距离函数)、lenses/probabilistic.md(互信息最大化)
12
+ - 知识:knowledge-base/probability/entropy.md(条件分布与似然)、
13
+ knowledge-base/differential-geometry/manifold.md(测地线与曲率)
14
+
15
+ ## 需要的数学知识
16
+ - **InfoNCE 损失**:L = -log[exp(sim(q,k⁺)/τ) / Σ_j exp(sim(q,k_j)/τ)]
17
+ 本质是对比学习中的互信息下界估计,τ 为温度参数控制分布锐度
18
+ - **Margin-based 度量学习**:Triplet Loss = max(0, d(a,p) - d(a,n) + margin)
19
+ 在度量空间中显式拉开正负对距离差
20
+ - **NT-Xent (Normalized Temperature-scaled Cross Entropy)**:
21
+ 在单位球面 S^{d-1} 上的 softmax 对比,归一化消除尺度影响
22
+ - **去偏对比学习 (Debiased Contrastive)**:
23
+ 修正负样本中的假阴性问题,使用先验 τ⁺ 估计真实负样本分布
24
+
25
+ ## AI 模块形式
26
+ ```
27
+ 模块:ContrastiveLoss
28
+ 输入:锚点 z_a ∈ R^{B×d},正样本 z_p ∈ R^{B×d},负样本库 z_n ∈ R^{N×d}
29
+
30
+ 核心公式 (InfoNCE + 温度缩放):
31
+ sim(q, k) = q^T k / (‖q‖ · ‖k‖) // cosine 相似度
32
+ logits_i = [sim(z_a_i, z_p_i)] ⊕ [sim(z_a_i, z_n_j)]_{j=1}^N // 拼接
33
+ L_contrast = -1/B · Σ_i log( exp(logits_i[0]/τ) / Σ_j exp(logits_i[j]/τ) )
34
+
35
+ Queue 机制(MoCo 风格):
36
+ z_n = FIFO_queue.enqueue(z_p.detach()) // 负样本队列,容量 N >> B
37
+ // 队列中存储的是历史 batch 的编码,增大负样本数而不增加显存
38
+
39
+ Hard Negative Mining:
40
+ top-k indices = argsort(sim(z_a, z_n), descending=True)[:k]
41
+ z_n_hard = z_n[top-k indices] // 只保留最难的 k 个负样本
42
+ ```
43
+
44
+ ## 可实现结构
45
+ - **双塔编码器 + 投影头**:encoder → projection_head(MLP 2层) → 归一化 → loss
46
+ - **负样本队列**:维护 momentum encoder 输出的 FIFO queue,容量 N=65536
47
+ - **对称损失**:L = L(a→p) + L(p→a),正负角色互换,增强训练稳定性
48
+ - **多粒度对比**:同时在 token-level、sequence-level、expert-level 施加对比
49
+
50
+ ## GPU 可行性
51
+ - **张量化**:sim 计算为 z_a @ z_n^T → 标准 GEMM (B×d) @ (d×N) = B×N
52
+ - **GEMM 可映射**:核心就是 1-2 次矩阵乘法,完美映射 cuBLAS
53
+ - **复杂度**:O(B·N·d) 计算 + O(B·N) 存储 logits 矩阵,B=256,N=65536 时约 64MB
54
+ - **显存与 KV-Cache**:负样本队列占 N·d·4 bytes ≈ 65536·256·4 = 64MB,固定开销
55
+ - **低精度稳定**:cosine 相似度 + softmax 在 fp16 下需注意 exp 溢出,用 log-sum-exp trick
56
+ - **并行与通信**:多 GPU 时用 all-gather 收集其他 GPU 的负样本扩大 N(MoCo v3 策略)
57
+ - **稀疏结构**:hard negative mining 后只保留 k<<N 个负样本,有效稀疏化 logits
58
+ - **算子融合**:L2-norm → matmul → scale → log-softmax → nll_loss 可融合
59
+
60
+ ## 论文表述方式
61
+ "采用温度缩放的 InfoNCE 对比损失,通过动量编码器维护 N=65536 的负样本队列,
62
+ 在单位球面上最大化正对互信息的下界,理论分析表明该下界以 O(1/√N) 收敛。"
63
+
64
+ ## 风险
65
+ - τ 过小导致训练不稳定(梯度过大),τ 过大导致所有样本不分难易(退化均匀分布)
66
+ - 负样本队列中的过期编码引入 stale representation 偏差
67
+ - 假阴性问题:无监督负采样可能采到语义相似但标注不同的样本
68
+ - B 过小时 batch 内正负对不平衡,需依赖队列补偿
@@ -0,0 +1,69 @@
1
+ # Information Bottleneck Loss
2
+ > **Rigor disclaimer**: Claims about complexity, memory, FlashAttention fusion, Tensor Core, and KV-Cache compression are marked as ✅ verified / ⚠️ retrofittable (needs validation) / ❌ infeasible. Unmarked claims are theoretically possible but require engineering validation.
3
+
4
+ ## Applicable Problems
5
+ When a representation $Z$ must achieve an optimal balance between "retaining task-relevant information" and "compressing input redundancy." Typical scenarios: (1) Shared representations should retain only cross-task common information, discarding task-specific noise; (2) Private representations should retain only single-task unique information; (3) Routing features should maximize expert-task matching information. Core objective: **optimal information compression -- nothing more, nothing less, retaining only what is useful**.
6
+
7
+ ## Mathematical Inspiration
8
+ - Lenses: lenses/probabilistic.md (information bottleneck principle, mutual information variational), lenses/variational.md (Lagrangian duality)
9
+ - Knowledge: knowledge-base/probability/kl-divergence.md (IB theory, rate-distortion function), knowledge-base/probability/entropy.md (mutual information and conditional entropy)
10
+
11
+ ## Required Mathematical Knowledge
12
+ - **Information Bottleneck Objective**: $\min I(X;Z) - \beta \cdot I(Z;Y)$, compressing $X \to Z$ while preserving the predictive power of $Z$ for $Y$
13
+ - **Variational Bounds on Mutual Information**:
14
+ $I(X;Z) \leq \mathbb{E}_{p(x,z)}[\log q(z|x)] - \mathbb{E}_{p(z)}[\log q(z)]$ (upper bound for compression term)
15
+ $I(Z;Y) \geq \mathbb{E}_{p(z,y)}[\log q(y|z)] + H(Y)$ (lower bound for prediction term)
16
+ - **CPC (Contrastive Predictive Coding)**: InfoNCE lower bound on $I(Z_t; Z_{t+k})$
17
+ - **MINE (Mutual Information Neural Estimation)**:
18
+ $I(X;Z) = \sup_\theta \{ \mathbb{E}[\log T_\theta(x,z)] - \log \mathbb{E}[T_\theta(x,z')] \}$
19
+
20
+ ## AI Module Form
21
+ ```
22
+ Module: InformationBottleneckLoss
23
+ Input: representation Z in R^{B x d}, input X (or its encoding), label Y
24
+
25
+ Method 1 - VIB (Variational Information Bottleneck):
26
+ // Compression upper bound: variational approximation q(z) = N(0, I)
27
+ I_upper = KL(q(z|x) || p(z)) // standard VAE KL term
28
+ // Prediction lower bound: classifier/regressor q(y|z)
29
+ I_lower = CE(q(y|z), y) // cross-entropy = estimate of -H(Y|Z)
30
+ L_IB = I_upper + beta * I_lower
31
+ // beta controls compression-prediction trade-off: larger beta = more aggressive compression
32
+
33
+ Method 2 - Contrastive Mutual Information Estimation (no distributional assumptions):
34
+ // NWJ estimator instead of KL
35
+ I_nwj(x;z) = E[f(x,z)] - exp(E[f(x,z')] - 1) // f is a discriminator network
36
+ L_IB_contrast = I_nwj(x;z) - beta * InfoNCE(z, y) // both terms differentiable
37
+
38
+ Method 3 - Shared/Private IB Decomposition:
39
+ Z_s = enc_shared(x), Z_p = enc_private(x)
40
+ L = I(Z_s; X) + I(Z_p; X) // total compression
41
+ - beta_1 * I(Z_s; Y_common) // Shared retains common information
42
+ - beta_2 * I(Z_p; Y_specific) // Private retains specific information
43
+ + gamma * OrthLoss(Z_s, Z_p) // orthogonality ensures decomposition
44
+ ```
45
+
46
+ ## Implementable Architectures
47
+ - **Dual-Encoder Architecture**: enc_shared and enc_private share a base trunk, branching into separate heads
48
+ - **Mutual Information Estimator**: Small MLP discriminator $T(x,z) \to$ scalar, alternating variational with the main network
49
+ - **Beta Scheduling**: Set $\beta = 0$ at training start (no compression), gradually increase to target value during training
50
+ - **Gradient Reversal**: Gradient of $I(X;Z)$ is reversed via z.flip_gradient(), implementing adversarial compression
51
+
52
+ ## GPU Feasibility
53
+ - **Tensorization**: Mutual information estimator is a standard MLP -> GEMM chain; KL is element-wise
54
+ - **GEMM-mappability**: VIB method requires only encoder GEMM + KL computation; contrastive method adds 1 GEMM for shuffled negatives
55
+ - **Complexity**: One additional KL term $O(B \cdot d)$ or one discriminator forward pass $O(B \cdot d^2)$ beyond the standard network; acceptable
56
+ - **Memory & KV-Cache**: Requires additional storage for discriminator parameters (small MLP) and intermediate activations, <10MB
57
+ - **Low Precision Stability**: The exp operation in the MINE estimator requires clipping under fp16; VIB KL is recommended in fp32
58
+ - **Parallelism & Communication**: Discriminator and main network forward passes can run in parallel; gradients are synchronized through the shared representation layer
59
+ - **Sparse Structure**: Compressed $Z$ dimensions can be dynamically pruned (Automatic Relevance Determination, ARD)
60
+ - **Operator Fusion**: Encoder forward + KL computation + discriminator forward can be partially fused
61
+
62
+ ## Paper Phrasing
63
+ "Based on information bottleneck theory, we formalize Shared/Private decomposition as $\min I(X;Z_s) + I(X;Z_p) - \beta_1 I(Z_s;Y_c) - \beta_2 I(Z_p;Y_s)$, replacing mutual information terms with variational upper and lower bounds for end-to-end variational, theoretically guaranteeing beta-optimality on the compression-prediction Pareto frontier."
64
+
65
+ ## Risks
66
+ - Mutual information estimators (MINE/NWJ) have high variance, causing training instability; large batches or moving averages are needed
67
+ - Improper beta selection leads to over-compression (underfitting) or insufficient compression (overfitting)
68
+ - VIB assumes Gaussian posteriors, which may be inadequate for complex posterior distributions
69
+ - When optimizing multiple IB objectives jointly, the relative ratio of $\beta_1$ and $\beta_2$ is sensitive
@@ -0,0 +1,74 @@
1
+ # Information Bottleneck Loss(信息瓶颈损失)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当需要让表示 Z 在"保留任务相关信息"与"压缩输入冗余信息"之间取得最优平衡时使用。
6
+ 典型场景:(1) Shared 表示应只保留跨任务共性信息,丢弃任务特异噪声;
7
+ (2) Private 表示应只保留单任务独有信息;(3) 路由特征应最大化专家-任务匹配信息。
8
+ 核心诉求:**信息最优压缩——不多不少,只保留有用的**。
9
+
10
+ ## 数学思想来源
11
+ - 透镜:lenses/probabilistic.md(信息瓶颈原理、互信息优化)、lenses/variational.md(拉格朗日对偶)
12
+ - 知识:knowledge-base/probability/kl-divergence.md(IB 理论、率失真函数)、
13
+ knowledge-base/probability/entropy.md(互信息与条件熵)
14
+
15
+ ## 需要的数学知识
16
+ - **信息瓶颈目标**:min I(X;Z) - β·I(Z;Y),压缩 X→Z 同时保留 Z 对 Y 的预测力
17
+ - **互信息变分下界/上界**:
18
+ I(X;Z) ≤ E_{p(x,z)}[log q(z|x)] - E_{p(z)}[log q(z)] (用上界估计压缩项)
19
+ I(Z;Y) ≥ E_{p(z,y)}[log q(y|z)] + H(Y) (用下界估计预测项)
20
+ - **CPC (Contrastive Predictive Coding)**:I(Z_t; Z_{t+k}) 的 InfoNCE 下界
21
+ - **MINE (Mutual Information Neural Estimation)**:
22
+ I(X;Z) = sup_θ { E[log T_θ(x,z)] - log E[T_θ(x,z')] }
23
+
24
+ ## AI 模块形式
25
+ ```
26
+ 模块:InformationBottleneckLoss
27
+ 输入:表示 Z ∈ R^{B×d},输入 X(或其编码),标签 Y
28
+
29
+ 方法1 - VIB (Variational Information Bottleneck):
30
+ // 压缩项上界:用变分近似 q(z) = N(0, I)
31
+ I_upper = KL(q(z|x) ‖ p(z)) // 标准 VAE 的 KL 项
32
+ // 预测项下界:用分类器/回归器 q(y|z)
33
+ I_lower = CE(q(y|z), y) // 交叉熵 = -H(Y|Z) 的估计
34
+ L_IB = I_upper + β · I_lower
35
+ // β 控制压缩-预测权衡:β↑ 更激进压缩,β↓ 保留更多预测信息
36
+
37
+ 方法2 - 对比式互信息估计(无需分布假设):
38
+ // 用 NWJ 估计器替代 KL
39
+ I_nwj(x;z) = E[f(x,z)] - exp(E[f(x,z')] - 1) // f 为判别网络
40
+ L_IB_contrast = I_nwj(x;z) - β · InfoNCE(z, y) // 两项均可微
41
+
42
+ 方法3 - Shared/Private IB 分解:
43
+ Z_s = enc_shared(x), Z_p = enc_private(x)
44
+ L = I(Z_s; X) + I(Z_p; X) // 总压缩
45
+ - β₁ · I(Z_s; Y_common) // Shared 保留公共信息
46
+ - β₂ · I(Z_p; Y_specific) // Private 保留特异信息
47
+ + γ · OrthLoss(Z_s, Z_p) // 正交性确保分解
48
+ ```
49
+
50
+ ## 可实现结构
51
+ - **双编码器架构**:enc_shared 和 enc_private 共享底层 trunk,分叉出各自 head
52
+ - **互信息估计器**:小型 MLP 判别器 T(x,z) → scalar,与主网络交替优化
53
+ - **β 调度**:训练初期 β=0(不压缩),随训练进行逐步增大到目标值
54
+ - **梯度反转**:I(X;Z) 的梯度通过 z.flip_gradient() 反转,实现对抗式压缩
55
+
56
+ ## GPU 可行性
57
+ - **张量化**:互信息估计器为标准 MLP → GEMM 链;KL 为 element-wise
58
+ - **GEMM 可映射**:VIB 方法仅需 encoder GEMM + KL 计算;对比方法额外 1 次 GEMM 做 shuffle 负样本
59
+ - **复杂度**:比标准网络多 1 个 KL 项 O(B·d) 或 1 个判别器前向 O(B·d²),可接受
60
+ - **显存与 KV-Cache**:需额外存储判别器参数(小型 MLP)和中间激活,<10MB
61
+ - **低精度稳定**:MINE 估计器的 exp 运算在 fp16 下需 clip;VIB 的 KL 建议 fp32
62
+ - **并行与通信**:判别器与主网络可并行前向,梯度通过共享表示层同步
63
+ - **稀疏结构**:压缩后的 Z 维度可动态裁剪(自动相关性确定 ARD)
64
+ - **算子融合**:encoder 前向 + KL 计算 + 判别器前向可部分融合
65
+
66
+ ## 论文表述方式
67
+ "基于信息瓶颈理论,将 Shared/Private 分解形式化为 min I(X;Z_s)+I(X;Z_p)-β₁I(Z_s;Y_c)-β₂I(Z_p;Y_s),
68
+ 通过变分上下界替代互信息项实现端到端优化,理论上保证压缩-预测 Pareto 前沿的 β-最优性。"
69
+
70
+ ## 风险
71
+ - 互信息估计(MINE/NWJ)方差大,训练不稳定,需要大 batch 或 moving average
72
+ - β 选择不当导致过度压缩(欠拟合)或压缩不足(过拟合)
73
+ - VIB 假设高斯后验,对复杂后验分布近似不足
74
+ - 多 IB 联合优化时 β₁, β₂ 的相对比例敏感
@@ -0,0 +1,56 @@
1
+ # Orthogonality Loss
2
+ > **Rigor disclaimer**: Claims about complexity, memory, FlashAttention fusion, Tensor Core, and KV-Cache compression are marked as ✅ verified / ⚠️ retrofittable (needs validation) / ❌ infeasible. Unmarked claims are theoretically possible but require engineering validation.
3
+
4
+ ## Applicable Problems
5
+ In multi-expert / multi-task settings, representations learned by submodules are highly overlapping and redundant, leading to poor parameter utilization. This loss is used when the $d$-dimensional feature space needs to be partitioned into $K$ non-interfering subspaces -- such as Shared-Private separation, MoE expert differentiation, and multi-task head decorrelation. Core objective: **ensure different modules see different things**.
6
+
7
+ ## Mathematical Inspiration
8
+ - Lenses: lenses/projection.md (orthogonal projection and subspace decomposition), lenses/variational.md (regularization and saddle points)
9
+ - Knowledge: knowledge-base/matrix-analysis/projection.md (spectral theorem, SVD, Schur decomposition), knowledge-base/probability/kl-divergence.md (redundancy and mutual information)
10
+
11
+ ## Required Mathematical Knowledge
12
+ - **Frobenius Inner Product and Orthogonality**: $\langle A, B \rangle_F = \text{tr}(A^T B)$; when $\langle A, B \rangle_F = 0$, $A \perp B$
13
+ - **Stiefel Manifold Constraint**: $W \in \text{St}(d, k)$, i.e., $W^T W = I_k$, projecting onto the set of orthogonal matrices
14
+ - **DPP (Determinantal Point Process)**: $\det(W^T W)$ increases as column vectors become more spread out, serving as a diversity proxy
15
+ - **Off-Diagonal Elements of the Cosine Similarity Matrix**: $C_{ij} = |\langle w_i, w_j \rangle| / (\|w_i\|\|w_j\|)$, minimizing $\sum_{i \neq j} C_{ij}^2$
16
+
17
+ ## AI Module Form
18
+ ```
19
+ Module: OrthogonalDiversityLoss
20
+ Input: K feature matrices {W_k in R^{d x r}}_{k=1}^K (weights or features of K submodules)
21
+
22
+ Method 1 - Frobenius Orthogonal Regularization:
23
+ L_orth = Sum_{i<j} ||W_i^T W_j||_F^2
24
+ // Computation: O(K^2 * d * r^2), K typically <16 so cost is manageable
25
+
26
+ Method 2 - Grassmann Distance (based on principal angles):
27
+ sigma_k = singular values of SVD(W_i^T W_j)
28
+ L_grass = Sum_{i<j} Sum_k sigma_k^2 * (1 - sigma_k^2) // penalizes singular values that are neither 0 nor 1
29
+
30
+ Method 3 - Efficient Cosine Decorrelation:
31
+ G = concat([W_1,...,W_K])^T * concat([W_1,...,W_K]) // single GEMM
32
+ L_corr = ||G * (1 - I)||_F^2 // mask out diagonal, penalize off-diagonal elements
33
+ ```
34
+
35
+ ## Implementable Architectures
36
+ - **Embedded as nn.Module**: forward receives $K$ tensors and returns a scalar loss; supports direct .backward()
37
+ - **Weighted Combination with Main Loss**: L_total = L_task + lambda * L_orth; lambda can use cosine annealing or warm-up
38
+ - **Block Computation**: When $K$ is large, perform mini-batch sampling over $(i,j)$ pairs, computing only $B$ out of $\binom{K}{2}$ pairs per step
39
+
40
+ ## GPU Feasibility
41
+ - **Tensorization**: Core operation is matmul ($W^T W$) -- standard GEMM, perfectly mapped to Tensor Cores
42
+ - **GEMM-mappability**: Method 3 requires only 1 GEMM + 1 element-wise mask + Frobenius norm
43
+ - **Complexity**: $O(K \cdot d \cdot r)$ storage + $O(d \cdot r^2 \cdot K)$ or $O(K^2 \cdot d \cdot r^2)$ computation; negligible when $K < 16$
44
+ - **Memory & KV-Cache**: Intermediate matrices are on the order of $d \times r \cdot K$, adding no KV-Cache overhead
45
+ - **Low Precision Stability**: Frobenius norm is a sum of squares, safe under fp16; Grassmann SVD is recommended in fp32
46
+ - **Parallelism & Communication**: The $K$ pairs are embarrassingly parallel; can be distributed across GPUs with all-reduce
47
+ - **Sparse Structure**: If $W_k$ is itself sparse (e.g., MoE gate), masking further increases sparsity
48
+ - **Operator Fusion**: matmul -> mask -> square -> sum can be fused into a single CUDA kernel
49
+
50
+ ## Paper Phrasing
51
+ "We introduce an orthogonality regularizer L_orth = Sum_{i<j} ||W_i^T W_j||_F^2 that constrains the feature spaces of submodules to the approximately orthogonal Grassmann sub-manifold, theoretically guaranteeing that redundancy across $K$ subspaces decays as $O(1/\sqrt{d})$."
52
+
53
+ ## Risks
54
+ - Excessively large lambda causes variational difficulties (orthogonal constraint conflicts with task objective); requires careful tuning or adaptive lambda
55
+ - The SVD in Method 2 produces unstable gradients during backpropagation; epsilon-regularization on singular values is needed
56
+ - When $K \cdot r > d$, strict orthogonality is impossible; dimensionality reduction or acceptance of approximate orthogonality is required
@@ -0,0 +1,60 @@
1
+ # Orthogonality Loss(正交性损失)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 多专家/多任务场景中,各子模块学习到的表示高度重叠、冗余,导致参数利用率低下。
6
+ 当需要将 d 维特征空间分割为 K 个互不干扰的子空间时使用——如 Shared-Private 分离、
7
+ MoE 专家差异化、多任务 head 去相关。核心诉求:**让不同模块看到不同的东西**。
8
+
9
+ ## 数学思想来源
10
+ - 透镜:lenses/projection.md(正交投影与子空间分解)、lenses/variational.md(正则化与鞍点)
11
+ - 知识:knowledge-base/matrix-analysis/projection.md(谱定理、SVD、Schur 分解)、
12
+ knowledge-base/probability/kl-divergence.md(冗余度与互信息)
13
+
14
+ ## 需要的数学知识
15
+ - **Frobenius 内积与正交性**:⟨A, B⟩_F = tr(A^T B),当 ⟨A, B⟩_F = 0 时 A⊥B
16
+ - **Stiefel 流形约束**:W ∈ St(d, k) 即 W^T W = I_k,投影到正交矩阵集合
17
+ - **DPP 行列式点过程**:det(W^T W) 越大表示列向量越分散,可作为多样性代理
18
+ - **cosine 相似度矩阵去对角外元素**:C_ij = |⟨w_i, w_j⟩| / (‖w_i‖‖w_j‖),最小化 Σ_{i≠j} C_ij²
19
+
20
+ ## AI 模块形式
21
+ ```
22
+ 模块:OrthogonalDiversityLoss
23
+ 输入:K 个特征矩阵 {W_k ∈ R^{d×r}}_{k=1}^K(K 个子模块的权重或特征)
24
+
25
+ 方法1 - Frobenius 正交正则:
26
+ L_orth = Σ_{i<j} ‖W_i^T W_j‖_F²
27
+ // 计算量:O(K² · d · r²),K 一般 <16 所以可控
28
+
29
+ 方法2 - Grassmann 距离(基于主角度):
30
+ σ_k = SVD(W_i^T W_j) 的奇异值
31
+ L_grass = Σ_{i<j} Σ_k σ_k²(1 - σ_k²) // 惩罚非 0 非 1 的奇异值
32
+
33
+ 方法3 - 高效 cosine 去相关:
34
+ G = concat([W_1,...,W_K])^T · concat([W_1,...,W_K]) // 一次 GEMM
35
+ L_corr = ‖G ⊙ (1 - I)‖_F² // mask 掉对角线,惩罚非对角元素
36
+ ```
37
+
38
+ ## 可实现结构
39
+ - **嵌入为 nn.Module**:forward 接收 K 个 tensor,返回标量 loss,可直接 .backward()
40
+ - **与主 loss 加权组合**:L_total = L_task + λ · L_orth,λ 可用 cosine annealing 或 warm-up
41
+ - **分块计算**:当 K 很大时,对 (i,j) 对做 mini-batch 采样,每步只算 C(K,2) 中的 B 对
42
+
43
+ ## GPU 可行性
44
+ - **张量化**:核心操作为 matmul(W^T W)→ 标准 GEMM,完美映射 Tensor Core
45
+ - **GEMM 可映射**:方法3 只需 1 次 GEMM + 1 次 element-wise mask + Frobenius 范数
46
+ - **复杂度**:O(K·d·r) 存储 + O(d·r²·K) 或 O(K²·d·r²) 计算,K<16 时 negligible
47
+ - **显存与 KV-Cache**:中间矩阵 d×r·K 量级,不增加 KV-Cache 负担
48
+ - **低精度稳定**:Frobenius 范数为平方和,fp16 下 OK;Grassmann SVD 建议 fp32
49
+ - **并行与通信**:K 对之间 embarrassingly parallel,可分 GPU 计算后 all-reduce
50
+ - **稀疏结构**:若 W_k 本身稀疏(如 MoE gate),mask 后稀疏度进一步提升
51
+ - **算子融合**:matmul → mask → square → sum 可融合为单个 CUDA kernel
52
+
53
+ ## 论文表述方式
54
+ "我们引入正交性正则项 L_orth = Σ_{i<j}‖W_i^T W_j‖_F²,将各子模块的特征空间约束
55
+ 到近似正交的 Grassmann 子流形上,理论上保证 K 个子空间的冗余度以 O(1/√d) 衰减。"
56
+
57
+ ## 风险
58
+ - λ 过大导致优化困难(正交约束与任务目标冲突),需 careful tuning 或 adaptive λ
59
+ - 方法2 的 SVD 在反向传播时梯度不稳定,需添加 ε-正则化到奇异值
60
+ - 当 K·r > d 时正交性不可能严格满足,需降维或接受近似正交