File size: 13,463 Bytes
bb5e4ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
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
"""Canonical BioHCL-SSSM architecture matching the verified Aug-12 checkpoints.

Defaults to the verified 256-d 2-block Student configuration (`8,424,323` params)
with explicit ablation switches for positional encoding, biological prior, skip
connections, and MHSA vs. Selective State-Space block comparison.
"""
from __future__ import annotations

import timm
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp


def strip_thop_keys(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
    """Remove thop profiling buffer keys (`total_ops`, `total_params`) if present."""
    return {
        k: v
        for k, v in state_dict.items()
        if not k.endswith(("total_ops", "total_params"))
    }


def build_baseline_resnet50(
    num_classes: int = 2, pretrained: bool = True
) -> nn.Module:
    """Create the ResNet-50 comparison baseline (`timm` implementation)."""
    return timm.create_model("resnet50", pretrained=pretrained, num_classes=num_classes)


class ResidualConnector(nn.Module):
    """Cross-block projection connector carrying `skip_step` residual metadata."""

    def __init__(self, embed_dim: int, skip_step: int = 2):
        super().__init__()
        self.skip_step = skip_step
        self.proj = nn.Linear(embed_dim, embed_dim)
        self.norm = nn.LayerNorm(embed_dim)

    def forward(
        self, x: torch.Tensor, residuals: dict[str, torch.Tensor]
    ) -> torch.Tensor:
        skip = residuals.get("skip", torch.zeros_like(x))
        return self.norm(x + self.proj(skip))


class BackboneExtractor(nn.Module):
    """Pretrained global visual backbone projected to `embed_dim`."""

    BACKBONE_DIMS = {"densenet": 1024, "swin": 768, "vit": 768}

    def __init__(
        self,
        backbone_type: str = "densenet",
        embed_dim: int = 256,
        dropout: float = 0.1,
        pretrained: bool = True,
    ):
        super().__init__()
        if backbone_type == "densenet":
            self.backbone = timm.create_model(
                "densenet121", pretrained=pretrained, num_classes=0, global_pool="avg"
            )
        elif backbone_type == "swin":
            self.backbone = timm.create_model(
                "swin_tiny_patch4_window7_224", pretrained=pretrained, num_classes=0
            )
        elif backbone_type == "vit":
            self.backbone = timm.create_model(
                "vit_base_patch16_224", pretrained=pretrained, num_classes=0
            )
        else:
            raise ValueError(f"Unsupported backbone_type: {backbone_type}")

        backbone_dim = self.BACKBONE_DIMS[backbone_type]
        self.proj = nn.Linear(backbone_dim, embed_dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        feats = self.backbone(x)
        if feats.dim() == 3:
            feats = feats.mean(dim=1)
        return self.dropout(self.proj(feats))


class QuadraticPositionalEncoder(nn.Module):
    """Multi-level quadratic sinusoidal token positional encoder."""

    def __init__(self, embed_dim: int, num_levels: int = 3):
        super().__init__()
        self.num_levels = num_levels
        self.proj = nn.Linear(embed_dim, embed_dim * num_levels)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        b, n, _ = x.shape
        feat_proj = self.proj(x).view(b, n, self.num_levels, -1)
        pos_enc = torch.zeros_like(feat_proj)
        for lvl in range(self.num_levels):
            lp = feat_proj[:, :, lvl, :]
            pos_enc[:, :, lvl, :] = (lp**2) * torch.sin(lvl * torch.pi * lp)
        return pos_enc.mean(dim=2)


class HierarchicalConvBlock(nn.Module):
    """Multi-scale 3x3/5x5/7x7 CNN pyramid pooled to an 8x8 (64-token) grid."""

    def __init__(
        self, in_channels: int, embed_dim: int, kernel_sizes: tuple[int, ...] = (3, 5, 7)
    ):
        super().__init__()
        self.per_conv = embed_dim // len(kernel_sizes)
        self.convs = nn.ModuleList(
            [
                nn.Conv2d(in_channels, self.per_conv, k, padding=k // 2)
                for k in kernel_sizes
            ]
        )
        actual = self.per_conv * len(kernel_sizes)
        self.fusion = nn.Conv2d(actual, embed_dim, 1)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        feats = [F.adaptive_avg_pool2d(conv(x), (8, 8)) for conv in self.convs]
        return self.fusion(torch.cat(feats, dim=1)).flatten(2).transpose(1, 2)


class LinearBioSSSMBlock(nn.Module):
    """Selective State-Space block with FP32 recurrent scan and biological gating."""

    def __init__(self, d_model: int, d_state: int = 16, expand: int = 2):
        super().__init__()
        self.d_inner = int(expand * d_model)
        self.d_state = d_state
        self.in_proj = nn.Linear(d_model, self.d_inner * 2)
        self.bio_proj = nn.Linear(d_model, 1)
        self.x_proj = nn.Linear(self.d_inner, d_state * 2 + 1)
        self.dt_proj = nn.Linear(1, self.d_inner)
        self.A_log = nn.Parameter(torch.log(torch.arange(1, d_state + 1).float()))
        self.D = nn.Parameter(torch.ones(self.d_inner))
        self.out_proj = nn.Linear(self.d_inner, d_model)
        self.norm = nn.LayerNorm(d_model)

    def forward(
        self, x: torch.Tensor, residuals: torch.Tensor | None = None
    ) -> torch.Tensor:
        with torch.autocast(device_type=x.device.type, enabled=False):
            x_f = x.float()
            b, seq_len, _ = x_f.shape
            bio_gate = torch.sigmoid(self.bio_proj(x_f.mean(dim=1, keepdim=True)))
            xz = self.in_proj(x_f)
            x_in, z = xz.chunk(2, dim=-1)
            x_in = F.silu(x_in)
            ssm = self.x_proj(x_in)
            dt_raw = ssm[:, :, :1]
            b_mat = ssm[:, :, 1 : 1 + self.d_state]
            c_mat = ssm[:, :, 1 + self.d_state :]
            dt = F.softplus(self.dt_proj(dt_raw))

            a_neg = -torch.exp(self.A_log.float())
            h = torch.zeros(
                b, self.d_inner, self.d_state, device=x.device, dtype=torch.float32
            )
            ys = []
            for t in range(seq_len):
                da = torch.exp(dt[:, t, :, None] * a_neg[None, None, :])
                db = dt[:, t, :, None] * b_mat[:, t, None, :]
                h = h * da + db * x_in[:, t, :, None]
                y_t = (h * c_mat[:, t, None, :]).sum(-1) + self.D.float() * x_in[:, t, :]
                ys.append(y_t)

            out = torch.stack(ys, dim=1)
            out = out * torch.sigmoid(z) * bio_gate
            out = self.out_proj(out)
            res_val = residuals.float() if residuals is not None else 0
            out = self.norm(out + res_val)

        return out.to(x.dtype)


class MHSATokenBlock(nn.Module):
    """Multi-Head Self-Attention + FFN drop-in replacement for LinearBioSSSMBlock."""

    def __init__(
        self, d_model: int, num_heads: int = 8, mlp_ratio: float = 2.0, dropout: float = 0.1
    ):
        super().__init__()
        self.attn = nn.MultiheadAttention(
            embed_dim=d_model, num_heads=num_heads, dropout=dropout, batch_first=True
        )
        self.norm1 = nn.LayerNorm(d_model)
        hidden = int(d_model * mlp_ratio)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, hidden),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(hidden, d_model),
            nn.Dropout(dropout),
        )
        self.norm2 = nn.LayerNorm(d_model)

    def forward(
        self, x: torch.Tensor, residuals: torch.Tensor | None = None
    ) -> torch.Tensor:
        attn_out, _ = self.attn(x, x, x, need_weights=False)
        res_val = residuals if residuals is not None else 0
        h = self.norm1(attn_out + res_val)
        return self.norm2(h + self.ffn(h))


class DualChainExtractor(nn.Module):
    """Parallel Hierarchical-CNN spatial token branch + DenseNet-121 global branch."""

    def __init__(
        self,
        embed_dim: int,
        backbone_type: str = "densenet",
        use_positional: bool = True,
        pretrained_backbone: bool = True,
    ):
        super().__init__()
        self.use_positional = use_positional
        self.hier_cnn = HierarchicalConvBlock(3, embed_dim // 2)
        self.backbone = BackboneExtractor(
            backbone_type, embed_dim // 2, pretrained=pretrained_backbone
        )
        self.fusion = nn.Linear(embed_dim, embed_dim)
        self.pos_enc = QuadraticPositionalEncoder(embed_dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        cnn_feats = self.hier_cnn(x)
        bb_feats = self.backbone(x).unsqueeze(1).expand(-1, cnn_feats.size(1), -1)
        fused = self.fusion(torch.cat([cnn_feats, bb_feats], dim=-1))
        if self.use_positional:
            return fused + self.pos_enc(fused)
        return fused


class SingleChainExtractor(nn.Module):
    """Single-branch ablation extractor (`single_cnn` or `single_backbone`)."""

    def __init__(
        self,
        embed_dim: int,
        mode: str = "hier_cnn",
        backbone_type: str = "densenet",
        use_positional: bool = True,
        pretrained_backbone: bool = True,
    ):
        super().__init__()
        self.use_positional = use_positional
        self.extractor = (
            HierarchicalConvBlock(3, embed_dim)
            if mode == "hier_cnn"
            else BackboneExtractor(
                backbone_type, embed_dim, pretrained=pretrained_backbone
            )
        )
        self.pos_enc = QuadraticPositionalEncoder(embed_dim)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        feats = self.extractor(x)
        if feats.dim() == 2:
            feats = feats.unsqueeze(1)
        if self.use_positional:
            return feats + self.pos_enc(feats)
        return feats


class BioHCLSSSM(nn.Module):
    """BioHCL-SSSM hybrid visual-sequence classifier.

    Returns `(logits, global_feat)` for both inference and feature-consistency
    regularization / knowledge distillation.
    """

    def __init__(
        self,
        num_classes: int = 2,
        embed_dim: int = 256,
        chain_mode: str = "dual",
        backbone_type: str = "densenet",
        num_sssm_blocks: int = 2,
        skip_step: int = 2,
        d_state_base: int = 16,
        d_state_step: int = 4,
        use_bio_prior: bool = True,
        use_positional: bool = True,
        use_skip: bool = True,
        block_type: str = "sssm",
        grad_checkpoint: bool = False,
        pretrained_backbone: bool = True,
    ):
        super().__init__()
        self.chain_mode = chain_mode
        self.num_blocks = num_sssm_blocks
        self.use_bio_prior = use_bio_prior
        self.use_skip = use_skip
        self.block_type = block_type
        self.grad_checkpoint = grad_checkpoint

        if chain_mode == "dual":
            self.extractor = DualChainExtractor(
                embed_dim,
                backbone_type,
                use_positional=use_positional,
                pretrained_backbone=pretrained_backbone,
            )
        else:
            mode = "hier_cnn" if chain_mode == "single_cnn" else "backbone"
            self.extractor = SingleChainExtractor(
                embed_dim,
                mode=mode,
                backbone_type=backbone_type,
                use_positional=use_positional,
                pretrained_backbone=pretrained_backbone,
            )

        if block_type == "sssm":
            self.sssm_blocks = nn.ModuleList(
                [
                    LinearBioSSSMBlock(
                        embed_dim, d_state=d_state_base + i * d_state_step
                    )
                    for i in range(num_sssm_blocks)
                ]
            )
        elif block_type == "mhsa":
            self.sssm_blocks = nn.ModuleList(
                [MHSATokenBlock(embed_dim, num_heads=8) for _ in range(num_sssm_blocks)]
            )
        else:
            raise ValueError(f"Unsupported block_type: {block_type}")

        self.res_connectors = nn.ModuleList(
            [ResidualConnector(embed_dim, skip_step) for _ in range(num_sssm_blocks)]
        )
        self.norm = nn.LayerNorm(embed_dim)
        self.head = nn.Linear(embed_dim, num_classes)
        self.bio_prior = nn.Parameter(torch.randn(1, embed_dim) * 0.1)

    def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
        tokens = self.extractor(x)
        residuals: dict[str, torch.Tensor] = {}
        block_outs = [tokens]
        for i, (block, res_conn) in enumerate(
            zip(self.sssm_blocks, self.res_connectors)
        ):
            prev_out = block_outs[-1]
            res_input = residuals.get("skip", prev_out) if self.use_skip else None
            if self.training and self.grad_checkpoint:
                out = cp.checkpoint(block, prev_out, res_input, use_reentrant=False)
            else:
                out = block(prev_out, res_input)
            if self.use_skip:
                residuals["skip"] = (
                    block_outs[i - res_conn.skip_step]
                    if i >= res_conn.skip_step
                    else prev_out
                )
            block_outs.append(out)

        last_out = block_outs[-1]
        if self.use_bio_prior:
            x_out = self.norm(last_out + self.bio_prior)
        else:
            x_out = self.norm(last_out)
        global_feat = x_out.mean(dim=1)
        return self.head(global_feat), global_feat