| import math |
|
|
| import torch |
| import torch.nn as nn |
|
|
|
|
| |
| |
| |
|
|
| class ActionFFNEncoder(nn.Module): |
| """MLP encoder: (B, T, action_dim) -> (B, T, embed_dim). |
| |
| Output tokens replace the text context in DiT cross-attention. |
| """ |
|
|
| def __init__( |
| self, |
| action_dim: int, |
| embed_dim: int, |
| num_layers: int = 2, |
| max_timesteps: int = 16, |
| ): |
| super().__init__() |
|
|
| layers = [nn.Linear(action_dim, embed_dim), nn.GELU()] |
| for _ in range(max(0, num_layers - 2)): |
| layers += [nn.Linear(embed_dim, embed_dim), nn.GELU()] |
|
|
| self.mlp = nn.Sequential(*layers) |
| self.norm = nn.LayerNorm(embed_dim) |
|
|
| pe = self._sinusoidal_pe(max_timesteps, embed_dim) |
| self.temporal_pe = nn.Parameter(pe) |
|
|
| @staticmethod |
| def _sinusoidal_pe(length: int, dim: int) -> torch.Tensor: |
| pos = torch.arange(length).unsqueeze(1).float() |
| div = torch.exp( |
| torch.arange(0, dim, 2).float() * (-math.log(10000.0) / dim) |
| ) |
|
|
| pe = torch.zeros(length, dim) |
| pe[:, 0::2] = torch.sin(pos * div) |
| pe[:, 1::2] = torch.cos(pos * div) |
| return pe |
|
|
| def forward(self, actions: torch.Tensor) -> torch.Tensor: |
| """ |
| Args: |
| actions: (B, T, action_dim) |
| |
| Returns: |
| (B, T, embed_dim) |
| """ |
| x = self.mlp(actions) |
|
|
| T = actions.shape[1] |
| x = x + self.temporal_pe[:T].to( |
| dtype=x.dtype, |
| device=x.device, |
| ) |
|
|
| return self.norm(x) |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| |
| batch_size = 2 |
| timesteps = 16 |
| action_dim = 7 |
| embed_dim = 512 |
|
|
| |
| actions = torch.randn(batch_size, timesteps, action_dim) |
|
|
| |
| model = ActionFFNEncoder( |
| action_dim=action_dim, |
| embed_dim=embed_dim, |
| num_layers=2, |
| max_timesteps=32, |
| ) |
|
|
| |
| outputs = model(actions) |
|
|
| print(f"Input shape : {actions.shape}") |
| print(f"Output shape: {outputs.shape}") |
| print(f"Output dtype: {outputs.dtype}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |