| from __future__ import annotations | |
| import torch | |
| import torch.nn as nn | |
| class SIFQ(nn.Module): | |
| """Full SIFQ model wrapper.""" | |
| def __init__( | |
| self, | |
| backbone: nn.Module, | |
| concept_head: nn.Module, | |
| aggregator: nn.Module, | |
| sensor_disc: nn.Module, | |
| ): | |
| super().__init__() | |
| self.backbone = backbone | |
| self.concept_head = concept_head | |
| self.aggregator = aggregator | |
| self.sensor_disc = sensor_disc | |
| def forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]: | |
| if getattr(self.concept_head, "uses_spatial", False): | |
| # SpatialConceptHead: pass full 14×14 token map [B, N, D] | |
| spatial = self.backbone.forward_spatial(x) # [B, N, D] | |
| features = spatial.mean(dim=1) # [B, D] — for sensor_disc & L_mat | |
| concepts = self.concept_head(spatial) # [B, k] | |
| else: | |
| # ConceptHead (legacy): pass globally-pooled vector [B, D] | |
| features = self.backbone(x) # [B, D] | |
| concepts = self.concept_head(features) # [B, k] | |
| score = self.aggregator(concepts) | |
| sensor_logits = self.sensor_disc(features) | |
| return { | |
| "score": score, | |
| "concepts": concepts, | |
| "sensor_logits": sensor_logits, | |
| "features": features, | |
| } | |