Skip to content

[SIGGRAPH Asia 2026] UniMate: One Unified Model to Animate Diverse Skeletons

Python
4.6 KB
Raw Blame
"""``attention='graph'`` + ``text_cond='adaln'`` — the default pairing."""

import torch.nn as nn
import einops

from unimate.models.denoiser.base import UniMateDenoiserBase
from unimate.models.denoiser.blocks.graph import (GraphAttnBias,
                                                       SpatioTemporalBlock)


class UniMateGraphAdaLN(UniMateDenoiserBase):
    """Factored spatial (per-frame) + temporal (per-joint) attention.

    Spatial attention carries learned graph-distance + edge-type biases
    (Graphormer-style), so the skeleton's topology enters the attention
    logits rather than only the token features. The caption reaches the
    network through the adaLN vector.
    Position encoding on the joint axis is controlled by ``use_spectral_rope``:
      - True: SpectralJointRoPE (sign-invariant SignNet on Laplacian eigvecs).
      - False: 1D sinusoidal RopeND with integer joint indices.
    Temporal axis always uses sinusoidal RopeND with integer frame indices.
    """

    def __init__(self, use_graph_attn_bias=True, share_graph_attn_bias=False,
                 gradient_checkpointing=False, **kwargs):
        super().__init__(**kwargs)
        self.use_graph_attn_bias = use_graph_attn_bias
        self.gradient_checkpointing = gradient_checkpointing

        # One bias for the whole stack (Graphormer's arrangement) instead of a
        # private one per block: built here, evaluated once per forward, and
        # handed to every layer.
        self.graph_bias = (
            GraphAttnBias(self.latent_dim, self.num_heads)
            if share_graph_attn_bias and use_graph_attn_bias else None
        )

        # Positional encoding: separate rope module per axis.
        self._build_axis_ropes()

        # Transformer blocks
        self.transformer_blocks = nn.ModuleList(
            [
                SpatioTemporalBlock(
                    hidden_size=self.latent_dim,
                    num_heads=self.num_heads,
                    mlp_size=self.ff_size,
                    rope_spatial=self.rope_j,
                    rope_temporal=self.rope_t,
                    qk_norm=True,
                    dropout=self.dropout,
                    use_graph_attn_bias=self.use_graph_attn_bias,
                    own_graph_bias=self.graph_bias is None,
                    gradient_checkpointing=self.gradient_checkpointing,
                )
                for _ in range(self.num_layers)
            ]
        )

        self._finish_build()

    def forward(self, x, timesteps, cond=None, force_mask=False):
        """
        Args:
            x: [batch_size, max_joints, nfeats, max_frames], denoted x_t in the paper
            timesteps: [batch_size] (int)
            cond: Optional dict with conditioning information
        Returns:
            output: [batch_size, max_joints, nfeats, max_frames]
        """
        bs, njoints, nfeats, nframes = x.shape

        # adaLN conditioning: timestep + (CFG-masked) caption embedding
        y = self._build_adaln_y(x, timesteps, cond, force_mask)  # (B, latent_dim)

        # Input layer: encode tpos + motion, prepend the conditioning frame
        x, tpos_emb, joints_valid = self.input_layer(x, cond)
        if self.inject_tpos_to_adaln:
            y = y + self.tpos_pool(tpos_emb, joints_valid)  # (B, latent_dim)

        # Optional graph / depth / joint-name token embeddings
        x = self._apply_token_embeddings(x, cond)

        # Prepare attention masks
        temporal_valid = self.lengths_to_mask(cond['motion_length'] + self.n_prefix, nframes + self.n_prefix)  # (B, F+n_prefix)
        temporal_mask = temporal_valid.unsqueeze(1).unsqueeze(1)  # (B, 1, 1, F+1)
        joint_mask = joints_valid.unsqueeze(1).unsqueeze(2)  # (B, 1, 1, J)

        # Spatial rope: spectral pulls from cond; standard uses integer joint ids.
        spatial_pos_ids = self._spatial_position_ids(njoints)
        # Shared graph bias (when enabled): one (B, H, J, J) build for the stack.
        graph_bias = (self.graph_bias(cond, joint_mask)
                      if self.graph_bias is not None else None)
        for block in self.transformer_blocks:
            x = block(x, y, spatial_mask=joint_mask, temporal_mask=temporal_mask,
                      position_ids_spatial=spatial_pos_ids,
                      position_ids_temporal=self.temporal_position_ids[:, :nframes + self.n_prefix],
                      cond=cond, graph_bias=graph_bias)

        # Final layer
        x = self.final_layer(x, y, joints_valid=joints_valid)  # (B, feature_len, F+n_prefix, J)
        x = einops.rearrange(x, 'b d f j -> b j d f')  # (B, J, D, F+n_prefix)
        x = x[:, :, :, self.n_prefix:]  # remove prefix frames (B, J, D, F)

        return x