Write me a python class that implements feature fusion across channels from multiple visual encoders: clip, siglip, dinov2 and convnext. Load the encoders from huggingface. Stack features along channel dimension. Interpolate the feature grid to the dimensions of the encoder with highest resolution.
Assistant
Certainly! Below is a Python class FeatureFusion that implements feature fusion across channels from multiple visual encoders: CLIP, DINOv2, and ConvNeXt. The encoders are loaded from Hugging Face, and their features are stacked along the channel dimension. The feature grids are interpolated to the dimensions of the encoder with the highest resolution.
Please note that as of my knowledge cutoff in September 2021, the SigLIP model is not publicly available on Hugging Face. If it becomes available, you can add it following the same pattern as the other models.
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import (
CLIPFeatureExtractor, CLIPVisionModel,
DINOv2FeatureExtractor, DINOv2Model,
ConvNextFeatureExtractor, ConvNextModel
)
class FeatureFusion(nn.Module):
def __init__(self):
super(FeatureFusion, self).__init__()
# Initialize models and their corresponding feature extractors
self.models = {}
self.feature_extractors = {}
# CLIP
self.models['clip'] = CLIPVisionModel.from_pretrained('openai/clip-vit-base-patch32')
self.feature_extractors['clip'] = CLIPFeatureExtractor.from_pretrained('openai/clip-vit-base-patch32')
# DINOv2
self.models['dinov2'] = DINOv2Model.from_pretrained('facebook/dinov2-base')
self.feature_extractors['dinov2'] = DINOv2FeatureExtractor.from_pretrained('facebook/dinov2-base')
# ConvNeXt
self.models['convnext'] = ConvNextModel.from_pretrained('facebook/convnext-base-224')
self.feature_extractors['convnext'] = ConvNextFeatureExtractor.from_pretrained('facebook/convnext-base-224')
# If SigLIP becomes available, you can add it here
# self.models['siglip'] = ...
# self.feature_extractors['siglip'] = ...
def forward(self, images):
"""
Args:
images: List of images, each image can be a PIL Image or numpy array.
The feature extractors will handle preprocessing.
Returns:
fused_features: Tensor of shape [batch_size, total_channels, H_max, W_max]
where total_channels is the sum of channels from all models,
and (H_max, W_max) is the highest resolution among models.
"""
features_list = []
resolutions = []
for name in self.models:
model = self.models[name]
feature_extractor = self.feature_extractors[name]
# Preprocess images using the model's feature extractor
inputs = feature_extractor(images=images, return_tensors='pt')
# Move inputs to the same device as the model
device = next(model.parameters()).device
inputs = {k: v.to(device) for k, v in inputs.items()}
model = model.to(device)
# Forward pass
outputs = model(**inputs)
# Extract features and reshape as needed
if name == 'clip':
# CLIP outputs last_hidden_state: [batch_size, seq_len, hidden_size]
features = outputs.last_hidden_state # Remove CLS token
features = features[:, 1:, :] # [batch_size, seq_len - 1, hidden_size]
batch_size, seq_len, hidden_size = features.shape
grid_size = int(seq_len ** 0.5) # Assuming square grid
features = features.permute(0, 2, 1).contiguous()
features = features.view(batch_size, hidden_size, grid_size, grid_size)
elif name == 'dinov2':
# DINOv2 processing similar to CLIP
features = outputs.last_hidden_state[:, 1:, :] # Remove CLS token
batch_size, seq_len, hidden_size = features.shape
grid_size = int(seq_len ** 0.5)
features = features.permute(0, 2, 1).contiguous()
features = features.view(batch_size, hidden_size, grid_size, grid_size)
elif name == 'convnext':
# ConvNext outputs last_hidden_state: [batch_size, hidden_size, H', W']
features = outputs.last_hidden_state
else:
# Handle additional models here
continue
features_list.append(features)
resolutions.append(features.shape[-2:])
# Determine the highest resolution among all feature maps
max_resolution = max(resolutions, key=lambda x: x[0] * x[1])
# Resize feature maps to the highest resolution
resized_features = []
for features in features_list:
resized = F.interpolate(features, size=max_resolution, mode='bilinear', align_corners=False)
resized_features.append(resized)
# Concatenate features along the channel dimension
fused_features = torch.cat(resized_features, dim=1)
return fused_features
Usage Example:
python
# Assume you have a list of images (e.g., PIL Images or numpy arrays)
from PIL import Image
# Load images (replace with your own images)
images = [Image.open('image1.jpg'), Image.open('image2.jpg')]
# Instantiate the FeatureFusion class
feature_fusion = FeatureFusion()
# Move the model to the desired device (e.g., GPU if available)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
feature_fusion = feature_fusion.to(device)
# Forward pass
fused_features = feature_fusion(images)
print(fused_features.shape) # Output shape: [batch_size, total_channels, H_max, W_max]
Explanation:
Model Initialization: We load the CLIP, DINOv2, and ConvNeXt models along with their corresponding feature extractors from Hugging Face.
Forward Method:
Preprocessing: Each model's feature extractor preprocesses the images appropriately, including resizing and normalization.
Feature Extraction: For each model, we extract the feature maps. For models like CLIP and DINOv2, which output sequential features, we reshape them into spatial grids.
Resolution Handling: We determine the highest resolution among the feature maps and resize all feature maps to this resolution using bilinear interpolation.
Feature Fusion: We concatenate the resized feature maps along the channel dimension to obtain the fused features.
Flexibility: You can easily add other models (e.g., SigLIP) by following the same pattern.
Remember to install the required packages if you haven't already:
bash
pip install torch torchvision transformers
This class should fulfill your requirements by loading the encoders from Hugging Face, stacking the features along the channel dimension, and interpolating the feature grids to match the highest resolution.