|
import torch |
|
from torch import nn |
|
from huggingface_hub import PyTorchModelHubMixin |
|
|
|
from torch_geometric.data import Batch |
|
from model_components import EfficientNetV2FeatureExtractor, GATGNN, TransformerEncoder, MLPBlock |
|
from graph_construction import build_graph_from_patches, build_graph_data_from_patches |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SAGViTClassifier(nn.Module, PyTorchModelHubMixin): |
|
""" |
|
SAG-ViT: Scale-Aware Graph Attention Vision Transformer |
|
|
|
This model integrates the following steps: |
|
- Extract multi-scale features from images using a CNN backbone (EfficientNetv2 here). |
|
- Partition the feature map into patches and build a graph where each node is a patch. |
|
- Use a Graph Attention Network (GAT) to refine patch embeddings based on local spatial relationships. |
|
- Utilize a Transformer encoder to model long-range dependencies and integrate multi-scale information. |
|
- Finally, classify the resulting representation into desired classes. |
|
|
|
Inputs: |
|
- x (Tensor): Input images (B, 3, H, W) |
|
|
|
Outputs: |
|
- out (Tensor): Classification logits (B, num_classes) |
|
""" |
|
def __init__( |
|
self, |
|
patch_size=(4,4), |
|
num_classes=10, |
|
d_model=64, |
|
nhead=4, |
|
num_layers=2, |
|
dim_feedforward=64, |
|
hidden_mlp_features=64, |
|
in_channels=2560, |
|
gcn_hidden=128, |
|
gcn_out=64 |
|
): |
|
super(SAGViTClassifier, self).__init__() |
|
|
|
|
|
self.cnn = EfficientNetV2FeatureExtractor() |
|
|
|
|
|
self.gcn = GATGNN(in_channels=in_channels, hidden_channels=gcn_hidden, out_channels=gcn_out) |
|
|
|
|
|
self.positional_embedding = nn.Parameter(torch.randn(1, 1, d_model)) |
|
|
|
self.extra_embedding = nn.Parameter(torch.randn(1, d_model)) |
|
|
|
|
|
self.transformer_encoder = TransformerEncoder(d_model, nhead, num_layers, dim_feedforward) |
|
|
|
|
|
self.mlp = MLPBlock(d_model, hidden_mlp_features, num_classes) |
|
|
|
self.patch_size = patch_size |
|
|
|
def forward(self, x): |
|
|
|
feature_map = self.cnn(x) |
|
|
|
|
|
G_global_batch, patches = build_graph_from_patches(feature_map, self.patch_size) |
|
|
|
|
|
data_list = build_graph_data_from_patches(G_global_batch, patches) |
|
device = x.device |
|
batch = Batch.from_data_list(data_list).to(device) |
|
|
|
|
|
x_gcn = self.gcn(batch) |
|
|
|
|
|
|
|
B = x.size(0) |
|
D = x_gcn.size(-1) |
|
|
|
|
|
|
|
patch_embeddings = x_gcn.unsqueeze(1) |
|
|
|
|
|
patch_embeddings = patch_embeddings + self.positional_embedding |
|
|
|
|
|
patch_embeddings = torch.cat([patch_embeddings, self.extra_embedding.unsqueeze(0).expand(B, -1, -1)], dim=1) |
|
|
|
|
|
x_trans = self.transformer_encoder(patch_embeddings) |
|
|
|
|
|
x_pooled = x_trans.mean(dim=1) |
|
|
|
|
|
out = self.mlp(x_pooled) |
|
return out |
|
|