Spaces:
Runtime error
Runtime error
File size: 2,797 Bytes
ffb63d1 |
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 |
"""
Projection layers for multimodal fusion
"""
import torch
import torch.nn as nn
from typing import Optional
class VisionProjector(nn.Module):
"""Projects vision features to language model embedding space"""
def __init__(
self,
vision_dim: int,
language_dim: int,
hidden_dim: Optional[int] = None,
dropout: float = 0.1
):
super().__init__()
hidden_dim = hidden_dim or language_dim
self.projector = nn.Sequential(
nn.Linear(vision_dim, hidden_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.Linear(hidden_dim, language_dim),
nn.LayerNorm(language_dim)
)
# Initialize weights
self._init_weights()
def _init_weights(self):
"""Initialize projection weights"""
for module in self.modules():
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, std=0.02)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
def forward(self, vision_features: torch.Tensor) -> torch.Tensor:
"""
Args:
vision_features: [batch_size, vision_dim]
Returns:
projected_features: [batch_size, language_dim]
"""
return self.projector(vision_features)
class AudioProjector(nn.Module):
"""Projects audio features to language model embedding space"""
def __init__(
self,
audio_dim: int,
language_dim: int,
dropout: float = 0.1
):
super().__init__()
self.projector = nn.Sequential(
nn.Linear(audio_dim, language_dim),
nn.GELU(),
nn.Dropout(dropout),
nn.LayerNorm(language_dim)
)
# Initialize weights
self._init_weights()
def _init_weights(self):
"""Initialize projection weights"""
for module in self.modules():
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, std=0.02)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
def forward(self, audio_features: torch.Tensor) -> torch.Tensor:
"""
Args:
audio_features: [batch_size, audio_dim]
Returns:
projected_features: [batch_size, language_dim]
"""
return self.projector(audio_features)
|