Download action_encoder.py from syCen/action-worldmodel-bench: direct link, hf CLI and curl.
- Browser
- Download file 2.49 kB
-
https://huggingface.co/datasets/syCen/action-worldmodel-bench/resolve/main/action_encoder.py
- Command line
-
hf download hf://datasets/syCen/action-worldmodel-bench/action_encoder.py
-
curl -L -o action_encoder.py https://huggingface.co/datasets/syCen/action-worldmodel-bench/resolve/main/action_encoder.py
2.49 kB
| import math | |
| import torch | |
| import torch.nn as nn | |
| # ============================================================================ | |
| # ActionFFNEncoder | |
| # ============================================================================ | |
| 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) # (max_timesteps, embed_dim) | |
| 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) | |
| # ============================================================================ | |
| # Main | |
| # ============================================================================ | |
| def main(): | |
| # Hyperparameters | |
| batch_size = 2 | |
| timesteps = 16 | |
| action_dim = 7 | |
| embed_dim = 512 | |
| # Random input | |
| actions = torch.randn(batch_size, timesteps, action_dim) | |
| # Model | |
| model = ActionFFNEncoder( | |
| action_dim=action_dim, | |
| embed_dim=embed_dim, | |
| num_layers=2, | |
| max_timesteps=32, | |
| ) | |
| # Forward | |
| 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() |