dawin 1.0.1__py3-none-any.whl

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.
dawin/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ from .core import DAWINLinear, compute_dawin_laplacian_loss
2
+ from .models import DAWINMLP, DAWINTransformer, DAWINGNN
3
+
4
+ try:
5
+ from .triton_scan import TritonDAWINLinear, triton_dawin_scan
6
+ except ImportError:
7
+ TritonDAWINLinear = None
8
+ triton_dawin_scan = None
9
+
10
+ __version__ = "1.0.1"
11
+ __all__ = [
12
+ "DAWINLinear",
13
+ "TritonDAWINLinear",
14
+ "triton_dawin_scan",
15
+ "compute_dawin_laplacian_loss",
16
+ "DAWINMLP",
17
+ "DAWINTransformer",
18
+ "DAWINGNN",
19
+ ]
20
+
dawin/core.py ADDED
@@ -0,0 +1,212 @@
1
+ import math
2
+ from typing import Optional, Tuple
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ try:
8
+ from torch._higher_order_ops import associative_scan
9
+ HAS_ASSOC_SCAN = True
10
+ except ImportError:
11
+ HAS_ASSOC_SCAN = False
12
+
13
+
14
+ def _dawin_binary_op(
15
+ elem_l: Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],
16
+ elem_r: Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor],
17
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
18
+ """
19
+ Associative binary operator for paired-real complex tuples:
20
+ (d_r, u_r) (+) (d_l, u_l) = (d_r * d_l, d_r * u_l + u_r)
21
+ where d = d_re + i * d_im and u = u_re + i * u_im.
22
+ """
23
+ d_re_l, d_im_l, u_re_l, u_im_l = elem_l
24
+ d_re_r, d_im_r, u_re_r, u_im_r = elem_r
25
+
26
+ # Complex multiplication: d_new = d_r * d_l
27
+ d_re = d_re_r * d_re_l - d_im_r * d_im_l
28
+ d_im = d_re_r * d_im_l + d_im_r * d_re_l
29
+
30
+ # Complex multiply-add: u_new = d_r * u_l + u_r
31
+ u_re = (d_re_r * u_re_l - d_im_r * u_im_l) + u_re_r
32
+ u_im = (d_re_r * u_im_l + d_im_r * u_re_l) + u_im_r
33
+ return (d_re, d_im, u_re, u_im)
34
+
35
+
36
+ class DAWINLinear(nn.Module):
37
+ """
38
+ Damped Atomic Wave Integration Neuron (DAWIN) Layer.
39
+
40
+ Drop-in replacement for Linear + Activation blocks across MLPs, Transformers,
41
+ and GNNs. Supports exact parallel associative scan, serial recurrence fallback,
42
+ and built-in component ablation modes:
43
+ - 'none': Full DAWIN neuron (atomic spatiotemporal phase + damped integration)
44
+ - 'undamped': Removes damping (gamma = 0)
45
+ - 'memoryless': Instantaneous damping (gamma -> inf, recovers WFB 1.0)
46
+ - 'cosine_only': Zeroes imaginary quadrature propagation between steps
47
+ - 'decoupled': Removes spatial wavevector k^T x from phase (linear injection SSM control)
48
+ """
49
+
50
+ def __init__(
51
+ self,
52
+ in_features: int,
53
+ out_features: int,
54
+ mode: str = "quad",
55
+ gamma_min: float = 1e-4,
56
+ omega_init_max: float = math.pi,
57
+ use_parallel_scan: bool = True,
58
+ ablation: str = "none",
59
+ ):
60
+ super().__init__()
61
+ if mode not in ("real", "quad"):
62
+ raise ValueError(f"mode must be 'real' or 'quad', got {mode!r}")
63
+ if ablation not in ("none", "undamped", "memoryless", "cosine_only", "decoupled"):
64
+ raise ValueError(f"Unsupported ablation mode: {ablation!r}")
65
+
66
+ self.in_features = in_features
67
+ self.out_features = out_features
68
+ self.mode = mode
69
+ self.gamma_min = gamma_min
70
+ self.use_parallel_scan = use_parallel_scan and HAS_ASSOC_SCAN
71
+ self.ablation = ablation
72
+
73
+ # Learnable atomic wave & damper parameters
74
+ self.k = nn.Parameter(torch.randn(out_features, in_features) / math.sqrt(max(1, in_features)))
75
+ self.theta = nn.Parameter(torch.zeros(out_features))
76
+ self.omega = nn.Parameter(torch.linspace(0.1, omega_init_max, out_features))
77
+ self.raw_amp = nn.Parameter(torch.full((out_features,), math.log(math.e - 1.0)))
78
+ self.raw_gamma = nn.Parameter(torch.linspace(-2.0, 1.0, out_features))
79
+
80
+ if ablation == "decoupled":
81
+ self.linear_inj = nn.Linear(in_features, out_features, bias=False)
82
+ else:
83
+ self.register_parameter("linear_inj", None)
84
+
85
+ @property
86
+ def amplitude(self) -> torch.Tensor:
87
+ return F.softplus(self.raw_amp)
88
+
89
+ @property
90
+ def gamma(self) -> torch.Tensor:
91
+ if self.ablation == "undamped":
92
+ return torch.zeros_like(self.raw_gamma)
93
+ return F.softplus(self.raw_gamma) + self.gamma_min
94
+
95
+ def laplacian_penalty(self) -> torch.Tensor:
96
+ k = getattr(self, "k", getattr(self, "wavevector", getattr(self, "wavenumber", None)))
97
+ if k is None:
98
+ k = next(param for param in self.parameters() if param.ndim == 2)
99
+ k2 = k.float().pow(2).sum(dim=-1)
100
+ w2 = self.omega.float().pow(2) if hasattr(self, "omega") else torch.zeros_like(k2)
101
+ if hasattr(self, "raw_gamma"):
102
+ g = torch.nn.functional.softplus(self.raw_gamma.float()) + float(getattr(self, "gamma_min", 1e-4))
103
+ elif hasattr(self, "gamma"):
104
+ g = self.gamma.float() if isinstance(self.gamma, torch.Tensor) else self.gamma().float()
105
+ else:
106
+ g = torch.zeros_like(k2)
107
+ if hasattr(self, "amp"):
108
+ a = self.amp.float() if isinstance(self.amp, torch.Tensor) else self.amp().float()
109
+ elif hasattr(self, "raw_amp"):
110
+ a = torch.nn.functional.softplus(self.raw_amp.float())
111
+ else:
112
+ a = torch.ones_like(k2)
113
+ return (a.pow(2) * (k2 + w2 + g.pow(2)).pow(2)).mean()
114
+
115
+ def forward(
116
+ self,
117
+ x: torch.Tensor,
118
+ dt: Optional[torch.Tensor] = None,
119
+ reset_mask: Optional[torch.Tensor] = None,
120
+ ) -> torch.Tensor:
121
+ """
122
+ Args:
123
+ x: Spatial input tensor of shape [B, L, d_in]
124
+ dt: Non-negative elapsed intervals of shape [B, L] or [B, L, 1]
125
+ reset_mask: Optional binary reset mask [B, L] (1 resets carried state)
126
+ Returns:
127
+ Output tensor of shape [B, L, M] (mode='real') or [B, L, 2M] (mode='quad')
128
+ """
129
+ B, L, _ = x.shape
130
+ if dt is None:
131
+ dt = torch.zeros(B, L, 1, device=x.device, dtype=x.dtype)
132
+ elif dt.dim() == 2:
133
+ dt = dt.unsqueeze(-1)
134
+
135
+ # Retain FP32 precision inside wave phase & recurrence scan
136
+ orig_dtype = x.dtype
137
+ x_f = x.float()
138
+ dt_f = dt.float().clamp(min=0.0)
139
+
140
+ amp = self.amplitude.float().view(1, 1, -1)
141
+ gamma = self.gamma.float().view(1, 1, -1)
142
+ omega = self.omega.float().view(1, 1, -1)
143
+ theta = self.theta.float().view(1, 1, -1)
144
+
145
+ zoh = torch.where(dt_f > 0.0, 1.0 - torch.exp(-gamma * dt_f), torch.ones_like(dt_f))
146
+ if self.ablation == "decoupled":
147
+ phi = -dt_f * omega - theta
148
+ inj_scale = F.linear(x_f, self.linear_inj.weight.float())
149
+ u_re = (inj_scale * amp * zoh) * torch.cos(phi)
150
+ u_im = (inj_scale * amp * zoh) * torch.sin(phi)
151
+ else:
152
+ phi = F.linear(x_f, self.k.float()) - theta
153
+ u_re = (amp * zoh) * torch.cos(phi)
154
+ u_im = (amp * zoh) * torch.sin(phi)
155
+
156
+ if self.ablation == "memoryless":
157
+ p = u_re
158
+ q = torch.zeros_like(u_im) if self.ablation == "cosine_only" else u_im
159
+ out = p if self.mode == "real" else torch.cat([p, q], dim=-1)
160
+ return out.to(orig_dtype)
161
+
162
+ decay = torch.exp(-gamma * dt_f)
163
+ if reset_mask is not None:
164
+ decay = decay * (1.0 - reset_mask.unsqueeze(-1).float())
165
+
166
+ rot_angle = -omega * dt_f
167
+ d_re = decay * torch.cos(rot_angle)
168
+ d_im = decay * torch.sin(rot_angle)
169
+
170
+ if self.ablation == "cosine_only":
171
+ # Ablate quadrature coupling: propagate only real scalar state
172
+ p_list = []
173
+ p_prev = torch.zeros(B, self.out_features, device=x.device, dtype=torch.float32)
174
+ for t in range(L):
175
+ p_curr = d_re[:, t] * p_prev + u_re[:, t]
176
+ p_list.append(p_curr)
177
+ p_prev = p_curr
178
+ p = torch.stack(p_list, dim=1)
179
+ q = torch.zeros_like(p)
180
+ elif self.use_parallel_scan and L > 1:
181
+ _, _, p, q = associative_scan(
182
+ _dawin_binary_op, (d_re, d_im, u_re, u_im), dim=1, combine_mode="generic"
183
+ )
184
+ else:
185
+ p_list, q_list = [], []
186
+ p_prev = torch.zeros(B, self.out_features, device=x.device, dtype=torch.float32)
187
+ q_prev = torch.zeros_like(p_prev)
188
+ for t in range(L):
189
+ p_curr = d_re[:, t] * p_prev - d_im[:, t] * q_prev + u_re[:, t]
190
+ q_curr = d_re[:, t] * q_prev + d_im[:, t] * p_prev + u_im[:, t]
191
+ p_list.append(p_curr)
192
+ q_list.append(q_curr)
193
+ p_prev, q_prev = p_curr, q_curr
194
+ p = torch.stack(p_list, dim=1)
195
+ q = torch.stack(q_list, dim=1)
196
+
197
+ out = p if self.mode == "real" else torch.cat([p, q], dim=-1)
198
+ return out.to(orig_dtype)
199
+
200
+
201
+ def compute_dawin_laplacian_loss(model: nn.Module) -> torch.Tensor:
202
+ pens = []
203
+ for mod in model.modules():
204
+ if hasattr(mod, "laplacian_penalty"):
205
+ pens.append(mod.laplacian_penalty())
206
+ elif hasattr(mod, "k") and hasattr(mod, "omega"):
207
+ k2 = mod.k.float().pow(2).sum(dim=-1)
208
+ w2 = mod.omega.float().pow(2)
209
+ g = (torch.nn.functional.softplus(mod.raw_gamma.float()) + float(getattr(mod, "gamma_min", 1e-4))) if hasattr(mod, "raw_gamma") else (mod.gamma.float() if hasattr(mod, "gamma") else torch.zeros_like(k2))
210
+ a = torch.nn.functional.softplus(mod.raw_amp.float()) if hasattr(mod, "raw_amp") else (mod.amp.float() if hasattr(mod, "amp") else torch.ones_like(k2))
211
+ pens.append((a.pow(2) * (k2 + w2 + g.pow(2)).pow(2)).mean())
212
+ return torch.stack(pens).mean() if pens else torch.zeros((), device=next(model.parameters()).device, dtype=torch.float32)