math-skill 2.0.1 → 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 (206) hide show
  1. package/README.en-US.md +167 -175
  2. package/README.md +167 -175
  3. package/agents/math-critic.en.md +235 -0
  4. package/agents/math-critic.md +10 -8
  5. package/commands/ask.md +3 -12
  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 +39 -0
  97. package/knowledge-base/overview.md +29 -218
  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 +11 -3
  145. package/references/agentic-workflow.en.md +53 -0
  146. package/references/agentic-workflow.md +2 -0
  147. package/references/books/abstract-algebra.md +9 -5
  148. package/references/books/algebraic-geometry-rising-sea.md +9 -5
  149. package/references/books/differential-geometry.md +7 -3
  150. package/references/books/matrix-analysis.md +8 -4
  151. package/references/books/micro-lie-theory.md +7 -3
  152. package/references/books/optimization-ml.md +5 -1
  153. package/references/books/smooth-manifolds.md +7 -3
  154. package/references/gpu-friendly-math.en.md +65 -0
  155. package/references/gpu-friendly-math.md +4 -2
  156. package/references/inspiration.en.md +113 -0
  157. package/references/inspiration.md +4 -2
  158. package/skills/math-research-activator/SKILL.en.md +187 -0
  159. package/skills/math-research-activator/SKILL.md +162 -108
  160. package/skills/math-research-activator/original-texts.en.md +105 -0
  161. package/skills/math-research-activator/original-texts.md +11 -11
  162. package/commands/abstraction.md +0 -13
  163. package/commands/algorithmic-thinking.md +0 -13
  164. package/commands/axiomatization.md +0 -13
  165. package/commands/causal-inference.md +0 -13
  166. package/commands/discrete-combinatorial.md +0 -13
  167. package/commands/game-theory.md +0 -13
  168. package/commands/induction-analogy.md +0 -13
  169. package/commands/information-theory.md +0 -13
  170. package/commands/logic-deduction.md +0 -13
  171. package/commands/modeling.md +0 -13
  172. package/commands/optimization.md +0 -13
  173. package/commands/probability-statistics.md +0 -13
  174. package/commands/symmetry-invariance.md +0 -13
  175. package/commands/topological-thinking.md +0 -13
  176. package/commands/transformation.md +0 -13
  177. package/skills/abstraction/SKILL.md +0 -119
  178. package/skills/abstraction/original-texts.md +0 -175
  179. package/skills/algorithmic-thinking/SKILL.md +0 -136
  180. package/skills/algorithmic-thinking/original-texts.md +0 -256
  181. package/skills/axiomatization/SKILL.md +0 -149
  182. package/skills/axiomatization/original-texts.md +0 -160
  183. package/skills/causal-inference/SKILL.md +0 -149
  184. package/skills/causal-inference/original-texts.md +0 -167
  185. package/skills/discrete-combinatorial/SKILL.md +0 -129
  186. package/skills/discrete-combinatorial/original-texts.md +0 -185
  187. package/skills/game-theory/SKILL.md +0 -121
  188. package/skills/game-theory/original-texts.md +0 -131
  189. package/skills/induction-analogy/SKILL.md +0 -150
  190. package/skills/induction-analogy/original-texts.md +0 -154
  191. package/skills/information-theory/SKILL.md +0 -138
  192. package/skills/information-theory/original-texts.md +0 -127
  193. package/skills/logic-deduction/SKILL.md +0 -133
  194. package/skills/logic-deduction/original-texts.md +0 -173
  195. package/skills/modeling/SKILL.md +0 -137
  196. package/skills/modeling/original-texts.md +0 -165
  197. package/skills/optimization/SKILL.md +0 -133
  198. package/skills/optimization/original-texts.md +0 -168
  199. package/skills/probability-statistics/SKILL.md +0 -149
  200. package/skills/probability-statistics/original-texts.md +0 -193
  201. package/skills/symmetry-invariance/SKILL.md +0 -137
  202. package/skills/symmetry-invariance/original-texts.md +0 -221
  203. package/skills/topological-thinking/SKILL.md +0 -126
  204. package/skills/topological-thinking/original-texts.md +0 -164
  205. package/skills/transformation/SKILL.md +0 -122
  206. package/skills/transformation/original-texts.md +0 -216
@@ -0,0 +1,89 @@
1
+ # Equivariant Split(等变分割)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当输入具有对称性(如排列、旋转、平移),且表示应保持或反映这些对称性时使用。
6
+ 典型场景:(1) Token 排列等变——句子中 token 顺序变化,表示应相应变化(位置编码);
7
+ (2) 特征维度的对称性分组——某些特征维度在特定变换下不变,某些等变;
8
+ (3) 多专家对称分工——不同专家处理不同对称性子空间;
9
+ (4) 几何深度学习——3D 分子/蛋白质结构中 SE(3) 等变性。
10
+ 核心诉求:**让网络结构编码对称性先验,减少学习负担,提升泛化**。
11
+
12
+ ## 数学思想来源
13
+ - 透镜:lenses/geometric.md(群作用、不变/等变映射)、lenses/probabilistic.md(对称性与信息冗余)
14
+ - 知识:knowledge-base/matrix-analysis/projection.md(群表示论、不可约表示)、
15
+ knowledge-base/differential-geometry/manifold.md(李群、齐性空间)
16
+
17
+ ## 需要的数学知识
18
+ - **群作用与等变性**:映射 f 对群 G 等变 ⟺ f(g·x) = g·f(x), ∀g∈G
19
+ 不变性是等变性的特例(g·f(x) = f(x),即平凡表示)
20
+ - **Schur 引理与不可约表示分解**:
21
+ 任何有限群表示可分解为不可约表示的直和:V = ⊕_i m_i · V_i
22
+ 等变线性映射在不可约分量间是对角/块对角的
23
+ - **Peter-Weyl 定理**:紧群上的函数可分解为不可约表示矩阵元的级数
24
+ f(x) = Σ_ρ Σ_{ij} c_{ρ,ij} · ρ_{ij}(g)(广义 Fourier 展开)
25
+ - **Steerable 特征空间**:特征按群的不可约表示组织,
26
+ 变换 g 作用时各分量按对应的表示矩阵变换:f_i → Σ_j ρ_{ij}(g) f_j
27
+
28
+ ## AI 模块形式
29
+ ```
30
+ 模块:EquivariantSplit
31
+ 输入:X ∈ R^{N×d},对称群 G(如 S_n 排列群、Z_n 循环群、SO(3) 旋转群)
32
+
33
+ 方法1 - 按不可约表示分割特征维度:
34
+ // 将 d 维特征按群的不可约表示分解
35
+ irreps = decompose(G, d) // [(d₁, ρ₁), (d₂, ρ₂), ...] 其中 Σdᵢ = d
36
+ X_split = split(X, [d₁, d₂, ...], dim=-1) // 按不可约分量切分
37
+ // 每个分量用等变层独立处理:
38
+ for (X_i, ρ_i) in zip(X_split, irreps):
39
+ Y_i = EquivariantLinear(X_i, ρ_i) // 权重受 Schur 约束
40
+ Y = concat(Y_i, dim=-1) // 重组
41
+
42
+ 方法2 - 位置等变分割(Token 排列群 S_n):
43
+ // Transformer 自注意力天然对排列等变(无位置编码时)
44
+ // 显式引入可控的排列等变性:
45
+ X_content = X[:, :d_content] // 排列不变的内容部分
46
+ X_position = X[:, d_content:] // 位置相关的部分
47
+ // 内容部分用排列不变的池化:
48
+ z_inv = mean(X_content, dim=1) // 全局不变特征
49
+ // 位置部分用等变操作:
50
+ z_equiv = Attention(X_position, X_position, X_position) // 排列等变
51
+ output = z_equiv + MLP(z_inv).unsqueeze(1) // 不变信号广播回去
52
+
53
+ 方法3 - 群卷积/群池化:
54
+ // 特征定义在群 G 上:f: G → R^c
55
+ // 群卷积:(f * ψ)(g) = Σ_{h∈G} f(h) · ψ(h⁻¹g)
56
+ // 群池化:pool over orbits of subgroup H < G
57
+ // 实现为矩阵乘法(群乘法表→稀疏置换矩阵)
58
+ for g in generators(G):
59
+ X_g = permutation_matrix(g) @ X // 群生成元作用
60
+ features_g = Linear(X_g) // 共享权重的等变处理
61
+ output = aggregate(features_g) // 沿群维度聚合
62
+ ```
63
+
64
+ ## 可实现结构
65
+ - **e3nn / lie_learn 集成**:使用现有库处理 SO(3)/SE(3) 的不可约表示和球谐函数
66
+ - **特征分块存储**:按不可约表示组织特征维度,每个块独立归一化和处理
67
+ - **群操作预计算**:群乘法表、Clebsch-Gordan 系数等一次性计算并缓存
68
+ - **对称性增强**:训练时对输入施加随机群元素 g∈G(数据增强),鼓励等变性
69
+
70
+ ## GPU 可行性
71
+ - **张量化**:不可约分量的处理为 batched GEMM;群卷积为稀疏 GEMM 或 batched matmul
72
+ - **GEMM 可映射**:EquivariantLinear 的每个块为独立 GEMM (N×dᵢ)@(dᵢ×dᵢ_out),可 batch
73
+ - **复杂度**:与标准网络同阶(Schur 约束反而减少参数),群卷积额外 |G| 倍
74
+ - **显存与 KV-Cache**:群卷积需存储 |G| 份特征,|G| 大时显存压力显著
75
+ - **低精度稳定**:球谐函数 Y_l^m 的计算涉及阶乘和平方根,建议 fp32
76
+ - **并行与通信**:不可约分量间独立,完美并行;群卷积的不同 g 可并行
77
+ - **稀疏结构**:群卷积的置换矩阵极度稀疏(每行/列恰好一个非零),SpMM 高效
78
+ - **算子融合**:split → batched matmul → concat 可融合;群池化的 scatter+reduce 可融合
79
+
80
+ ## 论文表述方式
81
+ "利用群表示论的 Schur 引理,将 d 维特征空间按对称群 G 的不可约表示分解为直和 ⊕mᵢVᵢ,
82
+ 每个分量使用受等变约束的线性层独立处理,参数效率提升 |G|/Σmᵢ² 倍,
83
+ 同时保证网络对群作用的等变性,在对称数据上泛化误差降低 O(1/√|G|)。"
84
+
85
+ ## 风险
86
+ - 群的选择不当(过大约束导致欠拟合,过小无法捕获对称性)
87
+ - 不可约表示分解需要领域知识,非标准群的实现复杂
88
+ - 群卷积的 |G| 倍特征存储在群阶大时不可行(如 S_10 有 3.6M 个元素)
89
+ - 近似等变(soft equivariance)vs 严格等变的权衡难以控制
@@ -0,0 +1,85 @@
1
+ # Manifold Representation
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
+ Use when input data resides in a high-dimensional space but is actually distributed on a low-dimensional manifold. Typical scenarios:
6
+ (1) Semantic space of natural language tokens -- although dimensionality d = 4096, the effective degrees of freedom are far less than d;
7
+ (2) Multi-modal alignment -- text and image distributions lie on different manifolds that need to be aligned;
8
+ (3) Expert feature spaces -- each expert processes a different local region of the manifold;
9
+ (4) Dimensionality reduction / compression -- exploit the low-dimensional manifold nature to reduce parameter count.
10
+ Core requirement: **leverage the low-dimensional manifold structure of data to improve representation efficiency and generalization**.
11
+
12
+ ## Mathematical Inspiration
13
+ - Lenses: lenses/geometric.md (Riemannian geometry, geodesics, curvature), lenses/probabilistic.md (intrinsic dimensionality)
14
+ - Knowledge: knowledge-base/differential-geometry/manifold.md (manifolds, tangent spaces, exponential maps),
15
+ knowledge-base/matrix-analysis/projection.md (SVD, low-rank approximation, PCA)
16
+
17
+ ## Required Mathematical Background
18
+ - **Manifold Hypothesis**: Data x in R^D actually lies on a smooth d-dimensional manifold M with d << D
19
+ Locally approximable by the tangent space T_pM isomorphic to R^d
20
+ - **Local Coordinate Chart**: phi: U subset M -> R^d, mapping a manifold patch to low-dimensional Euclidean space
21
+ Multiple charts {phi_i} form an atlas covering the entire manifold
22
+ - **Geodesic Distance**: d_M(p, q) = inf integral ||gamma'(t)|| dt, the shortest path between two points on the manifold
23
+ Approximate computation: Dijkstra/Isomap on a k-NN graph
24
+ - **Exponential Map / Logarithmic Map**:
25
+ exp_p: T_pM -> M (tangent space to manifold), log_p: M -> T_pM (manifold to tangent space)
26
+ Used to perform linear operations in the tangent space and map back to the manifold
27
+
28
+ ## AI Module Form
29
+ ```
30
+ Module: ManifoldRepresentation
31
+ Input: X in R^{N x D} (high-dimensional input), target manifold dimension d << D
32
+
33
+ Method 1 - Local Linear Embedding (Chart-based):
34
+ // Partition the d-dimensional manifold into K local regions, each with a linear projection
35
+ assignments = cluster(X, K) // assign inputs to K local regions
36
+ for k in range(K):
37
+ z_k = W_k @ X[assignments==k] + b_k // local linear projection
38
+ // Equivalent to MoE: K "chart experts" each responsible for one manifold patch
39
+ z = sum_k g_k(x) * (W_k @ x + b_k) // g_k is the chart assignment weight
40
+
41
+ Method 2 - Geodesic Preservation Loss (global structure preservation):
42
+ // Preserve geodesic distances from high-dimensional space in the low-dimensional representation
43
+ D_high = geodesic_distance(X, k_nn=10) // shortest paths on k-NN graph
44
+ D_low = pairwise_distance(Z) // Euclidean distances in low-dim representation
45
+ L_geo = ||D_high - D_low||_F^2 / N^2 // Sammon mapping
46
+ // Or t-SNE-style KL divergence:
47
+ p_ij = exp(-D_high^2 / (2 sigma^2)) / sum // high-dim affinity
48
+ q_ij = 1 / (1 + D_low^2) / sum // low-dim t-distribution affinity
49
+ L_tsne = KL(P || Q)
50
+
51
+ Method 3 - Riemannian Optimization (optimize directly on the manifold):
52
+ // Parameters constrained to Stiefel/Grassmann manifold
53
+ W in St(d, r) i.e. W^T W = I_r // orthogonality constraint
54
+ // Riemannian SGD:
55
+ grad_euclidean = nabla f(W)
56
+ grad_riemannian = grad_euclidean - W @ (W^T @ grad_euclidean) // project to tangent space
57
+ W = retract(W, -lr * grad_riemannian) // retraction mapping back to manifold
58
+ // retract can be implemented via QR decomposition or Cayley transform
59
+ ```
60
+
61
+ ## Implementable Structures
62
+ - **Chart MoE**: K local linear projections + softmax gating => natural integration with the MoE framework
63
+ - **Manifold regularization**: L_manifold = tr(Z^T L Z) / N^2, where L is the graph Laplacian and Z is the representation
64
+ Encourages nearby samples to have similar representations
65
+ - **Intrinsic dimension estimation**: Use MLE or two-norm methods to estimate the effective dimensionality d* of the data
66
+ - **Adaptive d**: Local dimensionality varies across regions; estimate locally via PCA
67
+
68
+ ## GPU Feasibility
69
+ - **Tensorization**: Local linear projections are GEMM (d x D) @ (D x N); graph Laplacian regularization is SpMM
70
+ - **GEMM-mappable**: K linear projections in Chart MoE form a batched GEMM (K x d x D) @ (D x N)
71
+ - **Complexity**: k-NN construction O(N * D * log N) requires FAISS; manifold regularization O(N^2) requires sampling approximation
72
+ - **Memory & KV-Cache**: K chart parameters K * d * D typically < 10 MB; k-NN graph N * k * 4 bytes
73
+ - **Low-precision stability**: Distance computations and exp in fp16 require attention to numerical range; Riemannian retract recommended in fp32
74
+ - **Parallelism & Communication**: K charts computed independently, perfectly parallel; k-NN search accelerated with FAISS GPU
75
+ - **Sparse structure**: k-NN graph is naturally sparse; manifold regularization L is a sparse matrix, enabling SpMM acceleration
76
+ - **Operator fusion**: Matmul + bias + activation within a chart can be fused; gating softmax + weighted-sum can be fused
77
+
78
+ ## Paper-Worthy Formulation
79
+ "Based on the manifold hypothesis, we constrain D-dimensional token representations to a d*-dimensional (intrinsic dimension estimate) submanifold, achieving piecewise-linear approximation via K local coordinate charts (Chart MoE) and preserving global geodesic structure through graph Laplacian manifold regularization, with theoretical guarantees that embedding error converges at rate O(N^{-2/d*})."
80
+
81
+ ## Risks
82
+ - Inaccurate intrinsic dimension d* estimation leads to over-compression or dimension waste
83
+ - k-NN graph construction is computationally expensive at large scale, requiring sampling or approximation
84
+ - The N^2 complexity of manifold regularization limits batch size, necessitating mini-batch sampling
85
+ - Discontinuities at local chart boundaries require overlapping regions and smooth transitions
@@ -0,0 +1,87 @@
1
+ # Manifold Representation(流形表示)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当输入数据虽然在高维空间中,但实际分布在低维流形上时使用。典型场景:
6
+ (1) 自然语言 token 的语义空间——虽维度 d=4096,但有效自由度远小于 d;
7
+ (2) 多模态对齐——文本和图像分布在不同的流形上,需要对齐;
8
+ (3) 专家特征空间——每个专家处理流形的不同局部区域;
9
+ (4) 降维/压缩——利用流形低维本质减少参数量。
10
+ 核心诉求:**利用数据的低维流形结构,提高表示效率和泛化能力**。
11
+
12
+ ## 数学思想来源
13
+ - 透镜:lenses/geometric.md(黎曼几何、测地线、曲率)、lenses/probabilistic.md(内在维度)
14
+ - 知识:knowledge-base/differential-geometry/manifold.md(流形、切空间、指数映射)、
15
+ knowledge-base/matrix-analysis/projection.md(SVD、低秩近似、PCA)
16
+
17
+ ## 需要的数学知识
18
+ - **流形假设**:数据 x ∈ R^D 实际分布在 d << D 维的光滑流形 M 上
19
+ 局部可用切空间 T_pM ≈ R^d 线性近似
20
+ - **局部坐标卡 (Chart)**:φ: U ⊂ M → R^d,将流形局部映射到低维欧氏空间
21
+ 多个坐标卡 {φ_i} 构成图册(Atlas),覆盖整个流形
22
+ - **测地线距离**:d_M(p,q) = inf ∫‖γ'(t)‖dt,流形上两点间最短路径
23
+ 近似计算:k-NN 图上 Dijkstra/Isomap
24
+ - **指数映射/对数映射**:
25
+ exp_p: T_pM → M(切空间到流形),log_p: M → T_pM(流形到切空间)
26
+ 用于在切空间中做线性运算后映射回流形
27
+
28
+ ## AI 模块形式
29
+ ```
30
+ 模块:ManifoldRepresentation
31
+ 输入:X ∈ R^{N×D}(高维输入),目标流形维度 d << D
32
+
33
+ 方法1 - 局部线性嵌入(Chart-based):
34
+ // 将 d 维流形分成 K 个局部区域,每个区域用线性投影
35
+ assignments = cluster(X, K) // 将输入分配到 K 个局部区域
36
+ for k in range(K):
37
+ z_k = W_k @ X[assignments==k] + b_k // 局部线性投影 d×D → d×d
38
+ // 等效为 MoE:K 个"chart expert"各负责流形一个局部
39
+ z = Σ_k g_k(x) · (W_k @ x + b_k) // g_k 为 chart 分配权重
40
+
41
+ 方法2 - 测地线保持损失(全局结构保持):
42
+ // 保持高维空间的测地线距离在低维表示中不变
43
+ D_high = geodesic_distance(X, k_nn=10) // k-NN 图上最短路
44
+ D_low = pairwise_distance(Z) // 低维表示的欧氏距离
45
+ L_geo = ‖D_high - D_low‖_F² / N² // Sammon mapping
46
+ // 或用 t-SNE 式 KL 散度:
47
+ p_ij = exp(-D_high²/2σ²) / Σ // 高维亲和度
48
+ q_ij = 1/(1+D_low²) / Σ // 低维 t 分布亲和度
49
+ L_tsne = KL(P ‖ Q)
50
+
51
+ 方法3 - 黎曼优化(直接在流形上优化):
52
+ // 参数约束在 Stiefel/Grassmann 流形上
53
+ W ∈ St(d, r) i.e. W^T W = I_r // 正交约束
54
+ // Riemannian SGD:
55
+ grad_euclidean = ∇f(W)
56
+ grad_riemannian = grad_euclidean - W @ (W^T @ grad_euclidean) // 投影到切空间
57
+ W = retract(W, -lr · grad_riemannian) // 缩回映射到流形
58
+ // retract 可用 QR 分解或 Cayley 变换实现
59
+ ```
60
+
61
+ ## 可实现结构
62
+ - **Chart MoE**:K 个局部线性投影 + softmax 门控 → 天然与 MoE 框架集成
63
+ - **流形正则化**:L_manifold = tr(Z^T L Z) / N²,L 为图拉普拉斯,Z 为表示
64
+ 鼓励相邻样本的表示相近
65
+ - **内在维度估计**:用 MLE 或 two-norm 方法估计数据的有效维度 d*
66
+ - **自适应 d**:不同区域的局部维度不同,用 PCA 局部估计
67
+
68
+ ## GPU 可行性
69
+ - **张量化**:局部线性投影为 GEMM (d×D)@(D×N);图拉普拉斯正则为 SpMM
70
+ - **GEMM 可映射**:Chart MoE 的 K 个线性投影为 batched GEMM (K×d×D)@(D×N)
71
+ - **复杂度**:k-NN 构建 O(N·D·log N) 需 FAISS;流形正则 O(N²) 需采样近似
72
+ - **显存与 KV-Cache**:K 个 chart 参数 K·d·D 通常 <10MB;k-NN 图 N·k·4 bytes
73
+ - **低精度稳定**:距离计算和 exp 在 fp16 下需注意数值范围;黎曼 retract 建议 fp32
74
+ - **并行与通信**:K 个 chart 独立计算,完美并行;k-NN 搜索用 FAISS GPU 加速
75
+ - **稀疏结构**:k-NN 图天然稀疏,流形正则 L 为稀疏矩阵,SpMM 加速
76
+ - **算子融合**:chart 内的 matmul+bias+activation 可融合;门控 softmax+weighted-sum 可融合
77
+
78
+ ## 论文表述方式
79
+ "基于流形假设将 D 维 token 表示约束到 d*(内在维度估计)维子流形上,
80
+ 通过 K 个局部坐标卡(Chart MoE)实现分段线性近似,配合图拉普拉斯流形正则
81
+ 保持全局测地线结构,理论上保证嵌入误差以 O(N^{-2/d*}) 收敛。"
82
+
83
+ ## 风险
84
+ - 内在维度 d* 估计不准确导致过度压缩或维度浪费
85
+ - k-NN 图构建在大规模数据下计算代价高,需采样或近似
86
+ - 流形正则的 N² 复杂度限制 batch size,需 mini-batch 采样
87
+ - 局部 chart 边界处表示不连续,需重叠区域和平滑过渡
@@ -0,0 +1,84 @@
1
+ # Shared-Private Decomposition
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
+ Use in multi-task/multi-domain learning when representations need to be decomposed into a "cross-task common component" and a "task-specific component."
6
+ Typical scenarios: (1) Multi-task MoE -- Shared experts handle linguistic commonalities, Private experts handle task-specific logic;
7
+ (2) Multi-domain adaptation -- Shared representations capture general semantics, Private representations capture domain terminology;
8
+ (3) Continual learning -- Shared retains stable knowledge, Private accommodates new knowledge without interfering with old knowledge.
9
+ Core requirement: **explicitly separate commonality from individuality to prevent negative transfer and catastrophic forgetting**.
10
+
11
+ ## Mathematical Inspiration
12
+ - Lenses: lenses/projection.md (subspace decomposition, direct sum decomposition), lenses/probabilistic.md (information decomposition)
13
+ - Knowledge: knowledge-base/matrix-analysis/projection.md (direct sum decomposition V = U + W, projection operators),
14
+ knowledge-base/probability/kl-divergence.md (information decomposition: shared/synergy/unique)
15
+
16
+ ## Required Mathematical Background
17
+ - **Direct Sum Decomposition**: R^d = S + P, where S intersect P = {0}, and every x = x_S + x_P is unique
18
+ Projection matrices P_S + P_P = I, P_S * P_P = 0
19
+ - **Information Decomposition (Williams & Beer PID)**:
20
+ I(X; Y_1, Y_2) = Shared + Unique_1 + Unique_2 + Synergy
21
+ Shared = the redundant information component min(I(X; Y_1), I(X; Y_2))
22
+ - **Low-Rank + Sparse Decomposition (RPCA)**: M = L + S, where L is low-rank (common) + S is sparse (specific)
23
+ Solved via nuclear norm + L1 norm convex relaxation
24
+ - **CCA (Canonical Correlation Analysis)**: max corr(W_1^T X, W_2^T Y), extracting shared variation between two sets of variables
25
+
26
+ ## AI Module Form
27
+ ```
28
+ Module: SharedPrivateDecomposer
29
+ Input: X in R^{N x d}, task identifier t in {1, ..., T}
30
+
31
+ Method 1 - Additive Decomposition (most common):
32
+ z_shared = E_shared(X) // shared encoder: MLP or Transformer block
33
+ z_private = E_private[t](X) // private encoder: independent parameters per task
34
+ z = z_shared + z_private // additive fusion
35
+ // Training objective: L_task(z, y) + lambda_1 * OrthLoss(z_shared, z_private)
36
+ // Orthogonality ensures shared and private learn different information
37
+
38
+ Method 2 - Gated Decomposition (dynamic weighting):
39
+ z_shared = E_shared(X)
40
+ z_private = E_private[t](X)
41
+ gate = sigmoid(Linear(z_shared + z_private)) // dynamic fusion gate
42
+ z = gate * z_shared + (1 - gate) * z_private
43
+ // Gating allows per-dimension selection of shared/private contribution ratios
44
+
45
+ Method 3 - Adversarial Decomposition (information-theoretic guarantee):
46
+ z_shared = E_shared(X)
47
+ z_private = E_private[t](X)
48
+ // Shared should be indistinguishable across tasks (adversarial gradient):
49
+ task_pred = classifier(z_shared.flip_gradient())
50
+ L_adv = -CE(task_pred, t) // Shared contains no task information
51
+ // Private should be discriminative across tasks:
52
+ L_private = CE(classifier(z_private), t)
53
+ L = L_task + lambda_adv * L_adv + lambda_priv * L_private
54
+
55
+ Dimension Allocation Principle:
56
+ d_shared = d * T / (T + 1) // With T tasks, shared occupies the majority
57
+ d_private = d * 1 / (T + 1) // Each private occupies a smaller portion
58
+ // Or dynamically allocate based on PCA variance explained ratio
59
+ ```
60
+
61
+ ## Implementable Structures
62
+ - **Dual encoder + fusion layer**: shared_encoder (large) + T private_encoders (small) + fusion
63
+ - **Parameter efficiency**: Private uses LoRA (Low-Rank Adaptation) instead of full encoders, O(d * r) parameters per task
64
+ - **Dynamic routing integration**: Shared experts + private experts selected via MoE routing
65
+ - **Progressive expansion**: For new tasks, only add private encoders with frozen shared parameters
66
+
67
+ ## GPU Feasibility
68
+ - **Tensorization**: Two encoder forward passes are independent GEMM chains, executable in parallel
69
+ - **GEMM-mappable**: Shared/private encoders are each standard Transformer FFNs (2x GEMM)
70
+ - **Complexity**: Shared O(N * d^2) + T private encoders O(N * d^2 / T), total approximately 2x a single encoder
71
+ - **Memory & KV-Cache**: All T private encoder parameters stored; LoRA compression needed when T is large
72
+ - **Low-precision stability**: Additive/gated fusion is safe in fp16; adversarial training gradient reversal requires fp32
73
+ - **Parallelism & Communication**: Shared and private encoders can be assigned to different GPUs; multi-task batches mixed for training
74
+ - **Sparse structure**: Private encoders can be sparsified (only the current task's is activated); only 1 out of T activated
75
+ - **Operator fusion**: Additive fusion is trivial; gated fusion sigmoid -> multiply -> add can be fused
76
+
77
+ ## Paper-Worthy Formulation
78
+ "We decompose the multi-task representation space R^d into a direct sum S + P. The Shared subspace ensures task-invariance through adversarial training (H(T|Z_s) -> log T), while the Private subspace guarantees information complementarity with Shared via orthogonal regularization. Theoretical analysis shows that negative transfer decays as O(||P_S * P_P||_F) with increasing orthogonality."
79
+
80
+ ## Risks
81
+ - Min-max variational in adversarial training is unstable; the gradient reversal scale and lambda_adv require careful tuning
82
+ - Over-compression of Shared leads to insufficient common information, placing excessive burden on Private
83
+ - Total Private parameters grow linearly with T, requiring LoRA or adapter modules to control
84
+ - When task similarity is low, Shared may learn a vacuous "common component"
@@ -0,0 +1,86 @@
1
+ # Shared-Private Decomposition(共享-私有分解)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 多任务/多领域学习中,需要将表示分解为"跨任务共性部分"和"任务特异部分"。
6
+ 典型场景:(1) 多任务 MoE——Shared 专家处理语言共性,Private 专家处理任务特异逻辑;
7
+ (2) 多领域适配——Shared 表示捕获通用语义,Private 表示捕获领域术语;
8
+ (3) 持续学习——Shared 保留稳定知识,Private 容纳新知识而不干扰旧知识。
9
+ 核心诉求:**显式分离共性与个性,避免负迁移和灾难性遗忘**。
10
+
11
+ ## 数学思想来源
12
+ - 透镜:lenses/projection.md(子空间分解、直和分解)、lenses/probabilistic.md(信息分解)
13
+ - 知识:knowledge-base/matrix-analysis/projection.md(直和分解 V = U ⊕ W、投影算子)、
14
+ knowledge-base/probability/kl-divergence.md(信息分解:shared/synergy/unique)
15
+
16
+ ## 需要的数学知识
17
+ - **直和分解**:R^d = S ⊕ P,其中 S ∩ P = {0},每个 x = x_S + x_P 唯一
18
+ 投影矩阵 P_S + P_P = I,P_S · P_P = 0
19
+ - **信息分解 (Williams & Beer PID)**:
20
+ I(X;Y₁,Y₂) = Shared + Unique₁ + Unique₂ + Synergy
21
+ Shared = min(I(X;Y₁), I(X;Y₂)) 的冗余信息部分
22
+ - **低秩+稀疏分解 (RPCA)**:M = L + S,L 低秩(共性)+ S 稀疏(特异)
23
+ 通过核范数 + L1 范数凸松弛求解
24
+ - **CCA (典型相关分析)**:max corr(W₁^T X, W₂^T Y),提取两组变量的共享变异
25
+
26
+ ## AI 模块形式
27
+ ```
28
+ 模块:SharedPrivateDecomposer
29
+ 输入:X ∈ R^{N×d},任务标识 t ∈ {1,...,T}
30
+
31
+ 方法1 - 加法分解(最常用):
32
+ z_shared = E_shared(X) // 共享编码器:MLP or Transformer block
33
+ z_private = E_private[t](X) // 私有编码器:每个任务独立参数
34
+ z = z_shared + z_private // 加法融合
35
+ // 训练目标:L_task(z, y) + λ₁·OrthLoss(z_shared, z_private)
36
+ // 正交性确保 shared 和 private 学到不同的东西
37
+
38
+ 方法2 - 门控分解(动态权重):
39
+ z_shared = E_shared(X)
40
+ z_private = E_private[t](X)
41
+ gate = sigmoid(Linear(z_shared ⊕ z_private)) // 动态融合门
42
+ z = gate ⊙ z_shared + (1 - gate) ⊙ z_private
43
+ // 门控允许逐维度选择 shared/private 的贡献比例
44
+
45
+ 方法3 - 对抗分解(信息论保证):
46
+ z_shared = E_shared(X)
47
+ z_private = E_private[t](X)
48
+ // Shared 应无法区分任务(对抗梯度):
49
+ task_pred = classifier(z_shared.flip_gradient())
50
+ L_adv = -CE(task_pred, t) // Shared 不含任务信息
51
+ // Private 应能区分任务:
52
+ L_private = CE(classifier(z_private), t)
53
+ L = L_task + λ_adv·L_adv + λ_priv·L_private
54
+
55
+ 维度分配原则:
56
+ d_shared = d · T/(T+1) // T 个任务时 shared 占大部分
57
+ d_private = d · 1/(T+1) // 每个 private 占较小部分
58
+ // 或用 PCA 变异解释率动态分配
59
+ ```
60
+
61
+ ## 可实现结构
62
+ - **双编码器 + 融合层**:shared_encoder (大) + T 个 private_encoder (小) + fusion
63
+ - **参数效率**:private 用 LoRA(低秩适配)而非完整编码器,参数 O(d·r) per task
64
+ - **动态路由集成**:shared 专家 + private 专家通过 MoE 路由选择
65
+ - **渐进扩展**:新任务时只增加 private 编码器,frozen shared 参数
66
+
67
+ ## GPU 可行性
68
+ - **张量化**:两个编码器前向为独立 GEMM 链,可并行执行
69
+ - **GEMM 可映射**:shared/private 编码器各为标准 Transformer FFN(2×GEMM)
70
+ - **复杂度**:shared O(N·d²) + T 个 private O(N·d²/T),总 ≈ 2× 单编码器
71
+ - **显存与 KV-Cache**:T 个 private 编码器参数全存储,T 大时需 LoRA 压缩
72
+ - **低精度稳定**:加法/门控融合在 fp16 安全;对抗训练的梯度反转需 fp32
73
+ - **并行与通信**:shared 和 private 编码器可分配到不同 GPU;多任务 batch 混合训练
74
+ - **稀疏结构**:private 编码器可稀疏化(仅当前任务激活),T 个中仅激活 1 个
75
+ - **算子融合**:加法融合 trivial;门控融合的 sigmoid→multiply→add 可融合
76
+
77
+ ## 论文表述方式
78
+ "将多任务表示空间 R^d 分解为直和 S ⊕ P,Shared 子空间通过对抗训练确保任务无关性
79
+ (H(T|Z_s)→log T),Private 子空间通过正交正则保证与 Shared 的信息互补,
80
+ 理论分析表明负迁移随正交性以 O(‖P_S·P_P‖_F) 衰减。"
81
+
82
+ ## 风险
83
+ - 对抗训练的 min-max 优化不稳定,梯度反转的 scale 和 λ_adv 需精心调节
84
+ - Shared 过度压缩导致共性信息不足,Private 负担过重
85
+ - T 增大时 Private 参数总量线性增长,需要 LoRA 或 adapter 控制
86
+ - 任务相似度低时 Shared 可能学到空洞的"公共部分"
@@ -0,0 +1,90 @@
1
+ # Subspace Alignment
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
+ Use when two or more representation spaces need to be aligned to a common subspace. Typical scenarios:
6
+ (1) Multi-modal alignment -- aligning text and image representations to a shared semantic subspace;
7
+ (2) Cross-layer alignment -- aligning shallow features to the subspace of deep features for residual connections or distillation;
8
+ (3) Expert output alignment -- different experts produce outputs with different dimensions/distributions that must be aligned before fusion;
9
+ (4) Domain adaptation -- source and target domain feature distributions differ, requiring subspace alignment.
10
+ Core requirement: **find the optimal linear/nonlinear mapping between two spaces such that corresponding semantics are aligned**.
11
+
12
+ ## Mathematical Inspiration
13
+ - Lenses: lenses/geometric.md (Grassmann manifold, principal angles), lenses/variational.md (Procrustes problem)
14
+ - Knowledge: knowledge-base/matrix-analysis/projection.md (SVD, orthogonal Procrustes),
15
+ knowledge-base/differential-geometry/manifold.md (Grassmann distance, geodesics)
16
+
17
+ ## Required Mathematical Background
18
+ - **Orthogonal Procrustes Problem**: min_{W in O(d)} ||AW - B||_F^2
19
+ Closed-form solution: W* = UV^T, where USV^T = SVD(A^T B)
20
+ - **CCA (Canonical Correlation Analysis)**: max_{W_1, W_2} tr(W_1^T Sigma_{XY} W_2) s.t. W_1^T Sigma_{XX} W_1 = I
21
+ Solution via generalized eigenvalue problem or SVD(Sigma_{XX}^{-1/2} Sigma_{XY} Sigma_{YY}^{-1/2})
22
+ - **Distance on the Grassmann Manifold**: Gr(d, r) = {r-dimensional subspaces of R^d}
23
+ Distance between two points (subspaces) determined by principal angles theta_i: d_G(U, V) = sqrt(sum theta_i^2)
24
+ cos(theta_i) = sigma_i(U^T V) (singular values of U^T V)
25
+ - **Subspace Tracking**: Online update of subspace basis
26
+ Oja's rule: W_{t+1} = W_t + eta * (x_t x_t^T W_t - W_t diag(W_t^T x_t x_t^T W_t))
27
+
28
+ ## AI Module Form
29
+ ```
30
+ Module: SubspaceAligner
31
+ Input: Source representation A in R^{N x d_a}, target representation B in R^{N x d_b} (paired data)
32
+
33
+ Method 1 - Linear Procrustes Alignment (most common):
34
+ // Find optimal linear duality W such that A @ W is close to B
35
+ M = A^T @ B // d_a x d_b, single GEMM
36
+ U, S, V^T = SVD(M) // singular value decomposition
37
+ W* = U @ V^T // d_a x d_b optimal orthogonal duality
38
+ // Differentiable version: parameterize W as nn.Parameter, optimize with SGD
39
+ L_align = ||A @ W - B||_F^2 / N // alignment loss
40
+
41
+ Method 2 - Deep CCA (nonlinear subspace alignment):
42
+ f_A = MLP_A(A) // R^{d_a} -> R^r (nonlinear projection)
43
+ f_B = MLP_B(B) // R^{d_b} -> R^r
44
+ Sigma_AA = f_A^T @ f_A / N + lambda * I // r x r auto-covariance
45
+ Sigma_BB = f_B^T @ f_B / N + lambda * I
46
+ Sigma_AB = f_A^T @ f_B / N // r x r cross-covariance
47
+ T = Sigma_AA^{-1/2} @ Sigma_AB @ Sigma_BB^{-1/2} // whitened cross-correlation
48
+ L_cca = -tr(SVD(T).S[:k]) // maximize sum of top k canonical correlations
49
+ // Equivalent to minimizing Grassmann distance
50
+
51
+ Method 3 - Subspace Angle Regularization (multi-expert output alignment):
52
+ // Outputs of multiple experts should be aligned to the same subspace
53
+ U_k = SVD(expert_k_output)[0][:, :r] // r-dim principal components of each expert output
54
+ for i, j in expert_pairs:
55
+ cos_angles = SVD(U_i^T @ U_j).S // cosines of principal angles
56
+ L_subspace = -mean(cos_angles) // maximize principal angle cosines -> minimize angles
57
+ // Or use Grassmann distance:
58
+ L_grass = sum(angles^2) // angles = arccos(cos_angles)
59
+
60
+ Online Subspace Tracking (adaptation at inference):
61
+ // New samples arrive at test time; incrementally update alignment matrix
62
+ W_new = W_old + eta * (x_new @ (y_new^T - x_new^T @ W_old)) // Oja-like
63
+ // No need to recompute SVD; O(d^2) online update
64
+ ```
65
+
66
+ ## Implementable Structures
67
+ - **Alignment Layer**: nn.Linear(d_a, d_b, bias=False) initialized with the Procrustes solution
68
+ - **Whitening layer**: Use running mean/variance for online whitening, avoiding per-step Sigma^{-1/2} computation
69
+ - **CCA alternative**: Use Barlow Twins-style redundancy reduction loss instead of CCA (avoids matrix inversion)
70
+ L_BT = ||C - I||_F^2 where C = corr(f_A, f_B)
71
+ - **Chunked SVD**: Use randomized SVD approximation at large scale; sufficient precision and faster
72
+
73
+ ## GPU Feasibility
74
+ - **Tensorization**: A^T @ B is standard GEMM (d x N) @ (N x d); SVD has cuSOLVER implementations
75
+ - **GEMM-mappable**: Procrustes core requires 1 GEMM + 1 SVD; CCA requires 2 GEMMs + 1 SVD
76
+ - **Complexity**: GEMM O(N * d^2); SVD O(d^3) (d typically < 1024, acceptable); online tracking O(d^2)
77
+ - **Memory & KV-Cache**: Storing covariance matrix d x d (~4 MB for d = 1024); no KV-Cache overhead
78
+ - **Low-precision stability**: SVD strongly recommended in fp32; whitening matrix inversion requires fp32 + epsilon regularization
79
+ - **Parallelism & Communication**: Subspace angle computations for multiple expert pairs are independent and parallel; CCA GEMMs are highly parallel
80
+ - **Sparse structure**: When source/target representations are sparse, covariance matrix Sigma is sparse, enabling sparse SVD
81
+ - **Operator fusion**: Whitening (mean-sub -> cov -> inv_sqrt -> transform) can be partially fused
82
+
83
+ ## Paper-Worthy Formulation
84
+ "Based on orthogonal Procrustes theory, we obtain the optimal isometric mapping W* = UV^T (where USV^T = SVD(A^T B)) between source and target representations. Extending this to Deep CCA for nonlinear subspace alignment, principal angle analysis on the Grassmann manifold shows that post-alignment subspace distance converges at rate O(r/sqrt(N)), while the Barlow Twins redundancy reduction objective ensures feature dimension decorrelation."
85
+
86
+ ## Risks
87
+ - SVD during backpropagation produces undefined gradients when singular values coincide; epsilon regularization is needed
88
+ - CCA whitening requires matrix inversion; numerically unstable when the covariance matrix is near-singular
89
+ - Nonlinear CCA (Deep CCA) may overfit, particularly on small datasets
90
+ - Online subspace tracking learning rate eta requires a decay schedule to prevent continuous drift
@@ -0,0 +1,92 @@
1
+ # Subspace Alignment(子空间对齐)
2
+ > **严谨性声明**:本文件中涉及复杂度、显存、FlashAttention 融合、Tensor Core、KV-Cache 压缩的结论均标注为「✅ 已验证 / ⚠️ 可改造需验证 / ❌ 不可行」。未标注的视为理论可行,需工程验证。
3
+
4
+ ## 适用问题
5
+ 当两个或多个表示空间需要对齐到共同的子空间时使用。典型场景:
6
+ (1) 多模态对齐——将文本和图像的表示对齐到共享语义子空间;
7
+ (2) 跨层对齐——将浅层特征对齐到深层特征的子空间,便于残差连接或蒸馏;
8
+ (3) 专家输出对齐——不同专家的输出维度/分布不同,需要对齐后融合;
9
+ (4) 领域适配——源域和目标域的特征分布不同,需要对齐子空间。
10
+ 核心诉求:**找到两个空间之间的最优线性/非线性映射,使对应语义对齐**。
11
+
12
+ ## 数学思想来源
13
+ - 透镜:lenses/geometric.md(Grassmann 流形、主角度)、lenses/variational.md(Procrustes 问题)
14
+ - 知识:knowledge-base/matrix-analysis/projection.md(SVD、正交 Procrustes)、
15
+ knowledge-base/differential-geometry/manifold.md(Grassmann 距离、测地线)
16
+
17
+ ## 需要的数学知识
18
+ - **正交 Procrustes 问题**:min_{W∈O(d)} ‖AW - B‖_F²
19
+ 闭合解:W* = UV^T,其中 USV^T = SVD(A^T B)
20
+ - **CCA (典型相关分析)**:max_W₁,W₂ tr(W₁^T Σ_XY W₂) s.t. W₁^T Σ_XX W₁ = I
21
+ 解为广义特征值问题或 SVD(Σ_XX^{-1/2} Σ_XY Σ_YY^{-1/2})
22
+ - **Grassmann 流形上的距离**:Gr(d, r) = {r 维子空间 ⊂ R^d}
23
+ 两点(子空间)的距离由主角度 θ_i 决定:d_G(U,V) = √(Σ θ_i²)
24
+ cos(θ_i) = σ_i(U^T V)(U^T V 的奇异值)
25
+ - **子空间追踪 (Subspace Tracking)**:在线更新子空间基
26
+ Oja 规则:W_{t+1} = W_t + η(x_t x_t^T W_t - W_t diag(W_t^T x_t x_t^T W_t))
27
+
28
+ ## AI 模块形式
29
+ ```
30
+ 模块:SubspaceAligner
31
+ 输入:源表示 A ∈ R^{N×d_a},目标表示 B ∈ R^{N×d_b}(配对数据)
32
+
33
+ 方法1 - 线性 Procrustes 对齐(最常用):
34
+ // 找最优线性变换 W 使 A@W ≈ B
35
+ M = A^T @ B // d_a × d_b,一次 GEMM
36
+ U, S, V^T = SVD(M) // 奇异值分解
37
+ W* = U @ V^T // d_a × d_b 最优正交变换
38
+ // 可微版本:将 W 参数化为 nn.Parameter,用 SGD 优化
39
+ L_align = ‖A @ W - B‖_F² / N // 对齐损失
40
+
41
+ 方法2 - 深度 CCA(非线性子空间对齐):
42
+ f_A = MLP_A(A) // R^{d_a} → R^r(非线性投影)
43
+ f_B = MLP_B(B) // R^{d_b} → R^r
44
+ Σ_AA = f_A^T @ f_A / N + λI // r×r 自协方差
45
+ Σ_BB = f_B^T @ f_B / N + λI
46
+ Σ_AB = f_A^T @ f_B / N // r×r 互协方差
47
+ T = Σ_AA^{-1/2} @ Σ_AB @ Σ_BB^{-1/2} // 白化互相关
48
+ L_cca = -tr(SVD(T).S[:k]) // 最大化前 k 个典型相关的和
49
+ // 等效于最小化 Grassmann 距离
50
+
51
+ 方法3 - 子空间角度正则(多专家输出对齐):
52
+ // 多个专家的输出应对齐到同一子空间
53
+ U_k = SVD(expert_k_output)[0][:, :r] // 各专家输出的 r 维主成分
54
+ for i, j in expert_pairs:
55
+ cos_angles = SVD(U_i^T @ U_j).S // 主角度的余弦
56
+ L_subspace = -mean(cos_angles) // 最大化主角度余弦 → 最小化角度
57
+ // 或使用 Grassmann 距离:
58
+ L_grass = sum(angles²) // angles = arccos(cos_angles)
59
+
60
+ 在线子空间追踪(推理时适配):
61
+ // 测试时新样本到来,增量更新对齐矩阵
62
+ W_new = W_old + η · (x_new @ (y_new^T - x_new^T @ W_old)) // Oja-like
63
+ // 无需重新 SVD,O(d²) 在线更新
64
+ ```
65
+
66
+ ## 可实现结构
67
+ - **对齐层 (AlignmentLayer)**:nn.Linear(d_a, d_b, bias=False) 初始化为 Procrustes 解
68
+ - **白化层**:用 running mean/variance 做在线白化,避免每步计算 Σ^{-1/2}
69
+ - **CCA 替代方案**:用 Barlow Twins 式的冗余减少损失替代 CCA(避免矩阵逆)
70
+ L_BT = ‖C - I‖_F² 其中 C = corr(f_A, f_B)
71
+ - **分块 SVD**:大规模时用 randomized SVD 近似,精度足够且更快
72
+
73
+ ## GPU 可行性
74
+ - **张量化**:A^T@B 为标准 GEMM (d×N)@(N×d);SVD 有 cuSOLVER 实现
75
+ - **GEMM 可映射**:Procrustes 核心 1 次 GEMM + 1 次 SVD;CCA 2 次 GEMM + 1 次 SVD
76
+ - **复杂度**:GEMM O(N·d²);SVD O(d³)(d 通常 <1024,可接受);在线追踪 O(d²)
77
+ - **显存与 KV-Cache**:存储协方差矩阵 d×d(~4MB for d=1024),不增加 KV-Cache
78
+ - **低精度稳定**:SVD 强烈建议 fp32;白化的矩阵逆需 fp32 + ε 正则化
79
+ - **并行与通信**:多专家对的子空间角度计算独立并行;CCA 的 GEMM 高度并行
80
+ - **稀疏结构**:当源/目标表示稀疏时,协方差矩阵 Σ 稀疏,可用稀疏 SVD
81
+ - **算子融合**:白化 (mean-sub → cov → inv_sqrt → transform) 可部分融合
82
+
83
+ ## 论文表述方式
84
+ "基于正交 Procrustes 理论求得源-目标表示间的最优等距映射 W*=UV^T(USV^T=SVD(A^TB)),
85
+ 将其扩展为深度 CCA 实现非线性子空间对齐,Grassmann 流形上的主角度分析表明
86
+ 对齐后子空间距离以 O(r/√N) 收敛,同时 Barlow Twins 冗余减少目标保证特征维度解耦。"
87
+
88
+ ## 风险
89
+ - SVD 在反向传播时奇异值重合导致梯度未定义,需添加 ε 正则化
90
+ - CCA 的白化步骤需要矩阵逆,协方差矩阵近奇异时数值不稳定
91
+ - 非线性 CCA(深度 CCA)可能过拟合,特别是在小数据集上
92
+ - 在线子空间追踪的学习率 η 需要衰减调度,否则持续漂移