|
| 1 | +"""Composable multimodal encoders for DQN observations.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import torch |
| 6 | +from torch import Tensor, nn |
| 7 | + |
| 8 | + |
| 9 | +class VisionEncoder(nn.Module): |
| 10 | + """Small CNN encoder for image frame observations.""" |
| 11 | + |
| 12 | + def __init__(self, in_channels: int, embedding_dim: int) -> None: |
| 13 | + super().__init__() |
| 14 | + self.backbone = nn.Sequential( |
| 15 | + nn.Conv2d(in_channels, 32, kernel_size=8, stride=4), |
| 16 | + nn.ReLU(), |
| 17 | + nn.Conv2d(32, 64, kernel_size=4, stride=2), |
| 18 | + nn.ReLU(), |
| 19 | + nn.Conv2d(64, 64, kernel_size=3, stride=1), |
| 20 | + nn.ReLU(), |
| 21 | + nn.AdaptiveAvgPool2d((1, 1)), |
| 22 | + nn.Flatten(), |
| 23 | + nn.Linear(64, embedding_dim), |
| 24 | + nn.ReLU(), |
| 25 | + ) |
| 26 | + |
| 27 | + def forward(self, image_frames: Tensor) -> Tensor: |
| 28 | + return self.backbone(image_frames) |
| 29 | + |
| 30 | + |
| 31 | +class TelemetryEncoder(nn.Module): |
| 32 | + """MLP encoder for scalar telemetry channels.""" |
| 33 | + |
| 34 | + def __init__(self, input_dim: int, embedding_dim: int, hidden_dim: int = 128) -> None: |
| 35 | + super().__init__() |
| 36 | + self.model = nn.Sequential( |
| 37 | + nn.Linear(input_dim, hidden_dim), |
| 38 | + nn.ReLU(), |
| 39 | + nn.Linear(hidden_dim, embedding_dim), |
| 40 | + nn.ReLU(), |
| 41 | + ) |
| 42 | + |
| 43 | + def forward(self, scalar_telemetry: Tensor) -> Tensor: |
| 44 | + return self.model(scalar_telemetry) |
| 45 | + |
| 46 | + |
| 47 | +class EventSequenceEncoder(nn.Module): |
| 48 | + """Embedding + GRU encoder for event/text token sequences.""" |
| 49 | + |
| 50 | + def __init__(self, vocab_size: int, embedding_dim: int, output_dim: int) -> None: |
| 51 | + super().__init__() |
| 52 | + self.embedding = nn.Embedding(vocab_size, embedding_dim) |
| 53 | + self.gru = nn.GRU(embedding_dim, output_dim, batch_first=True) |
| 54 | + |
| 55 | + def forward(self, events_or_text: Tensor) -> Tensor: |
| 56 | + embedded = self.embedding(events_or_text.long()) |
| 57 | + _, hidden = self.gru(embedded) |
| 58 | + return hidden.squeeze(0) |
| 59 | + |
| 60 | + |
| 61 | +class ModalityFusion(nn.Module): |
| 62 | + """Fuse modality embeddings via concatenation projection or attention pooling.""" |
| 63 | + |
| 64 | + def __init__(self, input_dims: list[int], fused_dim: int, use_attention: bool = False) -> None: |
| 65 | + super().__init__() |
| 66 | + self.use_attention = use_attention |
| 67 | + self.fused_dim = fused_dim |
| 68 | + |
| 69 | + if use_attention: |
| 70 | + if len(set(input_dims)) != 1: |
| 71 | + raise ValueError("All modality dims must match when use_attention=True") |
| 72 | + self.attention = nn.MultiheadAttention(embed_dim=input_dims[0], num_heads=1, batch_first=True) |
| 73 | + self.output_projection = nn.Linear(input_dims[0], fused_dim) |
| 74 | + else: |
| 75 | + self.output_projection = nn.Linear(sum(input_dims), fused_dim) |
| 76 | + |
| 77 | + def forward(self, modality_embeddings: list[Tensor]) -> Tensor: |
| 78 | + if not modality_embeddings: |
| 79 | + raise ValueError("modality_embeddings cannot be empty") |
| 80 | + |
| 81 | + if self.use_attention: |
| 82 | + stacked = torch.stack(modality_embeddings, dim=1) |
| 83 | + attended, _ = self.attention(stacked, stacked, stacked) |
| 84 | + pooled = attended.mean(dim=1) |
| 85 | + return self.output_projection(pooled) |
| 86 | + |
| 87 | + concatenated = torch.cat(modality_embeddings, dim=1) |
| 88 | + return self.output_projection(concatenated) |
0 commit comments