OzzyGT HF Staff commited on
Commit
25496a5
·
1 Parent(s): 66e51fa

add blocks

Browse files
Files changed (11) hide show
  1. LICENSE +202 -0
  2. NOTICE +11 -0
  3. README.md +118 -0
  4. __init__.py +0 -0
  5. decoders.py +214 -0
  6. encoders.py +176 -0
  7. generation.py +215 -0
  8. modular_blocks_motionbricks.py +94 -0
  9. modular_config.json +10 -0
  10. modular_model_index.json +4 -0
  11. motion_utils.py +421 -0
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,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MotionBricks SOMA Modular Diffusers
2
+ Copyright 2026 The HuggingFace Team.
3
+
4
+ The guide encoding, root and output feature decoding, and endpoint correction in motion_utils.py are adapted from
5
+ NVIDIA MotionBricks (https://github.com/NVlabs/motionbricks):
6
+
7
+ SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
8
+ SPDX-License-Identifier: Apache-2.0
9
+
10
+ The MotionBricks model weights are not part of this repository. They are licensed under the NVIDIA Open Model
11
+ Agreement: https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-agreement/
README.md ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: apache-2.0
5
+ base_model:
6
+ - nvidia/MotionBricks
7
+ library_name: diffusers
8
+ tags:
9
+ - motion-generation
10
+ - motion-inbetweening
11
+ - motionbricks
12
+ - modular-diffusers
13
+ - soma
14
+ ---
15
+
16
+ # MotionBricks SOMA Modular Diffusers
17
+
18
+ <video controls loop muted playsinline src="https://huggingface.co/datasets/OzzyGT/diffusers-examples/resolve/main/motionbricks_soma_diffusers/motionbricks_soma_run_stop.mp4"></video>
19
+
20
+ *The start of a Kimodo run, then the 30 frames generated with the code below, then the standing end of another Kimodo take, placed 1.4 m ahead. The generated frames are drawn on SOMA77 with a relaxed finger pose. At normal playback speed; the cameras follow the root.*
21
+
22
+ Modular Diffusers blocks for [NVIDIA MotionBricks](https://huggingface.co/nvidia/MotionBricks) on the SOMA skeleton: generate the transition from the last poses of one motion to the first poses of another in a single forward pass, with no sampling loop. The model code and weights are in [OzzyGT/motionbricks_soma_diffusers](https://huggingface.co/OzzyGT/motionbricks_soma_diffusers).
23
+
24
+ MotionBricks has no text input. It fills the gap between poses you provide, for example two motions from [Kimodo SOMA Modular](https://huggingface.co/OzzyGT/Kimodo_SOMA_Modular), and chooses the length of the transition itself.
25
+
26
+ Requires PyTorch, `diffusers>=0.41.0` and `numpy`.
27
+
28
+ ## Licensing
29
+
30
+ The blocks are [Apache-2.0](LICENSE), adapted from the [MotionBricks runtime](https://github.com/NVlabs/motionbricks). See [NOTICE](NOTICE). This repository contains no model weights; they use the [NVIDIA Open Model Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-agreement/), see the [model repository](https://huggingface.co/OzzyGT/motionbricks_soma_diffusers).
31
+
32
+ ## Usage
33
+
34
+ The example uses `trust_remote_code=True`, which loads these blocks, and `trust_components_code=True`, which allows the model repository's custom classes.
35
+
36
+ > **Note:** both flags run Python code downloaded from the Hub: `trust_remote_code=True` runs the code of the blocks repository, and `trust_components_code=True` runs the code shipped in the `components_repo`. Only use them with repositories you trust, and review their code before passing different ones.
37
+
38
+ Bring a run to a stop, as in the video. Both clips come from [Kimodo SOMA Modular](https://huggingface.co/OzzyGT/Kimodo_SOMA_Modular): the start of a run, and a standing pose that the pipeline places 1.4 m ahead of it:
39
+
40
+ ```python
41
+ import numpy as np
42
+ import torch
43
+ from diffusers import ModularPipelineBlocks
44
+ from huggingface_hub import hf_hub_download
45
+
46
+ blocks = ModularPipelineBlocks.from_pretrained(
47
+ "OzzyGT/motionbricks_soma_custom_blocks",
48
+ trust_remote_code=True,
49
+ components_repo="OzzyGT/motionbricks_soma_diffusers",
50
+ trust_components_code=True,
51
+ )
52
+ pipe = blocks.init_pipeline()
53
+ pipe.load_components(dtype=torch.float32)
54
+ pipe.to("cuda")
55
+
56
+ first = hf_hub_download("OzzyGT/diffusers-examples", "motionbricks_soma_diffusers/first.npz", repo_type="dataset")
57
+ second = hf_hub_download("OzzyGT/diffusers-examples", "motionbricks_soma_diffusers/second.npz", repo_type="dataset")
58
+ context = dict(np.load(first))
59
+ target = dict(np.load(second))
60
+
61
+ motion = pipe(context=context, target=target, target_offset=(1.4, 0.0), num_target_poses=4, output="motion")[0]
62
+ np.savez_compressed("transition.npz", **{key: value.cpu().numpy() for key, value in motion.items()})
63
+ ```
64
+
65
+ Here the model picks a 30-frame transition.
66
+
67
+ ### Inputs
68
+
69
+ - `context`: the motion to continue from.
70
+ - `target`: the motion to arrive at.
71
+ - `target_offset`: where `target` starts, `(forward, left)` in meters from the end of `context`.
72
+ - `target_turn`: which way `target` faces, in degrees from the end of `context`, positive to the left.
73
+ - `num_target_poses`: how many frames of `target` to match, 1 to 4. Default 1.
74
+ - `num_tokens`: the lengths the model may choose. Default 26 to 50 frames.
75
+ - `correct_endpoints`: start and end exactly on the given poses. Default `True`.
76
+
77
+ ### Notes
78
+
79
+ - **Motions.** `context` and `target` are SOMA30 or SOMA77 motions at 30 FPS, such as Kimodo output loaded from an NPZ. The result is a SOMA30 motion.
80
+ - **Joining.** The transition starts on the last frame of `context` and ends on the first frame of `target`, so cut them where they should join. Ask for `output=["motion", "placed_target"]` to also get `target` where the pipeline placed it, to join the three motions.
81
+ - **Placement.** Without `target_offset` or `target_turn`, `target` stays where it is. With only one of them, the other is 0.
82
+ - **Target poses.** The model always reads the last 4 frames of `context` and the first `num_target_poses` frames of `target`, consecutive frames, to see how the body moves at each end. Use 4 whenever `target` has at least 4 frames, so the transition also matches how `target` moves; use 1 when it is a single pose.
83
+ - **Length.** `num_tokens` counts in steps of 4 frames, from 6 to 16; `n` tokens give `4 * n - 6` frames. Pass one value to fix the length.
84
+ - **Longer transitions.** Feed the generated motion back as the next `context`.
85
+
86
+ A call takes about 7.5 ms in float32 on an RTX 5090 and peaks at 0.8 GB of VRAM.
87
+
88
+ ## Precision
89
+
90
+ The weights are float32, and float32 reproduces NVIDIA's ONNX graph with PyTorch's default settings. Enabling TF32 matrix multiplication (`torch.backends.cuda.matmul.allow_tf32 = True`) can change a few pose codes. `dtype=torch.float16` halves the memory and is a little faster, with small drift: in a test of 8 transitions, every length matched float32 and joints moved by about 4 cm in the median. Avoid `torch.bfloat16`, which drifts much more. NVIDIA notes the same drift in its mixed FP16 model, and it grows when the output is fed back as context.
91
+
92
+ ## Real-time use
93
+
94
+ These blocks bring MotionBricks to apps and environments that already run on Diffusers. For a real-time product, such as a game or a robot, prefer NVIDIA's [MotionBricks runtime](https://github.com/NVlabs/motionbricks), which runs the ONNX models through TensorRT. With the blocks, about half of each call is Python and data preparation rather than GPU work.
95
+
96
+ To generate transitions while the motion plays in a Diffusers app, keep the pipeline loaded and capture the three models in CUDA graphs. On an RTX 5090, a call then takes about 4.5 ms instead of 7.5 ms.
97
+
98
+ Compile while loading, not in the loop: the first call compiles the models in about 15 seconds, and the second records the graphs.
99
+
100
+ ```python
101
+ for name in ("root_model", "pose_model", "pose_decoder"):
102
+ getattr(pipe, name).compile(mode="reduce-overhead", fullgraph=True)
103
+
104
+ for _ in range(2):
105
+ torch.compiler.cudagraph_mark_step_begin()
106
+ pipe(context=context, target=target, target_offset=(1.4, 0.0), num_target_poses=4, output="motion")
107
+ ```
108
+
109
+ Then, whenever a transition is needed:
110
+
111
+ ```python
112
+ torch.compiler.cudagraph_mark_step_begin()
113
+ motion = pipe(context=context, target=target, target_offset=(1.4, 0.0), num_target_poses=4, output="motion")[0]
114
+ ```
115
+
116
+ - Call `torch.compiler.cudagraph_mark_step_begin()` before every call, so the graphs can reuse their memory; without it, the second call fails.
117
+ - New clips, target placements, `num_target_poses`, `num_tokens` and `correct_endpoints` reuse the graphs. The first new batch size compiles again, once, in about 20 seconds; later sizes don't.
118
+ - Several characters, or several candidates for one character such as different stop distances, fit in one call: stack their motions on a leading batch dimension. Each gets its own transition and length, matching separate calls to within 0.01 mm. With CUDA graphs, a batch of 4 takes about 5.5 ms and a batch of 8 about 6 ms, against 4.5 ms for one.
__init__.py ADDED
File without changes
decoders.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
4
+
5
+ import torch
6
+
7
+ from diffusers import AutoModel
8
+ from diffusers.modular_pipelines import ModularPipelineBlocks, PipelineState
9
+ from diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParam
10
+
11
+ from .motion_utils import CONTEXT_FRAMES, decode_poses, integrate_local_root, select_root
12
+
13
+
14
+ class MotionBricksDecodeStep(ModularPipelineBlocks):
15
+ model_name = "motionbricks"
16
+
17
+ @property
18
+ def description(self) -> str:
19
+ return (
20
+ "Decode step that decodes the pose codes to frame features and integrates their local root into a global "
21
+ "one. When the decoded root height misses the target poses by more than 5 cm and the root step's is "
22
+ "closer, the root step's trajectory is kept."
23
+ )
24
+
25
+ @property
26
+ def expected_components(self) -> list[ComponentSpec]:
27
+ return [ComponentSpec("root_model", AutoModel), ComponentSpec("pose_decoder", AutoModel)]
28
+
29
+ @property
30
+ def inputs(self) -> list[InputParam]:
31
+ return [
32
+ InputParam(
33
+ "pose_codes",
34
+ required=True,
35
+ type_hint=torch.Tensor,
36
+ description="`(batch_size, 16, 5)` pose codes. Can be generated in the pose tokens step.",
37
+ ),
38
+ InputParam(
39
+ "pose_timeline",
40
+ required=True,
41
+ type_hint=torch.Tensor,
42
+ description="`(batch_size, 64, 268)` normalized guide poses on the frame timeline. Can be generated "
43
+ "in the pose tokens step.",
44
+ ),
45
+ InputParam(
46
+ "has_pose_timeline",
47
+ required=True,
48
+ type_hint=torch.Tensor,
49
+ description="`(batch_size, 64)` frames with a guide pose. Can be generated in the pose tokens step.",
50
+ ),
51
+ InputParam(
52
+ "local_root",
53
+ required=True,
54
+ type_hint=torch.Tensor,
55
+ description="`(batch_size, 64, 4)` normalized local root. Can be generated in the pose tokens step.",
56
+ ),
57
+ InputParam(
58
+ "motion_tokens",
59
+ required=True,
60
+ type_hint=torch.Tensor,
61
+ description="`(batch_size,)` motion lengths in tokens. Can be generated in the root step.",
62
+ ),
63
+ InputParam(
64
+ "root",
65
+ required=True,
66
+ type_hint=torch.Tensor,
67
+ description="`(batch_size, 64, 5)` normalized global root. Can be generated in the root step.",
68
+ ),
69
+ InputParam(
70
+ "guide_root",
71
+ required=True,
72
+ type_hint=torch.Tensor,
73
+ description="`(batch_size, 8, 5)` aligned global root of the guide poses. Can be generated in the "
74
+ "guides step.",
75
+ ),
76
+ InputParam(
77
+ "has_global_root",
78
+ required=True,
79
+ type_hint=torch.Tensor,
80
+ description="`(batch_size, 8)` guide poses with a global root. Can be generated in the guides step.",
81
+ ),
82
+ ]
83
+
84
+ @property
85
+ def intermediate_outputs(self) -> list[OutputParam]:
86
+ return [
87
+ OutputParam(
88
+ "motion_features",
89
+ type_hint=torch.Tensor,
90
+ description="`(batch_size, 64, 366)` float32 features in the aligned space: global root, child joint "
91
+ "positions, 6D global rotations, joint velocities and foot contacts.",
92
+ ),
93
+ ]
94
+
95
+ @torch.no_grad()
96
+ def __call__(self, components, state: PipelineState) -> PipelineState:
97
+ block_state = self.get_block_state(state)
98
+ root_model, pose_decoder = components.root_model, components.pose_decoder
99
+ num_tokens, guide_root = block_state.motion_tokens, block_state.guide_root
100
+ dtype = pose_decoder.dtype
101
+
102
+ features = pose_decoder(
103
+ block_state.pose_codes,
104
+ num_tokens,
105
+ block_state.pose_timeline.to(dtype),
106
+ block_state.has_pose_timeline,
107
+ block_state.local_root[..., 1:3].to(dtype),
108
+ ).features
109
+ features = pose_decoder.denormalize(features.float())
110
+ decoded_root = integrate_local_root(features[..., :4])
111
+ predicted_root = root_model.denormalize(block_state.root.float(), "global_root")
112
+ root = select_root(
113
+ decoded_root,
114
+ predicted_root,
115
+ guide_root[:, CONTEXT_FRAMES:, 1],
116
+ block_state.has_global_root[:, CONTEXT_FRAMES:],
117
+ num_tokens,
118
+ )
119
+ # Both roots start at the first context pose's ground position and heading.
120
+ angle = torch.atan2(root[..., 4], root[..., 3]) + torch.atan2(guide_root[:, :1, 4], guide_root[:, :1, 3])
121
+ origin = guide_root[:, :1]
122
+ root = torch.stack(
123
+ [
124
+ root[..., 0] + origin[..., 0],
125
+ root[..., 1],
126
+ root[..., 2] + origin[..., 2],
127
+ torch.cos(angle),
128
+ torch.sin(angle),
129
+ ],
130
+ dim=-1,
131
+ )
132
+ block_state.motion_features = torch.cat([root, features[..., 4:]], dim=-1)
133
+ self.set_block_state(state, block_state)
134
+ return components, state
135
+
136
+
137
+ class MotionBricksPostprocessStep(ModularPipelineBlocks):
138
+ model_name = "motionbricks"
139
+
140
+ @property
141
+ def description(self) -> str:
142
+ return (
143
+ "Postprocess step that drops the three boundary frames at each end, builds world-space SOMA30 poses by "
144
+ "forward kinematics on the skeleton's neutral bone offsets and, by default, blends corrections so the "
145
+ "motion starts at the last context pose and ends at the first target pose."
146
+ )
147
+
148
+ @property
149
+ def expected_components(self) -> list[ComponentSpec]:
150
+ return [ComponentSpec("pose_decoder", AutoModel)]
151
+
152
+ @property
153
+ def inputs(self) -> list[InputParam]:
154
+ return [
155
+ InputParam(
156
+ "correct_endpoints",
157
+ default=True,
158
+ type_hint=bool,
159
+ description="Blend the motion onto the last context pose and the first target pose. `False` keeps the "
160
+ "predicted endpoints.",
161
+ ),
162
+ InputParam(
163
+ "motion_features",
164
+ required=True,
165
+ type_hint=torch.Tensor,
166
+ description="`(batch_size, 64, 366)` frame features in the aligned space. Can be generated in the "
167
+ "decode step.",
168
+ ),
169
+ InputParam(
170
+ "motion_tokens",
171
+ required=True,
172
+ type_hint=torch.Tensor,
173
+ description="`(batch_size,)` motion lengths in tokens. Can be generated in the root step.",
174
+ ),
175
+ InputParam(
176
+ "alignment",
177
+ required=True,
178
+ type_hint=tuple,
179
+ description="`(origin, yaw)` from the aligned space back to the input space. Can be generated in the "
180
+ "guides step.",
181
+ ),
182
+ InputParam(
183
+ "endpoints",
184
+ required=True,
185
+ type_hint=dict,
186
+ description="Local rotations and root positions of the last context pose and the first target pose. "
187
+ "Can be generated in the guides step.",
188
+ ),
189
+ ]
190
+
191
+ @property
192
+ def intermediate_outputs(self) -> list[OutputParam]:
193
+ return [
194
+ OutputParam(
195
+ "motion",
196
+ type_hint=list[dict[str, torch.Tensor]],
197
+ description="One SOMA30 motion per batch item, 30 FPS, meters, +Y up, in the input space: "
198
+ "`posed_joints` `(frames, 30, 3)`, `global_rot_mats` and `local_rot_mats` `(frames, 30, 3, 3)`, "
199
+ "`root_positions` `(frames, 3)` and `foot_contacts` `(frames, 4)` with the left heel, left toe, right "
200
+ "heel and right toe contact confidences.",
201
+ ),
202
+ ]
203
+
204
+ @torch.no_grad()
205
+ def __call__(self, components, state: PipelineState) -> PipelineState:
206
+ block_state = self.get_block_state(state)
207
+ features = block_state.motion_features
208
+ neutral_joints = components.pose_decoder.neutral_joints.to(features.device, torch.float32)
209
+ endpoints = block_state.endpoints if block_state.correct_endpoints else None
210
+ block_state.motion = decode_poses(
211
+ features, block_state.motion_tokens, block_state.alignment, neutral_joints, endpoints
212
+ )
213
+ self.set_block_state(state, block_state)
214
+ return components, state
encoders.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
4
+
5
+ import torch
6
+
7
+ from diffusers import AutoModel
8
+ from diffusers.modular_pipelines import ModularPipelineBlocks, PipelineState
9
+ from diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParam
10
+
11
+ from .motion_utils import (
12
+ CONTEXT_FRAMES,
13
+ TARGET_FRAMES,
14
+ encode_guides,
15
+ guide_masks,
16
+ local_rotations,
17
+ place_target,
18
+ soma30,
19
+ )
20
+
21
+
22
+ MOTION_DESCRIPTION = (
23
+ "`posed_joints` `(frames, joints, 3)` and `global_rot_mats` `(frames, joints, 3, 3)`, optionally with a leading "
24
+ "batch dimension: SOMA30 or SOMA77 joints at 30 FPS, in meters with +Y up, with the rotations of Kimodo SOMA "
25
+ "motions (the identity is the neutral pose)."
26
+ )
27
+
28
+
29
+ def _motion(motion: dict, device: torch.device) -> tuple[torch.Tensor, torch.Tensor]:
30
+ positions = torch.as_tensor(motion["posed_joints"], device=device, dtype=torch.float32)
31
+ rotations = torch.as_tensor(motion["global_rot_mats"], device=device, dtype=torch.float32)
32
+ if positions.ndim == 3:
33
+ positions, rotations = positions[None], rotations[None]
34
+ return positions, rotations
35
+
36
+
37
+ class MotionBricksGuidesStep(ModularPipelineBlocks):
38
+ model_name = "motionbricks"
39
+
40
+ @property
41
+ def description(self) -> str:
42
+ return (
43
+ "Guide step that optionally places the target relative to the end of the context, then turns the last "
44
+ "four poses of the context and the first target poses into the model's normalized root and pose "
45
+ "features. The poses are turned so the last context pose faces +X."
46
+ )
47
+
48
+ @property
49
+ def expected_components(self) -> list[ComponentSpec]:
50
+ return [ComponentSpec("root_model", AutoModel)]
51
+
52
+ @property
53
+ def inputs(self) -> list[InputParam]:
54
+ return [
55
+ InputParam(
56
+ "context",
57
+ required=True,
58
+ type_hint=dict,
59
+ description="The motion to continue from; its last four frames are used. " + MOTION_DESCRIPTION,
60
+ ),
61
+ InputParam(
62
+ "target",
63
+ required=True,
64
+ type_hint=dict,
65
+ description="The motion to reach; its first `num_target_poses` frames are used. " + MOTION_DESCRIPTION,
66
+ ),
67
+ InputParam(
68
+ "num_target_poses",
69
+ default=1,
70
+ type_hint=int,
71
+ description="How many target poses to reach, 1 to 4. One pose sets where the motion ends; more also "
72
+ "set how it moves there.",
73
+ ),
74
+ InputParam(
75
+ "target_offset",
76
+ type_hint=tuple,
77
+ description="Where the first target pose stands, `(forward, left)` in meters from the last context "
78
+ "pose, along the direction the context faces; one pair, or one per batch item. With `target_offset` "
79
+ "or `target_turn`, `target` is moved and turned there; without either, it is used where it is.",
80
+ ),
81
+ InputParam(
82
+ "target_turn",
83
+ type_hint=float,
84
+ description="Which way the first target pose faces, in degrees relative to the last context pose, "
85
+ "positive to the left; one value, or one per batch item. Defaults to 0 when only `target_offset` is "
86
+ "given.",
87
+ ),
88
+ ]
89
+
90
+ @property
91
+ def intermediate_outputs(self) -> list[OutputParam]:
92
+ return [
93
+ OutputParam("guide_root", type_hint=torch.Tensor, description="`(batch_size, 8, 5)` aligned global root."),
94
+ OutputParam("guide_global_root", type_hint=torch.Tensor, description="Normalized, centered global root."),
95
+ OutputParam("guide_local_root", type_hint=torch.Tensor, description="Normalized local root."),
96
+ OutputParam("guide_pose", type_hint=torch.Tensor, description="`(batch_size, 8, 268)` normalized pose."),
97
+ OutputParam("has_global_root", type_hint=torch.Tensor, description="`(batch_size, 8)` given roots."),
98
+ OutputParam("has_local_root", type_hint=torch.Tensor, description="`(batch_size, 8)` given local roots."),
99
+ OutputParam("has_pose", type_hint=torch.Tensor, description="`(batch_size, 8)` given poses."),
100
+ OutputParam("alignment", type_hint=tuple, description="`(origin, yaw)` back to the input space."),
101
+ OutputParam(
102
+ "placed_target",
103
+ type_hint=list,
104
+ description="`target` as used, one dict per batch item with all its frames and joints: "
105
+ "`posed_joints` and `global_rot_mats`, moved by `target_offset` and `target_turn`.",
106
+ ),
107
+ OutputParam(
108
+ "endpoints",
109
+ type_hint=dict,
110
+ description="Local rotations and root positions of the last context pose and the first target pose.",
111
+ ),
112
+ ]
113
+
114
+ @torch.no_grad()
115
+ def __call__(self, components, state: PipelineState) -> PipelineState:
116
+ block_state = self.get_block_state(state)
117
+ root_model = components.root_model
118
+ device = components._execution_device
119
+ num_targets = block_state.num_target_poses
120
+ if not 1 <= num_targets <= TARGET_FRAMES:
121
+ raise ValueError(f"`num_target_poses` must be 1 to {TARGET_FRAMES}, got {num_targets}")
122
+
123
+ context_positions, context_rotations = _motion(block_state.context, device)
124
+ target_positions, target_rotations = _motion(block_state.target, device)
125
+ if context_positions.shape[1] < CONTEXT_FRAMES:
126
+ raise ValueError(f"`context` needs at least {CONTEXT_FRAMES} frames, got {context_positions.shape[1]}")
127
+ if context_positions.shape[0] != target_positions.shape[0]:
128
+ raise ValueError("`context` and `target` must have the same batch size")
129
+ if target_positions.shape[1] < num_targets:
130
+ raise ValueError(f"`target` has {target_positions.shape[1]} frames, fewer than `num_target_poses`")
131
+ context_positions = soma30(context_positions[:, -CONTEXT_FRAMES:], 2)
132
+ context_rotations = soma30(context_rotations[:, -CONTEXT_FRAMES:], 2)
133
+ if block_state.target_offset is not None or block_state.target_turn is not None:
134
+ batch_size = target_positions.shape[0]
135
+ offset = (0.0, 0.0) if block_state.target_offset is None else block_state.target_offset
136
+ turn = 0.0 if block_state.target_turn is None else block_state.target_turn
137
+ offset = torch.as_tensor(offset, device=device, dtype=torch.float32).reshape(-1, 2).expand(batch_size, 2)
138
+ turn = torch.deg2rad(torch.as_tensor(turn, device=device, dtype=torch.float32).reshape(-1))
139
+ target_positions, target_rotations = place_target(
140
+ target_positions, target_rotations, context_positions[:, -1], offset, turn.expand(batch_size)
141
+ )
142
+ block_state.placed_target = [
143
+ {"posed_joints": positions, "global_rot_mats": rotations}
144
+ for positions, rotations in zip(target_positions, target_rotations)
145
+ ]
146
+ target_positions = soma30(target_positions[:, :num_targets], 2)
147
+ target_rotations = soma30(target_rotations[:, :num_targets], 2)
148
+ # Unused target slots repeat the last target pose.
149
+ target_index = torch.arange(TARGET_FRAMES, device=device).clamp(max=num_targets - 1)
150
+ positions = torch.cat([context_positions, target_positions[:, target_index]], 1)
151
+ rotations = torch.cat([context_rotations, target_rotations[:, target_index]], 1)
152
+
153
+ global_root, local_root, pose, alignment = encode_guides(positions, rotations)
154
+ centered = global_root.clone()
155
+ centered[..., 0:3:2] -= global_root[:, :1, 0:3:2]
156
+ batch_size = positions.shape[0]
157
+ has_global_root, has_local_root, has_pose = guide_masks(torch.full((batch_size,), num_targets, device=device))
158
+
159
+ dtype = root_model.dtype
160
+ block_state.guide_root = global_root
161
+ block_state.guide_global_root = root_model.normalize(centered.to(dtype), "global_root")
162
+ block_state.guide_local_root = root_model.normalize(local_root.to(dtype), "local_root")
163
+ block_state.guide_pose = root_model.normalize(torch.cat([centered[..., 1:2], pose], -1).to(dtype), "pose")
164
+ block_state.has_global_root = has_global_root
165
+ block_state.has_local_root = has_local_root
166
+ block_state.has_pose = has_pose
167
+ block_state.alignment = alignment
168
+ block_state.endpoints = {
169
+ "context_local": local_rotations(rotations[:, CONTEXT_FRAMES - 1]),
170
+ "context_root": positions[:, CONTEXT_FRAMES - 1, 0],
171
+ "target_local": local_rotations(rotations[:, CONTEXT_FRAMES]),
172
+ "target_root": positions[:, CONTEXT_FRAMES, 0],
173
+ }
174
+
175
+ self.set_block_state(state, block_state)
176
+ return components, state
generation.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
4
+
5
+ import functools
6
+
7
+ import torch
8
+
9
+ from diffusers import AutoModel
10
+ from diffusers.modular_pipelines import ModularPipelineBlocks, PipelineState
11
+ from diffusers.modular_pipelines.modular_pipeline_utils import ComponentSpec, InputParam, OutputParam
12
+
13
+ from .motion_utils import FRAMES_PER_TOKEN, root_to_local
14
+
15
+
16
+ @functools.cache
17
+ def allowed_lengths(min_tokens: int, max_tokens: int, num_tokens: tuple, device: torch.device) -> torch.Tensor:
18
+ """`(1, lengths)` mask of the allowed lengths among `min_tokens` to `max_tokens`."""
19
+ lengths = torch.arange(min_tokens, max_tokens + 1)
20
+ return torch.isin(lengths, torch.tensor(num_tokens))[None].to(device)
21
+
22
+
23
+ class MotionBricksRootStep(ModularPipelineBlocks):
24
+ model_name = "motionbricks"
25
+
26
+ @property
27
+ def description(self) -> str:
28
+ return (
29
+ "Root step that chooses the length of the transition among the allowed ones and predicts the root "
30
+ "trajectory of every frame."
31
+ )
32
+
33
+ @property
34
+ def expected_components(self) -> list[ComponentSpec]:
35
+ return [ComponentSpec("root_model", AutoModel)]
36
+
37
+ @property
38
+ def inputs(self) -> list[InputParam]:
39
+ return [
40
+ InputParam(
41
+ "num_tokens",
42
+ default=list(range(8, 15)),
43
+ type_hint=int | list[int],
44
+ description="The transition lengths the model may choose, in tokens of 4 frames, from 6 to 16. A "
45
+ "length of `n` tokens gives `4 * n - 6` frames.",
46
+ ),
47
+ InputParam(
48
+ "guide_global_root",
49
+ required=True,
50
+ type_hint=torch.Tensor,
51
+ description="`(batch_size, 8, 5)` normalized global root of the guide poses. Can be generated in the "
52
+ "guides step.",
53
+ ),
54
+ InputParam(
55
+ "guide_local_root",
56
+ required=True,
57
+ type_hint=torch.Tensor,
58
+ description="`(batch_size, 8, 4)` normalized local root of the guide poses. Can be generated in the "
59
+ "guides step.",
60
+ ),
61
+ InputParam(
62
+ "guide_pose",
63
+ required=True,
64
+ type_hint=torch.Tensor,
65
+ description="`(batch_size, 8, 268)` normalized pose features of the guide poses. Can be generated in "
66
+ "the guides step.",
67
+ ),
68
+ InputParam(
69
+ "has_global_root",
70
+ required=True,
71
+ type_hint=torch.Tensor,
72
+ description="`(batch_size, 8)` guide poses with a global root. Can be generated in the guides step.",
73
+ ),
74
+ InputParam(
75
+ "has_local_root",
76
+ required=True,
77
+ type_hint=torch.Tensor,
78
+ description="`(batch_size, 8)` guide poses with a local root. Can be generated in the guides step.",
79
+ ),
80
+ InputParam(
81
+ "has_pose",
82
+ required=True,
83
+ type_hint=torch.Tensor,
84
+ description="`(batch_size, 8)` guide poses with pose features. Can be generated in the guides step.",
85
+ ),
86
+ ]
87
+
88
+ @property
89
+ def intermediate_outputs(self) -> list[OutputParam]:
90
+ return [
91
+ OutputParam("motion_tokens", type_hint=torch.Tensor, description="`(batch_size,)` chosen lengths."),
92
+ OutputParam("root", type_hint=torch.Tensor, description="`(batch_size, 64, 5)` normalized global root."),
93
+ ]
94
+
95
+ @torch.no_grad()
96
+ def __call__(self, components, state: PipelineState) -> PipelineState:
97
+ block_state = self.get_block_state(state)
98
+ root_model = components.root_model
99
+ config = root_model.config
100
+ num_tokens = block_state.num_tokens
101
+ num_tokens = [num_tokens] if isinstance(num_tokens, int) else list(num_tokens)
102
+ if not num_tokens or not all(config.min_tokens <= n <= config.max_tokens for n in num_tokens):
103
+ raise ValueError(f"`num_tokens` must be in {config.min_tokens} to {config.max_tokens}, got {num_tokens}")
104
+ allowed = allowed_lengths(
105
+ config.min_tokens, config.max_tokens, tuple(num_tokens), block_state.guide_pose.device
106
+ ).expand(block_state.guide_pose.shape[0], -1)
107
+
108
+ output = root_model(
109
+ block_state.guide_global_root,
110
+ block_state.guide_local_root,
111
+ block_state.guide_pose,
112
+ block_state.has_global_root,
113
+ block_state.has_local_root,
114
+ block_state.has_pose,
115
+ allowed,
116
+ )
117
+ block_state.motion_tokens = output.num_tokens
118
+ block_state.root = output.root
119
+ self.set_block_state(state, block_state)
120
+ return components, state
121
+
122
+
123
+ class MotionBricksPoseTokensStep(ModularPipelineBlocks):
124
+ model_name = "motionbricks"
125
+
126
+ @property
127
+ def description(self) -> str:
128
+ return (
129
+ "Pose step that places the guide poses on the frame timeline and predicts the pose codes of every token "
130
+ "in one pass of the masked token transformer."
131
+ )
132
+
133
+ @property
134
+ def expected_components(self) -> list[ComponentSpec]:
135
+ return [ComponentSpec("root_model", AutoModel), ComponentSpec("pose_model", AutoModel)]
136
+
137
+ @property
138
+ def inputs(self) -> list[InputParam]:
139
+ return [
140
+ InputParam(
141
+ "guide_local_root",
142
+ required=True,
143
+ type_hint=torch.Tensor,
144
+ description="`(batch_size, 8, 4)` normalized local root of the guide poses. Can be generated in the "
145
+ "guides step.",
146
+ ),
147
+ InputParam(
148
+ "guide_pose",
149
+ required=True,
150
+ type_hint=torch.Tensor,
151
+ description="`(batch_size, 8, 268)` normalized pose features of the guide poses. Can be generated in "
152
+ "the guides step.",
153
+ ),
154
+ InputParam(
155
+ "has_local_root",
156
+ required=True,
157
+ type_hint=torch.Tensor,
158
+ description="`(batch_size, 8)` guide poses with a local root. Can be generated in the guides step.",
159
+ ),
160
+ InputParam(
161
+ "has_pose",
162
+ required=True,
163
+ type_hint=torch.Tensor,
164
+ description="`(batch_size, 8)` guide poses with pose features. Can be generated in the guides step.",
165
+ ),
166
+ InputParam(
167
+ "motion_tokens",
168
+ required=True,
169
+ type_hint=torch.Tensor,
170
+ description="`(batch_size,)` motion lengths in tokens. Can be generated in the root step.",
171
+ ),
172
+ InputParam(
173
+ "root",
174
+ required=True,
175
+ type_hint=torch.Tensor,
176
+ description="`(batch_size, 64, 5)` normalized global root. Can be generated in the root step.",
177
+ ),
178
+ ]
179
+
180
+ @property
181
+ def intermediate_outputs(self) -> list[OutputParam]:
182
+ return [
183
+ OutputParam("pose_codes", type_hint=torch.Tensor, description="`(batch_size, 16, 5)` pose codes."),
184
+ OutputParam("pose_timeline", type_hint=torch.Tensor, description="`(batch_size, 64, 268)` guide poses."),
185
+ OutputParam("has_pose_timeline", type_hint=torch.Tensor, description="`(batch_size, 64)` given poses."),
186
+ OutputParam(
187
+ "local_root", type_hint=torch.Tensor, description="`(batch_size, 64, 4)` normalized local root."
188
+ ),
189
+ ]
190
+
191
+ @torch.no_grad()
192
+ def __call__(self, components, state: PipelineState) -> PipelineState:
193
+ block_state = self.get_block_state(state)
194
+ root_model, pose_model = components.root_model, components.pose_model
195
+ num_tokens, root = block_state.motion_tokens, block_state.root
196
+
197
+ local_root = root_to_local(root_model.denormalize(root.float(), "global_root"), num_tokens)
198
+ local_root = root_model.normalize(local_root.to(root.dtype), "local_root")
199
+ # A given local root at the last target pose replaces the derived one.
200
+ batch = torch.arange(len(num_tokens), device=num_tokens.device)
201
+ last = num_tokens * FRAMES_PER_TOKEN - 1
202
+ given = block_state.has_local_root[:, -1:]
203
+ local_root[batch, last] = torch.where(given, block_state.guide_local_root[:, -1], local_root[batch, last])
204
+
205
+ pose_timeline = root_model.place_guides(block_state.guide_pose, num_tokens, fill=0)
206
+ has_pose_timeline = root_model.place_guides(block_state.has_pose, num_tokens, fill=False)
207
+ ground_root = torch.cat([root[..., :1], root[..., 2:]], dim=-1)
208
+ logits = pose_model(pose_timeline, has_pose_timeline, ground_root, num_tokens).logits
209
+
210
+ block_state.pose_codes = logits.argmax(-1)
211
+ block_state.pose_timeline = pose_timeline
212
+ block_state.has_pose_timeline = has_pose_timeline
213
+ block_state.local_root = local_root
214
+ self.set_block_state(state, block_state)
215
+ return components, state
modular_blocks_motionbricks.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
4
+
5
+ from dataclasses import replace
6
+
7
+ from diffusers.modular_pipelines import ModularPipeline, SequentialPipelineBlocks
8
+ from diffusers.modular_pipelines.modular_pipeline_utils import OutputParam
9
+ from diffusers.utils.dynamic_modules_utils import get_class_from_dynamic_module
10
+
11
+ from .decoders import MotionBricksDecodeStep, MotionBricksPostprocessStep
12
+ from .encoders import MotionBricksGuidesStep
13
+ from .generation import MotionBricksPoseTokensStep, MotionBricksRootStep
14
+
15
+ # The remote-code loader only copies modules imported here directly, so the shared helpers are imported too.
16
+ from .motion_utils import encode_guides # noqa: F401
17
+
18
+
19
+ class MotionBricksBlocks(SequentialPipelineBlocks):
20
+ """Motion in-betweening with NVIDIA MotionBricks on the SOMA skeleton.
21
+
22
+ Every component loads from `components_repo`, one subfolder per component, and so does its code, which requires
23
+ `trust_components_code=True`.
24
+ """
25
+
26
+ model_name = "motionbricks"
27
+ block_classes = [
28
+ MotionBricksGuidesStep(),
29
+ MotionBricksRootStep(),
30
+ MotionBricksPoseTokensStep(),
31
+ MotionBricksDecodeStep(),
32
+ MotionBricksPostprocessStep(),
33
+ ]
34
+ block_names = ["guides", "root", "pose_tokens", "decode", "postprocess"]
35
+
36
+ _requirements = {"diffusers": ">=0.41.0"}
37
+
38
+ def __init__(self, components_repo=None, components_revision=None, trust_components_code=False):
39
+ super().__init__()
40
+ self.components_repo = components_repo
41
+ self.components_revision = components_revision
42
+ self.component_types = {}
43
+ if components_repo is None:
44
+ return
45
+ if not trust_components_code:
46
+ raise ValueError("Set `trust_components_code=True` to load the model code from the components repository")
47
+ index = ModularPipeline.load_config(str(components_repo), revision=components_revision)
48
+ for spec in super().expected_components:
49
+ module_name, class_name, _ = index[spec.name]
50
+ self.component_types[spec.name] = get_class_from_dynamic_module(
51
+ str(components_repo),
52
+ subfolder=spec.name,
53
+ module_file=f"{module_name}.py",
54
+ class_name=class_name,
55
+ revision=components_revision,
56
+ trust_remote_code=True,
57
+ )
58
+
59
+ @property
60
+ def expected_components(self):
61
+ if self.components_repo is None:
62
+ return super().expected_components
63
+ return [
64
+ replace(
65
+ spec,
66
+ type_hint=self.component_types.get(spec.name, spec.type_hint),
67
+ pretrained_model_name_or_path=str(self.components_repo),
68
+ subfolder=spec.name,
69
+ revision=self.components_revision,
70
+ )
71
+ for spec in super().expected_components
72
+ ]
73
+
74
+ @property
75
+ def description(self) -> str:
76
+ return (
77
+ "Generates the transition from the last poses of a context motion to target poses, choosing its length "
78
+ "among the allowed ones."
79
+ )
80
+
81
+ @property
82
+ def outputs(self):
83
+ return [
84
+ OutputParam(
85
+ "motion",
86
+ type_hint=list,
87
+ description="One SOMA30 motion dict per batch item, 30 FPS, meters, +Y up.",
88
+ ),
89
+ OutputParam(
90
+ "placed_target",
91
+ type_hint=list,
92
+ description="`target` as used, one dict per batch item, moved by `target_offset` and `target_turn`.",
93
+ ),
94
+ ]
modular_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "MotionBricksBlocks",
3
+ "_diffusers_version": "0.41.0",
4
+ "auto_map": {
5
+ "ModularPipelineBlocks": "modular_blocks_motionbricks.MotionBricksBlocks"
6
+ },
7
+ "requirements": {
8
+ "diffusers": ">=0.41.0"
9
+ }
10
+ }
modular_model_index.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "_class_name": "ModularPipeline",
3
+ "_blocks_class_name": "MotionBricksBlocks"
4
+ }
motion_utils.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0. See the LICENSE file in this repository.
4
+ #
5
+ # Feature encoding, decoding and endpoint correction adapted from NVIDIA MotionBricks
6
+ # (https://github.com/NVlabs/motionbricks), Apache-2.0. See NOTICE.
7
+
8
+ import functools
9
+ import math
10
+
11
+ import torch
12
+ import torch.nn.functional as F
13
+
14
+
15
+ FPS = 30.0
16
+ CONTEXT_FRAMES = 4
17
+ TARGET_FRAMES = 4
18
+ BOUNDARY_FRAMES = 3
19
+ FRAMES_PER_TOKEN = 4
20
+ # Heading angle of +X, which the last context pose is turned to face.
21
+ ALIGNED_HEADING = math.pi / 2
22
+
23
+ # SOMA30 joint names in model order; the root is Hips.
24
+ SOMA30_JOINTS = (
25
+ "Hips", "Spine1", "Spine2", "Chest", "Neck1", "Neck2", "Head", "Jaw", "LeftEye", "RightEye",
26
+ "LeftShoulder", "LeftArm", "LeftForeArm", "LeftHand", "LeftHandThumbEnd", "LeftHandMiddleEnd",
27
+ "RightShoulder", "RightArm", "RightForeArm", "RightHand", "RightHandThumbEnd", "RightHandMiddleEnd",
28
+ "LeftLeg", "LeftShin", "LeftFoot", "LeftToeBase", "RightLeg", "RightShin", "RightFoot", "RightToeBase",
29
+ ) # fmt: skip
30
+ SOMA30_PARENTS = (
31
+ -1, 0, 1, 2, 3, 4, 5, 6, 6, 6, 3, 10, 11, 12, 13, 13, 3, 16, 17, 18, 19, 19, 0, 22, 23, 24, 0, 26, 27, 28,
32
+ ) # fmt: skip
33
+ # SOMA77 index of each SOMA30 joint.
34
+ SOMA77_TO_SOMA30 = (
35
+ 0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 18, 28, 39, 40, 41, 42, 46, 56, 67, 68, 69, 70, 72, 73, 74, 75,
36
+ ) # fmt: skip
37
+ RIGHT_LEG, LEFT_LEG = SOMA30_JOINTS.index("RightLeg"), SOMA30_JOINTS.index("LeftLeg")
38
+ FOOT_CONTACT_JOINTS = ("LeftFoot", "LeftToeBase", "RightFoot", "RightToeBase")
39
+
40
+
41
+ @functools.cache
42
+ def soma77_index(device: torch.device) -> torch.Tensor:
43
+ return torch.tensor(SOMA77_TO_SOMA30, device=device)
44
+
45
+
46
+ def on_ground(positions: torch.Tensor) -> torch.Tensor:
47
+ """`(..., 3)` positions with their height set to 0."""
48
+ return torch.stack([positions[..., 0], torch.zeros_like(positions[..., 1]), positions[..., 2]], dim=-1)
49
+
50
+
51
+ @functools.cache
52
+ def following_frames(num_frames: int, device: torch.device) -> torch.Tensor:
53
+ """Index of the frame after each guide frame; the last context frame and the last frame are their own."""
54
+ following = torch.arange(1, num_frames + 1).clamp(max=num_frames - 1)
55
+ following[CONTEXT_FRAMES - 1] = CONTEXT_FRAMES - 1
56
+ return following.to(device)
57
+
58
+
59
+ def soma30(values: torch.Tensor, joint_dim: int) -> torch.Tensor:
60
+ """Select the SOMA30 joints of SOMA30 or SOMA77 values along `joint_dim`."""
61
+ count = values.shape[joint_dim]
62
+ if count == len(SOMA30_JOINTS):
63
+ return values
64
+ if count == 77:
65
+ return values.index_select(joint_dim, soma77_index(values.device))
66
+ raise ValueError(f"Expected SOMA30 or SOMA77 joints, got {count}")
67
+
68
+
69
+ def yaw_matrix(angle: torch.Tensor) -> torch.Tensor:
70
+ """Rotation about +Y by `angle` radians, `(..., 3, 3)`."""
71
+ c, s = torch.cos(angle), torch.sin(angle)
72
+ zero, one = torch.zeros_like(angle), torch.ones_like(angle)
73
+ return torch.stack([c, zero, s, zero, one, zero, -s, zero, c], dim=-1).unflatten(-1, (3, 3))
74
+
75
+
76
+ def heading_from_legs(right: torch.Tensor, left: torch.Tensor) -> torch.Tensor:
77
+ """Heading angle about +Y of the forward direction, from the right and left leg joint positions."""
78
+ across = right - left
79
+ length = torch.hypot(across[..., 0], across[..., 2])
80
+ angle = torch.atan2(across[..., 2], -across[..., 0])
81
+ return torch.where(length > 1e-6, angle, torch.zeros_like(angle))
82
+
83
+
84
+ def place_target(
85
+ positions: torch.Tensor,
86
+ rotations: torch.Tensor,
87
+ anchor: torch.Tensor,
88
+ offset: torch.Tensor,
89
+ turn: torch.Tensor,
90
+ ) -> tuple[torch.Tensor, torch.Tensor]:
91
+ """Move and turn a motion so its first pose stands relative to an anchor pose.
92
+
93
+ Args:
94
+ positions: `(batch_size, frames, joints, 3)` SOMA30 or SOMA77 joint positions of the motion.
95
+ rotations: `(batch_size, frames, joints, 3, 3)` global joint rotations of the motion.
96
+ anchor: `(batch_size, 30, 3)` SOMA30 joint positions of the anchor pose.
97
+ offset: `(batch_size, 2)` distance `(forward, left)` in meters from the anchor's ground point, along the
98
+ direction the anchor faces.
99
+ turn: `(batch_size,)` heading of the motion's first pose relative to the anchor's, in radians, positive to
100
+ the left.
101
+
102
+ Returns:
103
+ The moved `positions` and `rotations`.
104
+ """
105
+ first = soma30(positions[:, 0], 1)
106
+ anchor_angle = heading_from_legs(anchor[:, RIGHT_LEG], anchor[:, LEFT_LEG])
107
+ first_angle = heading_from_legs(first[:, RIGHT_LEG], first[:, LEFT_LEG])
108
+ zero = torch.zeros_like(anchor_angle)
109
+ forward = torch.stack([torch.sin(anchor_angle), zero, torch.cos(anchor_angle)], dim=-1)
110
+ left = torch.stack([torch.cos(anchor_angle), zero, -torch.sin(anchor_angle)], dim=-1)
111
+ destination = on_ground(anchor[:, 0]) + offset[:, :1] * forward + offset[:, 1:] * left
112
+ rotation = yaw_matrix(anchor_angle + turn - first_angle)[:, None, None]
113
+ origin = on_ground(first[:, 0])[:, None, None]
114
+ moved = (rotation @ (positions - origin)[..., None])[..., 0] + destination[:, None, None]
115
+ return moved, rotation @ rotations
116
+
117
+
118
+ def rotation_6d(rotations: torch.Tensor) -> torch.Tensor:
119
+ """The first two columns of `(..., 3, 3)` rotation matrices, `(..., 6)`."""
120
+ return torch.cat([rotations[..., :, 0], rotations[..., :, 1]], dim=-1)
121
+
122
+
123
+ def rotation_from_6d(features: torch.Tensor) -> torch.Tensor:
124
+ """Rotation matrices `(..., 3, 3)` from two `(..., 6)` column vectors, orthonormalized."""
125
+ x = F.normalize(features[..., :3], dim=-1)
126
+ z = F.normalize(torch.linalg.cross(x, features[..., 3:]), dim=-1)
127
+ y = torch.linalg.cross(z, x)
128
+ return torch.stack([x, y, z], dim=-1)
129
+
130
+
131
+ def encode_guides(positions: torch.Tensor, rotations: torch.Tensor):
132
+ """Encode the context and target poses as the model's guide features.
133
+
134
+ Args:
135
+ positions: `(batch_size, 8, 30, 3)` SOMA30 joint positions, four context poses then four target poses, in
136
+ meters with +Y up.
137
+ rotations: `(batch_size, 8, 30, 3, 3)` SOMA30 global joint rotations, in the convention where the identity is
138
+ the neutral pose of the skeleton.
139
+
140
+ Returns:
141
+ `(global_root, local_root, pose, alignment)`: `(batch_size, 8, 5)` root position and heading cosine and sine,
142
+ `(batch_size, 8, 4)` heading rate, ground velocity and height, `(batch_size, 8, 267)` root-relative joint
143
+ positions and 6D rotations, and the `(origin, yaw)` that maps aligned poses back to the input space.
144
+ """
145
+ last = CONTEXT_FRAMES - 1
146
+ origin = on_ground(positions[:, last, 0])
147
+ current = heading_from_legs(positions[:, last, RIGHT_LEG], positions[:, last, LEFT_LEG])
148
+ yaw = current - ALIGNED_HEADING
149
+ inverse = yaw_matrix(yaw).transpose(-1, -2)[:, None, None]
150
+ aligned = (inverse @ (positions - origin[:, None, None])[..., None])[..., 0]
151
+ aligned_rotations = inverse @ rotations
152
+
153
+ num_frames = positions.shape[1]
154
+ following = following_frames(num_frames, positions.device)
155
+ hips, next_hips = aligned[:, :, 0], aligned[:, following, 0]
156
+ angle = heading_from_legs(aligned[:, :, RIGHT_LEG], aligned[:, :, LEFT_LEG])
157
+ next_angle = heading_from_legs(aligned[:, following, RIGHT_LEG], aligned[:, following, LEFT_LEG])
158
+ delta = torch.atan2(torch.sin(next_angle - angle), torch.cos(next_angle - angle))
159
+
160
+ global_root = torch.cat([hips, torch.cos(angle)[..., None], torch.sin(angle)[..., None]], dim=-1)
161
+ velocity = (next_hips - hips) * FPS
162
+ local_root = torch.stack([delta * FPS, velocity[..., 0], velocity[..., 2], hips[..., 1]], dim=-1)
163
+ ground = on_ground(hips)
164
+ joint_positions = (aligned[:, :, 1:] - ground[:, :, None]).flatten(2)
165
+ pose = torch.cat([joint_positions, rotation_6d(aligned_rotations).flatten(2)], dim=-1)
166
+ return global_root, local_root, pose, (origin, yaw)
167
+
168
+
169
+ def guide_masks(num_targets: torch.Tensor):
170
+ """`(has_global_root, has_local_root, has_pose)` masks of the guide frames, `(batch_size, 8)` each.
171
+
172
+ The context poses and the first `num_targets` target poses are given. The local root, a derivative, is unknown
173
+ at the last context pose and the last target pose.
174
+ """
175
+ index = torch.arange(CONTEXT_FRAMES + TARGET_FRAMES, device=num_targets.device)[None]
176
+ given = index < CONTEXT_FRAMES + num_targets[:, None]
177
+ last = (index == CONTEXT_FRAMES - 1) | (index == CONTEXT_FRAMES + num_targets[:, None] - 1)
178
+ return given, given & ~last, given
179
+
180
+
181
+ def root_to_local(root: torch.Tensor, num_tokens: torch.Tensor) -> torch.Tensor:
182
+ """Local root `(heading rate, x velocity, z velocity, height)` of a `(batch_size, num_frames, 5)` global root.
183
+
184
+ The last frame of the motion repeats the derivatives of the frame before it.
185
+ """
186
+ angle = torch.atan2(root[..., 4], root[..., 3])
187
+ cos, sin = torch.cos(angle), torch.sin(angle)
188
+ rate = torch.atan2(
189
+ sin[:, 1:] * cos[:, :-1] - cos[:, 1:] * sin[:, :-1], cos[:, 1:] * cos[:, :-1] + sin[:, 1:] * sin[:, :-1]
190
+ )
191
+ rate = F.pad(rate * FPS, (0, 1))
192
+ velocity = F.pad((root[:, 1:, :3] - root[:, :-1, :3]) * FPS, (0, 0, 0, 1))
193
+ local = torch.cat([rate[..., None], velocity[..., 0:3:2], root[..., 1:2]], dim=-1)
194
+ batch = torch.arange(root.shape[0], device=root.device)
195
+ last = num_tokens * FRAMES_PER_TOKEN - 1
196
+ local[batch, last] = local[batch, last - 1]
197
+ local[batch, last, 3] = root[batch, last, 1]
198
+ return local
199
+
200
+
201
+ def integrate_local_root(local_root: torch.Tensor) -> torch.Tensor:
202
+ """Global root `(x, y, z, heading cosine, heading sine)` from a local root, starting at the origin."""
203
+ rate, vx, vz, height = local_root.unbind(-1)
204
+ angle = F.pad(torch.cumsum(rate[:, :-1] / FPS, dim=1), (1, 0))
205
+ x = F.pad(torch.cumsum(vx[:, :-1] / FPS, dim=1), (1, 0))
206
+ z = F.pad(torch.cumsum(vz[:, :-1] / FPS, dim=1), (1, 0))
207
+ return torch.stack([x, height, z, torch.cos(angle), torch.sin(angle)], dim=-1)
208
+
209
+
210
+ def select_root(
211
+ decoded_root: torch.Tensor,
212
+ predicted_root: torch.Tensor,
213
+ target_height: torch.Tensor,
214
+ has_target: torch.Tensor,
215
+ num_tokens: torch.Tensor,
216
+ ) -> torch.Tensor:
217
+ """Keep the decoded root, unless its height misses the targets by over 5 cm and the root model's is closer."""
218
+ frames = (
219
+ num_tokens[:, None] * FRAMES_PER_TOKEN - TARGET_FRAMES + torch.arange(TARGET_FRAMES, device=num_tokens.device)
220
+ )
221
+ batch = torch.arange(decoded_root.shape[0], device=decoded_root.device)[:, None]
222
+ weight = has_target.to(decoded_root.dtype)
223
+ count = weight.sum(-1)
224
+ decoded_error = ((decoded_root[batch, frames, 1] - target_height).abs() * weight).sum(-1) / count
225
+ predicted_error = ((predicted_root[batch, frames, 1] - target_height).abs() * weight).sum(-1) / count
226
+ use_predicted = (predicted_error < decoded_error) & (decoded_error > 0.05)
227
+ return torch.where(use_predicted[:, None, None], predicted_root, decoded_root)
228
+
229
+
230
+ def decode_poses(
231
+ motion: torch.Tensor,
232
+ num_tokens: torch.Tensor,
233
+ alignment: tuple[torch.Tensor, torch.Tensor],
234
+ neutral_joints: torch.Tensor,
235
+ endpoints: dict | None = None,
236
+ ):
237
+ """World-space SOMA30 poses of the valid frames of each motion.
238
+
239
+ Args:
240
+ motion: `(batch_size, num_frames, 366)` features: global root, child joint positions, 6D global rotations,
241
+ joint velocities and foot contacts, in the aligned space.
242
+ num_tokens: `(batch_size,)` motion lengths in tokens; the first and last three frames are dropped.
243
+ alignment: The `(origin, yaw)` from `encode_guides`.
244
+ neutral_joints: `(30, 3)` joint positions of the neutral pose, which give the bone offsets.
245
+ endpoints: The `endpoints` from `encode_guides`, to correct the endpoints with `correct_endpoints`.
246
+
247
+ Returns:
248
+ A list with one dict per motion: `posed_joints` `(frames, 30, 3)`, `global_rot_mats` `(frames, 30, 3, 3)`,
249
+ `local_rot_mats` `(frames, 30, 3, 3)`, `root_positions` `(frames, 3)` and `foot_contacts` `(frames, 4)`.
250
+ """
251
+ origin, yaw = alignment
252
+ rotation = yaw_matrix(yaw)
253
+ joints = len(SOMA30_JOINTS)
254
+ position_end = 5 + 3 * (joints - 1)
255
+ global_rots = rotation[:, None, None] @ rotation_from_6d(
256
+ motion[..., position_end : position_end + 6 * joints].unflatten(-1, (joints, 6))
257
+ )
258
+ roots = (rotation[:, None] @ motion[..., :3, None])[..., 0] + origin[:, None]
259
+ contacts = motion[..., -len(FOOT_CONTACT_JOINTS) :].clamp(0, 1)
260
+ local_rots = local_rotations(global_rots)
261
+ if endpoints is not None:
262
+ local_rots, roots = correct_endpoints(local_rots, roots, num_tokens, endpoints)
263
+ global_rots = global_rotations(local_rots)
264
+ positions = joint_positions(global_rots, roots, neutral_joints)
265
+ outputs = []
266
+ for i, count in enumerate((num_tokens * FRAMES_PER_TOKEN).tolist()):
267
+ frames = slice(BOUNDARY_FRAMES, count - BOUNDARY_FRAMES)
268
+ outputs.append(
269
+ {
270
+ "posed_joints": positions[i, frames],
271
+ "global_rot_mats": global_rots[i, frames],
272
+ "local_rot_mats": local_rots[i, frames],
273
+ "root_positions": roots[i, frames],
274
+ "foot_contacts": contacts[i, frames],
275
+ }
276
+ )
277
+ return outputs
278
+
279
+
280
+ @functools.cache
281
+ def skeleton(device: torch.device) -> tuple[torch.Tensor, list[torch.Tensor], torch.Tensor]:
282
+ """SOMA30 parent indices (the root its own parent), the non-root joints grouped by depth, and the `(30, 30)`
283
+ matrix whose row `j` marks the non-root joints on the path from `j` to the root."""
284
+ parents = torch.tensor(SOMA30_PARENTS).clamp(min=0)
285
+ depth = [0] * len(SOMA30_PARENTS)
286
+ ancestors = torch.zeros(len(SOMA30_PARENTS), len(SOMA30_PARENTS))
287
+ for joint in range(1, len(SOMA30_PARENTS)):
288
+ depth[joint] = depth[SOMA30_PARENTS[joint]] + 1
289
+ ancestors[joint] = ancestors[SOMA30_PARENTS[joint]]
290
+ ancestors[joint, joint] = 1
291
+ levels = [torch.tensor([j for j, d in enumerate(depth) if d == level]) for level in range(1, max(depth) + 1)]
292
+ return parents.to(device), [level.to(device) for level in levels], ancestors.to(device)
293
+
294
+
295
+ def local_rotations(global_rots: torch.Tensor) -> torch.Tensor:
296
+ """Local rotations of `(..., 30, 3, 3)` global rotations; the root's local rotation is its global one."""
297
+ parents, _, _ = skeleton(global_rots.device)
298
+ local = global_rots[..., parents, :, :].transpose(-1, -2) @ global_rots
299
+ return torch.cat([global_rots[..., :1, :, :], local[..., 1:, :, :]], dim=-3)
300
+
301
+
302
+ def joint_positions(global_rots: torch.Tensor, root_positions: torch.Tensor, neutral_joints: torch.Tensor):
303
+ """Joint positions from global rotations and a root trajectory, with the bone offsets of the neutral pose."""
304
+ parents, _, ancestors = skeleton(global_rots.device)
305
+ offsets = (neutral_joints - neutral_joints[parents]).to(global_rots.dtype)
306
+ bones = (global_rots[..., parents, :, :] @ offsets[:, :, None])[..., 0]
307
+ return root_positions[..., None, :] + torch.einsum("jk,...kc->...jc", ancestors.to(bones.dtype), bones)
308
+
309
+
310
+ def global_rotations(local_rots: torch.Tensor) -> torch.Tensor:
311
+ """Global rotations of `(..., 30, 3, 3)` local rotations."""
312
+ parents, levels, _ = skeleton(local_rots.device)
313
+ global_rots = local_rots.clone()
314
+ for joints in levels:
315
+ global_rots[..., joints, :, :] = global_rots[..., parents[joints], :, :] @ local_rots[..., joints, :, :]
316
+ return global_rots
317
+
318
+
319
+ def axis_angle(rotations: torch.Tensor) -> torch.Tensor:
320
+ """Axis-angle vectors of `(..., 3, 3)` rotation matrices."""
321
+ quaternion = matrix_to_quaternion(rotations)
322
+ quaternion = quaternion * torch.where(quaternion[..., :1] < 0, -1.0, 1.0)
323
+ vector = quaternion[..., 1:]
324
+ sin_half = vector.norm(dim=-1, keepdim=True)
325
+ angle = 2 * torch.atan2(sin_half, quaternion[..., :1])
326
+ scale = torch.where(sin_half > 1e-8, angle / sin_half.clamp(min=1e-8), torch.full_like(angle, 2.0))
327
+ return vector * scale
328
+
329
+
330
+ def axis_angle_matrix(vector: torch.Tensor) -> torch.Tensor:
331
+ angle = vector.norm(dim=-1, keepdim=True)[..., None]
332
+ axis = F.normalize(vector, dim=-1, eps=1e-12)
333
+ x, y, z = axis.unbind(-1)
334
+ zero = torch.zeros_like(x)
335
+ skew = torch.stack([zero, -z, y, z, zero, -x, -y, x, zero], dim=-1).unflatten(-1, (3, 3))
336
+ eye = torch.eye(3, dtype=vector.dtype, device=vector.device).expand_as(skew)
337
+ return eye + torch.sin(angle) * skew + (1 - torch.cos(angle)) * (skew @ skew)
338
+
339
+
340
+ def matrix_to_quaternion(rotations: torch.Tensor) -> torch.Tensor:
341
+ """`(w, x, y, z)` unit quaternions of `(..., 3, 3)` rotation matrices."""
342
+ m = rotations
343
+ trace = m[..., 0, 0] + m[..., 1, 1] + m[..., 2, 2]
344
+ candidates = torch.stack(
345
+ [
346
+ torch.stack(
347
+ [1 + trace, m[..., 2, 1] - m[..., 1, 2], m[..., 0, 2] - m[..., 2, 0], m[..., 1, 0] - m[..., 0, 1]], -1
348
+ ),
349
+ torch.stack(
350
+ [
351
+ m[..., 2, 1] - m[..., 1, 2],
352
+ 1 + m[..., 0, 0] - m[..., 1, 1] - m[..., 2, 2],
353
+ m[..., 0, 1] + m[..., 1, 0],
354
+ m[..., 0, 2] + m[..., 2, 0],
355
+ ],
356
+ -1,
357
+ ),
358
+ torch.stack(
359
+ [
360
+ m[..., 0, 2] - m[..., 2, 0],
361
+ m[..., 0, 1] + m[..., 1, 0],
362
+ 1 - m[..., 0, 0] + m[..., 1, 1] - m[..., 2, 2],
363
+ m[..., 1, 2] + m[..., 2, 1],
364
+ ],
365
+ -1,
366
+ ),
367
+ torch.stack(
368
+ [
369
+ m[..., 1, 0] - m[..., 0, 1],
370
+ m[..., 0, 2] + m[..., 2, 0],
371
+ m[..., 1, 2] + m[..., 2, 1],
372
+ 1 - m[..., 0, 0] - m[..., 1, 1] + m[..., 2, 2],
373
+ ],
374
+ -1,
375
+ ),
376
+ ],
377
+ dim=-2,
378
+ )
379
+ best = torch.stack([trace, m[..., 0, 0], m[..., 1, 1], m[..., 2, 2]], -1).argmax(-1)
380
+ quaternion = torch.gather(candidates, -2, best[..., None, None].expand(*best.shape, 1, 4))[..., 0, :]
381
+ return F.normalize(quaternion, dim=-1)
382
+
383
+
384
+ def scaled_rotation(rotations: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
385
+ """The rotations scaled by `weight` along their geodesic from the identity, as slerp(identity, q, weight)."""
386
+ return axis_angle_matrix(axis_angle(rotations) * weight[..., None])
387
+
388
+
389
+ def correct_endpoints(
390
+ local_rots: torch.Tensor, roots: torch.Tensor, num_tokens: torch.Tensor, endpoints: dict
391
+ ) -> tuple[torch.Tensor, torch.Tensor]:
392
+ """Blend corrections over each motion so its first valid frame is the last context pose and its last valid frame
393
+ the first target pose.
394
+
395
+ Args:
396
+ local_rots: `(batch_size, num_frames, 30, 3, 3)` local rotations.
397
+ roots: `(batch_size, num_frames, 3)` root positions.
398
+ num_tokens: `(batch_size,)` motion lengths in tokens.
399
+ endpoints: `context_local` and `target_local` `(batch_size, 30, 3, 3)` local rotations of the last context
400
+ pose and the first target pose, `context_root` and `target_root` `(batch_size, 3)` their root positions.
401
+
402
+ Returns:
403
+ The corrected local rotations and root positions.
404
+ """
405
+ batch = torch.arange(len(local_rots), device=local_rots.device)
406
+ first = BOUNDARY_FRAMES
407
+ last = num_tokens * FRAMES_PER_TOKEN - BOUNDARY_FRAMES - 1
408
+ frames = torch.arange(local_rots.shape[1], dtype=local_rots.dtype, device=local_rots.device)
409
+ end_weight = ((frames - first) / (last - first).to(local_rots.dtype)[:, None]).clamp(0, 1)
410
+ start_weight = 1 - end_weight
411
+ ends = torch.stack([local_rots[batch, first], local_rots[batch, last]], dim=1)
412
+ deltas = ends.transpose(-1, -2) @ torch.stack([endpoints["context_local"], endpoints["target_local"]], dim=1)
413
+ weights = torch.stack([start_weight, end_weight], dim=1)[..., None]
414
+ start, end = scaled_rotation(deltas[:, :, None], weights).unbind(1)
415
+ local_rots = local_rots @ start @ end
416
+ roots = (
417
+ roots
418
+ + (endpoints["context_root"] - roots[batch, first])[:, None] * start_weight[..., None]
419
+ + (endpoints["target_root"] - roots[batch, last])[:, None] * end_weight[..., None]
420
+ )
421
+ return local_rots, roots