Upload audited clean BioHCL-SSSM 256-d codebase, verified weights, 5-fold patient-grouped CV, and 11-variant ablations
bb5e4ec verified Download src/models/biohcl_sssm.py from unknownBrain/BioHCL-SSSM: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/unknownBrain/BioHCL-SSSM/resolve/main/src/models/biohcl_sssm.py
- Command line
-
hf download hf://unknownBrain/BioHCL-SSSM/src/models/biohcl_sssm.py
-
curl -L -o biohcl_sssm.py https://huggingface.co/unknownBrain/BioHCL-SSSM/resolve/main/src/models/biohcl_sssm.py
13.5 kB
| """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 | |