gnn_wm2 / Ctrl-World-Graph /graphwm /models /temporal_graph_conditioner.py
EndeavourDD's picture
Upload folder using huggingface_hub (part 17)
f15a766 verified
Raw
History Blame Contribute Delete
1.63 kB
from __future__ import annotations
import torch
import torch.nn as nn
class TemporalGraphConditioner(nn.Module):
"""Temporal transformer over per-frame graph tokens."""
def __init__(
self,
hidden_dim: int = 256,
cond_dim: int = 1024,
num_layers: int = 2,
num_heads: int = 8,
dropout: float = 0.1,
max_frames: int = 64,
):
super().__init__()
self.hidden_dim = hidden_dim
self.temporal_pos = nn.Parameter(torch.randn(max_frames, hidden_dim) * 0.02)
encoder_layer = nn.TransformerEncoderLayer(
d_model=hidden_dim,
nhead=num_heads,
dim_feedforward=hidden_dim * 4,
dropout=dropout,
activation="gelu",
batch_first=True,
norm_first=True,
)
self.temporal = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
self.proj = nn.Linear(hidden_dim, cond_dim)
self.out_norm = nn.LayerNorm(cond_dim)
def forward(self, frame_tokens: torch.Tensor) -> torch.Tensor:
bsz, num_frames, num_tokens, hidden_dim = frame_tokens.shape
if num_frames > self.temporal_pos.shape[0]:
raise ValueError(f"num_frames={num_frames} exceeds max_frames={self.temporal_pos.shape[0]}")
x = frame_tokens.permute(0, 2, 1, 3).reshape(bsz * num_tokens, num_frames, hidden_dim)
x = x + self.temporal_pos[:num_frames].unsqueeze(0)
x = self.temporal(x)
x = x.reshape(bsz, num_tokens, num_frames, hidden_dim).permute(0, 2, 1, 3)
x = self.out_norm(self.proj(x))
return x