thenukegun10x commited on
Commit
f680c1a
·
verified ·
1 Parent(s): 0e5bd10

Remove src/src/models/moe_vit.py

Browse files
Files changed (1) hide show
  1. src/src/models/moe_vit.py +0 -452
src/src/models/moe_vit.py DELETED
@@ -1,452 +0,0 @@
1
- """MoE-ViT: MoE++ (zero/copy/constant experts) on a pretrained DINOv3 ViT stem.
2
-
3
- Replaces the MoR recursive core with a plain stacked-transformer core whose
4
- FFNs are MoE++ layers (arXiv:2410.07348):
5
-
6
- dense MLP (d_ff=1536) -> 4 FFN experts (d_ff=384) + 1 zero + 1 copy
7
- + 2 constant experts, top_k=2 per token
8
-
9
- Routing is per patch token, so easy image regions land on zero/copy/constant
10
- specialists (near-zero compute) while hard regions route to real FFN experts -
11
- adaptive compute at the finest granularity, with no recursion machinery.
12
-
13
- The frozen stem and the study-level pooling/head mirror MoR-ViT so the two
14
- models share the same ``features()`` / ``forward()`` contract and can be
15
- compared on identical benchmarks.
16
- """
17
-
18
- from __future__ import annotations
19
-
20
- import torch
21
- import torch.nn as nn
22
- import torch.nn.functional as F
23
-
24
- try:
25
- import timm
26
-
27
- HAS_TIMM = True
28
- except ImportError: # pragma: no cover - optional dependency
29
- HAS_TIMM = False
30
-
31
-
32
- class SwiGLU(nn.Module):
33
- def __init__(self, d_model: int, d_ff: int):
34
- super().__init__()
35
- self.w1 = nn.Linear(d_model, d_ff, bias=False)
36
- self.w2 = nn.Linear(d_ff, d_model, bias=False)
37
- self.w3 = nn.Linear(d_model, d_ff, bias=False)
38
-
39
- def forward(self, x: torch.Tensor) -> torch.Tensor:
40
- return self.w2(F.silu(self.w1(x)) * self.w3(x))
41
-
42
-
43
- class ConstantExpert(nn.Module):
44
- """MoE++ constant expert: alpha1*x + alpha2*v (negligible params)."""
45
-
46
- def __init__(self, d_model: int):
47
- super().__init__()
48
- self.v = nn.Parameter(torch.zeros(d_model))
49
- self.wc = nn.Linear(d_model, 2, bias=False)
50
-
51
- def forward(self, x: torch.Tensor) -> torch.Tensor:
52
- alpha = F.softmax(self.wc(x), dim=-1)
53
- return (alpha[..., 0:1] * x + alpha[..., 1:2] * self.v.to(dtype=x.dtype)).to(dtype=x.dtype)
54
-
55
-
56
- class MoEFFN(nn.Module):
57
- """Sparse MoE FFN with MoE++ zero / copy / constant experts.
58
-
59
- Index layout: [FFN | zero | copy | constant]. Routing is softmax top-k
60
- with renormalisation; only tokens selected for a real FFN expert are
61
- computed (``index_select``), so zero-compute routing is real skipping.
62
- Returns the load-balance aux loss and pre-softmax gate logits.
63
- """
64
-
65
- def __init__(
66
- self,
67
- d_model: int,
68
- d_ff: int,
69
- num_ffn: int = 4,
70
- top_k: int = 2,
71
- n_zero: int = 1,
72
- n_copy: int = 1,
73
- n_const: int = 2,
74
- tau: float = 0.75,
75
- gating_residual: bool = True,
76
- gate_ctx: bool = False,
77
- ):
78
- super().__init__()
79
- self.num_ffn = num_ffn
80
- self.top_k = min(top_k, num_ffn + n_zero + n_copy + n_const)
81
- self.n_zero = max(0, n_zero)
82
- self.n_copy = max(0, n_copy)
83
- self.n_const = max(0, n_const)
84
- self.n_zc = self.n_zero + self.n_copy + self.n_const
85
- self.total_experts = num_ffn + self.n_zc
86
- self.last_counts: torch.Tensor | None = None
87
- self.tau = float(tau)
88
- self.gate_ctx = gate_ctx
89
-
90
- self.copy_start = num_ffn + self.n_zero
91
- self.const_start = self.copy_start + self.n_copy
92
-
93
- self.router = nn.Linear(d_model, self.total_experts, bias=False)
94
- self.experts = nn.ModuleList([SwiGLU(d_model, d_ff) for _ in range(num_ffn)])
95
- self.const_experts = nn.ModuleList([ConstantExpert(d_model) for _ in range(self.n_const)])
96
-
97
- self.gating_residual = None
98
- if gating_residual:
99
- self.gating_residual = nn.Linear(self.total_experts, self.total_experts, bias=False)
100
- nn.init.zeros_(self.gating_residual.weight)
101
-
102
- self.ctx_proj = None
103
- if gate_ctx:
104
- self.ctx_proj = nn.Linear(d_model, self.total_experts, bias=False)
105
- nn.init.zeros_(self.ctx_proj.weight)
106
-
107
- eta = torch.ones(self.total_experts)
108
- if self.n_zc > 0:
109
- eta[num_ffn:] = self.tau
110
- self.register_buffer("eta", eta, persistent=False)
111
-
112
- def forward(
113
- self,
114
- x: torch.Tensor,
115
- prev_gate: torch.Tensor | None = None,
116
- ctx: torch.Tensor | None = None,
117
- ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
118
- """Returns (output, aux_loss, gate_logits, gate_weights)."""
119
- B, T, D = x.shape
120
- x_2d = x.reshape(-1, D)
121
- N = x_2d.size(0)
122
-
123
- gate_logits = self.router(x_2d)
124
- if self.ctx_proj is not None and ctx is not None:
125
- gate_logits = gate_logits + self.ctx_proj(ctx).repeat_interleave(T, dim=0)
126
- if self.gating_residual is not None and prev_gate is not None:
127
- if prev_gate.dim() == 3:
128
- prev_gate = prev_gate.reshape(-1, prev_gate.size(-1))
129
- if prev_gate.size(0) == N and prev_gate.size(-1) == self.total_experts:
130
- gate_logits = gate_logits + self.gating_residual(prev_gate)
131
-
132
- gate_weights = F.softmax(gate_logits, dim=-1)
133
- top_weights, top_indices = gate_weights.topk(self.top_k, dim=-1)
134
- top_weights = top_weights / top_weights.sum(dim=-1, keepdim=True).clamp(min=1e-9)
135
- route_weights = top_weights.to(dtype=x_2d.dtype)
136
-
137
- flat_expert = top_indices.reshape(-1)
138
- flat_token = (
139
- torch.arange(N, device=x.device)
140
- .unsqueeze(1)
141
- .expand(-1, self.top_k)
142
- .reshape(-1)
143
- )
144
- flat_weight = route_weights.reshape(-1, 1)
145
-
146
- order = torch.argsort(flat_expert, stable=True)
147
- sorted_tokens = flat_token[order]
148
- sorted_weights = flat_weight[order]
149
- sorted_x = x_2d.index_select(0, sorted_tokens)
150
- counts = torch.bincount(
151
- flat_expert, minlength=self.total_experts
152
- ).to(torch.int64)
153
- offsets = torch.cat(
154
- [torch.zeros(1, dtype=torch.int64, device=x.device),
155
- torch.cumsum(counts, 0)[:-1]]
156
- )
157
-
158
- output = torch.zeros_like(x_2d)
159
-
160
- for expert_idx in range(self.num_ffn):
161
- lo = int(offsets[expert_idx])
162
- hi = lo + int(counts[expert_idx])
163
- if lo == hi:
164
- continue
165
- tids = sorted_tokens[lo:hi]
166
- w = sorted_weights[lo:hi]
167
- output.index_add_(
168
- 0, tids,
169
- (self.experts[expert_idx](sorted_x[lo:hi]) * w).to(dtype=output.dtype),
170
- )
171
-
172
- if self.n_zc > 0:
173
- for i in range(self.n_copy):
174
- expert_idx = self.copy_start + i
175
- lo = int(offsets[expert_idx])
176
- hi = lo + int(counts[expert_idx])
177
- if lo == hi:
178
- continue
179
- tids = sorted_tokens[lo:hi]
180
- w = sorted_weights[lo:hi]
181
- output.index_add_(
182
- 0, tids, (sorted_x[lo:hi] * w).to(dtype=output.dtype)
183
- )
184
-
185
- for i in range(self.n_const):
186
- expert_idx = self.const_start + i
187
- lo = int(offsets[expert_idx])
188
- hi = lo + int(counts[expert_idx])
189
- if lo == hi:
190
- continue
191
- tids = sorted_tokens[lo:hi]
192
- w = sorted_weights[lo:hi]
193
- output.index_add_(
194
- 0, tids,
195
- (self.const_experts[i](sorted_x[lo:hi]) * w).to(dtype=output.dtype),
196
- )
197
-
198
- counts = torch.zeros(self.total_experts, device=x.device, dtype=gate_weights.dtype)
199
- counts.scatter_add_(0, flat_expert, torch.ones_like(flat_expert, dtype=gate_weights.dtype))
200
- self.last_counts = counts.detach()
201
- fractions = counts / counts.sum().clamp(min=1e-12)
202
- avg_prob = gate_weights.mean(dim=0)
203
- if self.n_zc > 0:
204
- aux_loss = self.total_experts * (self.eta.to(dtype=gate_weights.dtype) * fractions * avg_prob).sum()
205
- else:
206
- aux_loss = self.total_experts * (fractions * avg_prob).sum()
207
-
208
- return (output.view(B, T, D), aux_loss, gate_logits,
209
- gate_weights.view(B, T, self.total_experts))
210
-
211
-
212
- class MoEAttentionBlock(nn.Module):
213
- """Pre-norm attention + MoE++ FFN. Stores the FFN gate maps for the
214
- spatial-smoothness (TV) loss."""
215
-
216
- def __init__(
217
- self,
218
- dim: int,
219
- n_heads: int = 6,
220
- d_ff: int = 384,
221
- num_ffn: int = 4,
222
- top_k: int = 2,
223
- n_zero: int = 1,
224
- n_copy: int = 1,
225
- n_const: int = 2,
226
- tau: float = 0.75,
227
- gating_residual: bool = True,
228
- gate_ctx: bool = False,
229
- ):
230
- super().__init__()
231
- self.n_heads = n_heads
232
- self.head_dim = dim // n_heads
233
- self.q = nn.Linear(dim, dim)
234
- self.k = nn.Linear(dim, dim)
235
- self.v = nn.Linear(dim, dim)
236
- self.proj = nn.Linear(dim, dim)
237
- self.norm1 = nn.LayerNorm(dim)
238
- self.norm2 = nn.LayerNorm(dim)
239
- self.moe = MoEFFN(
240
- dim, d_ff, num_ffn=num_ffn, top_k=top_k,
241
- n_zero=n_zero, n_copy=n_copy, n_const=n_const,
242
- tau=tau, gating_residual=gating_residual, gate_ctx=gate_ctx,
243
- )
244
-
245
- def forward(
246
- self, x: torch.Tensor, prev_gate: torch.Tensor | None = None,
247
- ctx: torch.Tensor | None = None,
248
- ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
249
- S, T, D = x.shape
250
- H = self.n_heads
251
- xn = self.norm1(x)
252
- q = self.q(xn).reshape(S, T, H, self.head_dim).transpose(1, 2)
253
- k = self.k(xn).reshape(S, T, H, self.head_dim).transpose(1, 2)
254
- v = self.v(xn).reshape(S, T, H, self.head_dim).transpose(1, 2)
255
- attn = (q @ k.transpose(-1, -2) / (self.head_dim ** 0.5)).softmax(dim=-1)
256
- out = (attn @ v).transpose(1, 2).reshape(S, T, D)
257
- x = x + self.proj(out)
258
-
259
- y, aux, gate_logits, gate_weights = self.moe(
260
- self.norm2(x), prev_gate=prev_gate, ctx=ctx)
261
- x = x + y
262
- return x, aux, gate_logits, gate_weights
263
-
264
-
265
- class SliceAttentionPool(nn.Module):
266
- """Weight slices by learned relevance before aggregating into a study vector."""
267
-
268
- def __init__(self, dim: int):
269
- super().__init__()
270
- self.query = nn.Parameter(torch.randn(dim))
271
- self.scale = dim ** -0.5
272
-
273
- def forward(self, x: torch.Tensor) -> torch.Tensor:
274
- w = F.softmax(x @ self.query * self.scale, dim=0)
275
- return (w.unsqueeze(1) * x).sum(0)
276
-
277
-
278
- class PerTargetPool(nn.Module):
279
- """Per-finding attention over slices: each of n_classes findings owns a
280
- query that weights the slices most relevant to it -> [n_classes, D]."""
281
-
282
- def __init__(self, dim: int, n_classes: int):
283
- super().__init__()
284
- self.queries = nn.Parameter(torch.randn(n_classes, dim) * dim ** -0.5)
285
- self.scale = dim ** -0.5
286
-
287
- def forward(self, x: torch.Tensor) -> torch.Tensor:
288
- # x: [S, D] slice vectors -> [n_classes, S] attention weights
289
- w = F.softmax(x @ self.queries.T * self.scale, dim=0)
290
- return (x.unsqueeze(0) * w.T.unsqueeze(-1)).sum(1)
291
-
292
-
293
- class PerTargetHead(nn.Module):
294
- """Shared MLP then per-target projection (12 findings, each its own weight)."""
295
-
296
- def __init__(self, dim: int, n_classes: int, hidden: int = 256):
297
- super().__init__()
298
- self.mlp = nn.Sequential(nn.Linear(dim, hidden), nn.GELU())
299
- self.w = nn.Parameter(torch.randn(n_classes, hidden) * hidden ** -0.5)
300
- self.b = nn.Parameter(torch.zeros(n_classes))
301
-
302
- def forward(self, ctx: torch.Tensor) -> torch.Tensor:
303
- # ctx: [n_classes, D] -> logits [n_classes]
304
- h = self.mlp(ctx)
305
- return (h * self.w).sum(-1) + self.b
306
-
307
-
308
- class MoEViT(nn.Module):
309
- """Pretrained DINOv3 stem + stacked MoE++ core with per-token routing."""
310
-
311
- def __init__(
312
- self,
313
- *,
314
- stem_name: str = "vit_small_patch16_dinov3",
315
- stem: nn.Module | None = None,
316
- pretrained: bool = True,
317
- freeze_stem: bool = True,
318
- core_blocks: int = 2,
319
- n_heads: int = 6,
320
- d_ff: int = 384,
321
- num_ffn: int = 4,
322
- top_k: int = 2,
323
- n_zero: int = 1,
324
- n_copy: int = 1,
325
- n_const: int = 2,
326
- tau: float = 0.75,
327
- gating_residual: bool = True,
328
- n_classes: int = 12,
329
- gate_ctx: bool = False,
330
- per_target: bool = False,
331
- ):
332
- super().__init__()
333
- if stem is None:
334
- if not HAS_TIMM:
335
- raise ImportError("timm is required for a pretrained stem")
336
- stem = timm.create_model(stem_name, pretrained=pretrained, num_classes=0)
337
- self.num_ffn = num_ffn
338
- self.top_k = top_k
339
- self.gate_ctx = gate_ctx
340
- self.per_target = per_target
341
-
342
- self.stem = stem
343
- stem_dim = self.stem.embed_dim
344
- self.core_dim = 384
345
- self.input_proj = nn.Linear(stem_dim, self.core_dim) if stem_dim != 384 else None
346
- dim = self.core_dim
347
- self.n_prefix = int(getattr(self.stem, "num_prefix_tokens", 1))
348
-
349
- if freeze_stem:
350
- for p in self.stem.parameters():
351
- p.requires_grad_(False)
352
-
353
- self._ffn_maps: list[torch.Tensor] = []
354
-
355
- self.blocks = nn.ModuleList(
356
- [
357
- MoEAttentionBlock(
358
- dim, n_heads=n_heads, d_ff=d_ff, num_ffn=num_ffn, top_k=top_k,
359
- n_zero=n_zero, n_copy=n_copy, n_const=n_const,
360
- tau=tau, gating_residual=gating_residual, gate_ctx=gate_ctx,
361
- )
362
- for _ in range(core_blocks)
363
- ]
364
- )
365
-
366
- self.exit_norm = nn.LayerNorm(dim)
367
- if per_target:
368
- self.pool = PerTargetPool(dim, n_classes)
369
- self.head = PerTargetHead(dim, n_classes)
370
- else:
371
- self.pool = SliceAttentionPool(dim)
372
- self.head = nn.Sequential(
373
- nn.Linear(dim, dim * 2),
374
- nn.GELU(),
375
- nn.Linear(dim * 2, n_classes),
376
- )
377
-
378
- def moe_aux_loss(self) -> torch.Tensor:
379
- total = None
380
- for b in self.blocks:
381
- if not hasattr(b, "_aux"):
382
- continue
383
- total = b._aux if total is None else total + b._aux
384
- if total is None:
385
- return torch.tensor(0.0, device=next(self.parameters()).device)
386
- return total / len(self.blocks)
387
-
388
- def routing_tv_loss(self) -> torch.Tensor:
389
- """Total-variation penalty on the per-patch FFN-mass maps.
390
-
391
- Knee findings occupy contiguous regions; scattered routing is a bug
392
- signal. The map is the probability mass routed to real FFN experts,
393
- reshaped to the patch grid.
394
- """
395
- if not self._ffn_maps:
396
- return torch.tensor(0.0, device=next(self.parameters()).device)
397
- total = None
398
- for p in self._ffn_maps:
399
- P = p.size(1)
400
- h = int(round(P ** 0.5))
401
- if h * h != P:
402
- continue
403
- g = p.reshape(p.size(0), h, h)
404
- tv = (g[:, 1:, :] - g[:, :-1, :]).abs().mean() + (
405
- g[:, :, 1:] - g[:, :, :-1]
406
- ).abs().mean()
407
- total = tv if total is None else total + tv
408
- if total is None:
409
- return torch.tensor(0.0, device=next(self.parameters()).device)
410
- return total / len(self._ffn_maps)
411
-
412
- def features(
413
- self, x: torch.Tensor, pool: str = "patchmean"
414
- ) -> torch.Tensor:
415
- """Per-slice features (no head): [S, D] from [S, 3, H, W] slices."""
416
- tokens = self.stem.forward_features(x) # [S, T, D]
417
- return self.features_from_tokens(tokens, pool)
418
-
419
- def features_from_tokens(
420
- self, tokens: torch.Tensor, pool: str = "patchmean"
421
- ) -> torch.Tensor:
422
- """Features from cached stem tokens (feat cache path): [S, D]."""
423
- tokens = tokens.float() # core internals are f32; bf16 cache upcasts exactly
424
- if self.input_proj is not None:
425
- with torch.autocast("cuda", enabled=False):
426
- tokens = self.input_proj(tokens).float() # keep f32; autocast would make it bf16
427
- self._ffn_maps = []
428
- prev_gate = None
429
- ctx = tokens.mean(dim=1) if self.gate_ctx else None # [B, D] per-slice context
430
- for b in self.blocks:
431
- tokens, aux, gate_logits, gate_weights = b(
432
- tokens, prev_gate=prev_gate, ctx=ctx)
433
- b._aux = aux
434
- self._ffn_maps.append(
435
- gate_weights[:, self.n_prefix:, : self.num_ffn].sum(dim=-1)
436
- )
437
- prev_gate = gate_logits
438
- tokens = self.exit_norm(tokens)
439
- if pool == "cls":
440
- return tokens[:, 0]
441
- return tokens[:, self.n_prefix:].mean(1)
442
-
443
- def forward(
444
- self, x: torch.Tensor
445
- ) -> tuple[torch.Tensor, list[float]]:
446
- """Forward one study: [S, 3, H, W] slices -> (logits [n_classes], aux_stats)."""
447
- slice_feats = self.features(x) # [S, D]
448
- study = self.pool(slice_feats) # [D] or [n_classes, D]
449
- logits = self.head(study)
450
- if logits.dim() == 2:
451
- logits = logits.squeeze(-1)
452
- return logits, [self.moe_aux_loss().item()]