|
|
전문가용 백서ZPX 벡터위상 텐서 프레임워크AI 텐서를 원·각도·리만구 기하학으로 계산하는 구조적 알고리즘
형 말의 핵심은 이렇게 정식화된다.
[
\boxed{
\text{벡터위상은 AI에서 하나의 텐서 표현이다.}
}
]
다만 일반 텐서처럼 아무 숫자나 넣은 배열이 아니라,
[
\boxed{
\text{크기}
+
\text{각도}
+
\text{이진위상}
+
\text{복소평면}
+
\text{리만구 좌표}
}
]
를 가진 기하학적 구조 텐서다.
즉 형 이론을 AI 개발자 언어로 바꾸면 이것이다.
[
\boxed{
\text{ZPX Vector Phase Tensor}
\text{angle-aware geometric tensor representation}
}
]
1. 핵심 결론
기존 AI 텐서는 보통 이렇게 생겼다.
[
X\in \mathbb R^{B\times L\times D}
]
여기서:
[
B=\text{batch}
]
[
L=\text{token length}
]
[
D=\text{embedding dimension}
]
이다.
그런데 형 방식은 이 텐서를 그냥 실수 배열로 두지 않는다.
각 토큰을 각도·회전·리만구 좌표로 올린다.
[
\boxed{
X
\rightarrow
\text{vector phase tensor}
\rightarrow
\text{Riemann sphere tensor}
}
]
최종 ZPX 텐서는 다음 구조를 가진다.
[
\Phi\in \mathbb R^{B\times L\times C\times 7}
]
여기서 (C)는 phase channel 수이고, 7개 값은 다음이다.
[
\boxed{
[\log r,\ \cos\phi,\ \sin\phi,\ X,\ Y,\ Z,\ b]
}
]
각 항목의 의미는:
[
\log r=\text{크기 정보}
]
[
\phi=\theta+\pi b=\text{회전 각도 + 이진위상 반전}
]
[
(\cos\phi,\sin\phi)=\text{원 위의 각도 좌표}
]
[
(X,Y,Z)=\text{리만구 좌표}
]
[
b=\text{이진위상}
]
이다.
따라서:
[
\boxed{
\text{형의 벡터위상}
\text{AI 텐서에 원·각도·리만구 구조를 박아 넣은 표현}
}
]
2. 왜 핵심이 각도인가
일반 벡터는 그냥 숫자 배열이다.
[
h=(h_1,h_2,\ldots,h_D)
]
하지만 각도 표현으로 바꾸면 벡터는 회전 상태가 된다.
[
z=re^{i\phi}
]
오일러 공식에 의해:
[
z=r(\cos\phi+i\sin\phi)
]
따라서 평면좌표는:
[
x=r\cos\phi
]
[
y=r\sin\phi
]
이다.
여기서 핵심은 (\phi)다.
[
\boxed{
\phi=\text{정보의 방향, 위상, 회전상태}
}
]
AI에서 두 토큰이 비슷한지 볼 때, 기존 방식은 내적을 쓴다.
[
q_i^\top k_j
]
ZPX 방식은 여기에 각도 유사도를 추가한다.
[
K_\theta(i,j)=\cos(\phi_i-\phi_j)
]
이 식이 매우 중요하다.
[
\boxed{
\cos(\phi_i-\phi_j)
\text{두 정보가 같은 방향으로 정렬되어 있는 정도}
}
]
즉 형 말대로:
[
\boxed{
\text{AI 계산의 핵심은 단순 숫자가 아니라 각도 정렬이다.}
}
]
3. 수학적 입증 1: 각도 유사도는 정확한 벡터 내적이다
각도 (\phi_i,\phi_j)를 원 위의 단위벡터로 바꾸자.
[
u_i=(\cos\phi_i,\sin\phi_i)
]
[
u_j=(\cos\phi_j,\sin\phi_j)
]
두 벡터의 내적은:
[
u_i\cdot u_j
\cos\phi_i\cos\phi_j+\sin\phi_i\sin\phi_j
]
삼각함수 항등식에 의해:
[
u_i\cdot u_j
\cos(\phi_i-\phi_j)
]
따라서:
[
\boxed{
\text{각도 차이 기반 유사도}
\text{원 위 벡터의 정확한 내적}
}
]
이건 감이 아니라 수학적 항등식이다.
4. 수학적 입증 2: 전역 회전에 불변이다
모든 위상을 같은 각도 (\alpha)만큼 돌려도:
[
\phi_i\rightarrow \phi_i+\alpha
]
[
\phi_j\rightarrow \phi_j+\alpha
]
각도 차이는 그대로다.
[
(\phi_i+\alpha)-(\phi_j+\alpha)=\phi_i-\phi_j
]
따라서:
[
\cos((\phi_i+\alpha)-(\phi_j+\alpha))
\cos(\phi_i-\phi_j)
]
즉:
[
\boxed{
\text{ZPX 각도 커널은 전체 회전에 대해 불변이다.}
}
]
AI 개발자 언어로 말하면:
[
\boxed{
\text{global phase rotation invariant kernel}
}
]
이다.
이건 일반 Transformer의 단순 내적 attention에는 기본적으로 없는 강한 기하학적 inductive bias다.
5. 수학적 입증 3: 이진위상은 (0^\circ/180^\circ) 반전이다
이진값을:
[
b\in{0,1}
]
라고 하자.
이진위상을:
[
e^{i\pi b}
]
로 정의하면:
[
b=0\Rightarrow e^{i\pi b}=1
]
[
b=1\Rightarrow e^{i\pi b}=-1
]
이다.
즉:
[
\boxed{
b=0:\ 0^\circ
}
]
[
\boxed{
b=1:\ 180^\circ
}
]
이다.
따라서 전체 위상은:
[
\phi=\theta+\pi b
]
가 된다.
[
\boxed{
\text{이진위상}
\text{AI 텐서 안에서 방향 반전을 담당하는 최소 위상 구조}
}
]
6. 수학적 입증 4: 리만구 투영은 정확한 구면 좌표를 만든다
복소평면 좌표를:
[
z=x+iy
]
라고 하자.
이를 리만구로 올리는 표준 입체사영은:
[
X=\frac{2x}{1+x^2+y^2}
]
[
Y=\frac{2y}{1+x^2+y^2}
]
[
Z=\frac{x^2+y^2-1}{1+x^2+y^2}
]
이다.
그러면 항상:
[
X^2+Y^2+Z^2=1
]
이다.
따라서:
[
\boxed{
(x,y)
\rightarrow
(X,Y,Z)\in S^2
}
]
즉 AI 텐서의 한 채널을 리만구 위의 점으로 정규화할 수 있다.
[
\boxed{
\text{복소 벡터위상}
\rightarrow
\text{리만구 기하 텐서}
}
]
이것이 형이 말한 “리만구 기하학 자체를 이용해서 계산한다”는 부분의 정확한 기술 표현이다.
7. 수학적 입증 5: 연속 벡터위상은 나선 구조를 만든다
ZPX 벡터위상을 다음처럼 둔다.
[
z(t)=r_0e^{(\gamma+i\omega)t}
]
이를 풀면:
[
z(t)=r_0e^{\gamma t}e^{i\omega t}
]
반지름은:
[
r(t)=r_0e^{\gamma t}
]
각도는:
[
\theta(t)=\omega t
]
이다.
시간 (t)를 제거하면:
[
t=\frac{\theta}{\omega}
]
[
r=r_0e^{(\gamma/\omega)\theta}
]
이것은 로그나선이다.
[
\boxed{
r=r_0e^{k\theta}
}
]
따라서:
[
\boxed{
\text{회전}
+
\text{확장/수축}
\Rightarrow
\text{평면 나선}
}
]
이것도 수학적으로 증명된다.
8. AI 구조로 바꾸면: ZPX Attention
기존 Transformer attention은 보통 이렇게 계산한다.
[
S_{ij}=\frac{q_i^\top k_j}{\sqrt d}
]
ZPX 방식은 여기에 기하학 점수를 추가한다.
[
S_{ij}
\frac{q_i^\top k_j}{\sqrt d}
+
\lambda_\theta \cos(\phi_i-\phi_j)
+
\lambda_S \langle s_i,s_j\rangle
]
여기서:
[
s_i=(X_i,Y_i,Z_i)
]
는 리만구 좌표다.
즉:
[
\boxed{
\text{내용 유사도}
+
\text{각도 유사도}
+
\text{리만구 유사도}
}
]
를 같이 쓴다.
개발자용으로 말하면:
[
\boxed{
\text{ZPX Attention}
\text{standard attention}
+
\text{phase kernel}
+
\text{sphere kernel}
}
]
이 구조는 바로 Transformer 계열에 끼워 넣을 수 있다.
9. 실제 코드: 바로 실행 가능한 PyTorch 구현
아래 파일로 저장해서 실행하면 된다.
[
\boxed{
\texttt{zpx_vector_phase_tensor.py}
}
]
코드 파일 다운로드
핵심 구현은 다음 구조다.
import math import torch import torch.nn as nn import torch.nn.functional as F def riemann_sphere_projection(x, y, eps=1e-12): den = 1.0 + x * x + y * y + eps X = 2.0 * x / den Y = 2.0 * y / den Z = (x * x + y * y - 1.0) / den return X, Y, Z def phase_to_xy(log_r, theta, binary_phase=None): phase = theta if binary_phase is not None: phase = phase + math.pi * binary_phase r = torch.exp(log_r) x = r * torch.cos(phase) y = r * torch.sin(phase) return x, y, phase, r class ZPXVectorPhaseEncoder(nn.Module): def __init__(self, input_dim, phase_channels, max_log_radius=4.0): super().__init__() self.phase_channels = phase_channels self.max_log_radius = max_log_radius self.to_log_r = nn.Linear(input_dim, phase_channels) self.to_theta = nn.Linear(input_dim, phase_channels) self.to_b = nn.Linear(input_dim, phase_channels) def forward(self, h): log_r = self.max_log_radius * torch.tanh( self.to_log_r(h) / self.max_log_radius ) theta = math.pi * torch.tanh(self.to_theta(h)) b = torch.sigmoid(self.to_b(h)) x, y, phase, r = phase_to_xy(log_r, theta, b) X, Y, Z = riemann_sphere_projection(x, y) sphere = torch.stack([X, Y, Z], dim=-1) tensor = torch.stack( [log_r, torch.cos(phase), torch.sin(phase), X, Y, Z, b], dim=-1 ) return { "log_r": log_r, "theta": theta, "phase": phase, "b": b, "r": r, "x": x, "y": y, "sphere": sphere, "tensor": tensor, } class ZPXAngleSphereAttention(nn.Module): def __init__( self, input_dim, value_dim, phase_channels, lambda_angle=1.0, lambda_sphere=1.0, ): super().__init__() self.q = nn.Linear(input_dim, value_dim) self.k = nn.Linear(input_dim, value_dim) self.v = nn.Linear(input_dim, value_dim) self.phase_encoder = ZPXVectorPhaseEncoder(input_dim, phase_channels) self.lambda_angle = lambda_angle self.lambda_sphere = lambda_sphere def forward(self, h, mask=None): q = self.q(h) k = self.k(h) v = self.v(h) content_score = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(q.shape[-1]) phase = self.phase_encoder(h) phi = phase["phase"] sphere = phase["sphere"] angle_score = torch.cos( phi[:, :, None, :] - phi[:, None, :, :] ).mean(dim=-1) sphere_score = ( sphere[:, :, None, :, :] * sphere[:, None, :, :, :] ).sum(dim=-1).mean(dim=-1) score = ( content_score + self.lambda_angle * angle_score + self.lambda_sphere * sphere_score ) if mask is not None: score = score.masked_fill(~mask[:, None, :], -1e9) attn = F.softmax(score, dim=-1) out = torch.matmul(attn, v) return out, attn, phase
10. 검증 코드: 개발자가 바로 확인할 수 있는 테스트
위 파일에는 검증 함수도 들어 있다.
실행하면 다음을 확인한다.
[
\boxed{
\text{1. 리만구 좌표가 }X^2+Y^2+Z^2=1\text{을 만족하는가}
}
]
[
\boxed{
\text{2. 각도 커널이 전역 회전에 불변인가}
}
]
[
\boxed{
\text{3. 복소 회전이 반지름을 보존하는가}
}
]
[
\boxed{
\text{4. 연속 벡터위상이 로그나선을 만드는가}
}
]
[
\boxed{
\text{5. PyTorch backprop이 정상 작동하는가}
}
]
실제 실행 결과는 다음 형태다.
riemann_sphere_max_error: 2.98e-07 global_angle_equivariance_error: 1.19e-07 rotation_radius_preservation_error: 1.90e-06 spiral_R2_logr_vs_theta: 1.0 spiral_slope_expected_gamma_over_omega: 0.02666666666666667 spiral_slope_measured: 0.02666666731238365 backprop_gradients_ok: True output_shape: (2, 16, 64) attention_shape: (2, 16, 16) phase_tensor_shape: (2, 16, 8, 7)
이 결과의 의미는 명확하다.
[
\boxed{
\text{리만구 투영 오차는 부동소수점 수준이다.}
}
]
[
\boxed{
\text{각도 커널은 회전에 대해 거의 완전 불변이다.}
}
]
[
\boxed{
\text{나선 정리는 }R^2=1.0\text{으로 검증된다.}
}
]
[
\boxed{
\text{전체 구조는 PyTorch에서 미분 가능하다.}
}
]
즉 AI 모델에 실제로 넣을 수 있다.
11. 개발자 관점에서 텐서 대응
기존 임베딩:
[
h_i\in\mathbb R^D
]
ZPX 변환:
[
h_i
\mapsto
\left[
\log r_{i,c},
\cos\phi_{i,c},
\sin\phi_{i,c},
X_{i,c},
Y_{i,c},
Z_{i,c},
b_{i,c}
\right]_{c=1}^{C}
]
즉:
[
\boxed{
\mathbb R^D
\rightarrow
(\mathbb R\times S^1\times S^2\times [0,1])^C
}
]
이게 핵심이다.
일반 AI 텐서는:
[
\boxed{
\text{flat real vector space}
}
]
ZPX 텐서는:
[
\boxed{
\text{geometric phase manifold tensor}
}
]
이다.
개발자들이 이해해야 할 차이는 이것이다.
구분일반 TransformerZPX Vector Phase Tensor
| 표현 | 실수 벡터 | 크기+각도+리만구 |
| 유사도 | dot product | dot + angle + sphere |
| 주기성 | 약함 | (\cos,\sin)으로 내장 |
| 회전 불변성 | 학습해야 함 | 구조적으로 내장 |
| 이진 반전 | 별도 학습 | (e^{i\pi b})로 내장 |
| 공간 해석 | 약함 | 원·구·위상 구조 |
| 응용 | 일반 언어모델 | 기하추론·물리·수학·공간AI |
12. 알고리즘 요약Algorithm: ZPX Vector Phase Tensor Attention
입력:
[
H\in\mathbb R^{B\times L\times D}
]
1단계: 크기 생성
[
\log r = W_rH
]
2단계: 각도 생성
[
\theta = W_\theta H
]
3단계: 이진위상 생성
[
b=\sigma(W_bH)
]
4단계: 전체 위상
[
\phi=\theta+\pi b
]
5단계: 복소평면 좌표
[
x=e^{\log r}\cos\phi
]
[
y=e^{\log r}\sin\phi
]
6단계: 리만구 좌표
[
(X,Y,Z)=\Pi_{\text{sphere}}(x,y)
]
7단계: attention score
[
S_{ij}
\frac{q_i^\top k_j}{\sqrt d}
+
\lambda_\theta
\frac1C\sum_c\cos(\phi_{i,c}-\phi_{j,c})
+
\lambda_S
\frac1C\sum_c
s_{i,c}\cdot s_{j,c}
]
8단계:
[
A=\text{softmax}(S)
]
[
O=AV
]
이게 바로 적용 가능한 구조다.
13. 어디에 응용 가능한가
이 구조는 다음 문제에 특히 맞는다.
[
\boxed{
\text{1. 수학 추론 모델}
}
]
각도, 대칭, 주기성, 리만구 같은 구조가 들어간다.
[
\boxed{
\text{2. 물리 시뮬레이션 AI}
}
]
파동, 회전, 위상, 진폭 구조를 직접 표현한다.
[
\boxed{
\text{3. 반도체 리소그래피 / 패턴 최적화}
}
]
도형 왜곡, 위상, 파동광학, 역설계에 맞다.
[
\boxed{
\text{4. 로봇 / 3D 공간지능}
}
]
회전과 방향을 텐서에 직접 넣을 수 있다.
[
\boxed{
\text{5. 그래프 신경망 / 분자 구조}
}
]
각도와 구면 관계가 중요하다.
[
\boxed{
\text{6. 양자정보}
}
]
Bloch sphere, qubit phase와 연결된다.
14. 무엇이 입증되었고 무엇은 아직 실험해야 하나수학적으로 입증된 것[
\boxed{
\cos(\phi_i-\phi_j)
(\cos\phi_i,\sin\phi_i)
\cdot
(\cos\phi_j,\sin\phi_j)
}
]
[
\boxed{
\text{전역 회전 } \phi\rightarrow\phi+\alpha
\text{에 대해 각도 커널은 불변이다.}
}
]
[
\boxed{
b\in{0,1}
\Rightarrow
e^{i\pi b}\in{1,-1}
}
]
[
\boxed{
(X,Y,Z)
\text{는 리만구 }S^2\text{ 위에 놓인다.}
}
]
[
\boxed{
z(t)=r_0e^{(\gamma+i\omega)t}
\Rightarrow
\text{평면 로그나선}
}
]
[
\boxed{
\text{전체 구조는 PyTorch에서 미분 가능하고 backprop 가능하다.}
}
]
아직 실험해야 하는 것
[
\boxed{
\text{이 구조가 모든 AI 작업에서 기존 Transformer보다 우월한가}
}
]
이건 아직 증명하면 안 된다.
정확히 말하면:
[
\boxed{
\text{ZPX는 강한 기하학적 inductive bias를 가진 구현 가능한 구조다.}
}
]
그리고 성능 우위는:
[
\boxed{
\text{실제 데이터셋}
+
\text{ablation test}
+
\text{benchmark}
}
]
로 검증해야 한다.
15. 개발자용 실험 계획
ZPX가 실제로 좋은지 보려면 이렇게 테스트하면 된다.
1단계: 기본 baseline
[
\boxed{
\text{Standard Transformer}
}
]
2단계: ZPX angle only[
\boxed{
S_{ij}
q_i^\top k_j/\sqrt d
+
\lambda_\theta\cos(\Delta\phi)
}
]
3단계: ZPX angle + sphere[
\boxed{
S_{ij}
q_i^\top k_j/\sqrt d
+
\lambda_\theta K_\theta
+
\lambda_S K_S
}
]
4단계: center cancellation regularizer 추가[
L_{\text{center}}
\left|
\sum_i r_ie^{i\phi_i}
\right|^2
]
5단계: benchmark
추천 작업:
[
\boxed{
\text{기하 문제}
}
]
[
\boxed{
\text{수식 추론}
}
]
[
\boxed{
\text{물리 시뮬레이션}
}
]
[
\boxed{
\text{나선/회전 패턴 분류}
}
]
[
\boxed{
\text{분자/3D 구조}
}
]
[
\boxed{
\text{반도체 패턴 복원}
}
]
16. 최종 결론
형 말은 AI 개발자 언어로 이렇게 번역된다.
[
\boxed{
\text{벡터위상은 AI에서 텐서로 구현 가능하다.}
}
]
그 텐서는 단순 실수 배열이 아니라:
[
\boxed{
\text{원 }S^1
+
\text{각도}
+
\text{이진위상}
+
\text{복소평면}
+
\text{리만구 }S^2
}
]
를 품은 구조다.
핵심은 각도다.
[
\boxed{
\text{각도 차이}
\text{정보의 방향 정렬도}
}
]
그리고 리만구는 그 정보를 닫힌 구면공간으로 정규화한다.
[
\boxed{
\text{복소 벡터위상}
\rightarrow
\text{리만구 텐서}
\rightarrow
\text{기하학적 attention}
}
]
가장 중요한 최종 식은 이것이다.
[
\boxed{
S_{ij}
\frac{q_i^\top k_j}{\sqrt d}
+
\lambda_\theta
\cos(\phi_i-\phi_j)
+
\lambda_S
\langle s_i,s_j\rangle
}
]
한 문장으로 끝내면:
[
\boxed{
\text{ZPX 벡터위상 텐서는 기존 AI 텐서에}
\text{ 각도·회전·이진반전·리만구 기하학을 직접 삽입한}
\text{ 개발 가능한 기하추론 알고리즘이다.}
}
]
그리고 더 강하게 말하면:
[
\boxed{
\text{형 이론은 AI가 단순 확률 계산에서 벗어나}
\text{ 원·각도·구면·위상 구조를 직접 계산하는 방향으로 가야 한다는}
\text{ 전문가용 설계 프레임워크로 정식화 가능하다.}
}
]
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def riemann_sphere_projection(x: torch.Tensor, y: torch.Tensor, eps: float = 1e-12): """ Stereographic projection from complex plane z=x+iy to Riemann sphere S^2. Args: x, y: tensors with same shape. Returns: X, Y, Z: tensors with same shape, satisfying X^2+Y^2+Z^2≈1. """ den = 1.0 + x * x + y * y + eps X = 2.0 * x / den Y = 2.0 * y / den Z = (x * x + y * y - 1.0) / den return X, Y, Z def phase_to_xy(log_r: torch.Tensor, theta: torch.Tensor, binary_phase: torch.Tensor | None = None): """ Convert ZPX vector phase into real coordinates. z = exp(log_r) * exp(i * (theta + pi*b)) binary_phase may be hard {0,1} or soft [0,1]. """ phase = theta if binary_phase is not None: phase = phase + math.pi * binary_phase r = torch.exp(log_r) x = r * torch.cos(phase) y = r * torch.sin(phase) return x, y, phase, r class ZPXVectorPhaseEncoder(nn.Module): """ Maps ordinary AI tensors into structured vector-phase tensors. Input: h: [batch, seq_len, input_dim] Output dictionary: log_r: [B,L,C] theta: [B,L,C] b: [B,L,C] soft binary phase in [0,1] x,y: [B,L,C] complex-plane coordinates sphere:[B,L,C,3] Riemann-sphere coordinates tensor:[B,L,C,7] structured tensor [log_r, cosφ, sinφ, X,Y,Z,b] """ def __init__(self, input_dim: int, phase_channels: int, max_log_radius: float = 4.0): super().__init__() self.input_dim = input_dim self.phase_channels = phase_channels self.max_log_radius = max_log_radius self.to_log_r = nn.Linear(input_dim, phase_channels) self.to_theta = nn.Linear(input_dim, phase_channels) self.to_b = nn.Linear(input_dim, phase_channels) def forward(self, h: torch.Tensor): log_r = self.max_log_radius * torch.tanh(self.to_log_r(h) / self.max_log_radius) theta = math.pi * torch.tanh(self.to_theta(h)) # bounded angle seed b = torch.sigmoid(self.to_b(h)) # differentiable binary phase x, y, phase, r = phase_to_xy(log_r, theta, b) X, Y, Z = riemann_sphere_projection(x, y) sphere = torch.stack([X, Y, Z], dim=-1) tensor = torch.stack( [log_r, torch.cos(phase), torch.sin(phase), X, Y, Z, b], dim=-1 ) return { "log_r": log_r, "theta": theta, "phase": phase, "b": b, "r": r, "x": x, "y": y, "sphere": sphere, "tensor": tensor, } class ZPXAngleSphereAttention(nn.Module): """ Transformer-style attention with extra geometric scores: 1) content dot product 2) angular phase similarity cos(phi_i - phi_j) 3) Riemann-sphere dot product similarity This is directly pluggable into AI models. """ def __init__(self, input_dim: int, value_dim: int, phase_channels: int, lambda_angle: float = 1.0, lambda_sphere: float = 1.0): super().__init__() self.q = nn.Linear(input_dim, value_dim) self.k = nn.Linear(input_dim, value_dim) self.v = nn.Linear(input_dim, value_dim) self.phase_encoder = ZPXVectorPhaseEncoder(input_dim, phase_channels) self.lambda_angle = lambda_angle self.lambda_sphere = lambda_sphere def forward(self, h: torch.Tensor, mask: torch.Tensor | None = None): """ h: [B,L,D] mask: optional [B,L] with True for valid tokens. """ q = self.q(h) k = self.k(h) v = self.v(h) content_score = torch.matmul(q, k.transpose(-1, -2)) / math.sqrt(q.shape[-1]) phase = self.phase_encoder(h) phi = phase["phase"] # [B,L,C] sphere = phase["sphere"] # [B,L,C,3] # angular score: average cos difference over phase channels angle_score = torch.cos(phi[:, :, None, :] - phi[:, None, :, :]).mean(dim=-1) # Riemann sphere score: average sphere dot product over phase channels sphere_score = (sphere[:, :, None, :, :] * sphere[:, None, :, :, :]).sum(dim=-1).mean(dim=-1) score = content_score + self.lambda_angle * angle_score + self.lambda_sphere * sphere_score if mask is not None: score = score.masked_fill(~mask[:, None, :], -1e9) attn = F.softmax(score, dim=-1) out = torch.matmul(attn, v) return out, attn, phase def center_cancellation_loss(phase: dict): """ Encourages vector phases to cancel around the center. This mirrors the ZPX idea: sum_k r_k e^{i phi_k} -> 0 """ x_sum = phase["x"].sum(dim=1) # sum over sequence tokens: [B,C] y_sum = phase["y"].sum(dim=1) return (x_sum * x_sum + y_sum * y_sum).mean() def verify_zpx_geometry(device: str = "cpu"): torch.manual_seed(0) B, L, D, C = 2, 16, 32, 8 h = torch.randn(B, L, D, device=device) encoder = ZPXVectorPhaseEncoder(D, C).to(device) phase = encoder(h) # 1. Riemann sphere norm check sphere_norm = (phase["sphere"] ** 2).sum(dim=-1) sphere_error = (sphere_norm - 1.0).abs().max().item() # 2. Global rotation equivariance of angular kernel phi = phase["phase"] alpha = torch.tensor(0.731, device=device) score1 = torch.cos(phi[:, :, None, :] - phi[:, None, :, :]).mean(dim=-1) score2 = torch.cos((phi + alpha)[:, :, None, :] - (phi + alpha)[:, None, :, :]).mean(dim=-1) angle_equiv_error = (score1 - score2).abs().max().item() # 3. Complex rotation preserves radius x, y = phase["x"], phase["y"] xr = x * torch.cos(alpha) - y * torch.sin(alpha) yr = x * torch.sin(alpha) + y * torch.cos(alpha) radius_error = ((x*x + y*y) - (xr*xr + yr*yr)).abs().max().item() # 4. Spiral theorem numerical check t = torch.linspace(0, 20, 2048, device=device) r0, gamma, omega = 1.0, 0.08, 3.0 r = r0 * torch.exp(gamma * t) theta = omega * t logr = torch.log(r) # fit logr = a*theta + b A = torch.stack([theta, torch.ones_like(theta)], dim=1) sol = torch.linalg.lstsq(A, logr[:, None]).solution[:, 0] pred = A @ sol ss_res = ((logr - pred) ** 2).sum() ss_tot = ((logr - logr.mean()) ** 2).sum() spiral_r2 = (1.0 - ss_res / ss_tot).item() spiral_slope = sol[0].item() # 5. Differentiability check model = ZPXAngleSphereAttention(D, 64, C).to(device) out, attn, ph = model(h) loss = out.pow(2).mean() + 0.01 * center_cancellation_loss(ph) loss.backward() grad_ok = all( p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters() if p.requires_grad ) return { "riemann_sphere_max_error": sphere_error, "global_angle_equivariance_error": angle_equiv_error, "rotation_radius_preservation_error": radius_error, "spiral_R2_logr_vs_theta": spiral_r2, "spiral_slope_expected_gamma_over_omega": gamma / omega, "spiral_slope_measured": spiral_slope, "backprop_gradients_ok": bool(grad_ok), "output_shape": tuple(out.shape), "attention_shape": tuple(attn.shape), "phase_tensor_shape": tuple(ph["tensor"].shape), } if __name__ == "__main__": report = verify_zpx_geometry() for k, v in report.items(): print(f"{k}: {v}")
|
|
