OzzyGT HF Staff commited on
Commit
77dc9d8
·
verified ·
1 Parent(s): 8bb1efd

Upload 19 files

Browse files
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
NOTICE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GEM-X SOMA Diffusers
2
+ Copyright 2026 The HuggingFace Team.
3
+
4
+ The model code in keypoint_model, pose_encoder and motion_transformer is adapted from NVIDIA GEM-X
5
+ (https://github.com/NVlabs/GEM-X) and the DINOv3 ViT of Hugging Face Transformers, both Apache-2.0:
6
+
7
+ SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
8
+ SPDX-License-Identifier: Apache-2.0
9
+
10
+ The neutral SOMA77 skeleton in skeleton comes from NVIDIA Kimodo (https://github.com/nv-tlabs/kimodo), Apache-2.0.
11
+
12
+ Weights:
13
+ - keypoint_model, pose_encoder and motion_transformer are converted from nvidia/GEM-X
14
+ (https://huggingface.co/nvidia/GEM-X, revision b111f2dcf3ebcf57965fd53499cb645dfa5ba25c), licensed under the
15
+ NVIDIA Open Model License: https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/
16
+ Licensed by NVIDIA Corporation under the NVIDIA Open Model License.
17
+ - person_detector and detector_processor are PekingU/rtdetr_r101vd_coco_o365
18
+ (https://huggingface.co/PekingU/rtdetr_r101vd_coco_o365, revision ff44b69152a72cc752677665fb4539507d56a99d),
19
+ Apache-2.0. The weights are unchanged; image_processor_type in
20
+ detector_processor/preprocessor_config.json is set to RTDetrImageProcessorFast.
README.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: other
5
+ license_name: nvidia-open-model-license
6
+ license_link: https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/
7
+ base_model:
8
+ - nvidia/GEM-X
9
+ - PekingU/rtdetr_r101vd_coco_o365
10
+ library_name: diffusers
11
+ tags:
12
+ - gem-x
13
+ - modular-diffusers
14
+ - motion-capture
15
+ - pose-estimation
16
+ - video
17
+ - soma
18
+ ---
19
+
20
+ # GEM-X SOMA Diffusers
21
+
22
+ <video controls autoplay loop muted playsinline src="https://huggingface.co/datasets/OzzyGT/diffusers-examples/resolve/main/gem-x/gemx_soma_karate.mp4"></video>
23
+
24
+ *Left: the camera-space skeleton and 2D keypoints. Right: the world motion. The clip is AI-generated, the first frame with MiniMax-H3-Image and the video with MiniMax-H3.*
25
+
26
+ A Diffusers conversion of the native77 body model of [nvidia/GEM-X](https://huggingface.co/nvidia/GEM-X), which reconstructs the 3D motion of one person in a video. This repository holds the weights, configs and model code: the RT-DETR person detector, GEM-X's keypoint model, pose encoder and motion transformer, and Kimodo's neutral SOMA77 skeleton.
27
+
28
+ For model details, see the [original model card](https://huggingface.co/nvidia/GEM-X) and the [GEM-X repository](https://github.com/NVlabs/GEM-X).
29
+
30
+ ## Usage
31
+
32
+ Install PyTorch for your GPU, then:
33
+
34
+ ```bash
35
+ pip install "diffusers>=0.41.0" "transformers>=5.3.0" "torchvision>=0.25" "opencv-python-headless>=4.10" "scipy>=1.11" imageio imageio-ffmpeg
36
+ ```
37
+
38
+ The model runs with the [GEM-X SOMA Modular Diffusers](https://huggingface.co/OzzyGT/gemx_soma_custom_blocks) blocks.
39
+
40
+ > **Note:** `trust_remote_code=True` runs the code of the blocks repository and `trust_components_code=True` the model code in this one, both downloaded from the Hub. Only use them with repositories you trust.
41
+
42
+ ```python
43
+ import numpy as np
44
+ import torch
45
+ from diffusers import ModularPipelineBlocks
46
+ from diffusers.utils import load_video
47
+
48
+
49
+ blocks = ModularPipelineBlocks.from_pretrained(
50
+ "OzzyGT/gemx_soma_custom_blocks",
51
+ trust_remote_code=True,
52
+ components_repo="OzzyGT/gemx_soma_diffusers",
53
+ trust_components_code=True,
54
+ )
55
+ pipe = blocks.init_pipeline()
56
+ pipe.load_components(dtype=torch.float32)
57
+ pipe.to("cuda")
58
+
59
+ video = load_video("clip_30fps.mp4")
60
+ motion = pipe(video=video, output="motion")
61
+ np.savez_compressed("motion.npz", **{key: value.cpu().numpy() for key, value in motion.items()})
62
+ ```
63
+
64
+ The clip must be at 30 FPS. The result is a SOMA77 motion in meters, +Y up, with Kimodo's joint order and rotation convention; the blocks can also return the SOMA body parameters. The world motion isn't foot-locked, so the feet can slide slightly. Use float32, which matches GEM-X. See the [blocks](https://huggingface.co/OzzyGT/gemx_soma_custom_blocks) for the inputs and outputs.
65
+
66
+ ## Licenses
67
+
68
+ - GEM-X weights: [NVIDIA Open Model License](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/), from [nvidia/GEM-X](https://huggingface.co/nvidia/GEM-X). See [NOTICE](NOTICE).
69
+ - Person detector: Apache-2.0, from [PekingU/rtdetr_r101vd_coco_o365](https://huggingface.co/PekingU/rtdetr_r101vd_coco_o365), unchanged.
70
+ - Model code and the skeleton from [NVIDIA Kimodo](https://github.com/nv-tlabs/kimodo): [Apache-2.0](LICENSE).
detector_processor/preprocessor_config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_valid_processor_keys": [
3
+ "images",
4
+ "annotations",
5
+ "return_segmentation_masks",
6
+ "masks_path",
7
+ "do_resize",
8
+ "size",
9
+ "resample",
10
+ "do_rescale",
11
+ "rescale_factor",
12
+ "do_normalize",
13
+ "do_convert_annotations",
14
+ "image_mean",
15
+ "image_std",
16
+ "do_pad",
17
+ "pad_size",
18
+ "format",
19
+ "return_tensors",
20
+ "data_format",
21
+ "input_data_format"
22
+ ],
23
+ "do_convert_annotations": true,
24
+ "do_normalize": false,
25
+ "do_pad": false,
26
+ "do_rescale": true,
27
+ "do_resize": true,
28
+ "format": "coco_detection",
29
+ "image_mean": [
30
+ 0.485,
31
+ 0.456,
32
+ 0.406
33
+ ],
34
+ "image_processor_type": "RTDetrImageProcessorFast",
35
+ "image_std": [
36
+ 0.229,
37
+ 0.224,
38
+ 0.225
39
+ ],
40
+ "pad_size": null,
41
+ "resample": 2,
42
+ "rescale_factor": 0.00392156862745098,
43
+ "size": {
44
+ "height": 640,
45
+ "width": 640
46
+ }
47
+ }
keypoint_model/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "GEMXKeypointModel",
3
+ "_diffusers_version": "0.44.0.dev0",
4
+ "auto_map": {
5
+ "AutoModel": "keypoints_gemx.GEMXKeypointModel"
6
+ },
7
+ "head_channels": 256,
8
+ "hidden_size": 1280,
9
+ "intermediate_size": 5120,
10
+ "layer_norm_eps": 1e-06,
11
+ "num_heads": 20,
12
+ "num_keypoints": 77,
13
+ "num_layers": 32,
14
+ "num_register_tokens": 4,
15
+ "patch_size": 16
16
+ }
keypoint_model/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4e6dcfac97569f4d6418d309570a37332681645fcb9821fb1adcc0ee5f48a8a1
3
+ size 3387834068
keypoint_model/keypoints_gemx.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # Adapted from NVIDIA GEM-X (https://github.com/NVlabs/GEM-X), Apache-2.0, and the DINOv3 ViT of Hugging Face
16
+ # Transformers, Apache-2.0.
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+
25
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
26
+ from diffusers.models.attention import AttentionMixin, AttentionModuleMixin
27
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
28
+ from diffusers.models.modeling_utils import ModelMixin
29
+ from diffusers.utils import BaseOutput
30
+
31
+
32
+ def apply_rotary_emb(hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
33
+ """Rotate the patch tokens of `(batch_size, seq_len, heads, head_dim)` states by half-split rotary embeddings of
34
+ shape `(num_patches, head_dim)`; the leading class and register tokens are left unchanged."""
35
+ num_prefix_tokens = hidden_states.shape[1] - cos.shape[0]
36
+ prefix, patches = hidden_states.split((num_prefix_tokens, cos.shape[0]), dim=1)
37
+ first, second = patches.chunk(2, dim=-1)
38
+ rotated = torch.cat((-second, first), dim=-1)
39
+ patches = patches * cos[None, :, None] + rotated * sin[None, :, None]
40
+ return torch.cat((prefix, patches), dim=1)
41
+
42
+
43
+ class GEMXKeypointAttnProcessor:
44
+ """The keypoint model was trained with one fused QKV projection and with the query and key rounded to bfloat16
45
+ for the rotary embedding, the class and register tokens included. Both are kept: the rounding depends on them."""
46
+
47
+ _attention_backend = None
48
+ _parallel_config = None
49
+
50
+ def __call__(
51
+ self,
52
+ attn: "GEMXKeypointAttention",
53
+ hidden_states: torch.Tensor,
54
+ rotary_emb: tuple[torch.Tensor, torch.Tensor],
55
+ ) -> torch.Tensor:
56
+ query, key, value = attn.to_qkv(hidden_states).unflatten(-1, (3, attn.heads, -1)).unbind(2)
57
+ query = apply_rotary_emb(query.to(torch.bfloat16), *rotary_emb).to(value.dtype)
58
+ key = apply_rotary_emb(key.to(torch.bfloat16), *rotary_emb).to(value.dtype)
59
+ hidden_states = dispatch_attention_fn(
60
+ query, key, value, backend=self._attention_backend, parallel_config=self._parallel_config
61
+ )
62
+ return attn.to_out[0](hidden_states.flatten(2, 3))
63
+
64
+
65
+ class GEMXKeypointAttention(nn.Module, AttentionModuleMixin):
66
+ _default_processor_cls = GEMXKeypointAttnProcessor
67
+ _available_processors = [GEMXKeypointAttnProcessor]
68
+
69
+ def __init__(self, dim: int, heads: int):
70
+ super().__init__()
71
+ self.heads = heads
72
+ # The key bias is zero.
73
+ self.to_qkv = nn.Linear(dim, 3 * dim)
74
+ self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(0.0)])
75
+ self.set_processor(GEMXKeypointAttnProcessor())
76
+
77
+ def forward(self, hidden_states: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
78
+ return self.processor(self, hidden_states, rotary_emb)
79
+
80
+
81
+ class GEMXKeypointLayer(nn.Module):
82
+ def __init__(self, dim: int, heads: int, intermediate_size: int, layer_norm_eps: float):
83
+ super().__init__()
84
+ self.norm1 = nn.LayerNorm(dim, eps=layer_norm_eps)
85
+ self.attn = GEMXKeypointAttention(dim, heads)
86
+ self.layer_scale1 = nn.Parameter(torch.ones(dim))
87
+ self.norm2 = nn.LayerNorm(dim, eps=layer_norm_eps)
88
+ self.ff_gate = nn.Linear(dim, intermediate_size)
89
+ self.ff_up = nn.Linear(dim, intermediate_size)
90
+ self.ff_down = nn.Linear(intermediate_size, dim)
91
+ self.layer_scale2 = nn.Parameter(torch.ones(dim))
92
+
93
+ def forward(self, hidden_states: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
94
+ hidden_states = hidden_states + self.attn(self.norm1(hidden_states), rotary_emb) * self.layer_scale1
95
+ norm_hidden_states = self.norm2(hidden_states)
96
+ ff_output = self.ff_down(F.silu(self.ff_gate(norm_hidden_states)) * self.ff_up(norm_hidden_states))
97
+ return hidden_states + ff_output * self.layer_scale2
98
+
99
+
100
+ class GEMXKeypointRotaryEmbedding(nn.Module):
101
+ """Rotary embedding of the patch grid, computed in bfloat16 from the checkpoint's periods as in training."""
102
+
103
+ def __init__(self, head_dim: int, patch_size: int):
104
+ super().__init__()
105
+ self.patch_size = patch_size
106
+ self.register_buffer("periods", torch.ones(head_dim // 4))
107
+
108
+ def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
109
+ height, width = (size // self.patch_size for size in pixel_values.shape[-2:])
110
+ kwargs = {"device": pixel_values.device, "dtype": torch.bfloat16}
111
+ coords_y = torch.arange(0.5, height, **kwargs) / height
112
+ coords_x = torch.arange(0.5, width, **kwargs) / width
113
+ coords = torch.stack(torch.meshgrid(coords_y, coords_x, indexing="ij"), dim=-1).flatten(0, 1)
114
+ coords = 2.0 * coords - 1.0
115
+ angles = 2 * math.pi * coords[:, :, None] / self.periods.to(torch.bfloat16)[None, None]
116
+ angles = angles.flatten(1, 2).tile(2)
117
+ return angles.cos(), angles.sin()
118
+
119
+
120
+ @dataclass
121
+ class GEMXKeypointModelOutput(BaseOutput):
122
+ """
123
+ Args:
124
+ heatmaps (`torch.Tensor` of shape `(batch_size, num_keypoints, height // 4, width // 4)`):
125
+ One heatmap per SOMA77 joint, at a quarter of the crop resolution.
126
+ """
127
+
128
+ heatmaps: torch.Tensor
129
+
130
+
131
+ class GEMXKeypointModel(ModelMixin, ConfigMixin, AttentionMixin):
132
+ """The SOMA77 2D keypoint model of GEM-X: a DINOv3 ViT-H/16+ encoder and a heatmap head with two 2x upsampling
133
+ stages."""
134
+
135
+ _no_split_modules = ["GEMXKeypointLayer"]
136
+ _repeated_blocks = ["GEMXKeypointLayer"]
137
+ _skip_layerwise_casting_patterns = ["patch_embed", "norm", "rope"]
138
+
139
+ @register_to_config
140
+ def __init__(
141
+ self,
142
+ patch_size: int = 16,
143
+ hidden_size: int = 1280,
144
+ num_layers: int = 32,
145
+ num_heads: int = 20,
146
+ intermediate_size: int = 5120,
147
+ num_register_tokens: int = 4,
148
+ layer_norm_eps: float = 1e-6,
149
+ head_channels: int = 256,
150
+ num_keypoints: int = 77,
151
+ ):
152
+ super().__init__()
153
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, hidden_size))
154
+ self.register_tokens = nn.Parameter(torch.zeros(1, num_register_tokens, hidden_size))
155
+ self.patch_embed = nn.Conv2d(3, hidden_size, kernel_size=patch_size, stride=patch_size)
156
+ self.rope = GEMXKeypointRotaryEmbedding(hidden_size // num_heads, patch_size)
157
+ self.layers = nn.ModuleList(
158
+ [GEMXKeypointLayer(hidden_size, num_heads, intermediate_size, layer_norm_eps) for _ in range(num_layers)]
159
+ )
160
+ self.norm_out = nn.LayerNorm(hidden_size, eps=layer_norm_eps)
161
+ self.deconv1 = nn.ConvTranspose2d(hidden_size, head_channels, 4, stride=2, padding=1, bias=False)
162
+ self.deconv_norm1 = nn.BatchNorm2d(head_channels)
163
+ self.deconv2 = nn.ConvTranspose2d(head_channels, head_channels, 4, stride=2, padding=1, bias=False)
164
+ self.deconv_norm2 = nn.BatchNorm2d(head_channels)
165
+ self.conv_out = nn.Conv2d(head_channels, num_keypoints, 1)
166
+
167
+ def forward(self, pixel_values: torch.Tensor, return_dict: bool = True) -> GEMXKeypointModelOutput | tuple:
168
+ """
169
+ Args:
170
+ pixel_values (`torch.Tensor` of shape `(batch_size, 3, 256, 192)`):
171
+ Person crops normalized with the ImageNet mean and standard deviation.
172
+ return_dict (`bool`, defaults to `True`):
173
+ Whether to return a `GEMXKeypointModelOutput` instead of a tuple.
174
+
175
+ Returns:
176
+ `GEMXKeypointModelOutput` or a `(heatmaps,)` tuple.
177
+ """
178
+ batch_size, _, height, width = pixel_values.shape
179
+ pixel_values = pixel_values.to(self.patch_embed.weight.dtype)
180
+ rotary_emb = self.rope(pixel_values)
181
+ patches = self.patch_embed(pixel_values).flatten(2).transpose(1, 2)
182
+ hidden_states = torch.cat(
183
+ (self.cls_token.expand(batch_size, -1, -1), self.register_tokens.expand(batch_size, -1, -1), patches),
184
+ dim=1,
185
+ )
186
+ for layer in self.layers:
187
+ hidden_states = layer(hidden_states, rotary_emb)
188
+ hidden_states = self.norm_out(hidden_states)
189
+ patch_size = self.config.patch_size
190
+ hidden_states = hidden_states[:, 1 + self.config.num_register_tokens :]
191
+ hidden_states = hidden_states.transpose(1, 2).unflatten(-1, (height // patch_size, width // patch_size))
192
+
193
+ hidden_states = F.relu(self.deconv_norm1(self.deconv1(hidden_states.contiguous())))
194
+ hidden_states = F.relu(self.deconv_norm2(self.deconv2(hidden_states)))
195
+ heatmaps = self.conv_out(hidden_states)
196
+
197
+ if not return_dict:
198
+ return (heatmaps,)
199
+ return GEMXKeypointModelOutput(heatmaps=heatmaps)
modular_model_index.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ModularPipeline",
3
+ "_blocks_class_name": "GEMXBlocks",
4
+ "person_detector": [
5
+ "transformers",
6
+ "RTDetrForObjectDetection",
7
+ {
8
+ "pretrained_model_name_or_path": null,
9
+ "revision": null,
10
+ "subfolder": "person_detector",
11
+ "type_hint": [
12
+ "transformers",
13
+ "RTDetrForObjectDetection"
14
+ ],
15
+ "variant": null
16
+ }
17
+ ],
18
+ "detector_processor": [
19
+ "transformers",
20
+ "RTDetrImageProcessorFast",
21
+ {
22
+ "pretrained_model_name_or_path": null,
23
+ "revision": null,
24
+ "subfolder": "detector_processor",
25
+ "type_hint": [
26
+ "transformers",
27
+ "RTDetrImageProcessorFast"
28
+ ],
29
+ "variant": null
30
+ }
31
+ ],
32
+ "keypoint_model": [
33
+ "keypoints_gemx",
34
+ "GEMXKeypointModel",
35
+ {
36
+ "pretrained_model_name_or_path": null,
37
+ "revision": null,
38
+ "subfolder": "keypoint_model",
39
+ "type_hint": [
40
+ "keypoints_gemx",
41
+ "GEMXKeypointModel"
42
+ ],
43
+ "variant": null
44
+ }
45
+ ],
46
+ "pose_encoder": [
47
+ "pose_encoder_gemx",
48
+ "GEMXPoseEncoder",
49
+ {
50
+ "pretrained_model_name_or_path": null,
51
+ "revision": null,
52
+ "subfolder": "pose_encoder",
53
+ "type_hint": [
54
+ "pose_encoder_gemx",
55
+ "GEMXPoseEncoder"
56
+ ],
57
+ "variant": null
58
+ }
59
+ ],
60
+ "motion_transformer": [
61
+ "transformer_gemx",
62
+ "GEMXMotionTransformer",
63
+ {
64
+ "pretrained_model_name_or_path": null,
65
+ "revision": null,
66
+ "subfolder": "motion_transformer",
67
+ "type_hint": [
68
+ "transformer_gemx",
69
+ "GEMXMotionTransformer"
70
+ ],
71
+ "variant": null
72
+ }
73
+ ],
74
+ "skeleton": [
75
+ "skeleton_gemx",
76
+ "GEMXSOMASkeleton",
77
+ {
78
+ "pretrained_model_name_or_path": null,
79
+ "revision": null,
80
+ "subfolder": "skeleton",
81
+ "type_hint": [
82
+ "skeleton_gemx",
83
+ "GEMXSOMASkeleton"
84
+ ],
85
+ "variant": null
86
+ }
87
+ ]
88
+ }
motion_transformer/config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "GEMXMotionTransformer",
3
+ "_diffusers_version": "0.44.0.dev0",
4
+ "auto_map": {
5
+ "AutoModel": "transformer_gemx.GEMXMotionTransformer"
6
+ },
7
+ "hidden_dim": 512,
8
+ "image_feature_dim": 1024,
9
+ "keypoint_dim": 32,
10
+ "max_frames": 120,
11
+ "mlp_ratio": 4.0,
12
+ "motion_dim": 655,
13
+ "num_heads": 8,
14
+ "num_keypoints": 77,
15
+ "num_layers": 12
16
+ }
motion_transformer/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7951e9bc8d159402b863956abb1c5951f20db18c92134f18c8aa14c585502898
3
+ size 175498208
motion_transformer/transformer_gemx.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # Adapted from NVIDIA GEM-X (https://github.com/NVlabs/GEM-X), Apache-2.0.
16
+
17
+ from dataclasses import dataclass
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
23
+ from diffusers.models.attention import AttentionMixin, AttentionModuleMixin
24
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
25
+ from diffusers.models.modeling_utils import ModelMixin
26
+ from diffusers.utils import BaseOutput
27
+
28
+
29
+ class GEMXMLP(nn.Module):
30
+ def __init__(self, in_features: int, hidden_features: int, out_features: int, approximate: str = "none"):
31
+ super().__init__()
32
+ self.fc1 = nn.Linear(in_features, hidden_features)
33
+ self.act = nn.GELU(approximate=approximate)
34
+ self.fc2 = nn.Linear(hidden_features, out_features)
35
+
36
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
37
+ return self.fc2(self.act(self.fc1(hidden_states)))
38
+
39
+
40
+ def apply_interleaved_rotary_emb(hidden_states: torch.Tensor, angles: torch.Tensor) -> torch.Tensor:
41
+ """Rotate consecutive channel pairs of `(batch_size, seq_len, heads, head_dim)` states by `angles` of shape
42
+ `(seq_len, head_dim)`."""
43
+ pairs = hidden_states.unflatten(-1, (-1, 2))
44
+ first, second = pairs.unbind(-1)
45
+ rotated = torch.stack((-second, first), dim=-1).flatten(-2)
46
+ angles = angles[None, :, None, :]
47
+ return hidden_states * angles.cos() + rotated * angles.sin()
48
+
49
+
50
+ class GEMXMotionAttnProcessor:
51
+ _attention_backend = None
52
+ _parallel_config = None
53
+
54
+ def __call__(
55
+ self,
56
+ attn: "GEMXMotionAttention",
57
+ hidden_states: torch.Tensor,
58
+ rotary_angles: torch.Tensor,
59
+ attention_mask: torch.Tensor | None = None,
60
+ ) -> torch.Tensor:
61
+ query = attn.to_q(hidden_states).unflatten(-1, (attn.heads, -1))
62
+ key = attn.to_k(hidden_states).unflatten(-1, (attn.heads, -1))
63
+ value = attn.to_v(hidden_states).unflatten(-1, (attn.heads, -1))
64
+ # The rotary trigonometry runs in float32.
65
+ query = apply_interleaved_rotary_emb(query.float(), rotary_angles).to(value.dtype)
66
+ key = apply_interleaved_rotary_emb(key.float(), rotary_angles).to(value.dtype)
67
+ hidden_states = dispatch_attention_fn(
68
+ query,
69
+ key,
70
+ value,
71
+ attn_mask=attention_mask,
72
+ backend=self._attention_backend,
73
+ parallel_config=self._parallel_config,
74
+ )
75
+ return attn.to_out[0](hidden_states.flatten(2, 3))
76
+
77
+
78
+ class GEMXMotionAttention(nn.Module, AttentionModuleMixin):
79
+ """Temporal self-attention with interleaved rotary positions. `attention_mask` is a boolean `(1, 1, seq_len,
80
+ seq_len)` mask of the frames each frame attends to."""
81
+
82
+ _default_processor_cls = GEMXMotionAttnProcessor
83
+ _available_processors = [GEMXMotionAttnProcessor]
84
+
85
+ def __init__(self, dim: int, heads: int):
86
+ super().__init__()
87
+ self.heads = heads
88
+ self.to_q = nn.Linear(dim, dim)
89
+ self.to_k = nn.Linear(dim, dim)
90
+ self.to_v = nn.Linear(dim, dim)
91
+ self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(0.0)])
92
+ self.set_processor(GEMXMotionAttnProcessor())
93
+
94
+ def forward(
95
+ self, hidden_states: torch.Tensor, rotary_angles: torch.Tensor, attention_mask: torch.Tensor | None = None
96
+ ) -> torch.Tensor:
97
+ return self.processor(self, hidden_states, rotary_angles, attention_mask)
98
+
99
+
100
+ class GEMXMotionTransformerBlock(nn.Module):
101
+ """Pre-norm block whose attention and feed-forward residuals are scaled by learned gates."""
102
+
103
+ def __init__(self, dim: int, heads: int, mlp_ratio: float):
104
+ super().__init__()
105
+ self.norm1 = nn.LayerNorm(dim, eps=1e-6)
106
+ self.attn = GEMXMotionAttention(dim, heads)
107
+ self.norm2 = nn.LayerNorm(dim, eps=1e-6)
108
+ self.ff = GEMXMLP(dim, int(dim * mlp_ratio), dim, approximate="tanh")
109
+ self.gate_attn = nn.Parameter(torch.zeros(1, 1, dim))
110
+ self.gate_ff = nn.Parameter(torch.zeros(1, 1, dim))
111
+
112
+ def forward(
113
+ self, hidden_states: torch.Tensor, rotary_angles: torch.Tensor, attention_mask: torch.Tensor | None = None
114
+ ) -> torch.Tensor:
115
+ hidden_states = hidden_states + self.gate_attn * self.attn(
116
+ self.norm1(hidden_states), rotary_angles, attention_mask
117
+ )
118
+ return hidden_states + self.gate_ff * self.ff(self.norm2(hidden_states))
119
+
120
+
121
+ @dataclass
122
+ class GEMXMotionTransformerOutput(BaseOutput):
123
+ """
124
+ Args:
125
+ motion (`torch.Tensor` of shape `(batch_size, num_frames, 655)`):
126
+ The normalized motion features of every frame: 76 joint rotations (6D), 128 identity coefficients, 56 log
127
+ local scales, the camera-frame and gravity-view root rotations (6D each) and the root displacement in the
128
+ root frame. Identity and scales are averaged over the clip. `motion_mean` and `motion_std` undo the
129
+ normalization.
130
+ camera (`torch.Tensor` of shape `(batch_size, num_frames, 3)`):
131
+ The weak-perspective camera `(scale, x, y)` of the person's crop in every frame.
132
+ contact_logits (`torch.Tensor` of shape `(batch_size, num_frames, 6)`):
133
+ The static-contact logits of the left ankle, left foot, right ankle, right foot, left wrist and right
134
+ wrist.
135
+ """
136
+
137
+ motion: torch.Tensor
138
+ camera: torch.Tensor
139
+ contact_logits: torch.Tensor
140
+
141
+
142
+ class GEMXMotionTransformer(ModelMixin, ConfigMixin, AttentionMixin):
143
+ """Temporal regression transformer that predicts the SOMA body parameters, root motion and crop camera of every
144
+ frame of a clip from per-frame 2D keypoints, crop placement, camera rotation and Body Pose image features. Frames
145
+ attend to a window of `max_frames` around them in clips longer than `max_frames`."""
146
+
147
+ _no_split_modules = ["GEMXMotionTransformerBlock"]
148
+ _repeated_blocks = ["GEMXMotionTransformerBlock"]
149
+ _skip_layerwise_casting_patterns = ["norm", "embed", "keypoint"]
150
+
151
+ @register_to_config
152
+ def __init__(
153
+ self,
154
+ num_keypoints: int = 77,
155
+ keypoint_dim: int = 32,
156
+ image_feature_dim: int = 1024,
157
+ hidden_dim: int = 512,
158
+ num_layers: int = 12,
159
+ num_heads: int = 8,
160
+ mlp_ratio: float = 4.0,
161
+ motion_dim: int = 655,
162
+ max_frames: int = 120,
163
+ ):
164
+ super().__init__()
165
+ self.keypoint_proj = nn.Linear(2, keypoint_dim)
166
+ self.missing_keypoint_embed = nn.Parameter(torch.zeros(num_keypoints, keypoint_dim))
167
+ self.keypoint_embedder = GEMXMLP(num_keypoints * keypoint_dim, hidden_dim * 2, hidden_dim)
168
+ self.crop_embedder = nn.Sequential(nn.Linear(3, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim))
169
+ self.camera_rotation_embedder = nn.Sequential(
170
+ nn.Linear(6, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim)
171
+ )
172
+ self.image_embedder = nn.Sequential(nn.LayerNorm(image_feature_dim), nn.Linear(image_feature_dim, hidden_dim))
173
+ self.time_embedder = nn.Sequential(
174
+ nn.Linear(hidden_dim, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim)
175
+ )
176
+ self.proj_in = nn.Linear(hidden_dim, hidden_dim)
177
+ self.blocks = nn.ModuleList(
178
+ [GEMXMotionTransformerBlock(hidden_dim, num_heads, mlp_ratio) for _ in range(num_layers)]
179
+ )
180
+ self.motion_head = GEMXMLP(hidden_dim, hidden_dim, motion_dim)
181
+ self.camera_head = GEMXMLP(hidden_dim, hidden_dim, 3)
182
+ self.contact_head = GEMXMLP(hidden_dim, hidden_dim, 6)
183
+
184
+ # The sinusoidal encoding of the fixed timestep 999, kept from the checkpoint.
185
+ self.register_buffer("timestep_encoding", torch.zeros(hidden_dim))
186
+ self.register_buffer("motion_mean", torch.zeros(motion_dim))
187
+ self.register_buffer("motion_std", torch.ones(motion_dim))
188
+ head_dim = hidden_dim // num_heads
189
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, head_dim, 2).float() / head_dim))
190
+ self.register_buffer("rotary_inv_freq", inv_freq, persistent=False)
191
+ self.register_buffer("camera_rotation_mean", torch.tensor([1.0, 0.0, 0.0, 0.0, 1.0, 0.0]), persistent=False)
192
+ self.register_buffer("camera_rotation_std", torch.tensor([0.001, 0.1, 0.1, 0.1, 0.001, 0.1]), persistent=False)
193
+ self.register_buffer("camera_mean", torch.tensor([1.0606, -0.0027, 0.2702]), persistent=False)
194
+ self.register_buffer("camera_std", torch.tensor([0.1784, 0.0956, 0.0764]), persistent=False)
195
+
196
+ def forward(
197
+ self,
198
+ keypoints: torch.Tensor,
199
+ crop_conditions: torch.Tensor,
200
+ camera_rotation_velocity: torch.Tensor,
201
+ image_features: torch.Tensor,
202
+ return_dict: bool = True,
203
+ ) -> GEMXMotionTransformerOutput | tuple[torch.Tensor, ...]:
204
+ """
205
+ Args:
206
+ keypoints (`torch.Tensor` of shape `(batch_size, num_frames, num_keypoints, 3)`):
207
+ The SOMA77 2D keypoints of every frame, `x` and `y` normalized to `[-1, 1]` over the person's crop,
208
+ then the confidence. Keypoints with a confidence of 0.5 or less are treated as missing.
209
+ crop_conditions (`torch.Tensor` of shape `(batch_size, num_frames, 3)`):
210
+ The crop center relative to the principal point and the crop size, all divided by the focal length.
211
+ camera_rotation_velocity (`torch.Tensor` of shape `(batch_size, num_frames, 6)`):
212
+ The camera rotation from each frame to the next, in the 6D rotation representation.
213
+ image_features (`torch.Tensor` of shape `(batch_size, num_frames, image_feature_dim)`):
214
+ The Body Pose token of every frame.
215
+ return_dict (`bool`, defaults to `True`):
216
+ Whether to return a `GEMXMotionTransformerOutput` instead of a tuple.
217
+
218
+ Returns:
219
+ `GEMXMotionTransformerOutput` or a `(motion, camera, contact_logits)` tuple.
220
+ """
221
+ batch_size, num_frames = keypoints.shape[:2]
222
+ visible = keypoints[..., 2:] > 0.5
223
+ coordinates = keypoints[..., :2].masked_fill(~visible, 0)
224
+ encoded = torch.where(visible, self.keypoint_proj(coordinates), self.missing_keypoint_embed)
225
+ camera_rotation_velocity = (camera_rotation_velocity - self.camera_rotation_mean) / self.camera_rotation_std
226
+ hidden_states = (
227
+ self.keypoint_embedder(encoded.flatten(-2))
228
+ + self.crop_embedder(crop_conditions)
229
+ + self.camera_rotation_embedder(camera_rotation_velocity)
230
+ + self.image_embedder(image_features)
231
+ )
232
+ hidden_states = self.proj_in(hidden_states + self.time_embedder(self.timestep_encoding))
233
+
234
+ positions = torch.arange(num_frames, device=hidden_states.device, dtype=torch.float32)
235
+ rotary_angles = (positions[:, None] * self.rotary_inv_freq.float()).repeat_interleave(2, dim=-1)
236
+ attention_mask = None
237
+ max_frames = self.config.max_frames
238
+ if num_frames > max_frames:
239
+ # Each frame attends to `max_frames` frames centered on it, shifted inward at the clip ends.
240
+ index = torch.arange(num_frames, device=hidden_states.device)
241
+ start = (index - max_frames // 2).clamp(0, num_frames - max_frames)
242
+ stop = (index + max_frames // 2).clamp(max_frames, num_frames)
243
+ attention_mask = (index[None] >= start[:, None]) & (index[None] < stop[:, None])
244
+ attention_mask = attention_mask[None, None]
245
+ for block in self.blocks:
246
+ hidden_states = block(hidden_states, rotary_angles, attention_mask)
247
+
248
+ motion = self.motion_head(hidden_states)
249
+ # Identity and local scales are constant over a clip.
250
+ identity_and_scales = motion[..., 456:640].mean(dim=1, keepdim=True).expand(-1, num_frames, -1)
251
+ motion = torch.cat((motion[..., :456], identity_and_scales, motion[..., 640:]), dim=-1)
252
+ camera = self.camera_head(hidden_states) * self.camera_std + self.camera_mean
253
+ camera = torch.cat((camera[..., :1].clamp_min(0.25), camera[..., 1:]), dim=-1)
254
+ contact_logits = self.contact_head(hidden_states)
255
+
256
+ if not return_dict:
257
+ return (motion, camera, contact_logits)
258
+ return GEMXMotionTransformerOutput(motion=motion, camera=camera, contact_logits=contact_logits)
person_detector/config.json ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_dropout": 0.0,
3
+ "activation_function": "silu",
4
+ "anchor_image_size": null,
5
+ "architectures": [
6
+ "RTDetrForObjectDetection"
7
+ ],
8
+ "attention_dropout": 0.0,
9
+ "auxiliary_loss": true,
10
+ "backbone": null,
11
+ "backbone_config": {
12
+ "depths": [
13
+ 3,
14
+ 4,
15
+ 23,
16
+ 3
17
+ ],
18
+ "model_type": "rt_detr_resnet",
19
+ "out_features": [
20
+ "stage2",
21
+ "stage3",
22
+ "stage4"
23
+ ],
24
+ "out_indices": [
25
+ 2,
26
+ 3,
27
+ 4
28
+ ]
29
+ },
30
+ "backbone_kwargs": null,
31
+ "batch_norm_eps": 1e-05,
32
+ "box_noise_scale": 1.0,
33
+ "d_model": 256,
34
+ "decoder_activation_function": "relu",
35
+ "decoder_attention_heads": 8,
36
+ "decoder_ffn_dim": 1024,
37
+ "decoder_in_channels": [
38
+ 384,
39
+ 384,
40
+ 384
41
+ ],
42
+ "decoder_layers": 6,
43
+ "decoder_n_points": 4,
44
+ "disable_custom_kernels": true,
45
+ "dropout": 0.0,
46
+ "encode_proj_layers": [
47
+ 2
48
+ ],
49
+ "encoder_activation_function": "gelu",
50
+ "encoder_attention_heads": 8,
51
+ "encoder_ffn_dim": 2048,
52
+ "encoder_hidden_dim": 384,
53
+ "encoder_in_channels": [
54
+ 512,
55
+ 1024,
56
+ 2048
57
+ ],
58
+ "encoder_layers": 1,
59
+ "eos_coefficient": 0.0001,
60
+ "eval_size": null,
61
+ "feat_strides": [
62
+ 8,
63
+ 16,
64
+ 32
65
+ ],
66
+ "focal_loss_alpha": 0.75,
67
+ "focal_loss_gamma": 2.0,
68
+ "hidden_expansion": 1.0,
69
+ "id2label": {
70
+ "0": "person",
71
+ "1": "bicycle",
72
+ "2": "car",
73
+ "3": "motorbike",
74
+ "4": "aeroplane",
75
+ "5": "bus",
76
+ "6": "train",
77
+ "7": "truck",
78
+ "8": "boat",
79
+ "9": "traffic light",
80
+ "10": "fire hydrant",
81
+ "11": "stop sign",
82
+ "12": "parking meter",
83
+ "13": "bench",
84
+ "14": "bird",
85
+ "15": "cat",
86
+ "16": "dog",
87
+ "17": "horse",
88
+ "18": "sheep",
89
+ "19": "cow",
90
+ "20": "elephant",
91
+ "21": "bear",
92
+ "22": "zebra",
93
+ "23": "giraffe",
94
+ "24": "backpack",
95
+ "25": "umbrella",
96
+ "26": "handbag",
97
+ "27": "tie",
98
+ "28": "suitcase",
99
+ "29": "frisbee",
100
+ "30": "skis",
101
+ "31": "snowboard",
102
+ "32": "sports ball",
103
+ "33": "kite",
104
+ "34": "baseball bat",
105
+ "35": "baseball glove",
106
+ "36": "skateboard",
107
+ "37": "surfboard",
108
+ "38": "tennis racket",
109
+ "39": "bottle",
110
+ "40": "wine glass",
111
+ "41": "cup",
112
+ "42": "fork",
113
+ "43": "knife",
114
+ "44": "spoon",
115
+ "45": "bowl",
116
+ "46": "banana",
117
+ "47": "apple",
118
+ "48": "sandwich",
119
+ "49": "orange",
120
+ "50": "broccoli",
121
+ "51": "carrot",
122
+ "52": "hot dog",
123
+ "53": "pizza",
124
+ "54": "donut",
125
+ "55": "cake",
126
+ "56": "chair",
127
+ "57": "sofa",
128
+ "58": "pottedplant",
129
+ "59": "bed",
130
+ "60": "diningtable",
131
+ "61": "toilet",
132
+ "62": "tvmonitor",
133
+ "63": "laptop",
134
+ "64": "mouse",
135
+ "65": "remote",
136
+ "66": "keyboard",
137
+ "67": "cell phone",
138
+ "68": "microwave",
139
+ "69": "oven",
140
+ "70": "toaster",
141
+ "71": "sink",
142
+ "72": "refrigerator",
143
+ "73": "book",
144
+ "74": "clock",
145
+ "75": "vase",
146
+ "76": "scissors",
147
+ "77": "teddy bear",
148
+ "78": "hair drier",
149
+ "79": "toothbrush"
150
+ },
151
+ "initializer_range": 0.01,
152
+ "is_encoder_decoder": true,
153
+ "label2id": {
154
+ "aeroplane": 4,
155
+ "apple": 47,
156
+ "backpack": 24,
157
+ "banana": 46,
158
+ "baseball bat": 34,
159
+ "baseball glove": 35,
160
+ "bear": 21,
161
+ "bed": 59,
162
+ "bench": 13,
163
+ "bicycle": 1,
164
+ "bird": 14,
165
+ "boat": 8,
166
+ "book": 73,
167
+ "bottle": 39,
168
+ "bowl": 45,
169
+ "broccoli": 50,
170
+ "bus": 5,
171
+ "cake": 55,
172
+ "car": 2,
173
+ "carrot": 51,
174
+ "cat": 15,
175
+ "cell phone": 67,
176
+ "chair": 56,
177
+ "clock": 74,
178
+ "cow": 19,
179
+ "cup": 41,
180
+ "diningtable": 60,
181
+ "dog": 16,
182
+ "donut": 54,
183
+ "elephant": 20,
184
+ "fire hydrant": 10,
185
+ "fork": 42,
186
+ "frisbee": 29,
187
+ "giraffe": 23,
188
+ "hair drier": 78,
189
+ "handbag": 26,
190
+ "horse": 17,
191
+ "hot dog": 52,
192
+ "keyboard": 66,
193
+ "kite": 33,
194
+ "knife": 43,
195
+ "laptop": 63,
196
+ "microwave": 68,
197
+ "motorbike": 3,
198
+ "mouse": 64,
199
+ "orange": 49,
200
+ "oven": 69,
201
+ "parking meter": 12,
202
+ "person": 0,
203
+ "pizza": 53,
204
+ "pottedplant": 58,
205
+ "refrigerator": 72,
206
+ "remote": 65,
207
+ "sandwich": 48,
208
+ "scissors": 76,
209
+ "sheep": 18,
210
+ "sink": 71,
211
+ "skateboard": 36,
212
+ "skis": 30,
213
+ "snowboard": 31,
214
+ "sofa": 57,
215
+ "spoon": 44,
216
+ "sports ball": 32,
217
+ "stop sign": 11,
218
+ "suitcase": 28,
219
+ "surfboard": 37,
220
+ "teddy bear": 77,
221
+ "tennis racket": 38,
222
+ "tie": 27,
223
+ "toaster": 70,
224
+ "toilet": 61,
225
+ "toothbrush": 79,
226
+ "traffic light": 9,
227
+ "train": 6,
228
+ "truck": 7,
229
+ "tvmonitor": 62,
230
+ "umbrella": 25,
231
+ "vase": 75,
232
+ "wine glass": 40,
233
+ "zebra": 22
234
+ },
235
+ "label_noise_ratio": 0.5,
236
+ "layer_norm_eps": 1e-05,
237
+ "learn_initial_query": false,
238
+ "matcher_alpha": 0.25,
239
+ "matcher_bbox_cost": 5.0,
240
+ "matcher_class_cost": 2.0,
241
+ "matcher_gamma": 2.0,
242
+ "matcher_giou_cost": 2.0,
243
+ "model_type": "rt_detr",
244
+ "normalize_before": false,
245
+ "num_denoising": 100,
246
+ "num_feature_levels": 3,
247
+ "num_queries": 300,
248
+ "positional_encoding_temperature": 10000,
249
+ "torch_dtype": "float32",
250
+ "transformers_version": "4.42.0.dev0",
251
+ "use_focal_loss": true,
252
+ "use_pretrained_backbone": false,
253
+ "use_timm_backbone": false,
254
+ "weight_loss_bbox": 5.0,
255
+ "weight_loss_giou": 2.0,
256
+ "weight_loss_vfl": 1.0,
257
+ "with_box_refine": true
258
+ }
person_detector/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:48681f4087d220273d86b052001e19b738d1d1e54f02dfe98d71f4e7957458c5
3
+ size 307331000
pose_encoder/config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "GEMXPoseEncoder",
3
+ "_diffusers_version": "0.44.0.dev0",
4
+ "auto_map": {
5
+ "AutoModel": "pose_encoder_gemx.GEMXPoseEncoder"
6
+ },
7
+ "crop_condition_dim": 3,
8
+ "decoder_dim": 1024,
9
+ "decoder_head_dim": 64,
10
+ "decoder_heads": 8,
11
+ "decoder_mlp_dim": 1024,
12
+ "hidden_size": 1280,
13
+ "init_params_dim": 649,
14
+ "intermediate_size": 5120,
15
+ "layer_norm_eps": 1e-05,
16
+ "num_decoder_layers": 6,
17
+ "num_heads": 20,
18
+ "num_layers": 32,
19
+ "num_register_tokens": 4,
20
+ "patch_size": 16
21
+ }
pose_encoder/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4e65046683c2c4677fcda4f4dd7b183af8bd6064b858959e3d53aaf8034df6d
3
+ size 3522651756
pose_encoder/pose_encoder_gemx.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # Adapted from NVIDIA GEM-X (https://github.com/NVlabs/GEM-X), Apache-2.0, and the DINOv3 ViT of Hugging Face
16
+ # Transformers, Apache-2.0.
17
+
18
+ import math
19
+ from dataclasses import dataclass
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+
25
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
26
+ from diffusers.models.attention import AttentionMixin, AttentionModuleMixin
27
+ from diffusers.models.attention_dispatch import dispatch_attention_fn
28
+ from diffusers.models.modeling_utils import ModelMixin
29
+ from diffusers.utils import BaseOutput
30
+
31
+
32
+ def apply_rotary_emb(hidden_states: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
33
+ """Rotate the patch tokens of `(batch_size, seq_len, heads, head_dim)` states by half-split rotary embeddings of
34
+ shape `(num_patches, head_dim)`; the leading class and register tokens are left unchanged."""
35
+ num_prefix_tokens = hidden_states.shape[1] - cos.shape[0]
36
+ prefix, patches = hidden_states.split((num_prefix_tokens, cos.shape[0]), dim=1)
37
+ first, second = patches.chunk(2, dim=-1)
38
+ rotated = torch.cat((-second, first), dim=-1)
39
+ patches = patches * cos[None, :, None] + rotated * sin[None, :, None]
40
+ return torch.cat((prefix, patches), dim=1)
41
+
42
+
43
+ class GEMXDinoV3AttnProcessor:
44
+ _attention_backend = None
45
+ _parallel_config = None
46
+
47
+ def __call__(
48
+ self,
49
+ attn: "GEMXDinoV3Attention",
50
+ hidden_states: torch.Tensor,
51
+ rotary_emb: tuple[torch.Tensor, torch.Tensor],
52
+ ) -> torch.Tensor:
53
+ query = attn.to_q(hidden_states).unflatten(-1, (attn.heads, -1))
54
+ key = attn.to_k(hidden_states).unflatten(-1, (attn.heads, -1))
55
+ value = attn.to_v(hidden_states).unflatten(-1, (attn.heads, -1))
56
+ query = apply_rotary_emb(query, *rotary_emb)
57
+ key = apply_rotary_emb(key, *rotary_emb)
58
+ hidden_states = dispatch_attention_fn(
59
+ query, key, value, backend=self._attention_backend, parallel_config=self._parallel_config
60
+ )
61
+ return attn.to_out[0](hidden_states.flatten(2, 3))
62
+
63
+
64
+ class GEMXDinoV3Attention(nn.Module, AttentionModuleMixin):
65
+ _default_processor_cls = GEMXDinoV3AttnProcessor
66
+ _available_processors = [GEMXDinoV3AttnProcessor]
67
+
68
+ def __init__(self, dim: int, heads: int):
69
+ super().__init__()
70
+ self.heads = heads
71
+ self.to_q = nn.Linear(dim, dim)
72
+ self.to_k = nn.Linear(dim, dim, bias=False)
73
+ self.to_v = nn.Linear(dim, dim)
74
+ self.to_out = nn.ModuleList([nn.Linear(dim, dim), nn.Dropout(0.0)])
75
+ self.set_processor(GEMXDinoV3AttnProcessor())
76
+
77
+ def forward(self, hidden_states: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
78
+ return self.processor(self, hidden_states, rotary_emb)
79
+
80
+
81
+ class GEMXDinoV3Layer(nn.Module):
82
+ def __init__(self, dim: int, heads: int, intermediate_size: int, layer_norm_eps: float):
83
+ super().__init__()
84
+ self.norm1 = nn.LayerNorm(dim, eps=layer_norm_eps)
85
+ self.attn = GEMXDinoV3Attention(dim, heads)
86
+ self.layer_scale1 = nn.Parameter(torch.ones(dim))
87
+ self.norm2 = nn.LayerNorm(dim, eps=layer_norm_eps)
88
+ self.ff_gate = nn.Linear(dim, intermediate_size)
89
+ self.ff_up = nn.Linear(dim, intermediate_size)
90
+ self.ff_down = nn.Linear(intermediate_size, dim)
91
+ self.layer_scale2 = nn.Parameter(torch.ones(dim))
92
+
93
+ def forward(self, hidden_states: torch.Tensor, rotary_emb: tuple[torch.Tensor, torch.Tensor]) -> torch.Tensor:
94
+ hidden_states = hidden_states + self.attn(self.norm1(hidden_states), rotary_emb) * self.layer_scale1
95
+ norm_hidden_states = self.norm2(hidden_states)
96
+ ff_output = self.ff_down(F.silu(self.ff_gate(norm_hidden_states)) * self.ff_up(norm_hidden_states))
97
+ return hidden_states + ff_output * self.layer_scale2
98
+
99
+
100
+ class GEMXDinoV3RotaryEmbedding(nn.Module):
101
+ """Rotary embedding of the patch grid. The inverse frequencies come from the checkpoint, whose rounded periods
102
+ differ slightly from freshly computed ones."""
103
+
104
+ def __init__(self, head_dim: int, patch_size: int):
105
+ super().__init__()
106
+ self.patch_size = patch_size
107
+ self.register_buffer("inv_freq", torch.ones(head_dim // 4))
108
+
109
+ def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
110
+ height, width = (size // self.patch_size for size in pixel_values.shape[-2:])
111
+ kwargs = {"device": pixel_values.device, "dtype": torch.float32}
112
+ coords_y = torch.arange(0.5, height, **kwargs) / height
113
+ coords_x = torch.arange(0.5, width, **kwargs) / width
114
+ coords = torch.stack(torch.meshgrid(coords_y, coords_x, indexing="ij"), dim=-1).flatten(0, 1)
115
+ coords = 2.0 * coords - 1.0
116
+ angles = 2 * math.pi * coords[:, :, None] * self.inv_freq.float()[None, None, :]
117
+ angles = angles.flatten(1, 2).tile(2)
118
+ return angles.cos().to(pixel_values.dtype), angles.sin().to(pixel_values.dtype)
119
+
120
+
121
+ class GEMXPoseDecoderAttnProcessor:
122
+ _attention_backend = None
123
+ _parallel_config = None
124
+
125
+ def __call__(
126
+ self,
127
+ attn: "GEMXPoseDecoderAttention",
128
+ hidden_states: torch.Tensor,
129
+ encoder_hidden_states: torch.Tensor | None = None,
130
+ ) -> torch.Tensor:
131
+ if encoder_hidden_states is None:
132
+ encoder_hidden_states = hidden_states
133
+ query = attn.to_q(hidden_states).unflatten(-1, (attn.heads, -1))
134
+ key = attn.to_k(encoder_hidden_states).unflatten(-1, (attn.heads, -1))
135
+ value = attn.to_v(encoder_hidden_states).unflatten(-1, (attn.heads, -1))
136
+ hidden_states = dispatch_attention_fn(
137
+ query, key, value, backend=self._attention_backend, parallel_config=self._parallel_config
138
+ )
139
+ return attn.to_out[0](hidden_states.flatten(2, 3))
140
+
141
+
142
+ class GEMXPoseDecoderAttention(nn.Module, AttentionModuleMixin):
143
+ """Self-attention, or cross-attention to `encoder_hidden_states` of width `context_dim`."""
144
+
145
+ _default_processor_cls = GEMXPoseDecoderAttnProcessor
146
+ _available_processors = [GEMXPoseDecoderAttnProcessor]
147
+
148
+ def __init__(self, dim: int, heads: int, head_dim: int, context_dim: int | None = None):
149
+ super().__init__()
150
+ inner_dim = heads * head_dim
151
+ context_dim = context_dim or dim
152
+ self.heads = heads
153
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
154
+ self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
155
+ self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
156
+ self.to_out = nn.ModuleList([nn.Linear(inner_dim, dim), nn.Dropout(0.0)])
157
+ self.set_processor(GEMXPoseDecoderAttnProcessor())
158
+
159
+ def forward(self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor | None = None) -> torch.Tensor:
160
+ return self.processor(self, hidden_states, encoder_hidden_states)
161
+
162
+
163
+ class GEMXPoseDecoderLayer(nn.Module):
164
+ def __init__(self, dim: int, heads: int, head_dim: int, mlp_dim: int, context_dim: int):
165
+ super().__init__()
166
+ self.norm1 = nn.LayerNorm(dim)
167
+ self.attn1 = GEMXPoseDecoderAttention(dim, heads, head_dim)
168
+ self.norm2 = nn.LayerNorm(dim)
169
+ self.attn2 = GEMXPoseDecoderAttention(dim, heads, head_dim, context_dim)
170
+ self.norm3 = nn.LayerNorm(dim)
171
+ self.ff_in = nn.Linear(dim, mlp_dim)
172
+ self.ff_out = nn.Linear(mlp_dim, dim)
173
+
174
+ def forward(self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
175
+ hidden_states = self.attn1(self.norm1(hidden_states)) + hidden_states
176
+ hidden_states = self.attn2(self.norm2(hidden_states), encoder_hidden_states) + hidden_states
177
+ return self.ff_out(F.gelu(self.ff_in(self.norm3(hidden_states)))) + hidden_states
178
+
179
+
180
+ @dataclass
181
+ class GEMXPoseEncoderOutput(BaseOutput):
182
+ """
183
+ Args:
184
+ pose_tokens (`torch.Tensor` of shape `(batch_size, decoder_dim)`):
185
+ The final query token of the Body Pose decoder for every crop.
186
+ """
187
+
188
+ pose_tokens: torch.Tensor
189
+
190
+
191
+ class GEMXPoseEncoder(ModelMixin, ConfigMixin, AttentionMixin):
192
+ """The image part of GEM-X Body Pose: a DINOv3 ViT-H/16+ encoder and the query decoder whose final token is the
193
+ per-frame image feature of the motion model. The pose, shape and camera regression heads of the image model are
194
+ not included."""
195
+
196
+ _no_split_modules = ["GEMXDinoV3Layer", "GEMXPoseDecoderLayer"]
197
+ _repeated_blocks = ["GEMXDinoV3Layer", "GEMXPoseDecoderLayer"]
198
+ _keep_in_fp32_modules = ["rope"]
199
+ _skip_layerwise_casting_patterns = ["patch_embed", "norm", "rope", "init_params"]
200
+
201
+ @register_to_config
202
+ def __init__(
203
+ self,
204
+ patch_size: int = 16,
205
+ hidden_size: int = 1280,
206
+ num_layers: int = 32,
207
+ num_heads: int = 20,
208
+ intermediate_size: int = 5120,
209
+ num_register_tokens: int = 4,
210
+ layer_norm_eps: float = 1e-5,
211
+ init_params_dim: int = 649,
212
+ crop_condition_dim: int = 3,
213
+ decoder_dim: int = 1024,
214
+ num_decoder_layers: int = 6,
215
+ decoder_heads: int = 8,
216
+ decoder_head_dim: int = 64,
217
+ decoder_mlp_dim: int = 1024,
218
+ ):
219
+ super().__init__()
220
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, hidden_size))
221
+ self.register_tokens = nn.Parameter(torch.zeros(1, num_register_tokens, hidden_size))
222
+ self.patch_embed = nn.Conv2d(3, hidden_size, kernel_size=patch_size, stride=patch_size)
223
+ self.rope = GEMXDinoV3RotaryEmbedding(hidden_size // num_heads, patch_size)
224
+ self.layers = nn.ModuleList(
225
+ [GEMXDinoV3Layer(hidden_size, num_heads, intermediate_size, layer_norm_eps) for _ in range(num_layers)]
226
+ )
227
+ self.norm_out = nn.LayerNorm(hidden_size, eps=layer_norm_eps)
228
+
229
+ # The mean pose, shape and camera the Body Pose query starts from.
230
+ self.init_params = nn.Parameter(torch.zeros(1, init_params_dim))
231
+ self.token_proj = nn.Linear(init_params_dim + crop_condition_dim, decoder_dim)
232
+ self.token_pos_embed = nn.Parameter(torch.zeros(1, 1, decoder_dim))
233
+ self.decoder_layers = nn.ModuleList(
234
+ [
235
+ GEMXPoseDecoderLayer(decoder_dim, decoder_heads, decoder_head_dim, decoder_mlp_dim, hidden_size)
236
+ for _ in range(num_decoder_layers)
237
+ ]
238
+ )
239
+
240
+ def forward(
241
+ self, pixel_values: torch.Tensor, crop_conditions: torch.Tensor, return_dict: bool = True
242
+ ) -> GEMXPoseEncoderOutput | tuple[torch.Tensor]:
243
+ """
244
+ Args:
245
+ pixel_values (`torch.Tensor` of shape `(batch_size, 3, 256, 256)`):
246
+ Square person crops, normalized with the ImageNet mean and standard deviation.
247
+ crop_conditions (`torch.Tensor` of shape `(batch_size, 3)`):
248
+ The crop center relative to the principal point and the crop size, all divided by the focal length.
249
+ return_dict (`bool`, defaults to `True`):
250
+ Whether to return a `GEMXPoseEncoderOutput` instead of a tuple.
251
+
252
+ Returns:
253
+ `GEMXPoseEncoderOutput` or a `(pose_tokens,)` tuple.
254
+ """
255
+ batch_size = pixel_values.shape[0]
256
+ pixel_values = pixel_values.to(self.patch_embed.weight.dtype)
257
+ rotary_emb = self.rope(pixel_values)
258
+ patches = self.patch_embed(pixel_values).flatten(2).transpose(1, 2)
259
+ hidden_states = torch.cat(
260
+ (self.cls_token.expand(batch_size, -1, -1), self.register_tokens.expand(batch_size, -1, -1), patches),
261
+ dim=1,
262
+ )
263
+ for layer in self.layers:
264
+ hidden_states = layer(hidden_states, rotary_emb)
265
+ hidden_states = self.norm_out(hidden_states)
266
+ image_features = hidden_states[:, 1 + self.config.num_register_tokens :]
267
+
268
+ token_inputs = torch.cat(
269
+ (self.init_params.expand(batch_size, -1), crop_conditions.to(image_features.dtype)), dim=-1
270
+ )
271
+ tokens = self.token_proj(token_inputs)[:, None] + self.token_pos_embed
272
+ for layer in self.decoder_layers:
273
+ tokens = layer(tokens, image_features)
274
+ pose_tokens = tokens[:, 0]
275
+
276
+ if not return_dict:
277
+ return (pose_tokens,)
278
+ return GEMXPoseEncoderOutput(pose_tokens=pose_tokens)
skeleton/config.json ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "GEMXSOMASkeleton",
3
+ "_diffusers_version": "0.44.0.dev0",
4
+ "auto_map": {
5
+ "AutoModel": "skeleton_gemx.GEMXSOMASkeleton"
6
+ },
7
+ "joint_names": [
8
+ "Hips",
9
+ "Spine1",
10
+ "Spine2",
11
+ "Chest",
12
+ "Neck1",
13
+ "Neck2",
14
+ "Head",
15
+ "HeadEnd",
16
+ "Jaw",
17
+ "LeftEye",
18
+ "RightEye",
19
+ "LeftShoulder",
20
+ "LeftArm",
21
+ "LeftForeArm",
22
+ "LeftHand",
23
+ "LeftHandThumb1",
24
+ "LeftHandThumb2",
25
+ "LeftHandThumb3",
26
+ "LeftHandThumbEnd",
27
+ "LeftHandIndex1",
28
+ "LeftHandIndex2",
29
+ "LeftHandIndex3",
30
+ "LeftHandIndex4",
31
+ "LeftHandIndexEnd",
32
+ "LeftHandMiddle1",
33
+ "LeftHandMiddle2",
34
+ "LeftHandMiddle3",
35
+ "LeftHandMiddle4",
36
+ "LeftHandMiddleEnd",
37
+ "LeftHandRing1",
38
+ "LeftHandRing2",
39
+ "LeftHandRing3",
40
+ "LeftHandRing4",
41
+ "LeftHandRingEnd",
42
+ "LeftHandPinky1",
43
+ "LeftHandPinky2",
44
+ "LeftHandPinky3",
45
+ "LeftHandPinky4",
46
+ "LeftHandPinkyEnd",
47
+ "RightShoulder",
48
+ "RightArm",
49
+ "RightForeArm",
50
+ "RightHand",
51
+ "RightHandThumb1",
52
+ "RightHandThumb2",
53
+ "RightHandThumb3",
54
+ "RightHandThumbEnd",
55
+ "RightHandIndex1",
56
+ "RightHandIndex2",
57
+ "RightHandIndex3",
58
+ "RightHandIndex4",
59
+ "RightHandIndexEnd",
60
+ "RightHandMiddle1",
61
+ "RightHandMiddle2",
62
+ "RightHandMiddle3",
63
+ "RightHandMiddle4",
64
+ "RightHandMiddleEnd",
65
+ "RightHandRing1",
66
+ "RightHandRing2",
67
+ "RightHandRing3",
68
+ "RightHandRing4",
69
+ "RightHandRingEnd",
70
+ "RightHandPinky1",
71
+ "RightHandPinky2",
72
+ "RightHandPinky3",
73
+ "RightHandPinky4",
74
+ "RightHandPinkyEnd",
75
+ "LeftLeg",
76
+ "LeftShin",
77
+ "LeftFoot",
78
+ "LeftToeBase",
79
+ "LeftToeEnd",
80
+ "RightLeg",
81
+ "RightShin",
82
+ "RightFoot",
83
+ "RightToeBase",
84
+ "RightToeEnd"
85
+ ],
86
+ "parents": [
87
+ -1,
88
+ 0,
89
+ 1,
90
+ 2,
91
+ 3,
92
+ 4,
93
+ 5,
94
+ 6,
95
+ 6,
96
+ 6,
97
+ 6,
98
+ 3,
99
+ 11,
100
+ 12,
101
+ 13,
102
+ 14,
103
+ 15,
104
+ 16,
105
+ 17,
106
+ 14,
107
+ 19,
108
+ 20,
109
+ 21,
110
+ 22,
111
+ 14,
112
+ 24,
113
+ 25,
114
+ 26,
115
+ 27,
116
+ 14,
117
+ 29,
118
+ 30,
119
+ 31,
120
+ 32,
121
+ 14,
122
+ 34,
123
+ 35,
124
+ 36,
125
+ 37,
126
+ 3,
127
+ 39,
128
+ 40,
129
+ 41,
130
+ 42,
131
+ 43,
132
+ 44,
133
+ 45,
134
+ 42,
135
+ 47,
136
+ 48,
137
+ 49,
138
+ 50,
139
+ 42,
140
+ 52,
141
+ 53,
142
+ 54,
143
+ 55,
144
+ 42,
145
+ 57,
146
+ 58,
147
+ 59,
148
+ 60,
149
+ 42,
150
+ 62,
151
+ 63,
152
+ 64,
153
+ 65,
154
+ 0,
155
+ 67,
156
+ 68,
157
+ 69,
158
+ 70,
159
+ 0,
160
+ 72,
161
+ 73,
162
+ 74,
163
+ 75
164
+ ]
165
+ }
skeleton/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8a4d8df32e1f0552dba35530ae32e0445f6ea943526ca8f43b675b1b71d36ea8
3
+ size 1036
skeleton/skeleton_gemx.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # The neutral SOMA77 skeleton comes from NVIDIA Kimodo (https://github.com/nv-tlabs/kimodo), Apache-2.0.
16
+
17
+ from dataclasses import dataclass
18
+
19
+ import torch
20
+
21
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
22
+ from diffusers.models.modeling_utils import ModelMixin
23
+ from diffusers.utils import BaseOutput
24
+
25
+
26
+ @dataclass
27
+ class GEMXSOMASkeletonOutput(BaseOutput):
28
+ """
29
+ Args:
30
+ global_rot_mats (`torch.Tensor` of shape `(..., num_joints, 3, 3)`):
31
+ The rotation of every joint in world space.
32
+ posed_joints (`torch.Tensor` of shape `(..., num_joints, 3)`):
33
+ The position of every joint in world space, in meters.
34
+ """
35
+
36
+ global_rot_mats: torch.Tensor
37
+ posed_joints: torch.Tensor
38
+
39
+
40
+ class GEMXSOMASkeleton(ModelMixin, ConfigMixin):
41
+ """The neutral SOMA77 skeleton of Kimodo, Y up and facing +Z at rest. Joints are listed parents first. Its local
42
+ rotations are the SOMA body pose parameters: the root rotation followed by the 76 body joint rotations."""
43
+
44
+ @register_to_config
45
+ def __init__(self, joint_names: list[str], parents: list[int]):
46
+ super().__init__()
47
+ self.register_buffer("neutral_joints", torch.zeros(len(joint_names), 3))
48
+
49
+ def forward(
50
+ self, local_rot_mats: torch.Tensor, root_positions: torch.Tensor, return_dict: bool = True
51
+ ) -> GEMXSOMASkeletonOutput | tuple[torch.Tensor, torch.Tensor]:
52
+ """
53
+ Args:
54
+ local_rot_mats (`torch.Tensor` of shape `(..., num_joints, 3, 3)`):
55
+ The rotation of every joint relative to its parent.
56
+ root_positions (`torch.Tensor` of shape `(..., 3)`):
57
+ The world position of the root joint, in meters.
58
+ return_dict (`bool`, defaults to `True`):
59
+ Whether to return a `GEMXSOMASkeletonOutput` instead of a tuple.
60
+
61
+ Returns:
62
+ `GEMXSOMASkeletonOutput` or a `(global_rot_mats, posed_joints)` tuple.
63
+ """
64
+ neutral_joints = self.neutral_joints.to(local_rot_mats.dtype)
65
+ global_rot_mats, posed_joints = [], []
66
+ for joint, parent in enumerate(self.config.parents):
67
+ if parent < 0:
68
+ global_rot_mats.append(local_rot_mats[..., joint, :, :])
69
+ posed_joints.append(root_positions)
70
+ continue
71
+ offset = neutral_joints[joint] - neutral_joints[parent]
72
+ global_rot_mats.append(global_rot_mats[parent] @ local_rot_mats[..., joint, :, :])
73
+ posed_joints.append(posed_joints[parent] + global_rot_mats[parent] @ offset)
74
+ global_rot_mats = torch.stack(global_rot_mats, dim=-3)
75
+ posed_joints = torch.stack(posed_joints, dim=-2)
76
+
77
+ if not return_dict:
78
+ return (global_rot_mats, posed_joints)
79
+ return GEMXSOMASkeletonOutput(global_rot_mats=global_rot_mats, posed_joints=posed_joints)