File size: 2,485 Bytes
0ec2598
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
95
96
97
98
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)

    @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)


# ============================================================================
# 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()