# 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 GEMXKeypointAttnProcessor: """The keypoint model was trained with one fused QKV projection and with the query and key rounded to bfloat16 for the rotary embedding, the class and register tokens included. Both are kept: the rounding depends on them.""" _attention_backend = None _parallel_config = None def __call__( self, attn: "GEMXKeypointAttention", hidden_states: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor], ) -> torch.Tensor: query, key, value = attn.to_qkv(hidden_states).unflatten(-1, (3, attn.heads, -1)).unbind(2) query = apply_rotary_emb(query.to(torch.bfloat16), *rotary_emb).to(value.dtype) key = apply_rotary_emb(key.to(torch.bfloat16), *rotary_emb).to(value.dtype) 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 GEMXKeypointAttention(nn.Module, AttentionModuleMixin): _default_processor_cls = GEMXKeypointAttnProcessor _available_processors = [GEMXKeypointAttnProcessor] def __init__(self, dim: int, heads: int): super().__init__() self.heads = heads # The key bias is zero. self.to_qkv = nn.Linear(dim, 3 * dim) self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(0.0)]) self.set_processor(GEMXKeypointAttnProcessor()) 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 GEMXKeypointLayer(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 = GEMXKeypointAttention(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 GEMXKeypointRotaryEmbedding(nn.Module): """Rotary embedding of the patch grid, computed in bfloat16 from the checkpoint's periods as in training.""" def __init__(self, head_dim: int, patch_size: int): super().__init__() self.patch_size = patch_size self.register_buffer("periods", 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.bfloat16} 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.periods.to(torch.bfloat16)[None, None] angles = angles.flatten(1, 2).tile(2) return angles.cos(), angles.sin() @dataclass class GEMXKeypointModelOutput(BaseOutput): """ Args: heatmaps (`torch.Tensor` of shape `(batch_size, num_keypoints, height // 4, width // 4)`): One heatmap per SOMA77 joint, at a quarter of the crop resolution. """ heatmaps: torch.Tensor class GEMXKeypointModel(ModelMixin, ConfigMixin, AttentionMixin): """The SOMA77 2D keypoint model of GEM-X: a DINOv3 ViT-H/16+ encoder and a heatmap head with two 2x upsampling stages.""" _no_split_modules = ["GEMXKeypointLayer"] _repeated_blocks = ["GEMXKeypointLayer"] _skip_layerwise_casting_patterns = ["patch_embed", "norm", "rope"] @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-6, head_channels: int = 256, num_keypoints: int = 77, ): 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 = GEMXKeypointRotaryEmbedding(hidden_size // num_heads, patch_size) self.layers = nn.ModuleList( [GEMXKeypointLayer(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) self.deconv1 = nn.ConvTranspose2d(hidden_size, head_channels, 4, stride=2, padding=1, bias=False) self.deconv_norm1 = nn.BatchNorm2d(head_channels) self.deconv2 = nn.ConvTranspose2d(head_channels, head_channels, 4, stride=2, padding=1, bias=False) self.deconv_norm2 = nn.BatchNorm2d(head_channels) self.conv_out = nn.Conv2d(head_channels, num_keypoints, 1) def forward(self, pixel_values: torch.Tensor, return_dict: bool = True) -> GEMXKeypointModelOutput | tuple: """ Args: pixel_values (`torch.Tensor` of shape `(batch_size, 3, 256, 192)`): Person crops normalized with the ImageNet mean and standard deviation. return_dict (`bool`, defaults to `True`): Whether to return a `GEMXKeypointModelOutput` instead of a tuple. Returns: `GEMXKeypointModelOutput` or a `(heatmaps,)` tuple. """ batch_size, _, height, width = pixel_values.shape 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) patch_size = self.config.patch_size hidden_states = hidden_states[:, 1 + self.config.num_register_tokens :] hidden_states = hidden_states.transpose(1, 2).unflatten(-1, (height // patch_size, width // patch_size)) hidden_states = F.relu(self.deconv_norm1(self.deconv1(hidden_states.contiguous()))) hidden_states = F.relu(self.deconv_norm2(self.deconv2(hidden_states))) heatmaps = self.conv_out(hidden_states) if not return_dict: return (heatmaps,) return GEMXKeypointModelOutput(heatmaps=heatmaps)