muooon commited on
Commit
548e302
·
verified ·
1 Parent(s): 84ea961

Upload 4 files

Browse files
D‑RNA_paper_260507(ENG).txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Paper: High‑Density Transformer and Fast Convergence via Dual‑Helix Resonant Contraction Architecture (D‑RNA)
2
+
3
+ ~ Redefining the Transformer through Dual Helix and Rotational Fields ~
4
+ — Resonant Contraction (Resonant Projection Field) and Phase Rotation possess "depth × phase" evolving from "stacking" to "attracting" —
5
+
6
+ Attention is all you need_started,
7
+ Resonance is all you need_endure,
8
+ Neocognitron ― Transformer ― D‑RNA Dream Resonance Never Adjourns — it goes on...
9
+
10
+
11
+ Abstract
12
+ In this paper, we formulate the update rule of the Dual‑Helix Resonance Neural Architecture (D‑RNA) as an ordinary differential equation (ODE), and analyze the mathematical meaning of "Resonant Contraction" and the "Resonant Projection Field."
13
+ By interpreting the standard Transformer as a discrete‑time dynamical system on a residual stream, we show that D‑RNA rearranges its eigenvalue structure into "damped oscillatory modes," achieving fast convergence and high representational efficiency (depth × phase).
14
+ We also position theoretically how RoPE‑based phase rotation and the dual‑helix structure (synchronization of Attention/MLP) function as a "wave synthesizer" that reconstructs a smooth semantic space through Fourier‑like superposition, even under low‑bit discrete weights.
15
+
16
+
17
+ 1. Introduction
18
+ The Transformer has an additive dynamic that "stacks information" through residual connections, but its behavior along depth is not always stable or efficient. In early training, gradient explosion/vanishing and long detours before reaching the statistical center are often observed.
19
+ D‑RNA synchronizes Attention (recall) and MLP (memory) as a dual helix, uses RoPE‑based phase rotation as a "resonant field," and converges the residual stream as a superposition of "damped oscillatory modes."
20
+ Intuitively, while a standard Transformer wanders through fog searching for the goal, D‑RNA behaves like a funnel spiraling toward the center. The purpose of this paper is to formalize this intuition as follows:
21
+ ※ The D‑RNA treated in this paper adopts a "dynamic rotation field" that combines the static rotation field given by RoPE with the dynamic phase obtained from the Key vector, and has a structure in which Attention and MLP resonate in parallel.
22
+
23
+ (1) Formulate the residual stream as a continuous‑time ODE
24
+ (2) Analyze D‑RNA’s resonant contraction as damped oscillatory modes with eigenvalues λ = −α + iω (α>0)
25
+ (3) Show that RoPE‑based phase freedom yields representational growth via "depth × phase"
26
+ (4) Interpret ternary/low‑bit weights as Fourier‑type superposition, bridging "coarse weights → smooth representation"
27
+
28
+
29
+ 2. Transformer as a residual ODE
30
+ The residual update of a Transformer block can be written as:
31
+ x_{l+1} = x_l + Attn_l(x_l) + MLP_l(x_l)
32
+
33
+ Treating depth l as a continuous variable t with layer spacing Δt = 1, the residual update is approximated by the ODE:
34
+ dx/dt ≈ F(x) = A(x) + M(x)
35
+
36
+ Here A(x) is the vector field from Attention, and M(x) is the vector field from the MLP.
37
+ Linearizing locally, the update becomes:
38
+ x_{l+1} = (I + W_l) x_l
39
+ If the real part of an eigenvalue λ_k of W_l is negative, the system converges; if positive, it diverges; and a large imaginary part corresponds to strong rotational (oscillatory) behavior.
40
+
41
+ In a standard Transformer, Attention and MLP are learned independently, so the eigenvalue placement of W_l is implicit, and the depth dynamics resemble a simple accumulation of additions.
42
+
43
+
44
+ 3. D‑RNA architecture and resonant projection field
45
+ In D‑RNA, the residual stream x_l is not decomposed into a_l (Attention side) and b_l (MLP side), but is updated as a parallel resonant step.
46
+ Conceptually, the Attention resonance (recall) is applied first, followed by the MLP resonance (memory).
47
+
48
+ The Attention resonance (recall) can be written as:
49
+ (1) x_l → x_l + R(φ + θ(x_l)) A_l(Norm(x_l))
50
+
51
+ Here, θ(x_l) is the dynamic phase component obtained from the Key vector, which is added to the static rotation field φ of RoPE.
52
+
53
+ Next, the MLP resonance (memory) is:
54
+ (2) x_l → x_l + M_l(Norm(x_l))
55
+
56
+ Both Attention and MLP act on the same residual stream x_l and are synchronized on the same phase field.
57
+ The Attention side rotates through R(φ + θ(x)), while the MLP side does not rotate, but both merge along the same axis.
58
+
59
+ Combining these two resonant steps, the update of the entire layer can be written as:
60
+ x_{l+1} = x_l + R(φ + θ(x_l)) A_l(x_l) + M_l(x_l)
61
+
62
+ This corresponds to the special case (φ_A = φ_B = φ + θ(x)) of the original dual‑helix expression:
63
+ x_{l+1} = x_l + R(φ_A)A_l(x_l) + R(φ_B)M_l(x_l)
64
+
65
+ Viewed in continuous time, Attention and MLP interfere within the same phase field along the single main axis of the residual stream, forming a "dual‑helix dynamics" that converges information. When linearized, W_l ≈ W_l^{(A)} + W_l^{(B)}, and both are designed to resonate within the same phase space.
66
+
67
+
68
+ 4. Continuous-time ODE formulation
69
+ When the depth l is extended to a continuous variable t, the residual stream x(t) can be written as the sum of the Attention component a(t) and the MLP component b(t):
70
+ x(t) = a(t) + b(t)
71
+ (although in implementation a(t) and b(t) are not explicitly separated and run in parallel).
72
+ These follow the following coupled ODEs:
73
+ da/dt = F_A(x, t)
74
+ db/dt = F_B(x, t)
75
+
76
+ Here, F_A(x,t) is the vector field of Attention modulated by the rotation field R(φ + θ(x)), which combines the static phase φ from RoPE and the dynamic phase θ(x) obtained from the Key vector, and F_B(x,t) is the contractive vector field of the MLP.
77
+
78
+ Combining the two, the continuous‑time dynamics of the entire layer becomes:
79
+ dx/dt = F_A(x,t) + F_B(x,t)
80
+ This corresponds to the continuous‑time version of F(x) = A(x) + M(x) introduced in the previous section, with the dynamic phase applied to the A(x) side in D‑RNA.
81
+
82
+ When this ODE is locally linearized, it can be written as dx/dt = W(t) x(t). Here, W(t) is the combination of the linearizations of Attention and MLP, and the eigenvalues λ_k(t) are placed in the damped oscillation mode:
83
+ λ_k(t) = −α_k(t) + i ω_k(t)(α_k(t) > 0)
84
+
85
+ Each mode has the solution:
86
+ z_k(t) = c_k e^{−α_k t} ( cos(ω_k t) + i sin(ω_k t) ) v_k
87
+ where the real part −α_k produces contraction (attraction) and the imaginary part ω_k produces rotation (phase alignment). As a result, the depth‑wise dynamics of D‑RNA form a spiral trajectory that "rotates while converging."
88
+
89
+
90
+ 5. Resonant contraction vs. standard Transformer
91
+ In a standard Transformer, Attention and MLP are learned independently, so the eigenvalue placement of the linearization W_l of each layer is implicit, and the depth‑wise dynamics take a form close to a "sequence of additions":
92
+ x_{l+1} = x_l + Attn_l(x_l) + MLP_l(x_l)
93
+ In this case, convergence to a fixed point is not necessarily the shortest path, and the balance between convergence, divergence, and rotation is not controlled.
94
+
95
+ In contrast, in D‑RNA, Attention and MLP are projected onto the same phase space on the same residual stream and operate synchronously under the common rotation field R(φ + θ(x)). Here, θ(x) is the dynamic phase component obtained from the Key vector, which is added to the static phase φ of RoPE.
96
+
97
+ With this structure, the linearized eigenvalues λ tend to be placed in the damped oscillation mode:
98
+ λ = −α + i ω (α > 0)
99
+ The real part −α produces strong contraction (attraction), and the imaginary part ω produces phase alignment (rotation). When both act simultaneously, the residual stream forms a funnel‑like dynamics that "falls toward the center."
100
+
101
+ Furthermore, when the updates of Attention and MLP are projected into the same phase space under the rotation field created by the static RoPE and the dynamic phase θ(x), D‑RNA forms a resonant subspace within the high‑dimensional space.
102
+ This subspace functions as a "Resonant Projection Field" that rearranges information while preserving phase relationships and provides an organizing and compressive effect that cannot be obtained by simple residual addition.
103
+
104
+
105
+ 6. Depth × phase as an alternative to width
106
+ Normally, to increase a model’s expressive capacity, one increases d_model (width), but this rapidly increases computation and memory usage.
107
+ D‑RNA takes a different direction: by combining the static phase φ from RoPE with the dynamic phase θ(x) obtained from the Key vector, it utilizes phase degrees of freedom and achieves the following scaling:
108
+
109
+ Effective Capacity ≈ (bit count) × (number of layers) × (phase degrees of freedom)
110
+
111
+ Even with the same d_model, stacking layers with different phases φ_l + θ_l along the depth direction allows multiple pieces of information to be multiplexed within one dimension by shifting their phases.
112
+ This is a strategy for filling the spectrum using the combination of depth and phase without increasing width, thereby expanding effective expressive capacity without increasing VRAM.
113
+ Phenomena observed experimentally—such as "8 layers behaving like 16 layers" or "similar accuracy with roughly half the VRAM" — can be explained as the result of this spectral packing by "depth × phase."
114
+
115
+
116
+ 7. Fourier interpretation and ternary weights
117
+ D‑RNA can maintain high expressive power even when the weights are restricted to ternary low‑bit values −1, 0, 1.
118
+ Because the linear transformation W_l of each layer is ternary, the output of a single layer becomes a coarse signal similar to a rectangular wave, but by stacking layers with different phases φ_l and dynamic phases θ_l obtained from the Key vector along the depth direction, the final output approaches a smooth higher‑order function.
119
+ This is isomorphic to the structure in Fourier series where the superposition of rectangular waves approximates a smooth function.
120
+
121
+ From the viewpoint of ODEs, the solution of each eigenmode is
122
+ z_k(t) = c_k e^{−α_k t} e^{i ω_k t} v_k
123
+ which is a damped complex exponential function.
124
+ The complex exponential e^{i ω t} has the same structure as a Fourier basis, with the real part e^{−α t} producing contraction and the imaginary part ω producing rotation (phase alignment).
125
+
126
+ D‑RNA stacks these "damped complex exponentials" along the depth direction to reconstruct a smooth semantic manifold from low‑bit coarse components.
127
+ In other words, D‑RNA can be understood as an architecture that uses the ternary weight constraint not as a "loss of expressive power" but as part of a Fourier‑like synthesis through "phase × depth."
128
+
129
+
130
+ 8. Discussion
131
+ The D‑RNA ODE has properties different from those of a Transformer.
132
+ (1) Control of eigenvalue placement: through resonant contraction, the eigenvalues tend to be placed in the damped oscillation mode λ = −α + iω. This naturally produces depth‑wise dynamics that "rotate while converging."
133
+ (2) Reorganization and compression through projection: by interpreting RoPE as a rotation field combining the static phase φ with the dynamic phase θ(x) obtained from the Key vector, and synchronizing Attention and MLP on this field, information reorganization and compression occur simultaneously.
134
+ (3) Expressive power through depth × phase: without increasing width, having different phases φ_l + θ_l in each layer fills the spectrum, allowing high expressive power even under VRAM constraints.
135
+ (4) Fourier‑like superposition: even with coarse weights such as ternary (−1, 0, 1), stacking layers with different phases reconstructs smooth representations. This is isomorphic to the Fourier expansion of rectangular waves, and is naturally explained by the "depth × phase" structure of D‑RNA.
136
+
137
+ Future work includes rigorous analysis of nonlinear ODEs, the relationship between learning rate schedules and resonant contraction, and error analysis of ternary implementations.
138
+
139
+
140
+ 9. Conclusion
141
+ In this paper, D‑RNA is formulated as a residual ODE, and through resonant contraction, resonant projection fields, and Fourier‑like interpretation, we organized what D‑RNA gains compared to a Transformer.
142
+ By interpreting the residual stream as a dual helix, the phase rotation given by RoPE is used as a resonant field that combines the static phase φ with the dynamic phase θ(x) derived from the Key, and by pulling the eigenvalues toward the damped oscillation mode λ = −α + iω, D‑RNA shifts its paradigm from a model that "accumulates information" to a model that "attracts information while aligning phases."
143
+ As a result, the increase in expressive power through depth × phase and the Fourier‑like property that allows reconstruction of a smooth semantic space even with low‑bit weights can be understood as structural properties rather than empirical observations.
144
+ D‑RNA is not merely a trick, but can be considered an architecture that "re‑describes the world through depth and phase."
145
+
146
+
147
+ Supplement: Low‑bit D‑RNA and ternary theory
148
+ 1. Ternary weights as a structural prior
149
+ The linear transform W in D‑RNA is approximated by a ternary matrix W_hat with elements −1, 0, 1 and a scale factor S:
150
+ W ≈ S ⊙ W_hat
151
+ Ternary corresponds to log2(3) ≈ 1.58 bits, much coarser than high‑bit weights.
152
+
153
+ D‑RNA emphasizes phase and depth freedom rather than weight precision, treating the 1.58‑bit constraint as an "alternative form of representation."
154
+ Thus, low‑bit quantization is used as a structural prior rather than a performance loss.
155
+
156
+ 2. Ternary outputs as rectangular‑wave bases
157
+ Each layer’s output
158
+ f_l(x) = σ(W_hat_l x)
159
+ is locally a coarse rectangular wave due to ternary W_hat_l.
160
+
161
+ However, stacking layers with different phases φ_l + θ_l yields Fourier‑like interference, approximating smooth high‑order functions.
162
+ This mirrors how rectangular waves reconstruct smooth sine waves in Fourier expansion.
163
+
164
+ 3. Depth × phase scaling and holographic packing
165
+ D‑RNA’s expressiveness follows:
166
+ Effective Capacity ≈ (bit per weight) × (layer depth) × (phase DOF)
167
+
168
+ Although bit per weight is only 1.58, depth and phase DOF multiply, enabling "holographic information packing" via depth × phase.
169
+ This explains empirical observations such as "same accuracy with half the VRAM."
170
+
171
+ 4. Composite ODE of phase‑shifted ternary bases
172
+ The residual ODE is:
173
+ dx/dt = Σ_l R(φ_l) σ(W_hat_l x)
174
+
175
+ This is a "composite ODE of phase‑shifted ternary basis functions."
176
+ Each term is coarse, but many terms with different phases φ_l form a smooth vector field F(x).
177
+
178
+ Linearization yields eigenvalues:
179
+ λ = −α + i ω (α > 0)
180
+ forming damped oscillatory modes that converge toward the center while rotating.
181
+
182
+ 5. From digital primitives to analog manifolds
183
+ The solution of each damped oscillatory mode is:
184
+ z_k(t) = c_k e^{−α_k t} e^{i ω_k t} v_k
185
+ a complex exponential identical to a Fourier basis.
186
+
187
+ By stacking these along depth, D‑RNA synthesizes high‑bit‑equivalent analog representations from low‑bit digital primitives.
188
+ Thus, D‑RNA functions both as a function approximator and a waveform synthesizer.
189
+
190
+
191
+ Conclusion:
192
+ The D-RNA: Dual-Helix Resonance Neural Architecture is an application of the insights gained from the emo-series optimizer (https://github.com/muooon/EmoSens) and the concept of the Resonance Contraction Method (Resonance Projection Field) to the Transformer model.
193
+ This project resonates with those very methods and philosophies, as well as the tireless efforts of our predecessors.
194
+ It serves as a democratic framework designed to enable the learning of diverse cultures and languages, even within the research environments of developing nations or under low-resource computational constraints.
195
+ It is our hope that this architecture will contribute to the collective process of nurturing global knowledge.
196
+
197
+
198
+ Acknowledgments:
199
+ This work is built upon the foundation established by the Transformer architecture.
200
+ We express deep gratitude to the research community and open‑source contributors for advances in Attention mechanisms, positional encoding, and large‑scale model design.
201
+ Neocognitron ― Transformer ― D‑RNA Dream Resonance Never Adjourns — it goes on...
D‑RNA_paper_260507(JPN).txt ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 論文:二重らせん共鳴収縮構造(D‑RNA)による Transformer の高密度化と高速収束
2
+
3
+ 〜 二重らせんと回転場による Transformer の再定義 〜
4
+ — 共鳴収縮法(共鳴投影場)と位相回転は「深さ×位相」を持ち「積み上げる」から「引き寄せる」へ進化する —
5
+
6
+ 必要なのは「注意」だけ (Attention is all you need_started,)
7
+ 「共鳴」で保ち続けるだけ (Resonance is all you need_endure,)
8
+ Neocognitron ― Transformer ― Dream Resonance Never Adjourns — it goes on...
9
+
10
+
11
+ 要旨 (Abstract)
12
+ 本稿では Dual‑Helix Resonance Neural Architecture (D‑RNA) の更新則を 常微分方程式(ODE) として定式化し 「共鳴収縮法」(Resonant Contraction) および 「共鳴投影場」(Resonant Projection Field) の数学的意味を解析する。
13
+ 標準的 Transformer を残差ストリームの離散時間力学系として捉え、D‑RNA がその固有値構造を「減衰振動モード」へ再配置することで、高速収束と高い表現効率(深さ×位相)を実現していることを示す。
14
+ また RoPE による位相回転と二重らせん構造(Attention/MLP の同期)が、低ビット・離散重みであっても Fourier 的な重ね合わせにより滑らかな意味空間を再構成する「波の合成器」として機能することを理論的に位置づける。
15
+
16
+
17
+ 1. 緒言 (Introduction)
18
+ Transformer は残差接続を通じて「情報を積み上げる」加法的ダイナミクスを持つが、その深さ方向の振る舞いは必ずしも安定でも効率的でもない。 学習初期には勾配爆発・消失や、統計的中心への収束までの遠回りがしばしば観測される。
19
+ D‑RNA は Attention(想起)と MLP(記憶)を二重らせんとして同期させ、RoPE による位相回転を「共鳴場」として利用し、残差ストリームを「減衰振動モード」の重ね合わせとして収束させるという設計思想を持つ。
20
+ 直感的には、通常の Transformer が霧の中をさまよいながらゴールを探すのに対し、D‑RNA は中心に向かって渦を巻く漏斗のようなダイナミクスを持つ。 本稿の目的は、この直感を以下の形で厳密化することである。
21
+ ※ 本稿で扱う D‑RNA は、RoPE による静的な回転場に加えて、Key ベクトルから得られる動的位相を重ね合わせた「動的回転場」を採用し Attention と MLP を並列共鳴させる構造を持つ。
22
+
23
+ (1) 残差ストリームを連続時間 ODE として定式化する
24
+ (2) D‑RNA の共鳴収縮を、固有値 λ = −α + iω(α>0)を持つ減衰振動モードとして解析する
25
+ (3) RoPE による位相自由度が「深さ×位相」による表現力増大をもたらすことを示す
26
+ (4) ternary/低ビット重みを Fourier 的重ね合わせとして解釈し 「粗い重み → 滑らかな表現」 への橋渡しを与える
27
+
28
+
29
+ 2. 残差ODE(常微分方程式)としてのTransformer (Transformer as a residual ODE)
30
+ Transformer ブロックの残差更新は次のように書ける:
31
+ x_{l+1} = x_l + Attn_l(x_l) + MLP_l(x_l)
32
+
33
+ 深さ l を連続変数 t とみなし、層間隔 Δt = 1 とすると、残差更新は次の ODE に近似される:
34
+ dx/dt ≈ F(x) = A(x) + M(x)
35
+
36
+ ここで A(x) は Attention によるベクトル場、M(x) は MLP によるベクトル場を表す。
37
+ 局所的に線形化すると、更新は
38
+ x_{l+1} = (I + W_l) x_l
39
+ と書ける。 W_l の固有値 λ_k の実部が負なら収束、正なら発散し、虚部が大きいほど回転(振動)成分が強くなる。
40
+
41
+ 標準 Transformer では Attention と MLP が独立に学習されるため、W_l の固有値配置は暗黙的であり、深さ方向のダイナミクスは「加算の積み重ね」に近い構造となる。
42
+
43
+
44
+ 3. D-RNAアーキテクチャと共鳴投影場 (D‑RNA architecture and resonant projection field)
45
+ D‑RNA では残差ストリーム x_l を a_l(Attention 系)と b_l(MLP 系)に分解せず、並列的な共鳴ステップとして更新する。
46
+ 概念的には Attention 共鳴(想起)が適用され、続いて MLP 共鳴(記憶)が適用される。
47
+
48
+ Attention 共鳴(想起)は次のように書ける:
49
+ (1) x_l → x_l + R(φ + θ(x_l)) A_l(Norm(x_l))
50
+
51
+ ここで θ(x_l) は Key ベクトルから得られる動的な位相成分であり、静的 RoPE の回転場 φ に重ね合わせられる。
52
+
53
+ 続いて MLP 共鳴(記憶)は:
54
+ (2) x_l → x_l + M_l(Norm(x_l))
55
+
56
+ Attention と MLP はどちらも同じ残差ストリーム x_l に作用し、同じ位相空間(phase field)の上で同期している。
57
+ Attention 側は R(φ + θ(x)) によって回転し、MLP 側は回転しないが、両者は同じ軸上で合流する。
58
+
59
+ この二つの共鳴ステップを合成すると、層全体の更新は次のように書ける:
60
+ x_{l+1} = x_l + R(φ + θ(x_l)) A_l(x_l) + M_l(x_l)
61
+
62
+ これは元の二重らせん表現
63
+ x_{l+1} = x_l + R(φ_A)A_l(x_l) + R(φ_B)M_l(x_l)
64
+ の特殊ケース(φ_A = φ_B = φ + θ(x))に対応する。
65
+
66
+ このプロセスを連続時間的に見ると、残差ストリームという一本の主軸に対し、Attention と MLP が同じ位相場で干渉しながら情報を収束させる「二重らせんの動態」が形成される。 線形化すると W_l ≈ W_l^{(A)} + W_l^{(B)} となり、両者が同じ位相空間で共鳴するように設計されている。
67
+
68
+
69
+ 4. 連続時間ODEの定式化 (Continuous-time ODE formulation)
70
+ 深さ l を連続変数 t に拡張すると、残差ストリーム x(t) は Attention 系 a(t) と MLP 系 b(t) の和として
71
+ x(t) = a(t) + b(t)
72
+ と書ける(実装上は a(t) と b(t) に明確に分けずに並列)。
73
+ これらはそれぞれ次の連立 ODE に従う:
74
+ da/dt = F_A(x, t)
75
+ db/dt = F_B(x, t)
76
+
77
+ ここで F_A(x,t) は RoPE による静的な位相 φ と、Key ベクトルから得られる動的位相 θ(x) を合わせた回転場 R(φ + θ(x)) によって変調された Attention のベクトル場であり、F_B(x,t) は MLP による収縮的なベクトル場である。
78
+
79
+ 両者を合成すると、層全体の連続時間ダイナミクスは
80
+ dx/dt = F_A(x,t) + F_B(x,t)
81
+ となる。 これは前章で導入した F(x) = A(x) + M(x) の連続時間版に相当し、D‑RNA では A(x) 側に動的位相が付与される。
82
+
83
+ この ODE を局所的に線形化すると dx/dt = W(t) x(t) と書ける。 ここで W(t) は Attention と MLP の線形化を合わせたもので、
84
+ 固有値 λ_k(t) は λ_k(t) = −α_k(t) + i ω_k(t)(α_k(t) > 0) という 減衰振動モード に配置される。
85
+
86
+ 各モードの解は
87
+ z_k(t) = c_k e^{−α_k t} ( cos(ω_k t) + i sin(ω_k t) ) v_k
88
+ となり、実部 −α_k が収縮(引き寄せ)を、虚部 ω_k が回転(位相整列)を担う。 これにより、D‑RNA の深さ方向のダイナミクスは「収束しながら回転する」らせん状の軌道を形成する。
89
+
90
+
91
+ 5. 共鳴収縮 vs 標準的なTransformer (Resonant contraction vs. standard Transformer)
92
+ 標準的な Transformer では、Attention と MLP が独立に学習されるため、各層の線形化 W_l の固有値配置は暗黙的であり、深さ方向のダイナミクスは
93
+ x_{l+1} = x_l + Attn_l(x_l) + MLP_l(x_l)
94
+ という「加算の連続」に近い構造となる。
95
+ この場合、固定点への収束は必ずしも最短経路ではなく、収束・発散・回転のバランスも制御されない。
96
+
97
+ 一方 D‑RNA では、Attention と MLP が同じ残差ストリーム上で同一の位相空間に投影され、共通の回転場 R(φ + θ(x)) の下で同期して動作する。 ここで θ(x) は Key ベクトルから得られる動的な位相成分であり、静的 RoPE の位相 φ に重ね合わせられる。
98
+
99
+ この構造により、線形化された固有値 λ は
100
+ λ = −α + i ω(α > 0)
101
+ という 減衰振動モード に配置されやすくなる。
102
+ 実部 −α は強い収縮(引き寄せ)を、虚部 ω は位相整列(回転)を担い、両者が同時に働くことで、残差ストリームは「漏斗状に中心へ落ちていく」ダイナミクスを形成する。
103
+
104
+ さらに、静的 RoPE と動的位相 θ(x) による回転場の下で Attention と MLP の更新が同一位相空間に投影されると、D‑RNA は高次元空間の中に共鳴するサブスペース(Resonant Subspace)を形成する。
105
+ このサブスペースは、情報を引き寄せつつ位相関係を保ったまま再配置する 「共鳴投影場」(Resonant Projection Field) として機能し、単なる残差加算では得られない整理・圧縮効果をもたらす。
106
+
107
+
108
+ 6. 幅の代替案としての 「深さ × 位相」 (Depth × phase as an alternative to width)
109
+ 通常、モデルの表現力を高めるためには d_model(横幅)を増やすが、これは計算量とメモリ使用量を急増させる。
110
+ D‑RNA はこの方向とは異なり、RoPE による静的な位相 φ に加え、Key ベクトルから得られる動的位相 θ(x) を重ね合わせることで、位相自由度(phase degrees of freedom) を活用し、次のようなスケーリングを実現する:
111
+
112
+ Effective Capacity ≈ (bit 数) × (層数) × (位相自由度)
113
+
114
+ 同じ d_model であっても、深さ方向に異なる位相 φ_l + θ_l を持つ層を積み重ねることで、1次元内に複数の情報を 位相を変えて多重化(superposition) できる。 これは、横幅を増やさずに深さと位相の組み合わせでスペクトルを埋める戦略であり、VRAM を増やさずに実効的な表現力を拡張する。
115
+ 実験的に観測される 「8層で16層に匹敵する挙動」、「VRAM 半分程で同等精度」 といった現象は、この 「深さ × 位相」 によるスペクトル充填(spectral packing)の結果として説明できる。
116
+
117
+
118
+ 7. フーリエ解釈と三値重み (Fourier interpretation and ternary weights)
119
+ D‑RNA は、重みを −1, 0, 1 の三値に制限した 低ビット・ternary 重み であっても高い表現力を維持できる。
120
+ 各層の線形変換 W_l が ternary であるため、単層の出力は矩形波のような粗い信号になるが、深さ方向に異なる位相 φ_l と、Key ベクトルから得られる動的位相 θ_l を持つ層を重ね合わせることで、最終的な出力は滑らかな高次関数へと近づく。
121
+ これは Fourier 級数における「矩形波の重ね合わせが滑らかな関数を近似する」構造と同型である。
122
+
123
+ ODE の観点では、各固有モードの解は
124
+ z_k(t) = c_k e^{−α_k t} e^{i ω_k t} v_k
125
+ という 減衰付き複素指数関数 となる。
126
+ 複素指数 e^{i ω t} は Fourier 基底と同じ構造を持ち、実部 e^{−α t} が収縮、虚部 ω が回転(位相)を担う。
127
+
128
+ D‑RNA はこの「減衰付き複素指数」を深さ方向に積み重ねることで、低ビットの粗い構成要素から、滑らかな意味距離(semantic manifold)を再構成する。 つまり D‑RNA は ternary 重みの制約を 「表現力の低下」 ではなく 「位相 × 深さ」 による Fourier 的合成の一部として利用するアーキテクチャとして理解できる。
129
+
130
+
131
+ 8. 考察 (Discussion)
132
+ D‑RNA ODE は Transformer と異なる性質を持つ
133
+ (1) 固有値配置の制御:共鳴収縮により λ = −α + iω 型の減衰振動モードに配置されやすくなる。 これは「収束しながら回転する」深さ方向のダイナミクスを自然に生む
134
+ (2) 投影による再配置と圧縮:RoPE を Key 由来の動的位相 θ(x) を重ね合わせた回転場として解釈し、Attention/MLP をその上で同期させることで情報の再配置と圧縮を同時に行う
135
+ (3) 深さ×位相による表現力:横幅を増やさずに層ごとに異なる位相 φ_l + θ_l を持つことでスペクトルを埋める戦略は VRAM 制約下でも高い表現力を維持できる
136
+ (4) Fourier 的重ね合わせ:ternary(−1,0,1)などの粗い重みでも位相の異なる層を重ねることで滑らかな表現を再構成できる。 これは矩形波の Fourier 展開と同型であり、D‑RNA の 「深さ × 位相」 構造が自然に説明する
137
+ 今後の課題として、非線形 ODE の厳密解析、学習率スケジュールと共鳴収縮の関係、ternary 実装の誤差解析などが挙げられる
138
+
139
+
140
+ 9. 結論 (Conclusion)
141
+ 本稿では D‑RNA を残差 ODE として定式化し、共鳴収縮法・共鳴投影場・Fourier 的解釈を通じて、Transformer と比較したときに D‑RNA が何を得ているのかを整理した。
142
+ 残差ストリームを二重らせんとして捉えることで、RoPE による位相回転を、静的位相 φ と、Key 由来の動的位相 θ(x) を重ね合わせた共鳴場として利用し、固有値を λ = −α + iω 型の減衰振動モードに寄せることで、D‑RNA は「情報を積む」モデルから「情報を位相を合わせながら引き寄せる」モデルへとパラダイムを転換している。
143
+ その結果として、深さ×位相による表現力の増大、低ビット重みでも滑らかな意味空間を再構成しうる Fourier 的性質が、経験則ではなく構造的性質として理解できる。
144
+ D‑RNA は単なるトリックではなく、「深さと位相で世界を記述し直す」アーキテクチャになりうると考える。
145
+
146
+
147
+ 補足資料:Low‑bit D‑RNA と ternary 理論
148
+ 1. 構造的事前分布としての三値重み (Ternary weights as a structural prior)
149
+ D‑RNA の線形変換 W は、要素が −1, 0, 1 の ternary 行列 W_hat とスケール係数 S により
150
+ W ≈ S ⊙ W_hat
151
+ と近似される。ternary は log2(3) ≈ 1.58 bit に相当し、通常の高ビット重みに比べて極めて粗い。
152
+
153
+ D‑RNA は重みの精度そのものではなく、位相と深さの自由度を主役に据えることで、この 1.58 bit 制約を「表現の別形式」として扱う。 つまり、低ビット化は性能低下ではなく、構造的な前提(structural prior)として利用される。
154
+
155
+ 2. 矩形波基底としての三値出力 (Ternary outputs as rectangular-wave bases)
156
+ 各層の出力
157
+ f_l(x) = σ(W_hat_l x)
158
+ は、W_hat_l が ternary であるため局所的には凸凹した矩形波のような粗い信号になる。
159
+
160
+ しかし、深さ方向に異なる位相 φ_l + θ_l を持つ層を重ね合わせると、これらの矩形波基底が Fourier 的に干渉し、最終的な出力は滑らかな高次関数へと近似される。 この構造は、矩形波の Fourier 展開が滑らかな正弦波を再構成するのと同型である。
161
+
162
+ 3. 「深さ × 位相」のスケーリングとホログラフィック・パッキング (Depth × phase scaling and holographic packing)
163
+ D‑RNA の表現力は、重みのビット数ではなく
164
+ Effective Capacity ≈ (bit per weight) × (layer depth) × (phase DOF)
165
+ というスケーリングで決まる。
166
+
167
+ bit per weight は 1.58 に抑えられているが、深さ(layer depth)と位相自由度(phase DOF)が掛け算で効くため 「深さ × 位相」 によってスペクトルを埋める「ホログラフィックな情報パッキング」が可能になる。 これは実験的に観測される「VRAM を半分にしても精度が維持される」という事実の数理的裏付けとなる。
168
+
169
+ 4. 位相シフトされた三値基底の複合ODE (Composite ODE of phase‑shifted ternary bases)
170
+ 残差 ODE は次のように書ける:
171
+ dx/dt = Σ_l R(φ_l) σ(W_hat_l x)
172
+
173
+ これは「位相付き ternary ベース関数の合成 ODE」であり、各項は粗いが、位相 φ_l が異なる多数の項を重ねることで、滑らかなベクトル場 F(x) が形成される。
174
+
175
+ 線形化すると固有値は
176
+ λ = −α + i ω(α > 0)
177
+ という減衰振動モードに配置され、このベクトル場は中心へ収束しながら回転する。
178
+
179
+ 5. デジタル・プリミティブからアナログ多様体へ (From digital primitives to analog manifolds)
180
+ 減衰振動モードの解は
181
+ z_k(t) = c_k e^{−α_k t} e^{i ω_k t} v_k
182
+ であり、これは Fourier 基底と同型の複素指数関数である。
183
+
184
+ D‑RNA はこの「減衰付き複素指数」を深さ方向に積み重ねることで、低ビットのデジタル構成要素から、高ビット相当のアナログ表現を合成する。 したがって D‑RNA は、関数近似器(function approximator)、波形合成器(waveform synthesizer) の両方として理解できる。
185
+
186
+
187
+ 結語:
188
+ 本アーキテクチャ D-RNA:Dual‑Helix Resonance Neural Architecture (DRNA) は、emo系optimizer (https://github.com/muooon/EmoSens) により得られた知見、共鳴収縮法(共鳴投影場) の概念を Transformer へ応用したものである。 このプロジェクトはその手法と哲学と共鳴し、先人たちのたゆまぬ歩みに共鳴し、途上国のリサーチ環境や低リソースな計算資源においても、多様な文化や言語を学習可能にする民主的なフレームワークであり、共に知を育むプロセスの一助となることを期待する。
189
+
190
+
191
+ 謝辞:
192
+ 本研究は Transformer アーキテクチャによって築かれた基盤の上に成立します。
193
+ Attention 機構、位置エンコーディング、大規模モデル設計に関する研究とオープンソースコミュニティの貢献に深く感謝します。
194
+ Neocognitron ― Transformer ― D-RNA 夢の共鳴は決して休まない 夢はずっと続いていく・・・ (D-RNA Dream Resonance Never Adjourns — it goes on...)
drna/drna.py CHANGED
@@ -4,19 +4,32 @@ import torch.nn.functional as F
4
  import math
5
 
6
  '''
7
- D‑RNA: Dual‑Helix Resonance Neural Architecture (DRNA) 260501 【Pre-Norm版
 
8
  Transformerの全接続性を継承しつつ、二重らせん(Dual-Helix)構造による
9
  「共鳴収縮」(Resonant Contraction)を物理的に再現したニューラルアーキテクチャです
10
- 螺旋の同期: Attention(文脈の回想)とMLP(知識の定着)を直列に配置し RoPE で情報を同期
11
- 位相の保持: RoPE(Phase Field)を回転場として利用し、安定した相対位置を保ち早期収束を両立
12
- 高密度圧縮: Pre-Norm により、各らせんを安定的に収縮させ、全結合により記憶を定着させる
13
  '''
14
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  class DRNA_RoPE(nn.Module):
16
  """二重らせんの位相を決定する回転場"""
17
- def __init__(self, d_head, base=10000):
18
  super().__init__()
19
- inv_freq = 1.0 / (base ** (torch.arange(0, d_head, 2).float() / d_head))
20
  self.register_buffer("inv_freq", inv_freq)
21
 
22
  def forward(self, x, seq_len):
@@ -26,28 +39,26 @@ class DRNA_RoPE(nn.Module):
26
  return emb.cos()[None, None, :, :], emb.sin()[None, None, :, :]
27
 
28
  def apply_drna_rope(q, k, cos, sin):
29
- """位相回転の適用"""
30
  def rotate_half(x):
31
  x1, x2 = x.chunk(2, dim=-1)
32
  return torch.cat((-x2, x1), dim=-1)
33
- # DRNA_RoPE側で次元を揃えたので、ここの cos[:, None, :, :] は不要になる
34
- # q, k は [Batch, Head, Seq, d_head] なので、cos, sin もそれに合わせた
35
  return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
36
 
37
  class DRNA_Block(nn.Module):
38
  """DRNA共鳴ブロック:安定性を高めたPre-Norm直列共鳴構造"""
39
- def __init__(self, d_model, n_heads, d_ff=None, dropout=0.1):
40
  super().__init__()
41
  self.n_heads = n_heads
42
- self.d_head = d_model // n_heads
43
-
44
  # らせんA: 回想系 (Attention)
45
- self.norm1 = nn.LayerNorm(d_model) # 演算の前に配置
46
  self.qkv = nn.Linear(d_model, d_model * 3)
47
  self.out_proj = nn.Linear(d_model, d_model)
48
-
49
  # らせんB: 記憶系 (MLP)
50
- self.norm2 = nn.LayerNorm(d_model) # 演算の前に配置
51
  d_ff = d_ff or d_model * 4
52
  self.mlp = nn.Sequential(
53
  nn.Linear(d_model, d_ff),
@@ -58,68 +69,119 @@ class DRNA_Block(nn.Module):
58
  self.dropout = nn.Dropout(dropout)
59
 
60
  def forward(self, x, cos, sin, mask=None):
61
- b, s, d = x.shape
62
-
63
- # --- らせんA (Attention Resonance: Pre-Norm) ---
64
- residual = x
65
- x_norm = self.norm1(x) # 先にNormを計算
66
-
67
- qkv = self.qkv(x_norm).reshape(b, s, 3, self.n_heads, self.d_head).permute(2, 0, 3, 1, 4)
68
- q, k, v = qkv[0], qkv[1], qkv[2]
69
-
70
- q, k = apply_drna_rope(q, k, cos, sin)
71
-
72
- attn = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(self.d_head))
73
- if mask is not None:
74
- attn = attn + mask
75
-
76
- attn = F.softmax(attn, dim=-1)
77
- a_out = (attn @ v).transpose(1, 2).reshape(b, s, d)
78
-
79
- # 残差接続(収縮ではなく蓄積)
80
- x = residual + self.dropout(self.out_proj(a_out))
81
-
82
- # --- らせんB (MLP Resonance: Pre-Norm) ---
83
- residual = x
84
- x_norm = self.norm2(x) # 先にNorm計算
85
-
86
- # 残差接続
87
- x = residual + self.dropout(self.mlp(x_norm))
88
-
89
- return x
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  class DRNA_Model(nn.Module):
92
- """汎用 DRNA モデルコンテナ安定化 Pre-Norm 版"""
93
  def __init__(self, vocab_size, d_model=256, n_layers=16, n_heads=8, d_ff=1024):
94
  super().__init__()
95
  self.embed = nn.Embedding(vocab_size, d_model)
96
- self.rope = DRNA_RoPE(d_model // n_heads)
97
-
 
98
  self.layers = nn.ModuleList([
99
- DRNA_Block(d_model, n_heads, d_ff) for _ in range(n_layers)
100
  ])
101
-
102
  # Pre-Norm構造の場合、最終レイヤーの後に全体のNormを置くのが一般的
103
- self.final_norm = nn.LayerNorm(d_model)
104
  self.output_head = nn.Linear(d_model, vocab_size)
105
 
106
- def forward(self, x, mask=None):
107
  b, s = x.shape
 
 
108
 
109
  if mask is None:
110
- mask = torch.triu(torch.ones(s, s, device=x.device), diagonal=1) * float('-inf')
111
- mask = mask[None, None, :, :] # (1, 1, seq_len, seq_len) に拡張
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  cos, sin = self.rope(x, x.size(1))
114
- x = self.embed(x)
115
-
116
  for layer in self.layers:
117
  x = layer(x, cos, sin, mask=mask)
118
-
119
  x = self.final_norm(x) # 出力前の��終同期
120
  return self.output_head(x)
121
 
122
  '''
123
- 汎用型 D-RNA (Pre-Norm) License: Apache License 2.0
124
- https://github.com/muooon/DRNA
 
 
 
 
 
 
 
 
 
 
 
 
125
  '''
 
4
  import math
5
 
6
  '''
7
+ D‑RNA: Dual‑Helix Resonance Neural Architecture (DRNA) Pre-Norm・Kv-RoPE
8
+ 仕様:Pre-Norm(RMSNorm)、GELU(Activation)、Kv-RoPE(head_dim)、mask(padding + causal)
9
  Transformerの全接続性を継承しつつ、二重らせん(Dual-Helix)構造による
10
  「共鳴収縮」(Resonant Contraction)を物理的に再現したニューラルアーキテクチャです
11
+ 螺旋の同期Attention(文脈の回想)とMLP(知識の定着)を直列に配置し RoPE で情報を同期
12
+ 位相の保持RoPE(Phase Field)を回転場として利用し、安定した相対位置を保ち早期収束を両立
13
+ 高密度圧縮Pre-Norm により、各らせんを安定的に収縮させ、全結合により記憶を定着させる
14
  '''
15
 
16
+ class RMSNorm(nn.Module):
17
+ def __init__(self, d_model, eps=1e-6):
18
+ super().__init__()
19
+ self.eps = eps
20
+ self.weight = nn.Parameter(torch.ones(d_model))
21
+
22
+ def forward(self, x):
23
+ # 2乗平均の平方根で割る(平均を減算しない・中心化をしない)
24
+ norm = x.pow(2).mean(-1, keepdim=True)
25
+ x_normed = x * torch.rsqrt(norm + self.eps)
26
+ return self.weight * x_normed
27
+
28
  class DRNA_RoPE(nn.Module):
29
  """二重らせんの位相を決定する回転場"""
30
+ def __init__(self, head_dim, base=10000):
31
  super().__init__()
32
+ inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
33
  self.register_buffer("inv_freq", inv_freq)
34
 
35
  def forward(self, x, seq_len):
 
39
  return emb.cos()[None, None, :, :], emb.sin()[None, None, :, :]
40
 
41
  def apply_drna_rope(q, k, cos, sin):
42
+ """Kによる動的位相変調済み cos/sin を受け取る"""
43
  def rotate_half(x):
44
  x1, x2 = x.chunk(2, dim=-1)
45
  return torch.cat((-x2, x1), dim=-1)
 
 
46
  return (q * cos) + (rotate_half(q) * sin), (k * cos) + (rotate_half(k) * sin)
47
 
48
  class DRNA_Block(nn.Module):
49
  """DRNA共鳴ブロック:安定性を高めたPre-Norm直列共鳴構造"""
50
+ def __init__(self, d_model, n_heads, head_dim, d_ff=None, dropout=0.1):
51
  super().__init__()
52
  self.n_heads = n_heads
53
+ self.head_dim = head_dim
54
+
55
  # らせんA: 回想系 (Attention)
56
+ self.norm1 = RMSNorm(d_model) # 演算の前に配置
57
  self.qkv = nn.Linear(d_model, d_model * 3)
58
  self.out_proj = nn.Linear(d_model, d_model)
59
+
60
  # らせんB: 記憶系 (MLP)
61
+ self.norm2 = RMSNorm(d_model) # 演算の前に配置
62
  d_ff = d_ff or d_model * 4
63
  self.mlp = nn.Sequential(
64
  nn.Linear(d_model, d_ff),
 
69
  self.dropout = nn.Dropout(dropout)
70
 
71
  def forward(self, x, cos, sin, mask=None):
72
+ b, s, d = x.shape
73
+
74
+ # 1. 共通の残差(ベースとなる螺旋の軸)
75
+ residual = x
76
+
77
+ # 2. らせんA (Attention) 並列方式
78
+ x_norm1 = self.norm1(x)
79
+
80
+ # QKV生成 (3倍のまま)
81
+ # self.qkv(x_norm) x_norm1 になっているか確認してください
82
+ qkv = self.qkv(x_norm1).reshape(b, s, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)
83
+ q, k, v = qkv[0], qkv[1], qkv[2]
84
+
85
+ # K因果的動的回転:一つ前の単語の K が今の単語の座標を決める
86
+ # 自分の情報で自分を回さないよう、Kを1つ未来にシフトさせる
87
+ # これにより「赤い(K)」が「猫(Q,K)」の位相を決定する構造になる
88
+ k_for_phase = torch.cat([torch.zeros_like(k[:, :, :1, :]), k[:, :, :-1, :]], dim=2)
89
+
90
+ # Kのエネルギーを位相(回転角)に変換
91
+ rt_phase = torch.tanh(k_for_phase) * math.pi
92
+
93
+ # 静的RoPE (cos, sin) を動的位相 (rt_phase) で加法定理により変調
94
+ # apply_drna_rope に rt_phase を渡せるように関数側を調整するか、
95
+ # ここで dynamic_cos / sin 作って渡します
96
+ d_cos = (cos * torch.cos(rt_phase)) - (sin * torch.sin(rt_phase))
97
+ d_sin = (sin * torch.cos(rt_phase)) + (cos * torch.sin(rt_phase))
98
+
99
+ # 2重らせんをつくる (変調された座標で回転)
100
+ q, k = apply_drna_rope(q, k, d_cos, d_sin)
101
+
102
+ # Attention計算
103
+ attn = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(self.head_dim))
104
+ if mask is not None:
105
+ attn = attn + mask
106
+
107
+ attn = F.softmax(attn, dim=-1)
108
+ a_out_raw = (attn @ v).transpose(1, 2).reshape(b, s, d)
109
+ a_out = self.out_proj(a_out_raw)
110
+
111
+ # 3. らせんB (MLP)
112
+ x_norm2 = self.norm2(x)
113
+ m_out = self.mlp(x_norm2)
114
+
115
+ # 4. 並列方式
116
+ x = residual + self.dropout(a_out) + self.dropout(m_out)
117
+
118
+ return x
119
 
120
  class DRNA_Model(nn.Module):
121
+ """汎用 DRNA モデルコンテナ(安定化 Pre-Norm 版)"""
122
  def __init__(self, vocab_size, d_model=256, n_layers=16, n_heads=8, d_ff=1024):
123
  super().__init__()
124
  self.embed = nn.Embedding(vocab_size, d_model)
125
+ self.head_dim = d_model // n_heads
126
+ self.rope = DRNA_RoPE(self.head_dim)
127
+
128
  self.layers = nn.ModuleList([
129
+ DRNA_Block(d_model, n_heads, self.head_dim, d_ff) for _ in range(n_layers)
130
  ])
131
+
132
  # Pre-Norm構造の場合、最終レイヤーの後に全体のNormを置くのが一般的
133
+ self.final_norm = RMSNorm(d_model)
134
  self.output_head = nn.Linear(d_model, vocab_size)
135
 
136
+ def forward(self, x, mask=None, pad_id=None):
137
  b, s = x.shape
138
+ device = x.device
139
+ x = self.embed(x)
140
 
141
  if mask is None:
142
+ # 1. pad_mask (pad_id 型チェック)
143
+ # pad_id が整数(int/long)として有効な場合のみ pad_mask を作成
144
+ if isinstance(pad_id, (int, float, torch.Tensor)):
145
+ # Tensor の場合はスカラー値に変換
146
+ p_id = pad_id.item() if isinstance(pad_id, torch.Tensor) else pad_id
147
+ pad_mask = (x != p_id).unsqueeze(1).unsqueeze(2) # (B,1,1,S)
148
+ else:
149
+ # 数値でない場合(None含)は「全てが有効」なマスクを作る
150
+ # これにより enwik8 のようなケースでも正常に動作する
151
+ pad_mask = torch.ones((1, 1, 1, s), device=device, dtype=torch.bool)
152
+
153
+ # 2. causal mask
154
+ causal = torch.triu(torch.ones(s, s, device=device), diagonal=1).bool()
155
+ causal = causal.unsqueeze(0).unsqueeze(0) # (1,1,S,S)
156
+
157
+ # 3. 合成と NaN 対策
158
+ attn_mask = pad_mask & (~causal) # (B,1,S,S)
159
+ #mask = attn_mask.masked_fill(~attn_mask, float('-inf'))
160
+ # float('-inf') を、計算精度に合わせた最小値に変更
161
+ inf_value = torch.finfo(x.dtype).min if x.is_floating_point() else -1e9
162
+ mask = attn_mask.masked_fill(~attn_mask, inf_value)
163
 
164
  cos, sin = self.rope(x, x.size(1))
165
+
 
166
  for layer in self.layers:
167
  x = layer(x, cos, sin, mask=mask)
168
+
169
  x = self.final_norm(x) # 出力前の��終同期
170
  return self.output_head(x)
171
 
172
  '''
173
+ 260507:Kによる回転で文脈に単語を沿わせ2重らせんの干渉による取捨選択とホログラム合成を可能にする
174
+ 260505:model構成から学習解像度を自動化、汎用 mask の精度への適正化、RMSNormへの移行
175
+ 260503:padding を引数で指定できるよう変更
176
+ # 例:一般的な Tokenizer の pad_id が 0 の場合
177
+ output = model(input_ids, pad_id=0)
178
+ # 例:Hugging Face 等の tokenizer を使っている場合
179
+ output = model(input_ids, pad_id=tokenizer.pad_token_id)
180
+ 260502:変数名を正確化(head_dim)、汎用 mask に変更し padding 等に対応可
181
+ '''
182
+
183
+ '''
184
+ 汎用型 D-RNA (Pre-Norm) License: Apache License 2.0 https://github.com/muooon/DRNA
185
+ Attention is all you need_started, Resonance is all you need_endure,
186
+ Neocognitron ― Transformer ― D‑RNA Dream Resonance Never Adjourns — it goes on...
187
  '''