gemx_soma_diffusers / pose_encoder /pose_encoder_gemx.py
OzzyGT's picture
OzzyGT HF Staff
Upload 19 files
77dc9d8 verified
Raw History Blame Contribute Delete
12.8 kB
# Copyright 2026 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Adapted from NVIDIA GEM-X (https://github.com/NVlabs/GEM-X), Apache-2.0, and the DINOv3 ViT of Hugging Face
# Transformers, Apache-2.0.
import math
from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.models.attention import AttentionMixin, AttentionModuleMixin
from diffusers.models.attention_dispatch import dispatch_attention_fn
from diffusers.models.modeling_utils import ModelMixin
from diffusers.utils import BaseOutput
def apply_rotary_emb(hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
"""Rotate the patch tokens of `(batch_size, seq_len, heads, head_dim)` states by half-split rotary embeddings of
shape `(num_patches, head_dim)`; the leading class and register tokens are left unchanged."""
num_prefix_tokens = hidden_states.shape[1] - cos.shape[0]
prefix, patches = hidden_states.split((num_prefix_tokens, cos.shape[0]), dim=1)
first, second = patches.chunk(2, dim=-1)
rotated = torch.cat((-second, first), dim=-1)
patches = patches * cos[None, :, None] + rotated * sin[None, :, None]
return torch.cat((prefix, patches), dim=1)
class GEMXDinoV3AttnProcessor:
_attention_backend = None
_parallel_config = None
def __call__(
self,
attn: "GEMXDinoV3Attention",
hidden_states: torch.Tensor,
rotary_emb: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
query = attn.to_q(hidden_states).unflatten(-1, (attn.heads, -1))
key = attn.to_k(hidden_states).unflatten(-1, (attn.heads, -1))
value = attn.to_v(hidden_states).unflatten(-1, (attn.heads, -1))
query = apply_rotary_emb(query, *rotary_emb)
key = apply_rotary_emb(key, *rotary_emb)
hidden_states = dispatch_attention_fn(
query, key, value, backend=self._attention_backend, parallel_config=self._parallel_config
)
return attn.to_out[0](hidden_states.flatten(2, 3))
class GEMXDinoV3Attention(nn.Module, AttentionModuleMixin):
_default_processor_cls = GEMXDinoV3AttnProcessor
_available_processors = [GEMXDinoV3AttnProcessor]
def __init__(self, dim: int, heads: int):
super().__init__()
self.heads = heads
self.to_q = nn.Linear(dim, dim)
self.to_k = nn.Linear(dim, dim, bias=False)
self.to_v = nn.Linear(dim, dim)
self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(0.0)])
self.set_processor(GEMXDinoV3AttnProcessor())
def forward(self, hidden_states: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
return self.processor(self, hidden_states, rotary_emb)
class GEMXDinoV3Layer(nn.Module):
def __init__(self, dim: int, heads: int, intermediate_size: int, layer_norm_eps: float):
super().__init__()
self.norm1 = nn.LayerNorm(dim, eps=layer_norm_eps)
self.attn = GEMXDinoV3Attention(dim, heads)
self.layer_scale1 = nn.Parameter(torch.ones(dim))
self.norm2 = nn.LayerNorm(dim, eps=layer_norm_eps)
self.ff_gate = nn.Linear(dim, intermediate_size)
self.ff_up = nn.Linear(dim, intermediate_size)
self.ff_down = nn.Linear(intermediate_size, dim)
self.layer_scale2 = nn.Parameter(torch.ones(dim))
def forward(self, hidden_states: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
hidden_states = hidden_states + self.attn(self.norm1(hidden_states), rotary_emb) * self.layer_scale1
norm_hidden_states = self.norm2(hidden_states)
ff_output = self.ff_down(F.silu(self.ff_gate(norm_hidden_states)) * self.ff_up(norm_hidden_states))
return hidden_states + ff_output * self.layer_scale2
class GEMXDinoV3RotaryEmbedding(nn.Module):
"""Rotary embedding of the patch grid. The inverse frequencies come from the checkpoint, whose rounded periods
differ slightly from freshly computed ones."""
def __init__(self, head_dim: int, patch_size: int):
super().__init__()
self.patch_size = patch_size
self.register_buffer("inv_freq", torch.ones(head_dim // 4))
def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
height, width = (size // self.patch_size for size in pixel_values.shape[-2:])
kwargs = {"device": pixel_values.device, "dtype": torch.float32}
coords_y = torch.arange(0.5, height, **kwargs) / height
coords_x = torch.arange(0.5, width, **kwargs) / width
coords = torch.stack(torch.meshgrid(coords_y, coords_x, indexing="ij"), dim=-1).flatten(0, 1)
coords = 2.0 * coords - 1.0
angles = 2 * math.pi * coords[:, :, None] * self.inv_freq.float()[None, None, :]
angles = angles.flatten(1, 2).tile(2)
return angles.cos().to(pixel_values.dtype), angles.sin().to(pixel_values.dtype)
class GEMXPoseDecoderAttnProcessor:
_attention_backend = None
_parallel_config = None
def __call__(
self,
attn: "GEMXPoseDecoderAttention",
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor | None = None,
) -> torch.Tensor:
if encoder_hidden_states is None:
encoder_hidden_states = hidden_states
query = attn.to_q(hidden_states).unflatten(-1, (attn.heads, -1))
key = attn.to_k(encoder_hidden_states).unflatten(-1, (attn.heads, -1))
value = attn.to_v(encoder_hidden_states).unflatten(-1, (attn.heads, -1))
hidden_states = dispatch_attention_fn(
query, key, value, backend=self._attention_backend, parallel_config=self._parallel_config
)
return attn.to_out[0](hidden_states.flatten(2, 3))
class GEMXPoseDecoderAttention(nn.Module, AttentionModuleMixin):
"""Self-attention, or cross-attention to `encoder_hidden_states` of width `context_dim`."""
_default_processor_cls = GEMXPoseDecoderAttnProcessor
_available_processors = [GEMXPoseDecoderAttnProcessor]
def __init__(self, dim: int, heads: int, head_dim: int, context_dim: int | None = None):
super().__init__()
inner_dim = heads * head_dim
context_dim = context_dim or dim
self.heads = heads
self.to_q = nn.Linear(dim, inner_dim, bias=False)
self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
self.to_out = nn.ModuleList([nn.Linear(inner_dim, dim), nn.Dropout(0.0)])
self.set_processor(GEMXPoseDecoderAttnProcessor())
def forward(self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor | None = None) -> torch.Tensor:
return self.processor(self, hidden_states, encoder_hidden_states)
class GEMXPoseDecoderLayer(nn.Module):
def __init__(self, dim: int, heads: int, head_dim: int, mlp_dim: int, context_dim: int):
super().__init__()
self.norm1 = nn.LayerNorm(dim)
self.attn1 = GEMXPoseDecoderAttention(dim, heads, head_dim)
self.norm2 = nn.LayerNorm(dim)
self.attn2 = GEMXPoseDecoderAttention(dim, heads, head_dim, context_dim)
self.norm3 = nn.LayerNorm(dim)
self.ff_in = nn.Linear(dim, mlp_dim)
self.ff_out = nn.Linear(mlp_dim, dim)
def forward(self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.attn1(self.norm1(hidden_states)) + hidden_states
hidden_states = self.attn2(self.norm2(hidden_states), encoder_hidden_states) + hidden_states
return self.ff_out(F.gelu(self.ff_in(self.norm3(hidden_states)))) + hidden_states
@dataclass
class GEMXPoseEncoderOutput(BaseOutput):
"""
Args:
pose_tokens (`torch.Tensor` of shape `(batch_size, decoder_dim)`):
The final query token of the Body Pose decoder for every crop.
"""
pose_tokens: torch.Tensor
class GEMXPoseEncoder(ModelMixin, ConfigMixin, AttentionMixin):
"""The image part of GEM-X Body Pose: a DINOv3 ViT-H/16+ encoder and the query decoder whose final token is the
per-frame image feature of the motion model. The pose, shape and camera regression heads of the image model are
not included."""
_no_split_modules = ["GEMXDinoV3Layer", "GEMXPoseDecoderLayer"]
_repeated_blocks = ["GEMXDinoV3Layer", "GEMXPoseDecoderLayer"]
_keep_in_fp32_modules = ["rope"]
_skip_layerwise_casting_patterns = ["patch_embed", "norm", "rope", "init_params"]
@register_to_config
def __init__(
self,
patch_size: int = 16,
hidden_size: int = 1280,
num_layers: int = 32,
num_heads: int = 20,
intermediate_size: int = 5120,
num_register_tokens: int = 4,
layer_norm_eps: float = 1e-5,
init_params_dim: int = 649,
crop_condition_dim: int = 3,
decoder_dim: int = 1024,
num_decoder_layers: int = 6,
decoder_heads: int = 8,
decoder_head_dim: int = 64,
decoder_mlp_dim: int = 1024,
):
super().__init__()
self.cls_token = nn.Parameter(torch.zeros(1, 1, hidden_size))
self.register_tokens = nn.Parameter(torch.zeros(1, num_register_tokens, hidden_size))
self.patch_embed = nn.Conv2d(3, hidden_size, kernel_size=patch_size, stride=patch_size)
self.rope = GEMXDinoV3RotaryEmbedding(hidden_size // num_heads, patch_size)
self.layers = nn.ModuleList(
[GEMXDinoV3Layer(hidden_size, num_heads, intermediate_size, layer_norm_eps) for _ in range(num_layers)]
)
self.norm_out = nn.LayerNorm(hidden_size, eps=layer_norm_eps)
# The mean pose, shape and camera the Body Pose query starts from.
self.init_params = nn.Parameter(torch.zeros(1, init_params_dim))
self.token_proj = nn.Linear(init_params_dim + crop_condition_dim, decoder_dim)
self.token_pos_embed = nn.Parameter(torch.zeros(1, 1, decoder_dim))
self.decoder_layers = nn.ModuleList(
[
GEMXPoseDecoderLayer(decoder_dim, decoder_heads, decoder_head_dim, decoder_mlp_dim, hidden_size)
for _ in range(num_decoder_layers)
]
)
def forward(
self, pixel_values: torch.Tensor, crop_conditions: torch.Tensor, return_dict: bool = True
) -> GEMXPoseEncoderOutput | tuple[torch.Tensor]:
"""
Args:
pixel_values (`torch.Tensor` of shape `(batch_size, 3, 256, 256)`):
Square person crops, normalized with the ImageNet mean and standard deviation.
crop_conditions (`torch.Tensor` of shape `(batch_size, 3)`):
The crop center relative to the principal point and the crop size, all divided by the focal length.
return_dict (`bool`, defaults to `True`):
Whether to return a `GEMXPoseEncoderOutput` instead of a tuple.
Returns:
`GEMXPoseEncoderOutput` or a `(pose_tokens,)` tuple.
"""
batch_size = pixel_values.shape[0]
pixel_values = pixel_values.to(self.patch_embed.weight.dtype)
rotary_emb = self.rope(pixel_values)
patches = self.patch_embed(pixel_values).flatten(2).transpose(1, 2)
hidden_states = torch.cat(
(self.cls_token.expand(batch_size, -1, -1), self.register_tokens.expand(batch_size, -1, -1), patches),
dim=1,
)
for layer in self.layers:
hidden_states = layer(hidden_states, rotary_emb)
hidden_states = self.norm_out(hidden_states)
image_features = hidden_states[:, 1 + self.config.num_register_tokens :]
token_inputs = torch.cat(
(self.init_params.expand(batch_size, -1), crop_conditions.to(image_features.dtype)), dim=-1
)
tokens = self.token_proj(token_inputs)[:, None] + self.token_pos_embed
for layer in self.decoder_layers:
tokens = layer(tokens, image_features)
pose_tokens = tokens[:, 0]
if not return_dict:
return (pose_tokens,)
return GEMXPoseEncoderOutput(pose_tokens=pose_tokens)