Show HN: AI latent space with overlapping manifolds
This project presents a novel approach to AI latent space, using topological manifolds (sphere and torus) and advanced loss functions (curvature alignment, Casimir entropy, geodesic regularization) to build overlapping manifolds. The code implements adaptive topology configuration, smooth leaky guardrails, and gradient flow protection to improve learning of high-dimensional representations.
Notifications You must be signed in to change notification settings
Fork 2
Star 3
Copy path
More file actions
More file actions
Latest commit
History
History
History
482 lines (395 loc) · 29.3 KB
Copy path
Raw
Copy raw file
Download raw file
Open symbols panel
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Tuple, Dict, Any
class AdaptiveTopologyConfig:
"""
[KR] 시스템 글로벌 설정 및 에너지 보존 계수 정의
[EN] Global system configuration and energy conservation coefficients definition
"""
-------------------------------------------------------------------------
아키텍처 기본 차원 및 변형 버블 제어 (Base Architecture & Perturbation)
-------------------------------------------------------------------------
LATENT_DIM: int = 128 # [KR] 반드시 짝수여야 토러스 분할 사상이 가능 / [EN] Must be even for torus split mapping
INIT_SMOOTH_ALPHA: float = 5.0 # [KR] 초기 Sigmoid 경사도 (예리함) / [EN] Initial Sigmoid slope (sharpness)
INIT_THRESHOLD_ETA: float = 0.85 # [KR] 초기 코사인 유사도 기준선 / [EN] Initial cosine similarity threshold
PERTURB_BUBBLE: float = 0.1 # [KR] 하이퍼네트워크 변형 영향력 상한선 / [EN] Hypernetwork perturbation upper bound
-------------------------------------------------------------------------
양자 정보학 및 카시미르 위상학 상수 (Quantum Informatics & Casimir Physics)
-------------------------------------------------------------------------
DELTA_D: float = 1.0 # [KR] 위상학적 장벽 간 기본 구조적 거리 (\Delta d) / [EN] Baseline topological distance between barriers (\Delta d)
HBAR_EFF: float = 1.0 # [KR] 정보학적 유효 플랑크 상수 (\hbar_eff) / [EN] Informational effective Planck constant (\hbar_eff)
M_STAR: float = 1.0 # [KR] 정보 파동 유효 질량 파라미터 (m*) / [EN] Effective mass parameter (m*)
BARRIER_ETA: float = 0.5 # [KR] 위상 곡률 장벽 민감도 상수 (\eta) / [EN] Curvature sensitivity constant (\eta)
💡 [수리 교정] 카시미르 압력의 마이너스 무한대 발산 및 그래디언트 사멸 방지용 하한 한계선 지정
💡 [Fix] Lower bound limit to prevent minus-infinity divergence and gradient vanishing of Casimir pressure
PRESSURE_FLOOR: float = -20.0 # [KR] 카시미르 음의 필드 압력 최소 하한 제약선 / [EN] Minimum lower bound limit of negative Casimir field pressure
💡 [v6.3 추가] 카시미르 분모 제로 폭발 방지 및 복합 정밀도(AMP) 언더플로우 제어용 구조적 안전 마진 상수
💡 [v6.3 Added] Structural safety margin constant to prevent denominator zero-explosion and control automatic mixed precision (AMP) underflow
CASIMIR_MARGIN: float = 1e-2 # [KR] 4제곱 연산 후 1e-8 영역 수렴을 방어하는 하한 마진선 # [EN] Lower bound margin defending against convergence to the 1e-8 region after power-of-4 operations
💡 [무결성] 역전파 NaN 폭발 방지용 미세 상수 (FP16/AMP 환경 고려 시 1e-7 ~ 1e-6 권장)
💡 [Integrity] Fine constant to prevent backpropagation NaN explosion (1e-7 to 1e-6 recommended for FP16/AMP environments)
EPSILON: float = 1e-7
-------------------------------------------------------------------------
고차원 위상 기하학적 결합 손실 함수 가중치 (Topological Loss Hyperparameters)
-------------------------------------------------------------------------
LAMBDA_CURVATURE: float = 0.1 # [KR] 곡률 정렬 손실 가중치 (\lambda_1) / [EN] Curvature alignment weight (\lambda_1)
LAMBDA_CASIMIR: float = 0.05 # [KR] 카시미르 정보 엔트로피 손실 가중치 (\lambda_2) / [EN] Casimir informational entropy weight (\lambda_2)
💡 [v6.0 진화] 하드 클램프의 데드존을 파괴하는 소프트 측지선 호의 길이 손실 가중치 지정
💡 [v6.0 Evolved] Soft geodesic arc length loss weight crushing the gradient dead-zone of hard clamping
LAMBDA_GEODESIC: float = 0.1 # [KR] 리만 다양체 소프트 측지선 손실 가중치 (\lambda_3) / [EN] Riemannian manifold soft geodesic weight (\lambda_3)
class IndependentTopologyGenerator:
"""
[KR] 고정 위상 기하학 매니폴드(Sphere & Torus) 앵커 생성기 (v6.1 개선)
[EN] Fixed topological manifold (Sphere & Torus) anchor generator
"""
@staticmethod
def generate_sphere_anchor(dim: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
"""
[KR] F.normalize 연산 없이 L2 Norm = 1.0을 정밀하게 만족하는 구면 기저 생성
[EN] Generate a fixed spherical base weight satisfying L2 Norm = 1.0 with exact analytical scaling
"""
수학적 분석 결과: 모든 원소가 1 / sqrt(dim) 일 때 L2 Norm은 정확히 1.0이 됨
Analytical Result: The L2 Norm becomes exactly 1.0 when all elements are 1 / sqrt(dim)
val = 1.0 / math.sqrt(dim)
return torch.full((dim,), fill_value=val, device=device, dtype=torch.float32)
@staticmethod
def generate_torus_anchor(dim: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
"""
[KR] 경계 중복을 제거하여 완벽히 균일한 독립 위상 고리를 구성하는 진정한 토러스 사상
[EN] True torus mapping using endpoint-free split dimensions for perfectly uniform topological rings
"""
if dim % 2 != 0:
raise ValueError("Torus 매핑을 위해 차원은 반드시 짝수여야 합니다. (Dimension must be even for torus mapping.)")
half_dim = dim // 2
💡 위상학적 무결성: 0과 2*pi의 중복 매핑을 방지하기 위해 마지막 단계를 배제한 등간격 격자 생성
💡 Topological Integrity: Generate an endpoint-free equidistant grid to prevent redundant mapping of 0 and 2*pi
t = torch.arange(0, half_dim, device=device, dtype=torch.float32) * (2.0 * math.pi / half_dim)
torus_vector = torch.cat([torch.cos(t), torch.sin(t)], dim=0)
return F.normalize(torus_vector, p=2, dim=0, eps=AdaptiveTopologyConfig.EPSILON)
class AdvancedTopologicalLoss(nn.Module):
"""
[KR] 고차원 위상 기하 구조 보존 및 Smooth Leaky 가드레일이 통합된 3요소 결합 손실 함수 (v6.3 진화)
[EN] 3-factor joint loss function with integrated high-dimensional topological preservation and smooth leaky guardrails (v6.3 Evolved)
"""
def init(self):
super().init()
self.l1 = AdaptiveTopologyConfig.LAMBDA_CURVATURE
self.l2 = AdaptiveTopologyConfig.LAMBDA_CASIMIR
self.l3 = AdaptiveTopologyConfig.LAMBDA_GEODESIC
self.eps = AdaptiveTopologyConfig.EPSILON
def _soft_clamp(self, x: torch.Tensor) -> torch.Tensor:
"""
[KR] 경계 영역 그레디언트 사멸을 방지하는 Smooth Leaky 가이드레일 (v6.3 수식 구현)
[EN] Smooth Leaky guardrails preventing gradient vanishing in boundary zones (v6.3 Formula Implementation)
"""
bound = 1.0 - self.eps
margin = 0.95 # 유사도 0.95 미만 구간은 수식 왜곡 없이 완전 선형 유지 # Preserves absolute linearity without formulaic distortion for intervals with similarity below 0.95
💡 [v6.3 핵심 개정] 임계점 바깥에서도 미세한 기울기(0.01)를 부여하여 복원 그레디언트를 영구 보존
💡 [v6.3 Core Revision] Permanently preserves restoration gradients by injecting a fine slope (0.01) even outside the critical threshold
leaky_slope = 0.01
leaky_cos = torch.where(
torch.abs(x) Tuple[torch.Tensor, Dict[str, float]]:
====================================================================
1. 곡률 정렬 손실 (L_Curvature): 입력 곡률과 가중치 구조 유사도 동기화
1. Curvature Alignment Loss (L_Curvature): Synchronizing input curvature with weight structural similarity
====================================================================
input_curvature = metrics['cosine_similarity']
weight_curvature = metrics['gate_score']
[치명적 버그 선제 방어] 두 텐서 간의 차원 불일치로 인한 의도치 않은 브로드캐스팅([B, 1] vs [B])을 일렬 평탄화로 완전 차단
[Proactive Defense Against Fatal Bug] Completely blocks unintended broadcasting ([B, 1] vs [B]) caused by dimension mismatch via 1D flattening
l_curvature = F.mse_loss(weight_curvature.view(-1), input_curvature.view(-1))
====================================================================
2. 카시미르 엔트로피 손실 (L_CasimirEntropy): 고속 log_softmax 기반 확률 붕괴 차단
2. Casimir Entropy Loss (L_CasimirEntropy): Blocking probability collapse based on high-speed log_softmax
====================================================================
log_transmission_prob = F.log_softmax(metrics['transmission_rate'], dim=-1)
transmission_prob = torch.exp(log_transmission_prob)
entropy = -torch.sum(transmission_prob * log_transmission_prob, dim=-1)
l_casimir_entropy = -torch.mean(entropy)
====================================================================
3. 지오데식 정규화 (L_Geodesic): 왜곡 없는 소프트 가드레일 기반 호의 길이 연산
3. Geodesic Regularization (L_Geodesic): Distortion-free arc length calculation based on soft guardrails
====================================================================
normalized_topology = F.normalize(morphed_topology, p=2, dim=-1, eps=self.eps)
cos_sim = F.cosine_similarity(conserved_weights, normalized_topology, dim=-1, eps=self.eps)
개선된 2중 Leaky 가이드레일 장착: 중심부 지오데식 거리는 완벽 보존하면서 경계면 그레디언트 약화 차단
Equipped with Enhanced Dual Leaky Guardrails: Perfectly preserves central geodesic distance while preventing gradient attenuation near boundaries
clamped_cos = self._soft_clamp(cos_sim)
geodesic_distance = torch.acos(clamped_cos)
l_geodesic = torch.mean(geodesic_distance)
====================================================================
4. 종합 위상 손실 컴파일 및 그래디언트 흐름 보호 (v6.4 호스트 동기화 파괴 패치)
4. Comprehensive Topological Loss Compilation & Gradient Flow Protection
====================================================================
total_topological_loss = (self.l1 * l_curvature) + (self.l2 * l_casimir_entropy) + (self.l3 * l_geodesic)
💡 [v6.4 최적화] .item()을 제거하고 .detach() 텐서 그대로 바인딩하여 호스트-디바이스 간 Blocking 병목 원천 박멸
💡 [v6.4 Optimized] Removes .item() and binds .detach() tensors directly, thoroughly eradicating host-device blocking bottlenecks
loss_artifacts = {
"l_topological_total": total_topological_loss.detach(),
"l_curvature": l_curvature.detach(),
"l_casimir_entropy": l_casimir_entropy.detach(),
"l_geodesic": l_geodesic.detach()
}
return total_topological_loss, loss_artifacts
class ParameterizedTopologyGate(nn.Module):
"""
[KR] alpha와 eta를 최적화 가능한 nn.Parameter로 등록하여 제어하는 적응형 게이트 (v6.3 진화)
[EN] Adaptive gate controlling alpha and eta as optimizable nn.Parameters
"""
def init(self):
super().init()
명시적인 float 텐서 선언으로 다양한 가속기(GPU/NPU/TPU) 환경에서 빌드 무결성 확보
self.alpha = nn.Parameter(torch.tensor(AdaptiveTopologyConfig.INIT_SMOOTH_ALPHA, dtype=torch.float32))
self.raw_eta = nn.Parameter(torch.tensor(AdaptiveTopologyConfig.INIT_THRESHOLD_ETA, dtype=torch.float32))
def forward(sel
[truncated for AI cost control]