Skip to content

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

Python

Release the training and inference code

Friedrich-M0dd8855f858d
diff --git a/README.md b/README.md
index b5513df..b59ba6e 100644
--- a/README.md
+++ b/README.md
@@ -6,8 +6,8 @@
<a href="https://linzhanm.github.io/unimate/"><img alt="Project Page" src="https://img.shields.io/badge/Project_Page-6D28D9?style=for-the-badge&logo=githubpages&logoColor=white"></a>
<a href="https://linzhanmou.com/unimate/resources/unimate.pdf"><img alt="Paper" src="https://img.shields.io/badge/Paper-A855F7?style=for-the-badge&logo=googledocs&logoColor=white"></a>
<a href="https://linzhanmou.com/unimate/interactive.html"><img alt="Interactive Demo" src="https://img.shields.io/badge/Interactive_Demo-0EA5E9?style=for-the-badge&logo=threedotjs&logoColor=white"></a>
- <a href="https://huggingface.co/Linzhan"><img alt="Hugging Face Dataset" src="https://img.shields.io/badge/Dataset-FFD21E?style=for-the-badge&logo=huggingface&logoColor=000000"></a>
- <a href="https://asia.siggraph.org/2026/"><img alt="Venue" src="https://img.shields.io/badge/SIGGRAPH_Asia-2026-6D28D9?style=for-the-badge&labelColor=1E1B4B"></a>
+ <a href="https://huggingface.co/collections/Linzhan/unimate"><img alt="Hugging Face Dataset" src="https://img.shields.io/badge/Dataset-FFD21E?style=for-the-badge&logo=huggingface&logoColor=000000"></a>
+ <a href="https://linzhanmou.com/unimate/resources/unimate-poster.png"><img alt="SIGGRAPH Asia 2026 Poster" src="https://img.shields.io/badge/SIGGRAPH_Asia_2026-Poster-6D28D9?style=for-the-badge&labelColor=1E1B4B"></a>
</p>
<p align="center">
@@ -30,11 +30,13 @@
## ๐Ÿ”ฅ News
-- **[TODO]** Training and inference code will be released in this repository soon.
-- **[2026-08-30]** The **UniML3D dataset** and its [data-processing pipeline](data_process/) are released. ๐Ÿš€
+- **[2026-09-06]** The **training and inference code** is released. ๐Ÿš€
+- **[2026-08-30]** The raw **UniML3D dataset** and its [data-processing pipeline](data_process/) are released. ๐Ÿš€
- **[2026-08-01]** Our [Interactive Demo](https://linzhanmou.com/unimate/interactive.html) is live โ€” browse our animation results in 3D. ๐ŸŽฎ
- **[2026-07-18]** UniMate is accepted to SIGGRAPH Asia 2026! ๐ŸŽ‰
+> **[TODO]** Pretrained checkpoints, processed data and detailed documents are coming soon.
+
## ๐Ÿ› ๏ธ Environment Setup
All components share a single conda environment, specified in [`requirements.txt`](requirements.txt):
@@ -50,7 +52,7 @@ pip install -r requirements.txt --no-build-isolation
We introduce **UniML3D**, a large-scale dataset of 13,006 text-paired motion sequences covering diverse skeletal topologies โ€” bipedal, quadrupedal, avian, marine, insectoid, serpentine, and articulated rigid objects โ€” all brought into a unified canonicalization.
-The raw source assets are available on the Hugging Face Hub: [Mixamo-Animations-Characters](https://huggingface.co/datasets/Linzhan/Mixamo-Animations-Characters), [Objaverse-XL-Rigged-Animated](https://huggingface.co/datasets/Linzhan/Objaverse-XL-Rigged-Animated) and [Truebones-ZOO-Annotations](https://huggingface.co/datasets/Linzhan/Truebones-ZOO-Annotations) (prompts, metadata and renders only). The Truebones ZOO animal motions themselves are a commercial asset pack whose license does not permit redistribution โ€” please purchase the pack directly from [Truebones](https://truebones.com); our pipeline consumes the stock `Truebone_Z-OO` folder layout as-is.
+The raw source assets are available on the Hugging Face Hub (collected under [UniMate](https://huggingface.co/collections/Linzhan/unimate)): [Mixamo-Animations-Characters](https://huggingface.co/datasets/Linzhan/Mixamo-Animations-Characters), [Objaverse-XL-Rigged-Animated](https://huggingface.co/datasets/Linzhan/Objaverse-XL-Rigged-Animated) and [Truebones-ZOO-Annotations](https://huggingface.co/datasets/Linzhan/Truebones-ZOO-Annotations) (prompts, metadata and renders only). The Truebones ZOO animal motions themselves are a commercial asset pack whose license does not permit redistribution โ€” please purchase the pack directly from [Truebones](https://truebones.com); our pipeline consumes the stock `Truebone_Z-OO` folder layout as-is.
<div align="center">
<img src="assets/dataset_overview.png" alt="UniML3D dataset overview" width="100%">
@@ -58,6 +60,85 @@ The raw source assets are available on the Hugging Face Hub: [Mixamo-Animations-
See [`data_process/README.md`](data_process/README.md) for the full data processing pipeline that turns the raw assets into UniML3D (download โ†’ export โ†’ rendering โ†’ captioning โ†’ joint annotation โ†’ feature extraction โ†’ animation).
+## ๐Ÿ‹๏ธ Training
+
+Training reads the canonicalized clips under `dataset/features/<dataset>/`, produced by stage 4 of the [data-processing pipeline](data_process/README.md#stage-4--extract-npz--metadata--training-clips).
+
+Runs are configured by the JSON files in [`configs/`](configs/).
+
+<details>
+<summary><b>Config naming</b> โ€” <code>{dataset}_{frames}frames_{attention}_{text_cond}.json</code></summary>
+
+24 configs: 4 data combinations x 3 clip lengths x 2 model variants.
+
+| Prefix | Training data |
+|--------|---------------|
+| `uniml3d_*` | Full UniML3D dataset (Truebones + Mixamo + Objaverse) |
+| `truebones_*` / `mixamo_*` / `objaverse_*` | A single source |
+
+| Length | `dataset.max_motion_length` |
+|--------|-----------------------------|
+| `60frames` / `90frames` / `120frames` | 60 / 90 / 120 frames per clip |
+
+| Suffix | `model.attention` x `model.text_cond` |
+|--------|---------------------------------------|
+| `_graph_adaln` | `graph` x `adaln` โ€” attention factored into spatial (per frame) and temporal (per joint) passes with graph-distance, edge-type and depth biases; the caption is folded into the adaLN modulation |
+| `_full_cross_attn` | `full` x `cross_attn` โ€” one attention over the flattened joint x time tokens; the caption enters every block as cross-attention keys/values |
+
+The two axes are independent and all four combinations are implemented, so `full` x `adaln` and `graph` x `cross_attn` also run if you set them in a config; the two shipped pairings are the ones the paper compares.
+
+Not shared across configs: `training.batch_size` and `training.num_steps` are tuned per data combination and clip length (GPU memory tracks batch x frames x joints). Every other setting is identical โ€” including `dataset.{min,max}_joints = {5, 100}`, which bounds the skeleton sizes a run admits (object types outside the range are dropped) and, through what survives, the joint-axis padding width.
+
+</details>
+
+Launch with [๐Ÿค— Accelerate](https://github.com/huggingface/accelerate). Single GPU:
+
+```bash
+accelerate launch -m unimate.training.train --config configs/uniml3d_60frames_graph_adaln.json
+```
+
+Multi-GPU on one node (e.g. 8 GPUs):
+
+```bash
+accelerate launch --num_processes 8 -m unimate.training.train --config configs/uniml3d_60frames_graph_adaln.json
+```
+
+`scripts/run_train.sh <config> [-- extra args]` wraps the single-GPU command with the conda environment activated, the GPU with the most free memory selected, and anything after `--` forwarded to the training module.
+
+`--output_dir`, `--batch_size`, `--num_workers` and `--resume <checkpoint.pt>` override the config from the command line. Resuming restores model, EMA, optimizer, LR-scheduler and step counter, so a run continues exactly where it stopped.
+
+Each run writes to `outputs/<experiment name>/`:
+
+| Path | Content |
+|------|---------|
+| `config.json` | Resolved config, including the auto-computed `max_joints` / `max_depth`; inference reads it back to rebuild the model |
+| `dataset_stats.npy` | Normalization statistics, reused at inference |
+| `checkpoints/checkpoint_step_*.pt` | Model, EMA, optimizer and LR-scheduler state, every `training.save_interval` steps |
+| `debug/` | Sample visualizations, rendered once before training and at every checkpoint (EMA weights, `sampling.cfg_scale`) |
+| `logs/` | TensorBoard scalars (`tensorboard --logdir outputs/<experiment name>/logs`) |
+
+<details>
+<summary><b>What a training step does</b></summary>
+
+Clips are drawn by a power-law-balanced sampler when `training.balanced` is set โ€” a type with `n` clips is sampled in proportion to `n^(1-sampler_alpha)`, so at the default `sampler_alpha = 0.5` a species with 100 clips is seen ten times as often as one with a single clip rather than a hundred times โ€” then augmented on the fly โ€” joint addition, leaf removal, chain pooling and per-bone length perturbation (`dataset.use_*_aug`) โ€” so the model sees more topologies than the data literally contains. Every clip is padded to `max_joints` on the joint axis and `max_motion_length` on the time axis, with masks carried alongside; nothing padded ever contributes to attention or to the loss.
+
+Training is **flow matching** (`training.diff_model = "flow"`): the network predicts the velocity of a linear interpolant between noise and data, under a masked L2 loss plus an optional geodesic rotation term (`training.lambda_geo`). Conditioning is dropped with probability `model.cond_mask_prob` so the same weights serve the conditional and unconditional branches that classifier-free guidance interpolates at sampling time. AdamW with a cosine schedule and warmup, gradient clipping at `training.max_grad_norm`, and an EMA copy of the weights (`training.use_ema`) โ€” the copy inference loads by default.
+
+</details>
+
+<details>
+<summary><b>Pre-computing text embeddings</b></summary>
+
+The text encoder (`google/flan-t5-base` by default) is fetched from the Hugging Face Hub on first use. Every run loads it once to embed all captions and joint names; pre-computing those embeddings beside the features keeps it out of the run entirely:
+
+```bash
+python -m unimate.tools.precompute_text_emb --config configs/uniml3d_60frames_graph_adaln.json
+```
+
+This writes `caption_emb_cache.npz` and `joint_emb_cache.npz` into each `dataset/features/<dataset>/` the config uses. Captions are cached per token (the sequence `cross_attn` attends; `adaln` mean-pools it), joint names as one pooled vector each, keyed by the **cleaned** joint vocabulary that stage 3 produces โ€” the shared naming is what lets the same anatomical joint embed identically across rigs. Re-run it after regenerating captions or joint names: anything the cache misses is still encoded at load time, so a stale cache costs speed rather than correctness.
+
+</details>
+
## ๐ŸŽฌ Inference
Given a rigged 3D asset and a text prompt, UniMate generates articulated motion for arbitrary skeletons in real time โ€” with no per-skeleton retraining and no test-time optimization.
@@ -66,6 +147,153 @@ Given a rigged 3D asset and a text prompt, UniMate generates articulated motion
<img src="assets/qualitative.png" alt="Qualitative results" width="100%">
</div>
+Sampling starts from the output directory of a training run (`config.json`, `dataset_stats.npy`, `checkpoints/`) โ€” pretrained checkpoints in the same layout are coming soon. The target skeleton โ€” T-pose and topology conditioning โ€” is taken from the dataset, so the `dataset/features/<dataset>/` directory the model was trained on must be present.
+
+```bash
+python -m unimate.inference.sample \
+ --exp_dir outputs/uniml3d_60frames_graph_adaln \
+ --test_cases_json test_cases.json \
+ --num_repetitions 3
+```
+
+<details>
+<summary><b>Test cases, flags and outputs</b></summary>
+
+Test cases are a JSON map from `<object_type>-<case_id>` to a prompt. `object_type` must exist in the dataset; `case_id` is a free-form tag that names the output files:
+
+```json
+{
+ "Dog-walk": "a dog walks forward at a steady pace",
+ "Dragon-takeoff": "a dragon flaps its wings and takes off"
+}
+```
+
+`--test_cases_json` is itself optional: without it every clip of the dataset's eval split is enumerated as a test case (falling back to unique `(object_type, caption)` pairs on train when there is no eval split). `--test_cases_txt` (one `object_type` per line) drives unconditional sampling, which requires `--cfg_scale 1.0`.
+
+| Flag | Effect |
+|------|--------|
+| `--cfg_scale` | Classifier-free guidance scale (>= 1.0); defaults to the value saved in the run's config |
+| `--model_path` | A specific checkpoint; defaults to the latest step |
+| `--output_dir` | Defaults to `<exp_dir>/samples` |
+| `--num_repetitions` | Samples generated per test case |
+| `--batch_size` | Per-chunk inference batch; caps GPU memory regardless of how many cases there are |
+| `--seed` | Fixes the sampling noise |
+| `--only_save_motion` | Skip the MP4 renders, write only the `.npy` features |
+| `--save_ric` | Add the RIC-recovered render beside the FK one |
+
+Each run writes:
+
+| Path | Content |
+|------|---------|
+| `motions/<case_id>-rep_<r>-<i>.npy` | Generated motion features `(T, J, 12)`, one file per repetition |
+| `animations/<case_id>-rep_<r>-sample<i>_fk.mp4` | Skeleton render of each sample (`_ric.mp4` variants with `--save_ric`) |
+| `animations/<object_type>_tpos.png` | The conditioning T-pose |
+| `captions.json` | Prompt used for every saved `.npy` |
+
+`scripts/run_sample_motion_text.sh <exp_dir> [test_cases_json] [cfg_scale]` runs the command above with the conda environment activated, the GPU with the most free memory selected, and an output directory named after the test-case file. Run it with `-h` for its options.
+
+</details>
+
+<details>
+<summary><b>Driving a rigged mesh</b></summary>
+
+To animate the original mesh with a generated motion, hand the `.npy` files to stage 5 of the data pipeline, which exports an animated GLB + FBX:
+
+```bash
+bash scripts/run_animate_motion.sh objaverse \
+ outputs/uniml3d_60frames_graph_adaln/samples/motions/Dog-walk-rep_0-0.npy \
+ outputs/animated
+```
+
+It accepts several files or a directory, and reads the rig from `dataset/features/<dataset>/cond.npy` by default.
+
+</details>
+
+## ๐ŸŽจ Applications
+
+The same trained model does three more tasks with no extra training. Each is replacement-style sampling: part of the motion is pinned to a known signal and the flow ODE denoises only the rest at every step, so the constraint holds exactly rather than being encouraged by a loss.
+
+### Motion in-betweening
+
+Hold chosen keyframes at their ground truth and generate the transitions between them.
+
+<div align="center">
+ <img src="assets/motion-in-betweening.png" alt="Motion in-betweening" width="100%">
+</div>
+
+<details>
+<summary><b>How to run it</b></summary>
+
+`--keep_frames` takes signed indices (negatives count back from the generation window), so `"0,-1"` fills in everything between a clip's first and last pose.
+
+```json
+{ "mixamo-Squat-000": "A human squats and then rises back up" }
+```
+
+```bash
+KEEP_FRAMES="0,-1" bash scripts/run_sample_motion_inbetween.sh \
+ outputs/uniml3d_60frames_graph_adaln cases.json
+```
+
+</details>
+
+### Text-guided motion editing
+
+Hold chosen joints at their ground-truth motion for every frame and regenerate the rest under a new prompt โ€” keep what should stay, re-animate the rest.
+
+<div align="center">
+ <img src="assets/motion-editing.png" alt="Text-guided motion editing" width="100%">
+</div>
+
+<details>
+<summary><b>How to run it</b></summary>
+
+`--keep_joints` matches case-insensitively against either the rig's own bone names or the cleaned vocabulary.
+
+```json
+{ "<objaverse_uid>-turn-head-000": "The robot walks forward." }
+```
+
+```bash
+KEEP_JOINTS="Hips,Spine,Neck,Head" bash scripts/run_sample_motion_edit.sh \
+ outputs/uniml3d_60frames_graph_adaln cases.json
+```
+
+</details>
+
+### Motion expansion
+
+Chain several prompts into one long motion. The first segment is generated freely; every later one pins its first few frames to the previous segment's tail, and the segments are stitched at the seam.
+
+<div align="center">
+ <img src="assets/motion-expansion.png" alt="Motion expansion" width="100%">
+</div>
+
+<details>
+<summary><b>How to run it</b></summary>
+
+Test-case values become *lists* of prompts, one per segment; `--expand_overlap` sets how many frames consecutive segments share.
+
+```json
+{ "mixamo-sequence": ["A human stands up.", "A human walks forward.", "A human turns around in place."] }
+```
+
+```bash
+EXPAND_OVERLAP=10 bash scripts/run_sample_motion_expand.sh \
+ outputs/uniml3d_60frames_graph_adaln cases.json
+```
+
+</details>
+
+<details>
+<summary><b>Shared behaviour</b></summary>
+
+Each mode writes into its own subdirectory of `--output_dir` (`inbetween/`, `motion_edit/`, `motion_expand/`) alongside a small JSON recording the constraint that produced it, and each has a wrapper in `scripts/` โ€” run any of them with `-h` for the full option list.
+
+In-betweening and editing clamp against a real clip, so their test-case keys must be `<object_type>-<clip_id>` naming a clip the dataset actually holds; that clip's motion is saved beside the result as `<case_id>-gt_rep_<r>-<i>.npy` for side-by-side comparison. `--gt_start_frame` pins which window of the clip is used instead of a random one. Editing trims both the sample and the GT to the clip's true length, while in-betweening generates the full window and trims only the GT โ€” so align the two on frame 0 rather than assuming equal lengths. All three modes need `--cfg_scale > 1.0` and are mutually exclusive with each other.
+
+</details>
+
## ๐Ÿ“ Citation
If you find UniMate useful in your research, please consider citing our work:
diff --git a/assets/motion-editing.png b/assets/motion-editing.png
new file mode 100644
index 0000000..fca1fc4
Binary files /dev/null and b/assets/motion-editing.png differ
diff --git a/assets/motion-expansion.png b/assets/motion-expansion.png
new file mode 100644
index 0000000..703fb74
Binary files /dev/null and b/assets/motion-expansion.png differ
diff --git a/assets/motion-in-betweening.png b/assets/motion-in-betweening.png
new file mode 100644
index 0000000..856b115
Binary files /dev/null and b/assets/motion-in-betweening.png differ
diff --git a/configs/mixamo_120frames_full_cross_attn.json b/configs/mixamo_120frames_full_cross_attn.json
new file mode 100644
index 0000000..ebabdc1
--- /dev/null
+++ b/configs/mixamo_120frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "mixamo_120frames_full_cross_attn",
+ "output_dir": "./outputs/mixamo_120frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "mixamo"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 120,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": false,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": false,
+ "use_removal_aug": false,
+ "use_pooling_aug": false,
+ "use_perturbation_aug": false,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 32,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 120000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": false
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/mixamo_120frames_graph_adaln.json b/configs/mixamo_120frames_graph_adaln.json
new file mode 100644
index 0000000..8cfde50
--- /dev/null
+++ b/configs/mixamo_120frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "mixamo_120frames_graph_adaln",
+ "output_dir": "./outputs/mixamo_120frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "mixamo"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 120,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": false,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": false,
+ "use_removal_aug": false,
+ "use_pooling_aug": false,
+ "use_perturbation_aug": false,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 32,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 120000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": false
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/mixamo_60frames_full_cross_attn.json b/configs/mixamo_60frames_full_cross_attn.json
new file mode 100644
index 0000000..2c0bd91
--- /dev/null
+++ b/configs/mixamo_60frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "mixamo_60frames_full_cross_attn",
+ "output_dir": "./outputs/mixamo_60frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "mixamo"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 60,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": false,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": false,
+ "use_removal_aug": false,
+ "use_pooling_aug": false,
+ "use_perturbation_aug": false,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 32,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 120000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": false
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/mixamo_60frames_graph_adaln.json b/configs/mixamo_60frames_graph_adaln.json
new file mode 100644
index 0000000..00cf6e9
--- /dev/null
+++ b/configs/mixamo_60frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "mixamo_60frames_graph_adaln",
+ "output_dir": "./outputs/mixamo_60frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "mixamo"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 60,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": false,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": false,
+ "use_removal_aug": false,
+ "use_pooling_aug": false,
+ "use_perturbation_aug": false,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 32,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 120000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": false
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/mixamo_90frames_full_cross_attn.json b/configs/mixamo_90frames_full_cross_attn.json
new file mode 100644
index 0000000..6f897ec
--- /dev/null
+++ b/configs/mixamo_90frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "mixamo_90frames_full_cross_attn",
+ "output_dir": "./outputs/mixamo_90frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "mixamo"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 90,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": false,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": false,
+ "use_removal_aug": false,
+ "use_pooling_aug": false,
+ "use_perturbation_aug": false,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 32,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 120000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": false
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/mixamo_90frames_graph_adaln.json b/configs/mixamo_90frames_graph_adaln.json
new file mode 100644
index 0000000..5b045b9
--- /dev/null
+++ b/configs/mixamo_90frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "mixamo_90frames_graph_adaln",
+ "output_dir": "./outputs/mixamo_90frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "mixamo"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 90,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": false,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": false,
+ "use_removal_aug": false,
+ "use_pooling_aug": false,
+ "use_perturbation_aug": false,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 32,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 120000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": false
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/objaverse_120frames_full_cross_attn.json b/configs/objaverse_120frames_full_cross_attn.json
new file mode 100644
index 0000000..6747b01
--- /dev/null
+++ b/configs/objaverse_120frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "objaverse_120frames_full_cross_attn",
+ "output_dir": "./outputs/objaverse_120frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 120,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 8,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 24,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 100000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/objaverse_120frames_graph_adaln.json b/configs/objaverse_120frames_graph_adaln.json
new file mode 100644
index 0000000..23d094f
--- /dev/null
+++ b/configs/objaverse_120frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "objaverse_120frames_graph_adaln",
+ "output_dir": "./outputs/objaverse_120frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 120,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 8,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 24,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 100000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/objaverse_60frames_full_cross_attn.json b/configs/objaverse_60frames_full_cross_attn.json
new file mode 100644
index 0000000..3e10dc4
--- /dev/null
+++ b/configs/objaverse_60frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "objaverse_60frames_full_cross_attn",
+ "output_dir": "./outputs/objaverse_60frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 60,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 8,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 24,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 100000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/objaverse_60frames_graph_adaln.json b/configs/objaverse_60frames_graph_adaln.json
new file mode 100644
index 0000000..c3f85d1
--- /dev/null
+++ b/configs/objaverse_60frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "objaverse_60frames_graph_adaln",
+ "output_dir": "./outputs/objaverse_60frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 60,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 8,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 24,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 100000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/objaverse_90frames_full_cross_attn.json b/configs/objaverse_90frames_full_cross_attn.json
new file mode 100644
index 0000000..fdc5cba
--- /dev/null
+++ b/configs/objaverse_90frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "objaverse_90frames_full_cross_attn",
+ "output_dir": "./outputs/objaverse_90frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 90,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 8,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 24,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 100000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/objaverse_90frames_graph_adaln.json b/configs/objaverse_90frames_graph_adaln.json
new file mode 100644
index 0000000..b5e15ca
--- /dev/null
+++ b/configs/objaverse_90frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "objaverse_90frames_graph_adaln",
+ "output_dir": "./outputs/objaverse_90frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 90,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 8,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 24,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 100000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/truebones_120frames_full_cross_attn.json b/configs/truebones_120frames_full_cross_attn.json
new file mode 100644
index 0000000..34fd6be
--- /dev/null
+++ b/configs/truebones_120frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "truebones_120frames_full_cross_attn",
+ "output_dir": "./outputs/truebones_120frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 120,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 12,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 80000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/truebones_120frames_graph_adaln.json b/configs/truebones_120frames_graph_adaln.json
new file mode 100644
index 0000000..caf4140
--- /dev/null
+++ b/configs/truebones_120frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "truebones_120frames_graph_adaln",
+ "output_dir": "./outputs/truebones_120frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 120,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 12,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 80000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/truebones_60frames_full_cross_attn.json b/configs/truebones_60frames_full_cross_attn.json
new file mode 100644
index 0000000..062d82e
--- /dev/null
+++ b/configs/truebones_60frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "truebones_60frames_full_cross_attn",
+ "output_dir": "./outputs/truebones_60frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 60,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 24,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 80000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/truebones_60frames_graph_adaln.json b/configs/truebones_60frames_graph_adaln.json
new file mode 100644
index 0000000..9533615
--- /dev/null
+++ b/configs/truebones_60frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "truebones_60frames_graph_adaln",
+ "output_dir": "./outputs/truebones_60frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 60,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 24,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 80000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/truebones_90frames_full_cross_attn.json b/configs/truebones_90frames_full_cross_attn.json
new file mode 100644
index 0000000..effb03d
--- /dev/null
+++ b/configs/truebones_90frames_full_cross_attn.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "truebones_90frames_full_cross_attn",
+ "output_dir": "./outputs/truebones_90frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 90,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 16,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 80000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/truebones_90frames_graph_adaln.json b/configs/truebones_90frames_graph_adaln.json
new file mode 100644
index 0000000..5eb65c6
--- /dev/null
+++ b/configs/truebones_90frames_graph_adaln.json
@@ -0,0 +1,85 @@
+{
+ "experiment": {
+ "name": "truebones_90frames_graph_adaln",
+ "output_dir": "./outputs/truebones_90frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 90,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 6,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 16,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 80000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 3,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/uniml3d_120frames_full_cross_attn.json b/configs/uniml3d_120frames_full_cross_attn.json
new file mode 100644
index 0000000..8dc4d47
--- /dev/null
+++ b/configs/uniml3d_120frames_full_cross_attn.json
@@ -0,0 +1,87 @@
+{
+ "experiment": {
+ "name": "uniml3d_120frames_full_cross_attn",
+ "output_dir": "./outputs/uniml3d_120frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones",
+ "mixamo",
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 120,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 10,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 16,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 150000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 2,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/uniml3d_120frames_graph_adaln.json b/configs/uniml3d_120frames_graph_adaln.json
new file mode 100644
index 0000000..1bf9211
--- /dev/null
+++ b/configs/uniml3d_120frames_graph_adaln.json
@@ -0,0 +1,87 @@
+{
+ "experiment": {
+ "name": "uniml3d_120frames_graph_adaln",
+ "output_dir": "./outputs/uniml3d_120frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones",
+ "mixamo",
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 120,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 10,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 16,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 150000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 2,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/uniml3d_60frames_full_cross_attn.json b/configs/uniml3d_60frames_full_cross_attn.json
new file mode 100644
index 0000000..b0c8c8d
--- /dev/null
+++ b/configs/uniml3d_60frames_full_cross_attn.json
@@ -0,0 +1,87 @@
+{
+ "experiment": {
+ "name": "uniml3d_60frames_full_cross_attn",
+ "output_dir": "./outputs/uniml3d_60frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones",
+ "mixamo",
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 60,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 10,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 16,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 150000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 2,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/uniml3d_60frames_graph_adaln.json b/configs/uniml3d_60frames_graph_adaln.json
new file mode 100644
index 0000000..953b56d
--- /dev/null
+++ b/configs/uniml3d_60frames_graph_adaln.json
@@ -0,0 +1,87 @@
+{
+ "experiment": {
+ "name": "uniml3d_60frames_graph_adaln",
+ "output_dir": "./outputs/uniml3d_60frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones",
+ "mixamo",
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 60,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 10,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 16,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 150000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 2,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/uniml3d_90frames_full_cross_attn.json b/configs/uniml3d_90frames_full_cross_attn.json
new file mode 100644
index 0000000..b8b02c0
--- /dev/null
+++ b/configs/uniml3d_90frames_full_cross_attn.json
@@ -0,0 +1,87 @@
+{
+ "experiment": {
+ "name": "uniml3d_90frames_full_cross_attn",
+ "output_dir": "./outputs/uniml3d_90frames_full_cross_attn"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones",
+ "mixamo",
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 90,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "full",
+ "text_cond": "cross_attn",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 10,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 16,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 150000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 2,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/configs/uniml3d_90frames_graph_adaln.json b/configs/uniml3d_90frames_graph_adaln.json
new file mode 100644
index 0000000..33a79c4
--- /dev/null
+++ b/configs/uniml3d_90frames_graph_adaln.json
@@ -0,0 +1,87 @@
+{
+ "experiment": {
+ "name": "uniml3d_90frames_graph_adaln",
+ "output_dir": "./outputs/uniml3d_90frames_graph_adaln"
+ },
+ "truebones": {
+ "path": "dataset/features/truebones",
+ "objects_subset": "all"
+ },
+ "mixamo": {
+ "path": "dataset/features/mixamo"
+ },
+ "objaverse": {
+ "path": "dataset/features/objaverse",
+ "objects_num": -1,
+ "filter_object": false
+ },
+ "dataset": {
+ "dataset_list": [
+ "truebones",
+ "mixamo",
+ "objaverse"
+ ],
+ "topology_condition_type": "tpos",
+ "motion_repr": "unimate",
+ "test_split_ratio": 0.0,
+ "max_motion_length": 90,
+ "max_joints": 100,
+ "min_joints": 5,
+ "use_dataset_stats": true,
+ "balanced_stats": true,
+ "sampler_alpha": 0.5,
+ "use_addition_aug": true,
+ "use_removal_aug": true,
+ "use_pooling_aug": true,
+ "use_perturbation_aug": true,
+ "ground_motion_height": true,
+ "realign_feature": true
+ },
+ "model": {
+ "attention": "graph",
+ "text_cond": "adaln",
+ "use_joint_name_emb": true,
+ "latent_dim": 512,
+ "ff_size": 2048,
+ "num_layers": 10,
+ "num_heads": 8,
+ "dropout": 0.0,
+ "concat_parent_features": true,
+ "use_graph_emb": false,
+ "use_depth_emb": true,
+ "use_spectral_rope": true,
+ "max_freqs": 8,
+ "use_signnet": true,
+ "cond_mode": "text",
+ "cond_mask_prob": 0.1,
+ "text_encoder_type": "t5",
+ "text_encoder_version": "google/flan-t5-base",
+ "inject_tpos_to_adaln": true,
+ "num_tpos_queries": 4
+ },
+ "scheduler": {
+ "diffusion_steps": 100
+ },
+ "training": {
+ "batch_size": 16,
+ "seed": 10,
+ "diff_model": "flow",
+ "learning_rate": 0.0001,
+ "weight_decay": 1e-05,
+ "num_steps": 150000,
+ "log_interval": 50,
+ "save_interval": 10000,
+ "lambda_geo": 0.5,
+ "use_ema": true,
+ "ema_decay": 0.9999,
+ "max_grad_norm": 1.0,
+ "warmup_ratio": 0.03,
+ "min_lr_ratio": 0.05,
+ "balanced": true
+ },
+ "sampling": {
+ "num_samples": 2,
+ "num_repetitions": 3,
+ "cfg_scale": 3.0
+ }
+}
diff --git a/requirements.txt b/requirements.txt
index 1da48db..04b49b3 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -13,7 +13,10 @@
# envs ship setuptools >= 81 too); the pin below keeps it from upgrading.
#
# Only direct dependencies are listed; everything else (CUDA runtime libs,
-# tokenizers, HTTP stack, ...) is resolved transitively by pip.
+# tokenizers, HTTP stack, ...) is resolved transitively by pip. Versions are
+# pinned to the combination this project is developed and tested against;
+# `mathutils` / `bmesh` need no line of their own (they ship inside the bpy
+# wheel), nor does `mpl_toolkits` (inside matplotlib).
# PyTorch cu124 wheels (torch / torchvision "+cu124" pins below)
--extra-index-url https://download.pytorch.org/whl/cu124
@@ -25,6 +28,9 @@ setuptools<81 # keeps pkg_resources available (Motion build)
# โ”€โ”€ Core / training โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
numpy==2.2.6
torch==2.5.1+cu124
+# Pulled in by the CLIP text encoder (clip/clip.py imports torchvision.transforms
+# at module load). Pinned to the matching +cu124 build so pip cannot resolve a
+# torchvision compiled against a different torch/CUDA and drag torch with it.
torchvision==0.20.1+cu124
torch-geometric==2.7.0 # GCN graph embedding (use_graph_emb)
torchdiffeq==0.2.5 # ODE/SDE integrators for flow matching
@@ -36,10 +42,15 @@ tensorboard==2.20.0 # training logs (SummaryWriter)
transformers==5.16.1 # T5/BERT text encoders; local Qwen3-VL captioner needs >=4.57, Qwen3.5 (qwen3_5 arch) needs 5.x
sentencepiece==0.2.1 # T5 tokenizer backend
clip @ git+https://github.com/openai/CLIP.git # CLIP text encoder
-spacy # T5 conditioner text normalization
-num2words # number โ†’ word expansion in text normalization
-openai # OpenAI-compatible backends (captioning; DeepSeek/GPT joint annotation)
-google-genai # Gemini caption backend ("from google import genai")
+# spaCy must stay on the 3.8 line: the model wheel below is built for it and a
+# 3.9/4.x resolution would install a spaCy that cannot load it.
+spacy>=3.8,<3.9 # T5 conditioner text normalization
+# spaCy language model. Listing it here keeps offline compute nodes working:
+# the code's spacy.cli.download fallback needs internet access.
+en-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl
+num2words==0.5.14 # number โ†’ word expansion in text normalization
+openai==3.3.1 # OpenAI-compatible backends (captioning; DeepSeek/GPT joint annotation)
+google-genai==2.19.0 # Gemini caption backend ("from google import genai")
# OPTIONAL โ€” fused attention for the local Qwen3-VL captioner. The loader
# falls back to SDPA when absent, and the prebuilt wheels only exist for a
@@ -47,6 +58,13 @@ google-genai # Gemini caption backend ("from google import ge
# so it is not installed by default:
# pip install flash-attn==2.7.4.post1 --no-build-isolation
+# โ”€โ”€ Hugging Face Hub โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+# Also a transformers dependency, but listed on its own because the download
+# stage shells out to the `hf` CLI this package installs
+# (data_process/scripts/run_download.sh). The standalone installer at
+# https://hf.co/cli/install.sh works too if you prefer it outside the env.
+huggingface_hub==1.29.0
+
# โ”€โ”€ Motion / animation library (Holden-style Animation / Quaternions /
# InverseKinematics; used across data_process/) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Motion @ git+https://github.com/inbar-2344/Motion.git
@@ -67,5 +85,5 @@ pillow==12.2.0
# โ”€โ”€ CLI / logging โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
tyro==1.0.12 # config + CLI overrides
rich==14.3.3
-loguru
+loguru==0.7.3
tqdm==4.67.3
diff --git a/scripts/_common.sh b/scripts/_common.sh
new file mode 100644
index 0000000..916ea53
--- /dev/null
+++ b/scripts/_common.sh
@@ -0,0 +1,56 @@
+# shellcheck shell=bash
+# Shared prologue for every scripts/run_*.sh wrapper.
+#
+# source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
+#
+# Resolves PROJECT_ROOT (the repository root), cds into it, activates the
+# conda environment named by $CONDA_ENV (default: unimate) when conda is
+# available, and defines the helpers below.
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+# Resolve the sourcing wrapper's own path before the cd below so that
+# print_usage still finds it when the wrapper was invoked by a relative path.
+WRAPPER_PATH="${BASH_SOURCE[1]:-$0}"
+[[ "$WRAPPER_PATH" == /* ]] || WRAPPER_PATH="$PWD/$WRAPPER_PATH"
+cd "$PROJECT_ROOT"
+
+CONDA_ENV=${CONDA_ENV:-unimate}
+if command -v conda >/dev/null 2>&1; then
+ # conda activation hooks reference unset variables; relax `set -u` around them.
+ case $- in *u*) _had_nounset=1 ;; *) _had_nounset=0 ;; esac
+ set +u
+ eval "$(conda shell.bash hook 2>/dev/null)"
+ conda activate "$CONDA_ENV" 2>/dev/null \
+ || echo "warning: could not activate conda env '$CONDA_ENV'; using current python" >&2
+ [[ "$_had_nounset" == 1 ]] && set -u
+fi
+
+# print_usage : print the leading comment block of the calling wrapper.
+print_usage() {
+ sed -n '2,/^$/p' "$WRAPPER_PATH" | sed 's/^# \{0,1\}//'
+}
+
+# handle_help "$@" : print the wrapper usage and exit 0 on -h / --help.
+# Call it right after sourcing this file, before any other argument checks.
+handle_help() {
+ case "${1:-}" in
+ -h|--help) print_usage; exit 0 ;;
+ esac
+}
+
+# select_gpu : unless CUDA_VISIBLE_DEVICES is already set, pin the run to the
+# GPU with the most free memory. No-op when nvidia-smi is unavailable.
+select_gpu() {
+ if [[ -n "${CUDA_VISIBLE_DEVICES:-}" ]]; then
+ echo "GPU: CUDA_VISIBLE_DEVICES=$CUDA_VISIBLE_DEVICES"
+ return 0
+ fi
+ command -v nvidia-smi >/dev/null 2>&1 || return 0
+ local gpu
+ gpu=$(nvidia-smi --query-gpu=memory.free --format=csv,noheader,nounits \
+ | awk '{print NR-1, $1}' | sort -k2 -nr | head -n 1 | awk '{print $1}')
+ [[ -n "$gpu" ]] || return 0
+ export CUDA_VISIBLE_DEVICES=$gpu
+ echo "GPU: $gpu (most free memory)"
+}
diff --git a/scripts/run_animate_motion.sh b/scripts/run_animate_motion.sh
new file mode 100755
index 0000000..ec864dc
--- /dev/null
+++ b/scripts/run_animate_motion.sh
@@ -0,0 +1,158 @@
+#!/bin/bash
+# Drive a rigged character with motion clips โ€” generated .npy or extracted .npz โ€”
+# and export GLB + FBX (batch front-end for stage 5 of data_process/).
+#
+# Usage:
+# bash scripts/run_animate_motion.sh <DATASET_TYPE> <INPUT...> [OUTPUT_DIR]
+# bash scripts/run_animate_motion.sh -h | --help
+#
+# DATASET_TYPE: truebones | objaverse | mixamo
+# INPUT...: one or more .npy / .npz files, or a single directory containing them
+# OUTPUT_DIR: directory to save .glb / .fbx outputs (default: outputs/animated)
+# Detected as the last arg when it does not end in .npy / .npz.
+#
+# Env overrides:
+# ANIM_MODE (default: fk), CHAR_PATH (default: auto),
+# COND_PATH (default: dataset/features/<DATASET_TYPE>/cond.npy)
+#
+# Output: $OUTPUT_DIR/<anim_stem>.{glb,fbx}
+
+set -eo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+cd "$PROJECT_ROOT"
+
+STAGE1_WRAPPER="$PROJECT_ROOT/data_process/scripts/run_animate_motion.sh"
+# COND_PATH is an optional override; when unset, the data_process wrapper
+# defaults to the feature-extraction layout: dataset/features/<dataset>/cond.npy.
+
+if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
+ sed -n '2,/^$/p' "$0" | sed 's/^# \{0,1\}//'
+ exit 0
+fi
+
+if [ "$#" -lt 2 ]; then
+ echo "ERROR: expected at least 2 positional args: <DATASET_TYPE> <INPUT...> [OUTPUT_DIR]" >&2
+ echo "Usage: bash $(basename "$0") <DATASET_TYPE> <INPUT...> [OUTPUT_DIR]" >&2
+ exit 1
+fi
+
+DATASET_TYPE="$1"
+shift
+
+case "$DATASET_TYPE" in
+ truebones|objaverse|mixamo) ;;
+ *)
+ echo "ERROR: unknown DATASET_TYPE='$DATASET_TYPE' (expected: truebones | objaverse | mixamo)" >&2
+ exit 1
+ ;;
+esac
+
+# The last arg is OUTPUT_DIR iff it doesn't look like a motion file
+# (and there are at least 2 remaining args, so an input is still present).
+# Use a portable last-arg lookup so this still works when bash is invoked as `sh`
+# (where `${!#}` and `${@:1:N}` can misbehave under POSIX mode).
+ALL_ARGS=("$@")
+NARGS=$#
+LAST_ARG="${ALL_ARGS[$((NARGS - 1))]}"
+case "$LAST_ARG" in
+ *.npy|*.npz)
+ OUTPUT_DIR="outputs/animated"
+ INPUT_ARGS=("${ALL_ARGS[@]}")
+ ;;
+ *)
+ if [ "$NARGS" -eq 1 ]; then
+ OUTPUT_DIR="outputs/animated"
+ INPUT_ARGS=("${ALL_ARGS[@]}")
+ else
+ OUTPUT_DIR="$LAST_ARG"
+ unset 'ALL_ARGS[NARGS - 1]'
+ INPUT_ARGS=("${ALL_ARGS[@]}")
+ fi
+ ;;
+esac
+
+ANIM_PATHS=()
+if [ "${#INPUT_ARGS[@]}" -eq 1 ] && [ -d "${INPUT_ARGS[0]}" ]; then
+ INPUT_DIR="${INPUT_ARGS[0]}"
+ shopt -s nullglob
+ ANIM_PATHS=("$INPUT_DIR"/*.npy "$INPUT_DIR"/*.npz)
+ shopt -u nullglob
+ if [ "${#ANIM_PATHS[@]}" -eq 0 ]; then
+ echo "ERROR: no .npy / .npz motion files found in: '$INPUT_DIR'" >&2
+ exit 1
+ fi
+ INPUT_DESC="$INPUT_DIR"
+else
+ for f in "${INPUT_ARGS[@]}"; do
+ if [ ! -f "$f" ]; then
+ echo "ERROR: input not found: '$f'" >&2
+ exit 1
+ fi
+ ANIM_PATHS+=("$f")
+ done
+ INPUT_DESC="${#INPUT_ARGS[@]} file(s)"
+fi
+
+ANIM_MODE=${ANIM_MODE:-fk}
+
+mkdir -p "$OUTPUT_DIR"
+
+process_one_motion() {
+ local anim_path="$1"
+ local idx="$2"
+ local total="$3"
+
+ local anim_stem
+ anim_stem=$(basename "$anim_path")
+ anim_stem=${anim_stem%.*}
+
+ local exported_fbx="$OUTPUT_DIR/$anim_stem.fbx"
+ local exported_glb="$OUTPUT_DIR/$anim_stem.glb"
+
+ echo "############################################################"
+ echo "# [$idx/$total] $anim_stem"
+ echo "# ANIM_PATH = $anim_path"
+ echo "# DATASET_TYPE = $DATASET_TYPE"
+ echo "# OUTPUT_DIR = $OUTPUT_DIR"
+ echo "# ANIM_MODE = $ANIM_MODE"
+ echo "# CHAR_PATH = ${CHAR_PATH:-<auto>}"
+ echo "############################################################"
+ (
+ export OUTPUT_DIR ANIM_MODE
+ export ANIM_PATH="$anim_path"
+ if [ -n "${COND_PATH:-}" ]; then
+ export COND_PATH
+ fi
+ if [ -n "${CHAR_PATH:-}" ]; then
+ export CHAR_PATH
+ fi
+ bash "$STAGE1_WRAPPER" "$DATASET_TYPE"
+ )
+
+ if [ ! -f "$exported_fbx" ]; then
+ echo "ERROR: did not produce expected FBX at '$exported_fbx'" >&2
+ return 1
+ fi
+
+ echo "[$idx/$total] DONE glb=$exported_glb fbx=$exported_fbx"
+}
+
+TOTAL=${#ANIM_PATHS[@]}
+echo "============================================================"
+echo "DATASET_TYPE = $DATASET_TYPE (${TOTAL} motion(s))"
+echo "INPUT = $INPUT_DESC"
+echo "OUTPUT_DIR = $OUTPUT_DIR"
+for ((i = 0; i < TOTAL; i++)); do
+ echo " [$((i + 1))/$TOTAL] ${ANIM_PATHS[$i]}"
+done
+echo "============================================================"
+
+for ((i = 0; i < TOTAL; i++)); do
+ process_one_motion "${ANIM_PATHS[$i]}" "$((i + 1))" "$TOTAL"
+done
+
+echo "============================================================"
+echo "BATCH DONE โ€” ${TOTAL} motion(s) processed."
+echo "============================================================"
diff --git a/scripts/run_sample_motion_edit.sh b/scripts/run_sample_motion_edit.sh
new file mode 100755
index 0000000..575a134
--- /dev/null
+++ b/scripts/run_sample_motion_edit.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+# Text-guided motion editing: hold the listed joints of a reference clip at
+# their ground-truth motion and regenerate the remaining joints under a new
+# prompt (e.g. keep the lower body of a walk and add an upper-body wave).
+#
+# Usage:
+# KEEP_JOINTS="Hips,LeftUpLeg,LeftLeg,RightUpLeg,RightLeg" \
+# bash scripts/run_sample_motion_edit.sh <exp_dir> [test_cases_json] [cfg_scale]
+#
+# Arguments:
+# exp_dir training output directory (config.json, dataset_stats.npy, checkpoints/)
+# test_cases_json {"<object_type>-<clip_id>": "edited prompt"} โ€” keys must name
+# dataset clips (their motion is the clamped ground truth); omit
+# to use every clip of the eval split with its original caption
+# cfg_scale classifier-free guidance scale (default: value saved in the run's config)
+#
+# Env overrides:
+# KEEP_JOINTS (required) comma-separated joint names to hold, matched
+# case-insensitively against the rig's joint names
+# GT_START_FRAME absolute frame at which the reference window starts
+# (default: random window)
+# REPLICATE edits per clip (default: 3); each draws a new window and noise
+# SEED integer seed for deterministic cropping and noise (default: unset)
+# OUTPUT_DIR (default: <exp_dir>/samples[_<stem>]_edit_<first joint>_n<count>)
+# CONDA_ENV conda environment to activate (default: unimate)
+# CUDA_VISIBLE_DEVICES GPU to use (default: the one with the most free memory)
+#
+# Results land in <OUTPUT_DIR>/motion_edit/, next to the clamped ground truth (gt_rep_<r>-*).
+
+set -euo pipefail
+source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
+handle_help "$@"
+
+EXP_DIR=${1:?Usage: run_sample_motion_edit.sh <exp_dir> [test_cases_json] [cfg_scale]}
+TEST_CASES=${2:-}
+CFG_SCALE=${3:-}
+KEEP_JOINTS=${KEEP_JOINTS:?Set KEEP_JOINTS to a comma-separated list of joint names to hold}
+GT_START_FRAME=${GT_START_FRAME:-}
+REPLICATE=${REPLICATE:-3}
+SEED=${SEED:-}
+
+TEST_NAME=${TEST_CASES:+$(basename "${TEST_CASES%.json}")}
+# Filesystem-safe tag for the keep list: first joint name + joint count.
+FIRST_JOINT=$(echo "$KEEP_JOINTS" | cut -d',' -f1 | tr -cd '[:alnum:]_')
+N_JOINTS=$(echo "$KEEP_JOINTS" | awk -F',' '{print NF}')
+OUTPUT_DIR=${OUTPUT_DIR:-$EXP_DIR/samples${TEST_NAME:+_$TEST_NAME}_edit_${FIRST_JOINT}_n${N_JOINTS}}
+
+select_gpu
+echo "Exp dir: $EXP_DIR"
+echo "Test cases: ${TEST_CASES:-<eval split>}"
+echo "Cfg scale: ${CFG_SCALE:-<config default>}"
+echo "Keep joints: $KEEP_JOINTS"
+echo "GT start: ${GT_START_FRAME:-<random window>}"
+echo "Replicate: $REPLICATE"
+echo "Output dir: $OUTPUT_DIR/motion_edit"
+
+CMD=(python -m unimate.inference.sample
+ --exp_dir "$EXP_DIR" --output_dir "$OUTPUT_DIR" --num_repetitions "$REPLICATE"
+ --motion_edit --keep_joints "$KEEP_JOINTS")
+[[ -n "$TEST_CASES" ]] && CMD+=(--test_cases_json "$TEST_CASES")
+[[ -n "$CFG_SCALE" ]] && CMD+=(--cfg_scale "$CFG_SCALE")
+[[ -n "$GT_START_FRAME" ]] && CMD+=(--gt_start_frame "$GT_START_FRAME")
+[[ -n "$SEED" ]] && CMD+=(--seed "$SEED")
+
+"${CMD[@]}"
diff --git a/scripts/run_sample_motion_expand.sh b/scripts/run_sample_motion_expand.sh
new file mode 100644
index 0000000..f21cd75
--- /dev/null
+++ b/scripts/run_sample_motion_expand.sh
@@ -0,0 +1,55 @@
+#!/bin/bash
+# Motion expansion: chain several prompts into one long motion. The first
+# segment is generated freely; every later segment pins its first
+# EXPAND_OVERLAP frames to the previous segment's tail, and the segments are
+# stitched at the seam.
+#
+# Usage:
+# bash scripts/run_sample_motion_expand.sh <exp_dir> <test_cases_json> [cfg_scale]
+#
+# Arguments:
+# exp_dir training output directory (config.json, dataset_stats.npy, checkpoints/)
+# test_cases_json {"<object_type>-<label>": ["prompt 1", "prompt 2", ...]} โ€” one
+# prompt per segment, in order
+# cfg_scale classifier-free guidance scale (default: value saved in the run's config)
+#
+# Env overrides:
+# EXPAND_OVERLAP frames shared by consecutive segments; 0 < overlap <
+# max_motion_length (default: 10)
+# REPLICATE independent chains per case (default: 3)
+# SEED integer seed for deterministic noise (default: unset)
+# OUTPUT_DIR (default: <exp_dir>/samples_<stem>_expand_o<overlap>)
+# CONDA_ENV conda environment to activate (default: unimate)
+# CUDA_VISIBLE_DEVICES GPU to use (default: the one with the most free memory)
+#
+# Results land in <OUTPUT_DIR>/motion_expand/.
+
+set -euo pipefail
+source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
+handle_help "$@"
+
+EXP_DIR=${1:?Usage: run_sample_motion_expand.sh <exp_dir> <test_cases_json> [cfg_scale]}
+TEST_CASES=${2:?Usage: run_sample_motion_expand.sh <exp_dir> <test_cases_json> [cfg_scale]}
+CFG_SCALE=${3:-}
+EXPAND_OVERLAP=${EXPAND_OVERLAP:-10}
+REPLICATE=${REPLICATE:-3}
+SEED=${SEED:-}
+
+TEST_NAME=$(basename "${TEST_CASES%.json}")
+OUTPUT_DIR=${OUTPUT_DIR:-$EXP_DIR/samples_${TEST_NAME}_expand_o${EXPAND_OVERLAP}}
+
+select_gpu
+echo "Exp dir: $EXP_DIR"
+echo "Test cases: $TEST_CASES"
+echo "Cfg scale: ${CFG_SCALE:-<config default>}"
+echo "Overlap: $EXPAND_OVERLAP"
+echo "Replicate: $REPLICATE"
+echo "Output dir: $OUTPUT_DIR/motion_expand"
+
+CMD=(python -m unimate.inference.sample
+ --exp_dir "$EXP_DIR" --output_dir "$OUTPUT_DIR" --num_repetitions "$REPLICATE"
+ --motion_expand --expand_overlap "$EXPAND_OVERLAP" --test_cases_json "$TEST_CASES")
+[[ -n "$CFG_SCALE" ]] && CMD+=(--cfg_scale "$CFG_SCALE")
+[[ -n "$SEED" ]] && CMD+=(--seed "$SEED")
+
+"${CMD[@]}"
diff --git a/scripts/run_sample_motion_inbetween.sh b/scripts/run_sample_motion_inbetween.sh
new file mode 100755
index 0000000..b0af8e4
--- /dev/null
+++ b/scripts/run_sample_motion_inbetween.sh
@@ -0,0 +1,62 @@
+#!/bin/bash
+# Motion in-betweening: hold the listed frames of a reference clip at their
+# ground truth and let the flow ODE generate the rest.
+#
+# Usage:
+# bash scripts/run_sample_motion_inbetween.sh <exp_dir> [test_cases_json] [cfg_scale]
+# KEEP_FRAMES="0,15,-1" bash scripts/run_sample_motion_inbetween.sh <exp_dir> cases.json
+#
+# Arguments:
+# exp_dir training output directory (config.json, dataset_stats.npy, checkpoints/)
+# test_cases_json {"<object_type>-<clip_id>": "prompt"} โ€” keys must name dataset
+# clips (their motion is the clamped ground truth); omit to use
+# every clip of the eval split with its original caption
+# cfg_scale classifier-free guidance scale (default: value saved in the run's config)
+#
+# Env overrides:
+# KEEP_FRAMES comma-separated signed frame indices to hold; negatives
+# count from the end (default: "0,-1" โ€” first and last frame)
+# GT_START_FRAME absolute frame at which the reference window starts
+# (default: random window)
+# REPLICATE samples per clip (default: 3); each draws a new window and noise
+# SEED integer seed for deterministic cropping and noise (default: unset)
+# OUTPUT_DIR (default: <exp_dir>/samples[_<stem>]_inbetween_<keep tag>)
+# CONDA_ENV conda environment to activate (default: unimate)
+# CUDA_VISIBLE_DEVICES GPU to use (default: the one with the most free memory)
+#
+# Results land in <OUTPUT_DIR>/inbetween/, next to the clamped ground truth (gt_rep_<r>-*).
+
+set -euo pipefail
+source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
+handle_help "$@"
+
+EXP_DIR=${1:?Usage: run_sample_motion_inbetween.sh <exp_dir> [test_cases_json] [cfg_scale]}
+TEST_CASES=${2:-}
+CFG_SCALE=${3:-}
+KEEP_FRAMES=${KEEP_FRAMES:-0,-1}
+GT_START_FRAME=${GT_START_FRAME:-}
+REPLICATE=${REPLICATE:-3}
+SEED=${SEED:-}
+
+TEST_NAME=${TEST_CASES:+$(basename "${TEST_CASES%.json}")}
+KEEP_TAG=$(echo "$KEEP_FRAMES" | sed 's/,/_/g; s/-/n/g') # "0,-1" -> "0_n1"
+OUTPUT_DIR=${OUTPUT_DIR:-$EXP_DIR/samples${TEST_NAME:+_$TEST_NAME}_inbetween_${KEEP_TAG}}
+
+select_gpu
+echo "Exp dir: $EXP_DIR"
+echo "Test cases: ${TEST_CASES:-<eval split>}"
+echo "Cfg scale: ${CFG_SCALE:-<config default>}"
+echo "Keep frames: $KEEP_FRAMES"
+echo "GT start: ${GT_START_FRAME:-<random window>}"
+echo "Replicate: $REPLICATE"
+echo "Output dir: $OUTPUT_DIR/inbetween"
+
+CMD=(python -m unimate.inference.sample
+ --exp_dir "$EXP_DIR" --output_dir "$OUTPUT_DIR" --num_repetitions "$REPLICATE"
+ --inbetween --keep_frames "$KEEP_FRAMES")
+[[ -n "$TEST_CASES" ]] && CMD+=(--test_cases_json "$TEST_CASES")
+[[ -n "$CFG_SCALE" ]] && CMD+=(--cfg_scale "$CFG_SCALE")
+[[ -n "$GT_START_FRAME" ]] && CMD+=(--gt_start_frame "$GT_START_FRAME")
+[[ -n "$SEED" ]] && CMD+=(--seed "$SEED")
+
+"${CMD[@]}"
diff --git a/scripts/run_sample_motion_text.sh b/scripts/run_sample_motion_text.sh
new file mode 100644
index 0000000..f8c9ca4
--- /dev/null
+++ b/scripts/run_sample_motion_text.sh
@@ -0,0 +1,46 @@
+#!/bin/bash
+# Text-conditioned sampling from a trained UniMate run.
+#
+# Usage:
+# bash scripts/run_sample_motion_text.sh <exp_dir> [test_cases_json] [cfg_scale]
+#
+# Arguments:
+# exp_dir training output directory (config.json, dataset_stats.npy, checkpoints/)
+# test_cases_json {"<object_type>-<case_id>": "prompt"}; omit to enumerate the
+# dataset's eval split (or its train prompts when there is none)
+# cfg_scale classifier-free guidance scale (default: value saved in the run's config)
+#
+# Env overrides:
+# REPLICATE samples per test case (default: 3)
+# SEED integer seed for deterministic noise (default: unset)
+# OUTPUT_DIR (default: <exp_dir>/samples[_<test_cases stem>])
+# CONDA_ENV conda environment to activate (default: unimate)
+# CUDA_VISIBLE_DEVICES GPU to use (default: the one with the most free memory)
+
+set -euo pipefail
+source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
+handle_help "$@"
+
+EXP_DIR=${1:?Usage: run_sample_motion_text.sh <exp_dir> [test_cases_json] [cfg_scale]}
+TEST_CASES=${2:-}
+CFG_SCALE=${3:-}
+REPLICATE=${REPLICATE:-3}
+SEED=${SEED:-}
+
+TEST_NAME=${TEST_CASES:+$(basename "${TEST_CASES%.json}")}
+OUTPUT_DIR=${OUTPUT_DIR:-$EXP_DIR/samples${TEST_NAME:+_$TEST_NAME}}
+
+select_gpu
+echo "Exp dir: $EXP_DIR"
+echo "Test cases: ${TEST_CASES:-<dataset split>}"
+echo "Cfg scale: ${CFG_SCALE:-<config default>}"
+echo "Replicate: $REPLICATE"
+echo "Output dir: $OUTPUT_DIR"
+
+CMD=(python -m unimate.inference.sample
+ --exp_dir "$EXP_DIR" --output_dir "$OUTPUT_DIR" --num_repetitions "$REPLICATE")
+[[ -n "$TEST_CASES" ]] && CMD+=(--test_cases_json "$TEST_CASES")
+[[ -n "$CFG_SCALE" ]] && CMD+=(--cfg_scale "$CFG_SCALE")
+[[ -n "$SEED" ]] && CMD+=(--seed "$SEED")
+
+"${CMD[@]}"
diff --git a/scripts/run_train.sh b/scripts/run_train.sh
new file mode 100755
index 0000000..c86e9d3
--- /dev/null
+++ b/scripts/run_train.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+# Train a UniMate model on a single GPU.
+#
+# Usage:
+# bash scripts/run_train.sh [config] [-- extra args...]
+#
+# Arguments:
+# config training config JSON (default: configs/uniml3d_60frames_graph_adaln.json)
+# extra anything after `--` is forwarded to unimate.training.train,
+# e.g. --batch_size 8 --resume outputs/<run>/checkpoints/<ckpt>.pt
+#
+# Env overrides:
+# OUTPUT_DIR (default: the config's experiment.output_dir)
+# CONDA_ENV conda environment to activate (default: unimate)
+# CUDA_VISIBLE_DEVICES GPU to use (default: the one with the most free memory)
+#
+# For multi-GPU runs use scripts/slurm/slurm_train.sh instead.
+
+set -euo pipefail
+source "$(dirname "${BASH_SOURCE[0]}")/_common.sh"
+handle_help "$@"
+
+CONFIG=${1:-configs/uniml3d_60frames_graph_adaln.json}
+shift || true
+[[ "${1:-}" == "--" ]] && shift
+
+[[ -f "$CONFIG" ]] || { echo "No such config: $CONFIG" >&2; exit 1; }
+
+select_gpu
+echo "Config: $CONFIG"
+echo "Output dir: ${OUTPUT_DIR:-<config default>}"
+
+CMD=(accelerate launch -m unimate.training.train --config "$CONFIG")
+[[ -n "${OUTPUT_DIR:-}" ]] && CMD+=(--output_dir "$OUTPUT_DIR")
+
+"${CMD[@]}" "$@"
diff --git a/unimate/__init__.py b/unimate/__init__.py
new file mode 100644
index 0000000..a631cb1
--- /dev/null
+++ b/unimate/__init__.py
@@ -0,0 +1 @@
+"""UniMate: diffusion-based motion generation across heterogeneous skeleton topologies."""
diff --git a/unimate/configs/__init__.py b/unimate/configs/__init__.py
new file mode 100644
index 0000000..09298b0
--- /dev/null
+++ b/unimate/configs/__init__.py
@@ -0,0 +1,27 @@
+"""Re-export the config dataclasses so ``from unimate.configs import X`` works."""
+
+from unimate.configs.schema import (
+ MainConfig,
+ TruebonesConfig,
+ MixamoConfig,
+ ObjaverseConfig,
+ ExperimentConfig,
+ DatasetConfig,
+ ModelConfig,
+ SchedulerConfig,
+ TrainingConfig,
+ SamplingArgs,
+)
+
+__all__ = [
+ "MainConfig",
+ "TruebonesConfig",
+ "MixamoConfig",
+ "ObjaverseConfig",
+ "ExperimentConfig",
+ "DatasetConfig",
+ "ModelConfig",
+ "SchedulerConfig",
+ "TrainingConfig",
+ "SamplingArgs",
+]
diff --git a/unimate/configs/schema.py b/unimate/configs/schema.py
new file mode 100644
index 0000000..9c2d967
--- /dev/null
+++ b/unimate/configs/schema.py
@@ -0,0 +1,410 @@
+"""Configuration schema for motion generation.
+
+This module defines the configuration structure for the entire training pipeline.
+"""
+
+import dataclasses
+from dataclasses import dataclass, field
+from typing import Optional, Union, List, Dict
+from pathlib import Path
+import json
+
+
+# ---------------------------------------------------------------------------
+# Experiment config
+# ---------------------------------------------------------------------------
+
+@dataclass
+class ExperimentConfig:
+ """Experiment configuration."""
+ name: str
+ output_dir: str
+
+
+# ---------------------------------------------------------------------------
+# Per-dataset configs (top-level JSON keys)
+# ---------------------------------------------------------------------------
+
+@dataclass
+class TruebonesConfig:
+ """Truebones dataset specific configuration.
+
+ ``path`` points at a feature-extraction output directory (see
+ ``data_process/feature_extraction/extract_features.py``): ``cond.npy``,
+ ``captions.json`` and per-clip NPZs under ``motions/``.
+ """
+ type: str = "truebones"
+ path: str = "dataset/features/truebones"
+ objects_subset: str = "all" # 'all' or a key of {path}/category_groups.json
+
+
+@dataclass
+class MixamoConfig:
+ """Mixamo dataset specific configuration."""
+ type: str = "mixamo"
+ path: str = "dataset/features/mixamo"
+
+
+@dataclass
+class ObjaverseConfig:
+ """Objaverse dataset specific configuration."""
+ type: str = "objaverse"
+ path: str = "dataset/features/objaverse"
+ objects_num: int = -1 # Number of object types to use (-1 = all)
+ filter_object: bool = False # If True, exclude object types listed in {path}/filtered_objects.txt
+
+
+# ---------------------------------------------------------------------------
+# Dataset config (shared settings + mixture routing)
+# ---------------------------------------------------------------------------
+
+@dataclass
+class DatasetConfig:
+ """Dataset configuration.
+
+ All datasets are loaded via the unified Mixture pipeline.
+ Use ``dataset_list`` to specify which sub-datasets to include
+ (e.g. ``["truebones"]`` for single-dataset, ``["truebones", "mixamo"]`` for combined).
+ """
+ dataset_list: List[str] = field(default_factory=lambda: ["truebones"])
+
+ # Per-dataset configs (populated from top-level JSON keys)
+ truebones: Optional[TruebonesConfig] = None
+ mixamo: Optional[MixamoConfig] = None
+ objaverse: Optional[ObjaverseConfig] = None
+
+ # Topology conditioning
+ topology_condition_type: str = "tpos" # 'tpos' or 'first_frame'
+
+ # Motion representation. Only 'unimate' is supported: 12-dim per joint โ€”
+ # RIFKE position (3) + reordered 6D rotation (6) + local velocity (3).
+ motion_repr: str = "unimate"
+ max_motion_length: Optional[int] = 40 # Maximum frames per clip
+ max_joints: int = 100 # Filter cap: objects with > max_joints joints are skipped; the padded width is then auto-computed from what remains
+ min_joints: int = 5 # Filter floor: objects with < min_joints joints are skipped
+ max_depth: int = 0 # Depth cap: 0 = use auto-computed; >0 = min(auto-computed, max_depth)
+ feature_len: int = 12 # Per-joint feature width; always 12 (enforced in __post_init__)
+
+ # Normalization
+ use_dataset_stats: bool = True # True: stats keyed per dataset_type; False: one global pool across all motions
+ balanced_stats: bool = False # True: equal-weight per object type; False: frame-weighted pooling
+ tie_std: bool = False # True: average std within position(0:3) and rotation(3:9) groups
+
+ # Sampling
+ sampler_alpha: float = 0.5 # Power-law exponent: 0=uniform-per-sample, 0.5=sqrt-balanced, 1=uniform-per-type
+
+ # Train/eval split (clip-level, stratified per object_type).
+ # test_split_ratio=0 disables splitting (all clips โ†’ train).
+ test_split_ratio: float = 0.0
+ split_seed: int = 42
+
+ # Augmentation
+ use_addition_aug: bool = False # Joint addition (ellipsoid) augmentation
+ use_removal_aug: bool = False # Leaf-joint removal augmentation
+ use_pooling_aug: bool = False # Skeleton pooling (merge pass-through joints) augmentation
+ use_perturbation_aug: bool = False # Random per-bone length scaling (positions recomputed via FK)
+
+ # Per-clip Y grounding: shift so the lowest joint sits on Y=0 (also applied to tpos)
+ ground_motion_height: bool = True
+
+ # Re-align cropped clips so frame-0 facing is identity (only applies when start_idx > 0)
+ realign_feature: bool = True
+
+ # Runtime field โ€” populated in __post_init__, not serialized
+ data_configs: Optional[Dict[str, Union[TruebonesConfig, MixamoConfig, ObjaverseConfig]]] = field(default_factory=dict)
+
+ def __post_init__(self):
+ if not self.dataset_list:
+ raise ValueError("dataset_list must be non-empty.")
+
+ if self.motion_repr != 'unimate':
+ raise ValueError(
+ f"Unknown motion_repr: {self.motion_repr!r}, must be 'unimate'"
+ )
+ self.feature_len = 12
+
+ if self.topology_condition_type not in ('tpos', 'first_frame'):
+ raise ValueError(
+ f"Unknown topology_condition_type: {self.topology_condition_type!r}, "
+ "must be 'tpos' or 'first_frame'"
+ )
+
+ _config_map = {
+ 'truebones': lambda: self.truebones or TruebonesConfig(),
+ 'mixamo': lambda: self.mixamo or MixamoConfig(),
+ 'objaverse': lambda: self.objaverse or ObjaverseConfig(),
+ }
+ for ds_type in self.dataset_list:
+ factory = _config_map.get(ds_type)
+ if factory is None:
+ raise ValueError(f"Unknown dataset type in dataset_list: {ds_type}")
+ self.data_configs[ds_type] = factory()
+
+
+# ---------------------------------------------------------------------------
+# Model config
+# ---------------------------------------------------------------------------
+
+@dataclass
+class ModelConfig:
+ """Model configuration."""
+ # Two orthogonal axes, not one name.
+ # attention 'full' โ€” one attention over the flattened T*J tokens
+ # 'graph' โ€” factored spatial (per-frame) + temporal (per-joint),
+ # the spatial stage carrying graph-distance and
+ # edge-type biases
+ # text_cond 'adaln' โ€” the caption is folded into the adaLN vector
+ # 'cross_attn' โ€” the caption enters each block as
+ # cross-attention K/V
+ # The legacy single ``type`` field conflated the two, which hid that
+ # 'graph' and 'cross' shared an attention stack and differed only in how the
+ # caption enters; ``from_json`` still accepts it and maps it over. Not
+ # every pair is implemented โ€” ``models.factory`` owns that table.
+ attention: str = "graph"
+ text_cond: str = "adaln"
+
+ # Architecture
+ latent_dim: int = 512
+ ff_size: int = 2048
+ num_layers: int = 8
+ num_heads: int = 8
+ dropout: float = 0.0
+
+ # Positional encoding
+ use_spectral_rope: bool = False # True: spectral RoPE on the joint axis (backend per use_signnet); False: sinusoidal RoPE
+ max_freqs: int = 8 # Laplacian eigenvectors per joint (only used when use_spectral_rope=True)
+ use_signnet: bool = True # Spectral encoder backend: True=SignNet (sign-invariant), False=WIRE learnable frequencies
+
+ # Conditioning
+ cond_mode: str = "no_cond" # 'no_cond', 'text' (caption CFG)
+ cond_mask_prob: float = 0.0 # Probability of masking cond during training (enables CFG at inference)
+
+ # Embeddings
+ use_joint_name_emb: bool = False # Joint name embedding
+ use_graph_emb: bool = False # Graph structure embedding (GCN)
+ use_depth_emb: bool = False # Kinematic depth embedding per joint
+ concat_parent_features: bool = False # Concatenate parent joint features in input
+ num_tpos_queries: int = 0 # 0 = mean-pool tpos, >0 = cross-attention pool with K queries
+ inject_tpos_to_adaln: bool = False # Add pooled tpos embedding into the adaLN conditioning vector
+
+ # Graph attention bias (attention='graph'). True: spatial attention adds learned
+ # graph-distance + edge-type biases. False (ablation): vanilla self-attention
+ # over joints; the joint validity mask is applied via SDPA's attn_mask.
+ use_graph_attn_bias: bool = True
+ # False: every block learns its own bias (num_layers copies of the small
+ # distance/edge-type tables). True: the model owns ONE bias, computed once
+ # per forward and reused by every layer โ€” Graphormer's own arrangement,
+ # fewer parameters and one bias build instead of num_layers.
+ share_graph_attn_bias: bool = False
+
+ # Memory optimization (attention='graph', either text_cond)
+ gradient_checkpointing: bool = False # Trade compute for memory in attention blocks
+
+ # Text encoder
+ text_encoder_type: str = "t5" # 'clip', 'bert', 't5'
+ text_encoder_version: Optional[str] = None # None = use default for the type
+
+ ATTENTION_CHOICES = ('full', 'graph')
+ TEXT_COND_CHOICES = ('adaln', 'cross_attn')
+
+ def __post_init__(self):
+ # Fail on the config, not minutes later inside create_model once the
+ # dataset has already been loaded.
+ for field, value, choices in (
+ ('attention', self.attention, self.ATTENTION_CHOICES),
+ ('text_cond', self.text_cond, self.TEXT_COND_CHOICES)):
+ if value not in choices:
+ raise ValueError(
+ f"model.{field}={value!r} is not one of {list(choices)}")
+
+ _defaults = {
+ 'bert': 'distilbert/distilbert-base-uncased',
+ 'clip': 'ViT-B/32',
+ 't5': 'google/flan-t5-base',
+ }
+ if self.text_encoder_version is None:
+ if self.text_encoder_type not in _defaults:
+ raise ValueError(f"Unknown text_encoder_type: {self.text_encoder_type}")
+ self.text_encoder_version = _defaults[self.text_encoder_type]
+
+
+# ---------------------------------------------------------------------------
+# Scheduler config
+# ---------------------------------------------------------------------------
+
+@dataclass
+class SchedulerConfig:
+ """Diffusion scheduler configuration."""
+ diffusion_steps: int = 100
+ timestep_respacing: str = ""
+ rescale_timesteps: bool = False
+
+ noise_schedule: str = "cosine" # "linear", "cosine"
+ scale_beta: float = 1.0
+ predict_xstart: bool = True
+ learn_sigma: bool = False
+ sigma_small: bool = True
+
+
+# ---------------------------------------------------------------------------
+# Training config
+# ---------------------------------------------------------------------------
+
+@dataclass
+class TrainingConfig:
+ """Training configuration."""
+ batch_size: int = 16
+ num_workers: int = 8
+ seed: int = 10
+
+ # Generation paradigm
+ diff_model: str = "diffusion" # 'diffusion', 'flow'
+
+ # Optimizer
+ learning_rate: float = 1e-4
+ weight_decay: float = 1e-5
+ adam_beta1: float = 0.9
+ adam_beta2: float = 0.99
+ max_grad_norm: Optional[float] = None # Gradient clipping norm
+ gradient_accumulation_steps: int = 1 # Number of steps to accumulate gradients
+
+ # LR schedule
+ warmup_ratio: float = 0.02 # Fraction of num_steps used for warmup
+ min_lr_ratio: float = 0.01 # Min LR as a fraction of learning_rate
+
+ # Duration
+ num_epochs: Optional[int] = None
+ num_steps: Optional[int] = 100_000
+ log_interval: int = 50
+ save_interval: int = 10_000
+
+ # Loss weights
+ lambda_geo: float = 0.5
+ lambda_smooth: float = 0.1
+
+ # EMA
+ use_ema: bool = True
+ ema_decay: float = 0.9999
+
+ # Sampling
+ balanced: bool = False # Use balancing sampler for fairness between topologies
+
+
+# ---------------------------------------------------------------------------
+# Sampling config
+# ---------------------------------------------------------------------------
+
+@dataclass
+class SamplingArgs:
+ """Sampling arguments."""
+ model_path: Optional[str] = None
+ output_dir: Optional[str] = None
+ seed: Optional[int] = 10
+
+ # Sampling hyperparameters
+ object_type: Optional[List[str]] = None
+ num_samples: int = 4
+ num_repetitions: int = 3
+ device: str = "cuda"
+
+ # CFG
+ cfg_scale: float = 1.0
+
+
+# ---------------------------------------------------------------------------
+# Main config
+# ---------------------------------------------------------------------------
+
+@dataclass
+class MainConfig:
+ """Top-level config loaded from JSON.
+
+ JSON top-level keys: experiment, truebones, mixamo, objaverse,
+ dataset, model, scheduler, training, sampling.
+ """
+ experiment: ExperimentConfig
+ truebones: TruebonesConfig
+ mixamo: MixamoConfig
+ objaverse: ObjaverseConfig
+ dataset: DatasetConfig
+ model: ModelConfig
+ scheduler: SchedulerConfig
+ training: TrainingConfig
+ sampling: SamplingArgs
+
+ @classmethod
+ def from_json(cls, config_path: Union[str, Path]) -> 'MainConfig':
+ """Load config from JSON file."""
+ with open(config_path) as f:
+ data = json.load(f)
+
+ experiment = ExperimentConfig(**data['experiment'])
+
+ # Per-dataset configs live at top level in JSON
+ truebones = TruebonesConfig(**data.get('truebones', {}))
+ mixamo = MixamoConfig(**data.get('mixamo', {}))
+ objaverse = ObjaverseConfig(**data.get('objaverse', {}))
+
+ # Inject per-dataset configs into dataset block for __post_init__
+ dataset_data = data['dataset']
+ dataset_data['truebones'] = truebones
+ dataset_data['mixamo'] = mixamo
+ dataset_data['objaverse'] = objaverse
+ dataset = DatasetConfig(**dataset_data)
+
+ model_data = dict(data['model'])
+ # Legacy single-field form: {'type': 'native'|'graph'|'cross'}. Mapped
+ # rather than rejected so the config.json inside every existing
+ # experiment directory still loads.
+ legacy_type = model_data.pop('type', None)
+ if legacy_type is not None:
+ legacy_map = {'native': ('full', 'adaln'),
+ 'graph': ('graph', 'adaln'),
+ 'cross': ('graph', 'cross_attn')}
+ if legacy_type not in legacy_map:
+ raise ValueError(
+ f"Unknown legacy model type {legacy_type!r}; expected one "
+ f"of {sorted(legacy_map)}. New configs should set "
+ f"'attention' and 'text_cond' instead.")
+ attention, text_cond = legacy_map[legacy_type]
+ # A file carrying both forms is ambiguous: silently preferring one
+ # would hand back a model the config does not describe.
+ conflicts = {k: (model_data[k], v)
+ for k, v in (('attention', attention),
+ ('text_cond', text_cond))
+ if k in model_data and model_data[k] != v}
+ if conflicts:
+ detail = ', '.join(f'{k}={got!r} but type implies {want!r}'
+ for k, (got, want) in conflicts.items())
+ raise ValueError(
+ f"model config sets both the legacy 'type'={legacy_type!r} "
+ f"and a conflicting axis: {detail}. Drop 'type'.")
+ model_data['attention'] = attention
+ model_data['text_cond'] = text_cond
+ model = ModelConfig(**model_data)
+ scheduler = SchedulerConfig(**data['scheduler'])
+ training = TrainingConfig(**data['training'])
+ sampling = SamplingArgs(**data['sampling'])
+
+ return cls(
+ experiment=experiment,
+ truebones=truebones,
+ mixamo=mixamo,
+ objaverse=objaverse,
+ dataset=dataset,
+ model=model,
+ scheduler=scheduler,
+ training=training,
+ sampling=sampling,
+ )
+
+ def to_json(self, config_path: Union[str, Path]):
+ """Save config to JSON file."""
+ data = dataclasses.asdict(self)
+ # Remove runtime-only fields that are reconstructed in __post_init__
+ data['dataset'].pop('data_configs', None)
+ # Remove nested sub-configs from dataset (they live at top level)
+ for key in ('truebones', 'mixamo', 'objaverse'):
+ data['dataset'].pop(key, None)
+ with open(config_path, 'w') as f:
+ json.dump(data, f, indent=4)
diff --git a/unimate/dataset/__init__.py b/unimate/dataset/__init__.py
new file mode 100644
index 0000000..731ad28
--- /dev/null
+++ b/unimate/dataset/__init__.py
@@ -0,0 +1 @@
+"""Dataset loading, augmentation, and conditioning for the Mixture pipeline."""
diff --git a/unimate/dataset/conditioning.py b/unimate/dataset/conditioning.py
new file mode 100644
index 0000000..b8e3942
--- /dev/null
+++ b/unimate/dataset/conditioning.py
@@ -0,0 +1,270 @@
+"""Build conditioning batches for sampling / visualization / inference.
+
+``create_sample_condition`` selects reference clips from the loaded
+``MotionDataset`` (see the mode priority in its docstring), reruns the same
+crop โ†’ condition-extraction โ†’ normalization โ†’ padding pipeline used for
+training samples, and collates the result with ``mixture_batch_collate`` so
+the generative model sees exactly the training-time cond format.
+"""
+
+import random
+from typing import Dict, List, Optional, Tuple
+
+import numpy as np
+import torch
+
+from Quaternions import Quaternions
+
+from unimate.configs.schema import MainConfig
+from unimate.dataset.transforms import (
+ apply_cropping, extract_conditions, apply_normalization,
+ apply_padding, build_parent_features,
+)
+from unimate.dataset.mixture.collate import mixture_batch_collate
+from unimate.utils.motion_utils import realign_unimate_clip
+from unimate.utils.topology_utils import compute_edge_indexs
+
+
+def _resolve_dataset(data):
+ """Accept either a Dataset or DataLoader, return the underlying Dataset."""
+ if isinstance(data, torch.utils.data.DataLoader):
+ return data.dataset
+ if isinstance(data, torch.utils.data.Dataset):
+ return data
+ raise ValueError("data must be either a Dataset or DataLoader instance.")
+
+
+def create_sample_condition(
+ config: MainConfig,
+ data,
+ num_samples: int = 3,
+ object_types: Optional[List[str]] = None,
+ test_case_captions: Optional[List[Tuple]] = None,
+ gt_start_frame: Optional[int] = None,
+):
+ """Build a conditioning batch for sampling / visualization / inference.
+
+ Modes (in priority order):
+ 1. ``test_case_captions`` โ€” list of
+ ``(object_type, caption, caption_enc[, clip_name])``, where
+ ``caption_enc`` is ``{'caption_emb': (D,)[, 'caption_tokens':
+ (T, D)]}``. One reference
+ clip per entry provides the target skeleton; the clip's own caption
+ is replaced by the user-supplied text + embedding. If a 4th element
+ ``clip_name`` is provided, that exact clip is used (resolved against
+ train then eval motion dicts); otherwise a random clip is picked.
+ The explicit-clip variant is required for motion in-betweening so
+ the generated batch lines up with the GT being clamped at sample
+ time. Used by ``unimate/inference/sample.py``.
+ 2. ``object_types`` โ€” pick one train clip and/or one eval clip per
+ listed object_type (each emitted only when its map has clips).
+ 3. default โ€” auto-sample ``num_samples`` types per dataset, routed by
+ split mode so visualization always covers both train and eval:
+ * ``'object_type'`` (truebones, objaverse): pick ``num_samples``
+ train types + ``num_samples`` eval types, one random clip each.
+ * ``'clip'`` (mixamo): pick ``num_samples`` types and emit one
+ train + one eval clip per picked type (eval skipped when
+ ``eval_map`` is empty for that type).
+
+ Args:
+ gt_start_frame: when set, the GT clip is cropped starting at this
+ absolute frame index instead of the default random ('tpos') /
+ zero ('first_frame') start. If fewer than
+ ``max_motion_length`` frames remain, the crop is trimmed and the
+ tail is zero-padded. ``cond["motion_length"]`` does NOT report
+ that: it is deliberately pinned to ``max_motion_length`` so the
+ model generates (and attends over) the whole padded window. The
+ caller tracks the real length separately โ€” see
+ ``sample._gt_valid_lengths`` โ€” and trims outputs at save time.
+ """
+ dataset = _resolve_dataset(data)
+ md = dataset.motion_dataset
+
+ topology_cond_type = config.dataset.topology_condition_type
+
+ train_map = md.train_object_motions_map
+ eval_map = md.eval_object_motions_map
+ split_mode = md.split_mode_by_dataset
+
+ def _pick(pool, n):
+ if not pool:
+ return []
+ return random.sample(pool, n) if len(pool) >= n else random.choices(pool, k=n)
+
+ # selection: (object_type, clip_name, split_tag) tuples consumed by the
+ # batch-building loop below. caption overrides keyed by *selection index*
+ # so multiple test cases can share the same reference clip without
+ # overwriting each other's caption.
+ selection = []
+ caption_override_by_idx: Dict[int, Tuple[str, np.ndarray]] = {}
+
+ if test_case_captions is not None:
+ # Reference clip provides topology only; the user override supplies
+ # the caption. Prefer a train clip; fall back to eval for held-out
+ # types. When a 4th tuple element is given, use that exact clip
+ # (in-betweening / motion editing pin a specific GT motion).
+ for entry in test_case_captions:
+ if len(entry) == 4:
+ obj_type, caption, caption_enc, explicit_clip = entry
+ else:
+ obj_type, caption, caption_enc = entry
+ explicit_clip = None
+
+ train_clips = train_map.get(obj_type, [])
+ eval_clips = eval_map.get(obj_type, [])
+
+ if explicit_clip is not None:
+ if explicit_clip in train_clips:
+ clip_name, tag = explicit_clip, 'train'
+ elif explicit_clip in eval_clips:
+ clip_name, tag = explicit_clip, 'eval'
+ else:
+ raise ValueError(
+ f"clip_name={explicit_clip!r} not found for "
+ f"object_type={obj_type!r} in train or eval maps."
+ )
+ else:
+ primary = train_clips or eval_clips
+ tag = 'train' if train_clips else 'eval'
+ if not primary:
+ continue
+ clip_name = random.choice(primary)
+
+ caption_override_by_idx[len(selection)] = (caption, caption_enc)
+ selection.append((obj_type, clip_name, tag))
+ elif object_types is not None:
+ # One train + one eval clip per requested type when both pools have
+ # entries. With ``test_split_ratio == 0`` or a fully held-out type,
+ # emit just one โ€” no synthetic duplicate.
+ for object_type in object_types:
+ train_clips = train_map.get(object_type, [])
+ eval_clips = eval_map.get(object_type, [])
+ if not (train_clips or eval_clips):
+ continue
+ if train_clips:
+ selection.append((object_type, random.choice(train_clips), 'train'))
+ if eval_clips:
+ selection.append((object_type, random.choice(eval_clips), 'eval'))
+ else:
+ for dataset_type, obj_counts in md.dataset_object_count.items():
+ mode = split_mode.get(dataset_type, 'clip')
+
+ if mode == 'object_type':
+ train_types = [t for t in obj_counts if train_map.get(t)]
+ eval_types = [t for t in obj_counts if eval_map.get(t)]
+ for t in _pick(train_types, num_samples):
+ selection.append((t, random.choice(train_map[t]), 'train'))
+ for t in _pick(eval_types, num_samples):
+ selection.append((t, random.choice(eval_map[t]), 'eval'))
+ else:
+ # 'clip' mode: emit train (+eval when present) per picked type.
+ # With test_split_ratio==0 (eval_map empty) the train pool is
+ # not sampled twice just to hit a sample count.
+ all_types = list(obj_counts.keys())
+ for t in _pick(all_types, num_samples):
+ train_clips = train_map.get(t, [])
+ eval_clips = eval_map.get(t, [])
+ if not (train_clips or eval_clips):
+ continue
+ if train_clips:
+ selection.append((t, random.choice(train_clips), 'train'))
+ if eval_clips:
+ selection.append((t, random.choice(eval_clips), 'eval'))
+
+ batches = []
+ for sel_idx, (object_type, selected_motion_name, _split_tag) in enumerate(selection):
+ condition = md.cond_dict[object_type].copy()
+ source = md.train_motion_dict if _split_tag == 'train' else md.eval_motion_dict
+ motion_data = source[selected_motion_name].copy()
+ assert motion_data['object_type'] == object_type
+
+ raw_motion = motion_data['motion'] # (F, J, D)
+ parents = motion_data['parents'] # (J,)
+ tpos = np.array(condition['tpos_first_frame'])
+
+ max_motion_length = config.dataset.max_motion_length
+ raw_motion, start_idx = apply_cropping(
+ raw_motion, topology_cond_type, max_motion_length,
+ start_idx=gt_start_frame,
+ )
+
+ # Re-align so frame-0 facing is identity (matches training-time
+ # invariant assumed by the feature pipeline).
+ if start_idx > 0:
+ raw_motion = realign_unimate_clip(raw_motion, parents)
+
+ # Pad tpos (J, 3) to motion feature dim (J, 12): identity 6D
+ # rotation + zero velocity, matching the layout of motion features.
+ feature_len = config.dataset.feature_len
+ if tpos.shape[-1] < feature_len:
+ J = tpos.shape[0]
+ identity_6d = Quaternions.id(1).rotation_matrix(cont6d=True)[0]
+ pad = np.zeros((J, feature_len - 3))
+ pad[:, :6] = identity_6d
+ tpos = np.concatenate([tpos, pad], axis=-1)
+
+ conds = extract_conditions(raw_motion, tpos, topology_cond_type)
+ motion = conds['motion']
+ tpos_first_frame = conds['tpos_first_frame']
+ njoints, nfeats = tpos_first_frame.shape
+
+ # Dataset-level normalization stats (root vs. local split).
+ dataset_type = motion_data['dataset_type']
+ stats = md.dataset_stats[dataset_type]
+ mean = np.zeros((njoints, nfeats))
+ std = np.zeros((njoints, nfeats))
+ mean[0, :], std[0, :] = stats['mean_root'], stats['std_root']
+ mean[1:, :], std[1:, :] = stats['mean_local'], stats['std_local']
+
+ motion = apply_normalization(motion, mean, std)
+ tpos_first_frame = apply_normalization(tpos_first_frame, mean, std)
+
+ # Pad to fixed length so the generator always produces same-shape outputs.
+ motion, _ = apply_padding(motion, max_motion_length)
+
+ parent_feats = build_parent_features(tpos_first_frame, parents)
+ # Reuse the clip's stored eigenvectors (loaded via ``create_condition``)
+ # rather than recomputing: eigendecomposition signs are arbitrary, and
+ # the stored copy is the sign-pinned version the model saw at training
+ # time (matters for the non-sign-invariant WIRE spectral backend).
+ spectral_feats = motion_data['spectral_feats']
+
+ batch = {
+ 'motion': motion,
+ 'max_motion_length': config.dataset.max_motion_length,
+ # Always the full window, even for a short crop: the model is
+ # asked to generate every frame. See the gt_start_frame note above.
+ 'motion_length': max_motion_length,
+ 'max_joints': config.dataset.max_joints,
+ 'parents': parents,
+ 'edge_indexs': compute_edge_indexs(parents),
+ 'tpos_first_frame': tpos_first_frame,
+ 'tpos_first_frame_parents': parent_feats['tpos_first_frame_parents'],
+ 'offsets': motion_data['offsets'],
+ 'joint_graph_dist': motion_data['joint_graph_dist'],
+ 'joint_relations': motion_data['joint_relations'],
+ 'joint_depths': motion_data['joint_depths'],
+ 'spectral_feats': spectral_feats,
+ 'joint_names_emb': motion_data['joint_names_emb'],
+ 'object_type': object_type,
+ 'start_idx': start_idx,
+ 'mean': mean,
+ 'std': std,
+ 'split_tag': _split_tag,
+ }
+
+ if sel_idx in caption_override_by_idx:
+ caption, caption_enc = caption_override_by_idx[sel_idx]
+ batch['caption'] = caption
+ # caption_enc is {'caption_emb': (D,)[, 'caption_tokens': (T, D)]};
+ # a caller that only produced the pooled vector still works.
+ batch.update(caption_enc)
+ else:
+ for key in ('caption', 'caption_emb', 'caption_tokens'):
+ if key in motion_data:
+ batch[key] = motion_data[key]
+
+ batches.append(batch)
+
+ motion, cond = mixture_batch_collate(batches)
+ return motion, cond
diff --git a/unimate/dataset/factory.py b/unimate/dataset/factory.py
new file mode 100644
index 0000000..69ddfec
--- /dev/null
+++ b/unimate/dataset/factory.py
@@ -0,0 +1,104 @@
+"""Dataset / DataLoader factories for the unified Mixture pipeline."""
+
+from typing import Optional, Set
+
+from torch.utils.data import DataLoader
+
+from unimate.dataset.mixture.dataset import Mixture, MixtureSampler
+from unimate.dataset.mixture.collate import mixture_batch_collate
+
+
+def create_dataset(
+ dataset_config,
+ model_config,
+ inference: bool = False,
+ target_object_types: Optional[Set[str]] = None,
+ target_clip_stems: Optional[Set[str]] = None,
+ stats_path: Optional[str] = None,
+):
+ """Build the Mixture dataset.
+
+ The dataset iterates only over the train split; eval clips are kept in
+ memory and exposed via ``eval_object_motions_map`` for sampling /
+ visualization / inference.
+
+ Inference args (all ignored when ``inference=False``):
+ ``inference`` โ€” use saved ``max_joints`` / ``max_depth`` from the
+ config instead of recomputing from the on-disk data.
+ ``target_object_types`` โ€” restrict motion + joint-name loads to these
+ object types.
+ ``target_clip_stems`` โ€” restrict motion loads to these specific clip
+ stems (required for in-betweening / motion-editing).
+ ``stats_path`` โ€” load normalization stats from disk instead of
+ recomputing them.
+ """
+ if inference:
+ if dataset_config.max_joints <= 0 or dataset_config.max_depth <= 0:
+ raise ValueError(
+ f"inference=True requires saved max_joints/max_depth in the "
+ f"config, got max_joints={dataset_config.max_joints}, "
+ f"max_depth={dataset_config.max_depth}."
+ )
+ prebuilt_max_joints = dataset_config.max_joints
+ prebuilt_max_depth = dataset_config.max_depth
+ else:
+ prebuilt_max_joints = 0
+ prebuilt_max_depth = 0
+
+ dataset = Mixture(
+ data_configs=dataset_config.data_configs,
+ topology_condition_type=dataset_config.topology_condition_type,
+ max_motion_length=dataset_config.max_motion_length,
+ max_joints=dataset_config.max_joints,
+ min_joints=dataset_config.min_joints,
+ max_depth=dataset_config.max_depth,
+ feature_len=dataset_config.feature_len,
+ text_encoder_type=model_config.text_encoder_type,
+ text_encoder_version=model_config.text_encoder_version,
+ use_dataset_stats=dataset_config.use_dataset_stats,
+ balanced_stats=dataset_config.balanced_stats,
+ tie_std=dataset_config.tie_std,
+ use_addition_aug=dataset_config.use_addition_aug,
+ use_removal_aug=dataset_config.use_removal_aug,
+ use_pooling_aug=dataset_config.use_pooling_aug,
+ use_perturbation_aug=dataset_config.use_perturbation_aug,
+ test_split_ratio=dataset_config.test_split_ratio,
+ split_seed=dataset_config.split_seed,
+ max_freqs=model_config.max_freqs,
+ ground_motion_height=dataset_config.ground_motion_height,
+ realign_feature=dataset_config.realign_feature,
+ prebuilt_max_joints=prebuilt_max_joints,
+ prebuilt_max_depth=prebuilt_max_depth,
+ target_object_types=target_object_types,
+ target_clip_stems=target_clip_stems,
+ stats_path=stats_path,
+ )
+
+ # Propagate auto-computed max_joints and max_depth back to config so model uses them
+ dataset_config.max_joints = dataset.max_joints
+ dataset_config.max_depth = dataset.max_depth
+
+ return dataset
+
+
+def create_train_dataloader(
+ dataset_config,
+ model_config,
+ balanced: bool = False,
+ batch_size: int = 16,
+ num_workers: int = 8,
+):
+ """Build the training DataLoader over the train split of the Mixture dataset."""
+ dataset = create_dataset(dataset_config, model_config)
+
+ sampler = MixtureSampler(dataset, alpha=dataset_config.sampler_alpha) if balanced else None
+
+ return DataLoader(
+ dataset,
+ batch_size=batch_size,
+ sampler=sampler,
+ shuffle=(sampler is None),
+ num_workers=num_workers,
+ drop_last=True,
+ collate_fn=mixture_batch_collate,
+ )
diff --git a/unimate/dataset/mixture/__init__.py b/unimate/dataset/mixture/__init__.py
new file mode 100644
index 0000000..6ca81dd
--- /dev/null
+++ b/unimate/dataset/mixture/__init__.py
@@ -0,0 +1 @@
+"""The unified Mixture dataset: clips, augmentations, and collation."""
diff --git a/unimate/dataset/mixture/augmentations.py b/unimate/dataset/mixture/augmentations.py
new file mode 100644
index 0000000..a8b11d6
--- /dev/null
+++ b/unimate/dataset/mixture/augmentations.py
@@ -0,0 +1,449 @@
+"""Skeleton- and joint-level augmentations for the Mixture dataset.
+
+Pure functions mutating (and returning) a standard ``aug`` dict; ``max_freqs``
+is passed explicitly, no class state is required. Every aug function leaves
+the aug dict in a valid state (all derived arrays recomputed) ready for the
+next stage. All ops assume the UniMate 12-dim representation (HML-reordered
+rotation slots, identity rest rotations โ€” see ``unimate/utils/motion_utils.py``).
+
+Standard aug-dict keys: ``motion``, ``parents``, ``edge_indexs``,
+``joint_graph_dist``, ``joint_relations``, ``joint_depths``, ``spectral_feats``,
+``tpos``, ``offsets``, ``joint_names_emb``, ``mean``, ``std``.
+"""
+
+import random
+
+import numpy as np
+
+from Quaternions import Quaternions
+
+from unimate.utils.topology_utils import (
+ compute_edge_relations_and_distances,
+ compute_joint_depths,
+ compute_edge_indexs,
+ compute_laplacian_eigenvectors,
+)
+from unimate.utils.rotation_conversions import rotation_6d_to_matrix_np
+from unimate.utils.motion_utils import (
+ compute_rifke,
+ hml_rotations_to_bvh_quaternions,
+ fk_global_positions,
+)
+
+
+# ---------------------------------------------------------------------------
+# Low-level skeleton helpers
+# ---------------------------------------------------------------------------
+
+def build_children_map(parents):
+ """Build a list-of-lists mapping each joint to its children."""
+ children = [[] for _ in range(len(parents))]
+ for c, p in enumerate(parents):
+ if p >= 0 and c != p:
+ children[p].append(c)
+ return children
+
+
+def bone_length_weighted_sample(candidates, offsets, n_select, alpha=0.5):
+ """Sample joints weighted by inverse bone length (shorter = more likely).
+
+ Per-joint weight โˆ bone_length^(-alpha); ``alpha=0`` uniform,
+ ``alpha=1`` proportional to ``1/length``.
+ """
+ bone_lengths = np.array([np.linalg.norm(offsets[j]) for j in candidates])
+ bone_lengths = np.maximum(bone_lengths, 1e-8)
+ weights = bone_lengths ** (-alpha)
+ weights /= weights.sum()
+ n_select = min(n_select, len(candidates))
+ selected = np.random.choice(
+ candidates, size=n_select, replace=False, p=weights,
+ ).tolist()
+ return selected
+
+
+def delete_joint(aug, j):
+ """Delete joint *j* from all per-joint arrays and fix parent indices."""
+ aug['motion'] = np.delete(aug['motion'], j, axis=1)
+ aug['parents'] = np.delete(aug['parents'], j, axis=0)
+ aug['parents'][aug['parents'] > j] -= 1
+ for key in ('tpos', 'offsets', 'joint_names_emb', 'joint_depths', 'mean', 'std'):
+ aug[key] = np.delete(aug[key], j, axis=0)
+
+
+def collapse_single_child_joint(aug, j, c, p):
+ """Collapse a single-child interior joint *j* into its child *c*.
+
+ Merges offsets and rotation channels, then re-parents *c* to grandparent
+ *p*. In the HML layout, joint k's slot stores ``bvh[parents[k]]``: after
+ collapse, c's parent becomes p, so ``motion[c, 3:9]`` must hold
+ ``bvh[p]`` โ€” which is exactly what ``motion[j, 3:9]`` stored pre-collapse.
+ Grandchildren's slots hold ``bvh[c]`` which must remain ``bvh[c]_old``
+ for FK below c to be preserved, so they are left untouched. Offsets are
+ summed in the rest frame (identity rest rotations).
+ """
+ aug['motion'][:, c, 3:9] = aug['motion'][:, j, 3:9]
+ aug['offsets'][c] = aug['offsets'][j] + aug['offsets'][c]
+ aug['parents'][c] = p
+
+
+# ---------------------------------------------------------------------------
+# Derived-array recomputation
+# ---------------------------------------------------------------------------
+
+def _augmented_global_positions(aug):
+ """Run FK on the augmented skeleton via :func:`fk_global_positions`.
+
+ Root is pinned at ``(0, Y_height, 0)`` where ``Y_height`` is read from
+ the stored RIFKE Y channel (``motion[:, 0, 1]``). This keeps the
+ resulting Y consistent with the stored feature and zeroes out XZ โ€” both
+ properties required by :func:`compute_rifke` (which subtracts root XZ
+ and preserves Y).
+ """
+ motion = aug['motion']
+ T = motion.shape[0]
+ root_positions = np.zeros((T, 3))
+ root_positions[:, 1] = motion[:, 0, 1] # world Y from RIFKE root channel
+ bvh_rots = hml_rotations_to_bvh_quaternions(motion[:, :, 3:9], aug['parents'])
+ return fk_global_positions(
+ bvh_rots, aug['parents'], aug['offsets'], root_positions,
+ )
+
+
+def recompute_position_features(aug):
+ """Recompute RIFKE position features (0:3) for non-root joints via FK.
+
+ Re-runs the same FK pipeline used at data-processing time
+ (``positions_global`` + ``compute_rifke``) so the augmented clip is
+ consistent with the feature-extraction convention.
+ """
+ global_positions = _augmented_global_positions(aug)
+ root_facing_quat = Quaternions.from_transforms(
+ rotation_6d_to_matrix_np(aug['motion'][:, 0, 3:9])
+ )
+ rifke = compute_rifke(global_positions, root_facing_quat)
+ # Root RIFKE channels [0, Y, 0] are invariant to offset changes.
+ aug['motion'][:, 1:, :3] = rifke[:, 1:]
+
+
+def recompute_tpos_positions(aug):
+ """Recompute tpos global positions ``(J, 3)`` from offsets.
+
+ Rest rotations are identity, so global positions are the running sum of
+ ``offsets`` along the kinematic chain.
+ """
+ njoints = len(aug['parents'])
+ global_pos = np.zeros((njoints, 3))
+ for j, p in enumerate(aug['parents']):
+ if p == -1:
+ global_pos[j] = aug['offsets'][j]
+ else:
+ global_pos[j] = global_pos[p] + aug['offsets'][j]
+ aug['tpos'][:] = global_pos
+
+
+def recompute_topology_arrays(aug, max_freqs, max_path_len=5):
+ """Recompute topology-derived arrays from ``aug['parents']``."""
+ parents_list = aug['parents'].tolist()
+ aug['edge_indexs'] = compute_edge_indexs(aug['parents'])
+ aug['joint_relations'], aug['joint_graph_dist'] = \
+ compute_edge_relations_and_distances(parents_list, max_path_len=max_path_len)
+ aug['joint_depths'] = compute_joint_depths(parents_list)
+ aug['spectral_feats'], _ = compute_laplacian_eigenvectors(
+ parents_list, max_freqs=max_freqs,
+ )
+
+
+def _recompute_all(aug, max_freqs, max_path_len=5):
+ """Recompute position features + tpos + topology arrays in one call."""
+ recompute_position_features(aug)
+ recompute_tpos_positions(aug)
+ recompute_topology_arrays(aug, max_freqs, max_path_len=max_path_len)
+
+
+# ---------------------------------------------------------------------------
+# Joint removal
+# ---------------------------------------------------------------------------
+
+def apply_joint_removal(aug, removal_rate, max_freqs):
+ """Remove end-effector (leaf) joints from the skeleton.
+
+ Only leaves are removed; deletion requires no rotation composition or
+ offset merging. Processed in descending index order so deletions don't
+ shift later indices.
+ """
+ parents = aug['parents']
+ n_joints = len(parents)
+ children = build_children_map(parents)
+
+ removable = [j for j in range(1, n_joints) if len(children[j]) == 0]
+ if not removable:
+ return aug
+
+ n_remove = min(int(round(len(removable) * removal_rate)), 3)
+ if n_remove == 0:
+ return aug
+ to_remove = bone_length_weighted_sample(removable, aug['offsets'], n_remove)
+ to_remove.sort(reverse=True)
+
+ for j in to_remove:
+ # Re-check in case prior deletions turned a leaf into something else
+ children = build_children_map(aug['parents'])
+ if len(children[j]) != 0:
+ continue
+ delete_joint(aug, j)
+
+ _recompute_all(aug, max_freqs)
+ return aug
+
+
+# ---------------------------------------------------------------------------
+# Joint addition (linear split along the bone)
+# ---------------------------------------------------------------------------
+
+def apply_joint_addition_linear(aug, max_freqs, max_path_len=5.):
+ """Insert a kinematically neutral joint along a bone.
+
+ New joint has identity local rotation and splits the parentโ†’child offset,
+ so FK output is exactly preserved.
+
+ Not wired to any config flag โ€” the default addition aug is the ellipsoid
+ variant below; this simpler on-the-bone split is kept as an ablation
+ alternative.
+ """
+ motion = aug['motion']
+ parents = aug['parents']
+ offsets = aug['offsets']
+ tpos = aug['tpos']
+ joint_names_emb = aug['joint_names_emb']
+ mean, std = aug['mean'], aug['std']
+
+ n_frames, n_joints, D = motion.shape
+
+ candidates = list(range(1, n_joints))
+ if not candidates:
+ return aug
+
+ ji = random.choice(candidates)
+ pi = int(parents[ji])
+
+ alpha = random.uniform(0.3, 0.7)
+ offset_new = offsets[ji] * alpha
+ offset_ji_rem = offsets[ji] * (1 - alpha)
+
+ # HML: the new joint's slot stores bvh[parents[new]] = bvh[pi],
+ # which is exactly what old motion[ji, 3:9] already holds. With
+ # identity local rotation at the new joint, bvh[new] = bvh[pi],
+ # so after concat motion[ji+1, 3:9] (old-ji's shifted slot, which
+ # must store bvh[new]) is already correct โ€” leave it unchanged.
+ new_motion = np.zeros((n_frames, 1, D), dtype=motion.dtype)
+ new_motion[:, 0, 3:9] = motion[:, ji, 3:9]
+
+ aug['motion'] = np.concatenate(
+ [motion[:, :ji], new_motion, motion[:, ji:]], axis=1,
+ )
+ aug['offsets'] = np.concatenate(
+ [offsets[:ji], offset_new[None], offsets[ji:]], axis=0,
+ )
+ aug['offsets'][ji + 1] = offset_ji_rem
+
+ tpos_new = (tpos[pi] + offset_new).copy()
+ aug['tpos'] = np.concatenate([tpos[:ji], tpos_new[None], tpos[ji:]], axis=0)
+
+ name_new = (joint_names_emb[pi] + joint_names_emb[ji]) / 2
+ aug['joint_names_emb'] = np.concatenate(
+ [joint_names_emb[:ji], name_new[None], joint_names_emb[ji:]], axis=0,
+ )
+
+ mean_new = mean[ji].copy()
+ aug['mean'] = np.concatenate([mean[:ji], mean_new[None], mean[ji:]], axis=0)
+ aug['std'] = np.concatenate([std[:ji], std[ji:ji + 1], std[ji:]], axis=0)
+
+ new_parents = parents.copy()
+ new_parents[new_parents >= ji] += 1
+ aug['parents'] = np.concatenate([new_parents[:ji], [pi], new_parents[ji:]])
+ aug['parents'][ji + 1] = ji
+
+ _recompute_all(aug, max_freqs, max_path_len=max_path_len)
+ return aug
+
+
+# ---------------------------------------------------------------------------
+# Joint addition (ellipsoid sampling)
+# ---------------------------------------------------------------------------
+
+def sample_ellipsoid_gaussian(bone_offset, sigma=0.5, lateral_ratio=0.5):
+ """Sample a 3D displacement inside a bone-aligned ellipsoid with Gaussian falloff.
+
+ Long axis = bone direction (semi-axis = bone_length); perpendicular
+ semi-axes = ``bone_length * lateral_ratio``; radial density is a
+ truncated half-normal.
+ """
+ bone_length = np.linalg.norm(bone_offset)
+ if bone_length < 1e-8:
+ return np.zeros(3)
+
+ # Direction โ€” rejection-sample a uniform unit vector in [-1,1]^3.
+ while True:
+ d = np.random.uniform(-1, 1, size=3)
+ norm = np.linalg.norm(d)
+ if 0 < norm <= 1:
+ d /= norm
+ break
+ # Radius โ€” truncated half-normal.
+ while True:
+ r = abs(np.random.normal(0, sigma))
+ if r <= 1:
+ break
+ sphere_point = r * d
+
+ a = bone_length
+ b = bone_length * lateral_ratio
+ scaled = sphere_point * np.array([a, b, b])
+
+ e1 = bone_offset / bone_length
+ ref = np.array([0.0, 1.0, 0.0])
+ if abs(np.dot(e1, ref)) > 0.9:
+ ref = np.array([1.0, 0.0, 0.0])
+ e2 = np.cross(e1, ref)
+ e2 /= np.linalg.norm(e2)
+ e3 = np.cross(e1, e2)
+
+ R = np.column_stack([e1, e2, e3])
+ return R @ scaled
+
+
+def apply_joint_addition_ellipsoid(aug, max_freqs,
+ max_path_len=5., sigma=0.5, lateral_ratio=0.5):
+ """Insert a joint between a joint and its parent via ellipsoid sampling.
+
+ The new joint's offset is displaced from the linear split point by a
+ sample inside a bone-aligned ellipsoid with Gaussian falloff.
+
+ FK preservation: the rest skeleton shape is the running sum of
+ ``offsets`` (identity rest rotations), so all offsets stay in the rest
+ frame (``offset_ji_rem = d_rem_parent``) and the rest-pose position of
+ every node in ji's subtree is preserved. At every frame,
+ ``pi_world + bvh[pi]ยทoffsets[ji]
+ = pi_world + bvh[pi]ยทoffset_new + bvh[new]ยทoffset_ji_rem`` requires
+ ``bvh[new]ยทd_rem_parent = bvh[pi]ยทd_rem_parent``; choosing identity
+ local rotation at the new joint satisfies this exactly and leaves every
+ global rotation in the subtree unchanged โ€” so neither ji's HML slot
+ (now at ji+1, storing ``bvh[new] = bvh[pi]``, already the pre-existing
+ value) nor any descendant slot needs to be modified.
+ """
+ motion = aug['motion']
+ parents = aug['parents']
+ offsets = aug['offsets']
+ tpos = aug['tpos']
+ joint_names_emb = aug['joint_names_emb']
+ mean, std = aug['mean'], aug['std']
+
+ n_frames, n_joints, D = motion.shape
+
+ candidates = list(range(1, n_joints))
+ if not candidates:
+ return aug
+
+ ji = random.choice(candidates)
+ pi = int(parents[ji])
+
+ alpha = random.uniform(0.3, 0.7)
+ split_offset = offsets[ji] * alpha
+ displacement = sample_ellipsoid_gaussian(
+ offsets[ji], sigma=sigma, lateral_ratio=lateral_ratio,
+ )
+ offset_new = split_offset + displacement
+ offset_ji_rem = offsets[ji] - offset_new
+
+ new_motion = np.zeros((n_frames, 1, D), dtype=motion.dtype)
+ new_motion[:, 0, 3:9] = motion[:, ji, 3:9]
+
+ aug['motion'] = np.concatenate(
+ [motion[:, :ji], new_motion, motion[:, ji:]], axis=1,
+ )
+ aug['offsets'] = np.concatenate(
+ [offsets[:ji], offset_new[None], offsets[ji:]], axis=0,
+ )
+ aug['offsets'][ji + 1] = offset_ji_rem
+
+ tpos_new = (tpos[pi] + offset_new).copy()
+ aug['tpos'] = np.concatenate([tpos[:ji], tpos_new[None], tpos[ji:]], axis=0)
+
+ name_new = (joint_names_emb[pi] + joint_names_emb[ji]) / 2
+ aug['joint_names_emb'] = np.concatenate(
+ [joint_names_emb[:ji], name_new[None], joint_names_emb[ji:]], axis=0,
+ )
+
+ mean_new = mean[ji].copy()
+ aug['mean'] = np.concatenate([mean[:ji], mean_new[None], mean[ji:]], axis=0)
+ aug['std'] = np.concatenate([std[:ji], std[ji:ji + 1], std[ji:]], axis=0)
+
+ new_parents = parents.copy()
+ new_parents[new_parents >= ji] += 1
+ aug['parents'] = np.concatenate([new_parents[:ji], [pi], new_parents[ji:]])
+ aug['parents'][ji + 1] = ji
+
+ _recompute_all(aug, max_freqs, max_path_len=max_path_len)
+ return aug
+
+
+# ---------------------------------------------------------------------------
+# Skeleton pooling โ€” reduce toward minimal graph
+# ---------------------------------------------------------------------------
+
+def apply_skeleton_pooling(aug, pool_rate, max_freqs):
+ """Collapse degree-2 joints to reduce the skeleton toward its minimal graph.
+
+ Teaches the model that skeletons differing only in linear-chain length
+ are topologically equivalent. Rotation slots are re-wired into the
+ child and offsets are merged so the FK chain is preserved.
+ """
+ parents = aug['parents']
+ n_joints = len(parents)
+ children = build_children_map(parents)
+
+ degree2 = [j for j in range(1, n_joints) if len(children[j]) == 1]
+ if not degree2:
+ return aug
+
+ n_pool = max(1, int(len(degree2) * pool_rate))
+ to_pool = bone_length_weighted_sample(degree2, aug['offsets'], n_pool)
+ to_pool.sort(reverse=True)
+
+ for j in to_pool:
+ children = build_children_map(aug['parents'])
+ if len(children[j]) != 1:
+ continue
+ collapse_single_child_joint(
+ aug, j, children[j][0], int(aug['parents'][j]),
+ )
+ delete_joint(aug, j)
+
+ _recompute_all(aug, max_freqs)
+ return aug
+
+
+# ---------------------------------------------------------------------------
+# Joint perturbation
+# ---------------------------------------------------------------------------
+
+def apply_joint_perturbation(aug, max_scale=0.1):
+ """Apply random scale noise to bone lengths, then recompute positions via FK.
+
+ Each non-root joint gets an independent uniform scale factor in
+ ``[1 - max_scale, 1 + max_scale]`` so perturbations are not correlated
+ across the skeleton. Rotations are left unchanged. Only position features
+ are recomputed (topology is preserved).
+ """
+ offsets = aug['offsets']
+ parents = aug['parents']
+ J = len(parents)
+
+ scales = np.random.uniform(1.0 - max_scale, 1.0 + max_scale, size=J)
+
+ for j in range(1, J):
+ offsets[j] *= scales[j]
+
+ recompute_position_features(aug)
+ recompute_tpos_positions(aug)
+ return aug
diff --git a/unimate/dataset/mixture/collate.py b/unimate/dataset/mixture/collate.py
new file mode 100644
index 0000000..2c6b218
--- /dev/null
+++ b/unimate/dataset/mixture/collate.py
@@ -0,0 +1,211 @@
+"""Collate function for the Mixture dataset.
+
+Assembles per-sample dicts (numpy arrays from ``MotionDataset.__getitem__``)
+into a padded ``(motion_tensor, cond_dict)`` batch. All joint-axis fields are
+zero-padded to ``max_joints`` and all time-axis fields to ``max_motion_length``.
+Optional fields (captions, split tags, ...) are only emitted when present on
+every sample (or, for ``caption_emb``, on any sample).
+"""
+
+import torch
+
+
+# ---------------------------------------------------------------------------
+# Temporal / spatial mask helpers
+# ---------------------------------------------------------------------------
+
+def lengths_to_mask(lengths, max_len):
+ """(B,) int lengths -> (B, max_len) bool mask."""
+ mask = torch.arange(max_len, device=lengths.device).expand(
+ len(lengths), max_len) < lengths.unsqueeze(1)
+ return mask
+
+
+# ---------------------------------------------------------------------------
+# Collate helpers
+# ---------------------------------------------------------------------------
+
+def create_padded_matrix(relation_np, max_joints, n_joints, dtype=torch.float32):
+ """Pad a (n_joints, n_joints) numpy matrix to (max_joints, max_joints) torch tensor."""
+ relation = torch.as_tensor(relation_np, dtype=dtype)
+ padded_relation = torch.zeros((max_joints, max_joints), dtype=dtype)
+ padded_relation[:n_joints, :n_joints] = relation
+ return padded_relation
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _pad_joint_axis(batch, key, max_joints, tail_shape, dtype=torch.float32):
+ """Stack variable-joint numpy arrays into ``(B, max_joints, *tail_shape)``.
+
+ Each ``batch[i][key]`` has shape ``(n_joints_i, *tail_shape)`` and is
+ copied into the leading ``n_joints_i`` slots; trailing slots stay zero.
+ """
+ B = len(batch)
+ out = torch.zeros((B, max_joints, *tail_shape), dtype=dtype)
+ for i, data in enumerate(batch):
+ arr = data[key]
+ out[i, :arr.shape[0]] = torch.from_numpy(arr)
+ return out
+
+
+def _collect_scalar(batch, key, dtype=torch.long):
+ """Stack ``batch[i][key]`` (scalar) into a ``(B,)`` tensor."""
+ return torch.tensor([b[key] for b in batch], dtype=dtype)
+
+
+# ---------------------------------------------------------------------------
+# Collate
+# ---------------------------------------------------------------------------
+
+def mixture_batch_collate(batch):
+ """Collate per-sample dicts into ``(motion, cond)`` batched tensors."""
+ batch = [b for b in batch if b is not None]
+ if not batch:
+ return None, None
+
+ B = len(batch)
+ max_joints = batch[0]['max_joints']
+ n_feats = batch[0]['motion'].shape[-1]
+ max_len = batch[0]['motion'].shape[0] # already padded to max_motion_length
+
+ # --- Required fields: sizes / indices ---
+ n_joints_list = torch.tensor(
+ [len(b['parents']) for b in batch], dtype=torch.long
+ )
+ motion_lengths = _collect_scalar(batch, 'motion_length')
+ crop_start_inds = _collect_scalar(batch, 'start_idx')
+ parents_list = [b['parents'] for b in batch]
+ edge_indexs_list = [torch.as_tensor(b['edge_indexs'], dtype=torch.long) for b in batch]
+
+ # --- Motion tensor: (B, J, D, T); per-sample (F, nj, D) -> (nj, D, F) ---
+ motion = torch.zeros((B, max_joints, n_feats, max_len))
+ for i, data in enumerate(batch):
+ nj = n_joints_list[i].item()
+ m = torch.from_numpy(data['motion']).float() # (F, nj, D)
+ motion[i, :nj, :, :] = m.permute(1, 2, 0) # (nj, D, F)
+
+ # --- Joint-axis padded fields (always present) ---
+ tpos_first_frame = _pad_joint_axis(batch, 'tpos_first_frame', max_joints, (n_feats,))
+ mean = _pad_joint_axis(batch, 'mean', max_joints, (n_feats,))
+ std = _pad_joint_axis(batch, 'std', max_joints, (n_feats,))
+ joint_depths = _pad_joint_axis(batch, 'joint_depths', max_joints, (), dtype=torch.long)
+
+ # std must default to 1 on padding slots so division in the model is safe
+ std_ones = torch.ones_like(std)
+ std_mask = (torch.arange(max_joints)[None, :] < n_joints_list[:, None]).unsqueeze(-1)
+ std = torch.where(std_mask, std, std_ones)
+
+ # --- Pairwise joint-joint matrices (NxN) ---
+ # Stored as torch.long since both are consumed as nn.Embedding indices.
+ joint_relations = torch.zeros((B, max_joints, max_joints), dtype=torch.long)
+ graph_dist = torch.zeros((B, max_joints, max_joints), dtype=torch.long)
+ for i, data in enumerate(batch):
+ nj = n_joints_list[i].item()
+ joint_relations[i] = create_padded_matrix(
+ data['joint_relations'], max_joints, nj, dtype=torch.long,
+ )
+ graph_dist[i] = create_padded_matrix(
+ data['joint_graph_dist'], max_joints, nj, dtype=torch.long,
+ )
+
+ # --- Optional fields (present on every / any sample) ---
+ has_spectral_feats = all('spectral_feats' in b for b in batch)
+ has_joint_names_emb = all('joint_names_emb' in b for b in batch)
+ has_offsets = all('offsets' in b for b in batch)
+ has_tpos_ff_parents = all('tpos_first_frame_parents' in b for b in batch)
+ has_caption_emb = any('caption_emb' in b for b in batch)
+
+ spectral_feats = None
+ if has_spectral_feats:
+ # spectral width (k) can vary across samples โ€” pad both joints and k
+ max_freqs = max(b['spectral_feats'].shape[1] for b in batch)
+ spectral_feats = torch.zeros((B, max_joints, max_freqs))
+ for i, data in enumerate(batch):
+ ev = data['spectral_feats'] # (nj, k_i)
+ spectral_feats[i, :ev.shape[0], :ev.shape[1]] = torch.from_numpy(ev)
+
+ joint_names_emb = (
+ _pad_joint_axis(
+ batch, 'joint_names_emb', max_joints,
+ (batch[0]['joint_names_emb'].shape[-1],),
+ )
+ if has_joint_names_emb else None
+ )
+ offsets = (
+ _pad_joint_axis(batch, 'offsets', max_joints, (3,))
+ if has_offsets else None
+ )
+ tpos_ff_parents = (
+ _pad_joint_axis(batch, 'tpos_first_frame_parents', max_joints, (n_feats,))
+ if has_tpos_ff_parents else None
+ )
+ caption_emb = None
+ caption_tokens = None
+ caption_mask = None
+ if has_caption_emb:
+ text_dim = next(b['caption_emb'].shape[-1] for b in batch if 'caption_emb' in b)
+ caption_emb = torch.zeros((B, text_dim))
+ # Token sequences for text_cond='cross_attn', right-padded to the
+ # batch's longest caption with a validity mask. Every row keeps at
+ # least one valid position: an all-masked row makes SDPA return NaN,
+ # and a caption-less sample must contribute zeros, not NaNs.
+ max_tok = max((b['caption_tokens'].shape[0]
+ for b in batch if 'caption_tokens' in b), default=1)
+ caption_tokens = torch.zeros((B, max_tok, text_dim))
+ caption_mask = torch.zeros((B, max_tok), dtype=torch.bool)
+ caption_mask[:, 0] = True
+ for i, data in enumerate(batch):
+ if 'caption_emb' in data:
+ caption_emb[i] = torch.from_numpy(data['caption_emb'])
+ if 'caption_tokens' in data:
+ toks = torch.from_numpy(data['caption_tokens']) # (T_i, D)
+ caption_tokens[i, :toks.shape[0]] = toks
+ caption_mask[i, :toks.shape[0]] = True
+
+ # --- Masks ---
+ joint_mask = lengths_to_mask(
+ n_joints_list, max_len=max_joints,
+ ).unsqueeze(1).unsqueeze(1) # (B, 1, 1, J)
+
+ lengths_mask = lengths_to_mask(
+ motion_lengths, max_len=max_len,
+ ).unsqueeze(1).unsqueeze(1) # (B, 1, 1, F)
+
+ # --- Assemble cond dict ---
+ cond = {
+ 'crop_start_ind': crop_start_inds,
+ 'motion_length': motion_lengths,
+ 'lengths_mask': lengths_mask,
+ 'n_joints': n_joints_list,
+ 'joint_mask': joint_mask,
+ 'tpos_first_frame': tpos_first_frame,
+ 'parents': parents_list,
+ 'edge_indexs': edge_indexs_list,
+ 'joint_relations': joint_relations,
+ 'graph_dist': graph_dist,
+ 'joint_depths': joint_depths,
+ 'mean': mean,
+ 'std': std,
+ }
+
+ # Optional tensor fields
+ for key, value in (
+ ('spectral_feats', spectral_feats),
+ ('joint_names_emb', joint_names_emb),
+ ('offsets', offsets),
+ ('tpos_first_frame_parents', tpos_ff_parents),
+ ('caption_emb', caption_emb),
+ ('caption_tokens', caption_tokens),
+ ('caption_mask', caption_mask),
+ ):
+ if value is not None:
+ cond[key] = value
+
+ # Optional string/list fields (per-sample scalars, no padding)
+ for key in ('object_type', 'split_tag', 'caption'):
+ if all(key in b for b in batch):
+ cond[key] = [b[key] for b in batch]
+
+ return motion, cond
diff --git a/unimate/dataset/mixture/dataset.py b/unimate/dataset/mixture/dataset.py
new file mode 100644
index 0000000..b3a55a7
--- /dev/null
+++ b/unimate/dataset/mixture/dataset.py
@@ -0,0 +1,1666 @@
+"""The unified Mixture dataset: heterogeneous-skeleton motion clips in memory.
+
+Three layers:
+ * :class:`Mixture` โ€” top-level ``torch.utils.data.Dataset`` used by the
+ dataloader factory. Loads per-dataset ``cond.npy`` / captions /
+ ``test_objects.txt``, applies subset + joint-count filters, then builds
+ the inner :class:`MotionDataset`.
+ * :class:`MotionDataset` โ€” holds all clips in memory, pre-encodes text,
+ applies the train/eval split, augmentations, normalization stats, and
+ serves per-sample dicts consumed by ``collate.mixture_batch_collate``.
+ * :class:`MixtureSampler` โ€” optional power-law balanced sampler across
+ object types.
+"""
+
+import json
+import os
+import random
+from collections import defaultdict
+from os.path import join as pjoin
+from typing import Optional, Set
+
+import numpy as np
+import torch
+from torch.utils import data
+from tqdm import tqdm
+
+from Quaternions import Quaternions
+
+from unimate.dataset.transforms import (
+ apply_cropping, extract_conditions, apply_normalization,
+ apply_padding, build_parent_features,
+)
+from unimate.utils.motion_utils import (
+ realign_unimate_clip,
+ compute_unimate_motion_feats,
+ compute_rots_from_tpos,
+ recover_unimate_joint_pos_from_ric,
+ recover_unimate_joint_pos_from_rot,
+)
+from unimate.utils.topology_utils import compute_laplacian_eigenvectors
+from unimate.models.text_encoder.factory import create_text_encoder
+from unimate.utils.text_emb_cache import load_cache, load_caches, pool as pool_tokens
+from unimate.utils.logger import get_logger
+from unimate.dataset.mixture import augmentations as aug_ops
+from Animation import offsets_from_positions
+
+
+logger = get_logger(file_name=__file__, debug="mixture_dataset")
+
+
+# Per-dataset train/eval split mode:
+# - 'object_type' โ€” hold out whole object types as eval. Default for
+# multi-topology datasets (truebones, objaverse): training
+# never sees the held-out skeletons, so eval measures
+# generalization to unseen topologies.
+# - 'clip' โ€” stratified per-object-type at the clip level (train/eval
+# drawn from each type). Used for single-topology datasets
+# (mixamo) where there is only one object_type and an
+# object_type-level holdout would empty the train set.
+#
+# An explicit ``test_objects.txt`` next to ``cond.npy`` overrides the mode
+# above for that dataset: the listed object types become the eval set
+# (object_type-style split), regardless of ``test_split_ratio``. Useful when
+# the test set is fixed by hand (e.g. truebones evaluation list).
+_DATASET_SPLIT_MODE = {
+ 'mixamo': 'clip',
+ 'truebones': 'object_type',
+ 'objaverse': 'object_type',
+}
+
+# The UniMate representation stores per-frame deltas (root trajectory and
+# per-joint local velocity) without normalizing by the frame rate, so the
+# frame rate is part of the feature scale: the same physical motion sampled
+# at 60 fps yields half the velocity of a 30 fps one. Stage 4 emits 30 fps
+# clips (``data_process/utils/motion_features.py::_load_npz_anim`` downsamples
+# anything faster), so a clip declaring anything else was built under a
+# different assumption and is rejected rather than silently mixed in.
+EXPECTED_CLIP_FPS = 30
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def create_condition(cond_dict, max_freqs=8):
+ """Extract skeleton topology fields from a per-object condition dict.
+
+ All fields are pre-computed by
+ ``data_process.utils.motion_features.build_topology_cond`` โ€” reading them here
+ avoids dataloader-init recomputation and pins eigenvector signs that
+ ``compute_laplacian_eigenvectors`` would otherwise pick non-deterministically.
+ """
+ parents = np.asarray(cond_dict['parents'])
+ spectral_feats = np.asarray(cond_dict['spectral_feats'])
+ if spectral_feats.shape[-1] != max_freqs:
+ logger.warning(
+ f"Saved spectral_feats has shape[-1]={spectral_feats.shape[-1]} "
+ f"but max_freqs={max_freqs}; recomputing from parents."
+ )
+ spectral_feats, _ = compute_laplacian_eigenvectors(parents, max_freqs=max_freqs)
+
+ return {
+ 'parents': parents, # (J,)
+ 'edge_indexs': np.asarray(cond_dict['edge_indexs']), # (2, 2*(J-1))
+ 'joint_graph_dist': np.asarray(cond_dict['joint_graph_dists']), # (J, J)
+ 'joint_relations': np.asarray(cond_dict['joint_relations']), # (J, J)
+ 'joint_depths': np.asarray(cond_dict['joint_depths']), # (J,)
+ 'spectral_feats': spectral_feats, # (J, K)
+ 'tpos': np.asarray(cond_dict['tpos_first_frame']), # (J, 3)
+ }
+
+
+def _validate_motion(motion_data, parents=None, offsets=None,
+ gt_global_positions=None, recovery_tol=1e-4,
+ cross_check=False):
+ """Check motion array for NaN/Inf/zero-length. Returns (is_valid, reason).
+
+ For 12-dim UniMate features:
+ - ``gt_global_positions`` provided โ†’ round-trip via RIC and FK; both
+ must match GT within ``recovery_tol``.
+ - ``cross_check=True`` (no GT, e.g. post-aug) โ†’ RIC and FK must agree;
+ divergence signals the aug broke the positionโ†”rotation invariant.
+ """
+ if motion_data.size == 0 or motion_data.shape[0] == 0:
+ return False, "empty motion (0 frames)"
+ if np.isnan(motion_data).any():
+ nan_pct = 100 * np.isnan(motion_data).sum() / motion_data.size
+ return False, f"contains NaN ({nan_pct:.1f}% of values)"
+ if np.isinf(motion_data).any():
+ inf_count = np.isinf(motion_data).sum()
+ return False, f"contains {inf_count} Inf values"
+
+ if gt_global_positions is not None:
+ gt = gt_global_positions[:-1]
+ err_ric = np.abs(recover_unimate_joint_pos_from_ric(motion_data) - gt).max()
+ err_fk = np.abs(
+ recover_unimate_joint_pos_from_rot(motion_data, parents, offsets) - gt
+ ).max()
+ if err_ric > recovery_tol or err_fk > recovery_tol:
+ return False, (
+ f"recovery mismatch: ric_max={err_ric:.4g}, fk_max={err_fk:.4g} "
+ f"(tol={recovery_tol:g})"
+ )
+ elif cross_check:
+ ric_pos = recover_unimate_joint_pos_from_ric(motion_data)
+ fk_pos = recover_unimate_joint_pos_from_rot(motion_data, parents, offsets)
+ err = np.abs(ric_pos - fk_pos).max()
+ if err > recovery_tol:
+ return False, (
+ f"RICโ†”FK divergence: max={err:.4g} (tol={recovery_tol:g})"
+ )
+
+ return True, ""
+
+
+def model_joint_names(cond_entry, object_type):
+ """Joint names the model is conditioned on โ€” the CLEANED vocabulary.
+
+ ``clean_joint_names`` is stage 3's output (`data_process/joint_annotation`):
+ the rig's arbitrary bone strings (``Bip01_L_Thigh``, ``BN__Neck_L_01``)
+ mapped onto one shared anatomical vocabulary (``Left Thigh``, ``Neck``).
+ That shared vocabulary is the whole point of embedding joint names across
+ heterogeneous skeletons โ€” raw rig strings would make the same anatomical
+ joint embed differently per asset, which is exactly what this conditioning
+ exists to avoid.
+
+ Falling back to the raw names keeps an old ``cond.npy`` loadable, but it
+ silently degrades conditioning, so say so rather than doing it quietly.
+ The same rule is applied by ``unimate/tools/precompute_text_emb.py``; the
+ two must agree or the cached embeddings will not cover what is looked up.
+ """
+ names = cond_entry.get('clean_joint_names')
+ n_expected = len(cond_entry['joint_names'])
+ if names is not None and len(names) == n_expected and all(
+ str(n).strip() for n in names):
+ return [str(n) for n in names]
+
+ reason = ('absent' if names is None
+ else f'{len(names)} entries for {n_expected} joints'
+ if len(names) != n_expected else 'contains blank names')
+ logger.warning(
+ f"[{object_type}] clean_joint_names {reason}; conditioning on the raw "
+ f"rig names instead. Re-run data_process stage 3 (joint_annotation) "
+ f"for this asset โ€” raw names do not share a vocabulary across rigs."
+ )
+ return [str(n) for n in cond_entry['joint_names']]
+
+
+# ---------------------------------------------------------------------------
+# MotionDataset โ€” stores all motion clips in memory
+# ---------------------------------------------------------------------------
+
+class MotionDataset(data.Dataset):
+ """In-memory dataset of motion clips across heterogeneous skeletons.
+
+ ``__getitem__`` only yields train clips (from ``train_motion_dict`` /
+ ``train_name_list``). Eval clips are kept in memory and exposed via
+ ``eval_motion_dict`` / ``eval_name_list`` / ``eval_object_motions_map``
+ for inference and visualization. Normalization stats are computed from
+ train clips only to prevent leakage.
+ """
+
+ def __init__(
+ self,
+ data_dict: dict,
+ topology_condition_type: str,
+ max_motion_length: int,
+ config_max_depth: int = 0,
+ feature_len: int = 12,
+ text_encoder_type: str = "t5",
+ text_encoder_version: str = "t5-base",
+ use_dataset_stats: bool = True,
+ balanced_stats: bool = False,
+ tie_std: bool = False,
+ use_addition_aug: bool = False,
+ use_removal_aug: bool = False,
+ use_pooling_aug: bool = False,
+ use_perturbation_aug: bool = False,
+ test_split_ratio: float = 0.0,
+ split_seed: int = 42,
+ max_freqs: int = 8,
+ debug_validate_aug: bool = False,
+ ground_motion_height: bool = True,
+ realign_feature: bool = True,
+ prebuilt_max_joints: int = 0,
+ prebuilt_max_depth: int = 0,
+ target_object_types: Optional[Set[str]] = None,
+ target_clip_stems: Optional[Set[str]] = None,
+ stats_path: Optional[str] = None,
+ ):
+ self._init_config(
+ topology_condition_type, max_motion_length, config_max_depth,
+ feature_len, use_dataset_stats, balanced_stats,
+ tie_std, use_addition_aug, use_removal_aug, use_pooling_aug,
+ use_perturbation_aug, test_split_ratio, split_seed, max_freqs,
+ debug_validate_aug, ground_motion_height, realign_feature,
+ )
+ self._target_object_types = target_object_types
+ self._target_clip_stems = target_clip_stems
+ self._stats_path = stats_path
+ self._init_data_state(data_dict)
+ if self._target_object_types is not None:
+ # Sampling uses both train and eval maps; honoring test_objects.txt
+ # would route a target type entirely to eval and trip the
+ # _eval_clips_explicit "don't drain the dataset" guard.
+ self.explicit_eval_objects = {dt: [] for dt in self.explicit_eval_objects}
+ self._build_text_embeddings(
+ data_dict, text_encoder_type, text_encoder_version,
+ )
+ motion_dict, name_list, selected_object_types = self._load_all_clips(data_dict)
+ self._finalize_splits(motion_dict, name_list, selected_object_types)
+ if prebuilt_max_joints > 0 and prebuilt_max_depth > 0:
+ # On-disk data can grow between training and inference; trusting
+ # the saved values keeps the tensor dim matched to the checkpoint.
+ self.max_joints, self.max_depth = prebuilt_max_joints, prebuilt_max_depth
+ logger.info(
+ f'Using prebuilt max_joints={self.max_joints} | '
+ f'max_depth={self.max_depth} (skipping data scan).'
+ )
+ else:
+ self.max_joints, self.max_depth = self._compute_max_joints_and_depth()
+
+ logger.info(
+ f'MotionDataset loaded {len(self.train_motion_dict)} train + '
+ f'{len(self.eval_motion_dict)} eval clips '
+ f'from {len(self.selected_object_types)} object types '
+ f'| max_joints={self.max_joints} | max_depth={self.max_depth}'
+ )
+
+ self._calculate_dataset_stats()
+
+ # ------------------------------------------------------------------
+ # Init phases
+ # ------------------------------------------------------------------
+
+ def _init_config(self, topology_condition_type, max_motion_length,
+ config_max_depth, feature_len,
+ use_dataset_stats, balanced_stats, tie_std,
+ use_addition_aug, use_removal_aug, use_pooling_aug,
+ use_perturbation_aug, test_split_ratio, split_seed,
+ max_freqs, debug_validate_aug,
+ ground_motion_height, realign_feature):
+ """Stash hyperparameters as instance attributes."""
+ self.topology_condition_type = topology_condition_type
+ self.max_motion_length = max_motion_length
+ self.config_max_depth = config_max_depth
+ self.feature_len = feature_len
+ self.use_dataset_stats = use_dataset_stats
+ self.balanced_stats = balanced_stats
+ self.tie_std = tie_std
+ self.use_addition_aug = use_addition_aug
+ self.use_removal_aug = use_removal_aug
+ self.use_pooling_aug = use_pooling_aug
+ self.use_perturbation_aug = use_perturbation_aug
+ self.test_split_ratio = test_split_ratio
+ self.split_seed = split_seed
+ self.max_freqs = max_freqs
+ self.debug_validate_aug = debug_validate_aug
+ self.ground_motion_height = ground_motion_height
+ self.realign_feature = realign_feature
+ # Motion dirs already warned about for a missing clip fps field.
+ self._fps_unset_dirs = set()
+
+ def _init_data_state(self, data_dict):
+ """Initialize per-dataset state derived from ``data_dict``."""
+ self.dataset_stats = {}
+ self.cond_dict = {}
+ self.dataset_object_count = {}
+ self.split_mode_by_dataset = dict(_DATASET_SPLIT_MODE)
+ # ``explicit_eval_objects[dt]`` (from ``test_objects.txt``) overrides
+ # the per-dataset split mode and bypasses ``test_split_ratio``.
+ self.explicit_eval_objects = {
+ dt: list(info.get('test_objects') or [])
+ for dt, info in data_dict.items()
+ }
+
+ def _build_text_embeddings(self, data_dict, text_encoder_type,
+ text_encoder_version):
+ """Pre-encode joint names + captions, then drop the encoder.
+
+ Anything already in a feature directory's text-embedding cache (see
+ ``unimate/tools/precompute_text_emb.py``) is read from disk; the
+ encoder is built only if something is still missing, so a complete
+ cache keeps it off the GPU entirely.
+ """
+ self._encoder_spec = (text_encoder_type, text_encoder_version)
+ self.text_encoder = None
+ roots = [info.get('root_dir') for info in data_dict.values()]
+ # Joint names are shared vocabulary โ€” the same string encodes
+ # identically everywhere, so merging them by name across datasets is
+ # safe. Clip keys are NOT: the datasets name clips by different
+ # conventions and nothing guarantees they never collide, so a caption
+ # is keyed by (dataset_type, clip) and a collision is impossible
+ # rather than merely unlikely.
+ joint_cache = load_caches(roots, 'joint', text_encoder_type,
+ text_encoder_version)
+ text_cache = {
+ (ds_type, clip): tokens
+ for ds_type, info in data_dict.items()
+ for clip, tokens in load_cache(info.get('root_dir'), 'caption',
+ text_encoder_type,
+ text_encoder_version).items()
+ }
+ self._preencode_joint_names(data_dict, joint_cache)
+ self._preencode_captions(data_dict, text_cache)
+ if self.text_encoder is not None:
+ del self.text_encoder
+ self.text_encoder = None
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+
+ def _ensure_text_encoder(self):
+ """Build the text encoder on first use (i.e. on the first cache miss)."""
+ if self.text_encoder is None:
+ encoder_type, encoder_version = self._encoder_spec
+ logger.info(f'Text cache incomplete; loading {encoder_type} encoder')
+ self.text_encoder = create_text_encoder(
+ encoder_type=encoder_type,
+ encoder_version=encoder_version,
+ device='cuda' if torch.cuda.is_available() else 'cpu',
+ pool=False, # token sequences; pooling happens below
+ )
+ return self.text_encoder
+
+ def _load_all_clips(self, data_dict):
+ """Run each dataset's loader and return (motion_dict, names, types)."""
+ motion_dict = {}
+ name_list = []
+ selected_object_types = set()
+
+ loaders = {
+ 'truebones': self._load_multi_topology,
+ 'mixamo': self._load_single_topology,
+ 'objaverse': self._load_multi_topology,
+ }
+ for dataset_type, dataset_info in data_dict.items():
+ loader = loaders.get(dataset_type)
+ if loader is None:
+ raise ValueError(f"Unknown dataset type: {dataset_type}")
+ loader(dataset_info, dataset_type, motion_dict,
+ selected_object_types, name_list)
+
+ return motion_dict, name_list, selected_object_types
+
+ def _finalize_splits(self, motion_dict, name_list, selected_object_types):
+ """Apply the train/eval split and build the per-object_type maps."""
+ train_names, eval_names = self._split_names(
+ name_list, motion_dict, self.test_split_ratio, self.split_seed,
+ self.split_mode_by_dataset, self.explicit_eval_objects,
+ )
+ if not train_names:
+ if self._target_object_types is None:
+ raise ValueError(
+ f"Empty train split (test_split_ratio={self.test_split_ratio}).")
+ logger.info("Empty train split at inference; sampling will use eval map.")
+
+ self.train_motion_dict = {n: motion_dict[n] for n in train_names}
+ self.eval_motion_dict = {n: motion_dict[n] for n in eval_names}
+ self.train_name_list = train_names
+ self.eval_name_list = eval_names
+
+ self.train_object_motions_map = self._group_by_object(self.train_motion_dict)
+ self.eval_object_motions_map = self._group_by_object(self.eval_motion_dict)
+ self.selected_object_types = sorted(selected_object_types)
+
+ total = len(train_names) + len(eval_names)
+ effective_ratio = len(eval_names) / total if total else 0.0
+ logger.info(
+ f"Clip split: {len(train_names)} train / {len(eval_names)} eval "
+ f"(ratio={effective_ratio:.3f}, seed={self.split_seed})"
+ )
+
+ @staticmethod
+ def _group_by_object(clip_dict):
+ grouped = {}
+ for nm, entry in clip_dict.items():
+ grouped.setdefault(entry['object_type'], []).append(nm)
+ return grouped
+
+ # ------------------------------------------------------------------
+ # Per-dataset loaders
+ # ------------------------------------------------------------------
+
+ def _batch_encode_unique(self, texts, label: str, chunk_size: int = 256,
+ cache=None):
+ """Dedupe ``texts`` and encode the unique set in fixed-size chunks.
+
+ Returns ``{text: (T_i, emb_dim) ndarray}`` โ€” the token sequence with
+ padding removed; falsy strings dropped. Chunking bounds peak GPU
+ memory for long sequences.
+ """
+ unique, seen = [], set()
+ total = 0
+ for t in texts:
+ if not t:
+ continue
+ total += 1
+ if t not in seen:
+ seen.add(t)
+ unique.append(t)
+
+ if not unique:
+ return {}
+
+ cache = cache or {}
+ out = {t: cache[t] for t in unique if t in cache}
+ todo = [t for t in unique if t not in out]
+ if not todo:
+ logger.info(
+ f'Pre-encoding {label}: {len(unique)} unique / {total} total '
+ f'โ€” all from the text-embedding cache'
+ )
+ return out
+
+ logger.info(
+ f'Pre-encoding {label}: {len(unique)} unique / {total} total '
+ f'({len(out)} cached, {len(todo)} to encode, chunk_size={chunk_size})'
+ )
+ encoder = self._ensure_text_encoder()
+ n_chunks = (len(todo) + chunk_size - 1) // chunk_size
+ for i in tqdm(range(0, len(todo), chunk_size),
+ desc=f'Encoding {label}', total=n_chunks):
+ chunk = todo[i:i + chunk_size]
+ inputs = encoder.tokenize(chunk)
+ hidden = encoder(inputs).detach().cpu().numpy() # (B, T, D)
+ lengths = inputs['attention_mask'].sum(dim=-1).cpu().numpy()
+ for j, text in enumerate(chunk):
+ # Drop padding so the stored rows match the cache's ragged
+ # form; one row is kept even for an empty string.
+ out[text] = hidden[j, :max(int(lengths[j]), 1)]
+ return out
+
+ def _preencode_joint_names(self, data_dict, cache=None):
+ """Encode every unique joint name โ†’ ``self._joint_name_emb``.
+
+ Scoped to ``target_object_types`` when set.
+ """
+ targets = self._target_object_types
+ all_names = [
+ name
+ for dataset_info in data_dict.values()
+ for ot, cond_entry in dataset_info['cond_dict'].items()
+ if targets is None or ot in targets
+ for name in model_joint_names(cond_entry, ot)
+ ]
+ # One vector per joint. The cache already stores joint names pooled
+ # (it is all the model reads of them), so only freshly encoded
+ # sequences still need pooling here.
+ self._joint_name_emb = {
+ name: emb if emb.ndim == 1 else pool_tokens(emb)
+ for name, emb in self._batch_encode_unique(
+ all_names, 'joint names', cache=cache).items()
+ }
+
+ def _preencode_captions(self, data_dict, cache=None):
+ """Encode each clip's caption โ†’ ``self._caption_tokens`` (+ pooled).
+
+ Skipped when ``target_object_types`` is set: captions come from the
+ per-test-case spec and are encoded inline at sample time.
+ """
+ if self._target_object_types is not None:
+ self._caption_emb = {}
+ self._caption_tokens = {}
+ logger.info('Skipping caption pre-encoding (inference mode).')
+ return
+ caption_by_clip = {
+ (ds_type, clip): cap
+ for ds_type, dataset_info in data_dict.items()
+ for clip, cap in dataset_info.get('captions', {}).items()
+ if cap
+ }
+ # Keyed by (dataset_type, clip): a clip's
+ # features are one lookup, with no caption-string round trip. Repeated
+ # captions are still encoded once โ€” _batch_encode_unique dedupes the
+ # strings before the forward pass.
+ cache = cache or {}
+ todo = {k: c for k, c in caption_by_clip.items() if k not in cache}
+ by_text = self._batch_encode_unique(list(todo.values()), 'captions')
+
+ # A cache hit carries both views: the token sequence text_cond=
+ # 'cross_attn' attends, and the pooled vector text_cond='adaln' reads
+ # โ€” the latter exactly as the encoder produced it, so adaLN gets the
+ # same number the pooled encoder always returned. Only a cache MISS
+ # falls back to pooling the sequence here.
+ self._caption_tokens, self._caption_emb = {}, {}
+ for k in caption_by_clip:
+ if k in cache:
+ tokens, pooled = cache[k]
+ else:
+ tokens = by_text.get(caption_by_clip[k])
+ if tokens is None:
+ continue
+ pooled = pool_tokens(tokens)
+ self._caption_tokens[k] = tokens
+ self._caption_emb[k] = pooled
+
+ def _precompute_object_type_meta(self, object_type, cond_entry):
+ """Per-object-type meta reused across all clips of that type."""
+ condition = create_condition(cond_entry, max_freqs=self.max_freqs)
+
+ # Ground the T-pose to match how ``_load_motion_file`` grounds motion;
+ # otherwise the network sees two different Y references when
+ # ``topology_condition_type='tpos'``.
+ if self.ground_motion_height:
+ condition['tpos'] = condition['tpos'].copy()
+ condition['tpos'][..., 1] -= condition['tpos'][..., 1].min()
+
+ joint_names = model_joint_names(cond_entry, object_type)
+ joint_names_emb = np.stack(
+ [self._joint_name_emb[n] for n in joint_names]
+ ) # (J, emb_dim)
+ assert joint_names_emb.shape[0] == condition['parents'].shape[0], (
+ f"Joints names embedding / joint count mismatch for {object_type}."
+ )
+
+ offsets = offsets_from_positions(condition['tpos'], condition['parents']) # (J, 3)
+
+ return {
+ 'object_type': object_type,
+ 'joint_names_emb': joint_names_emb,
+ 'condition': condition,
+ 'offsets': offsets,
+ 'tpos_local_rotations': np.asarray(cond_entry['tpos_local_rotations']),
+ }
+
+ def _load_motion_file(self, motion_dir, motion_name, dataset_type, meta, captions):
+ """Load one clip, validate it, and build its entry dict. Returns
+ ``None`` when the file is invalid or has no caption.
+ """
+ # Check caption first โ€” depends only on the filename, so failing here
+ # avoids the NPZ load + feature compute for any clip we'd discard.
+ clip_key = os.path.splitext(motion_name)[0]
+ caption = captions.get(clip_key, '')
+ if not caption and self._target_object_types is None:
+ logger.warning(f'Skipping {motion_name}: missing caption for {clip_key}')
+ return None
+
+ parents = meta['condition']['parents']
+ offsets = meta['offsets']
+ npz = np.load(pjoin(motion_dir, motion_name), allow_pickle=False)
+ global_positions = npz['global_positions'] # (F, J, 3)
+ local_rotations = npz['local_rotations'] # (F, J, 4)
+ root_facing_quat = npz['root_facing_quat'] # (F, 4)
+ self._check_clip_fps(motion_dir, motion_name, npz)
+
+ if self.ground_motion_height:
+ global_positions = global_positions.copy()
+ global_positions[..., 1] -= global_positions[..., 1].min()
+
+ # Rebase against the T-pose reference so features live in a
+ # topology-consistent rotation frame.
+ tpos_q = np.broadcast_to(
+ meta['tpos_local_rotations'][None],
+ local_rotations.shape,
+ ).copy()
+
+ rebased = compute_rots_from_tpos(
+ Quaternions(tpos_q), Quaternions(local_rotations), parents,
+ )
+ motion_feats = compute_unimate_motion_feats(
+ global_positions, rebased, parents, Quaternions(root_facing_quat),
+ ) # (F-1, J, 12)
+
+ valid, reason = _validate_motion(
+ motion_feats,
+ parents=parents,
+ offsets=offsets,
+ gt_global_positions=global_positions,
+ )
+ if not valid:
+ logger.warning(f'Skipping {motion_name}: {reason}')
+ return None
+
+ entry = {
+ 'motion': motion_feats, # (F-1, J, 12)
+ 'offsets': offsets, # (J, 3)
+ 'object_type': meta['object_type'],
+ 'joint_names_emb': meta['joint_names_emb'], # (J, emb_dim)
+ 'dataset_type': dataset_type,
+ }
+ entry.update(meta['condition'])
+
+ entry['caption'] = caption
+ cap_key = (dataset_type, clip_key)
+ if cap_key in self._caption_emb:
+ entry['caption_emb'] = self._caption_emb[cap_key] # (D,)
+ entry['caption_tokens'] = self._caption_tokens[cap_key] # (T, D)
+ return entry
+
+ def _check_clip_fps(self, motion_dir, motion_name, npz):
+ """Reject clips whose frame rate is not the one the features assume.
+
+ Pre-``fps`` feature sets predate the field; they were all built at 30
+ fps, so a missing field is accepted with one warning per directory
+ rather than failing the run.
+ """
+ if 'fps' not in npz:
+ if motion_dir not in self._fps_unset_dirs:
+ self._fps_unset_dirs.add(motion_dir)
+ logger.warning(
+ f'{motion_dir}: clips carry no fps field (pre-fps feature '
+ f'set); assuming {EXPECTED_CLIP_FPS} fps.'
+ )
+ return
+ fps = int(npz['fps'])
+ if fps != EXPECTED_CLIP_FPS:
+ raise ValueError(
+ f'{pjoin(motion_dir, motion_name)}: clip is {fps} fps, but the '
+ f'motion features assume {EXPECTED_CLIP_FPS} fps โ€” velocities '
+ f'would be off by {fps / EXPECTED_CLIP_FPS:.3g}x. Re-run stage 4 '
+ f'(data_process/scripts/run_extract_features.sh) for this dataset.'
+ )
+
+ @staticmethod
+ def _log_dataset_loaded(dataset_type, loaded, total, n_types):
+ logger.info(
+ f'{dataset_type.capitalize()} loaded {loaded}/{total} valid motions '
+ f'across {n_types} object type{"s" if n_types != 1 else ""}'
+ )
+
+ def _load_multi_topology(self, dataset_info, dataset_type, motion_dict,
+ selected_object_types, name_list):
+ """Loader for multi-topology datasets (truebones, objaverse)."""
+ cond_dict = dataset_info['cond_dict']
+ motion_dir = dataset_info['motion_dir']
+ captions = dataset_info.get('captions', {})
+
+ all_object_types = sorted(cond_dict.keys())
+ logger.info(f'{dataset_type.capitalize()} dataset has {len(all_object_types)} object types')
+
+ # Bucket files by object_type via one directory scan. Filenames are
+ # ``{object_type}-{clip_id}.npz`` and object_type names never contain
+ # ``-``, so the type is everything before the first ``-``.
+ type_set = set(all_object_types)
+ files_by_type = defaultdict(list)
+ for f in sorted(os.listdir(motion_dir)):
+ if not f.endswith('.npz'):
+ continue
+ sep_idx = f.find('-')
+ if sep_idx <= 0:
+ continue
+ object_type = f[:sep_idx]
+ if object_type in type_set:
+ files_by_type[object_type].append(f)
+
+ self.dataset_object_count[dataset_type] = {}
+ total_seen = 0
+ total_loaded = 0
+ skipped_no_files = 0
+ skipped_off_target = 0
+ for object_type in tqdm(
+ all_object_types, total=len(all_object_types),
+ desc=f'Loading {dataset_type.capitalize()} motions',
+ ):
+ object_motions = files_by_type[object_type]
+ if not object_motions:
+ skipped_no_files += 1
+ continue
+
+ if (self._target_object_types is not None
+ and object_type not in self._target_object_types):
+ skipped_off_target += 1
+ continue
+
+ if self._target_clip_stems is not None:
+ object_motions = [
+ f for f in object_motions
+ if os.path.splitext(f)[0] in self._target_clip_stems
+ ]
+ elif self._target_object_types is not None:
+ # Headroom > 1 so one bad NPZ doesn't drop the whole type;
+ # create_sample_condition picks one at random anyway.
+ object_motions = object_motions[:3]
+
+ self.cond_dict[object_type] = cond_dict[object_type]
+ meta = self._precompute_object_type_meta(
+ object_type, cond_dict[object_type],
+ )
+
+ total_seen += len(object_motions)
+ loaded_count = 0
+ for motion_name in object_motions:
+ entry = self._load_motion_file(
+ motion_dir, motion_name, dataset_type, meta, captions,
+ )
+ if entry is None:
+ continue
+ motion_dict[motion_name] = entry
+ selected_object_types.add(object_type)
+ name_list.append(motion_name)
+ loaded_count += 1
+
+ self.dataset_object_count[dataset_type][object_type] = loaded_count
+ total_loaded += loaded_count
+
+ if skipped_no_files:
+ logger.info(
+ f'{dataset_type.capitalize()}: skipped {skipped_no_files}/'
+ f'{len(all_object_types)} object types with no motion files in {motion_dir}'
+ )
+ if skipped_off_target:
+ logger.info(
+ f'{dataset_type.capitalize()}: skipped {skipped_off_target}/'
+ f'{len(all_object_types)} object types outside inference target set'
+ )
+
+ self._log_dataset_loaded(
+ dataset_type, total_loaded, total_seen,
+ len(self.dataset_object_count[dataset_type]),
+ )
+
+ def _load_single_topology(self, dataset_info, dataset_type, motion_dict,
+ selected_object_types, name_list):
+ """Loader for single-topology datasets (e.g. mixamo)."""
+ cond_dict = dataset_info['cond_dict']
+ motion_dir = dataset_info['motion_dir']
+ captions = dataset_info.get('captions', {})
+
+ assert len(cond_dict) == 1, (
+ f'Single-topology loader expects exactly 1 object type, got {len(cond_dict)}'
+ )
+ object_type = next(iter(cond_dict))
+ cond_data = cond_dict[object_type]
+
+ logger.info(f'{dataset_type.capitalize()} dataset has 1 object type: {object_type}')
+
+ self.dataset_object_count[dataset_type] = {}
+ if (self._target_object_types is not None
+ and object_type not in self._target_object_types):
+ logger.info(
+ f'{dataset_type.capitalize()}: object_type {object_type!r} not in '
+ f'inference target set; skipping entire dataset.'
+ )
+ return
+
+ object_motions = sorted(
+ f for f in os.listdir(motion_dir) if f.endswith('.npz')
+ )
+
+ # Mixamo clip names are prefixed at load (``{object_type}_{motion_name}``);
+ # the target stem comparison must mirror that prefix.
+ if self._target_clip_stems is not None:
+ object_motions = [
+ f for f in object_motions
+ if f'{object_type}_{os.path.splitext(f)[0]}' in self._target_clip_stems
+ ]
+ elif self._target_object_types is not None:
+ object_motions = object_motions[:3]
+
+ if not object_motions:
+ logger.info(
+ f'{dataset_type.capitalize()}: no motion files in {motion_dir}; '
+ f'skipping object type {object_type}'
+ )
+ return
+
+ # Register only after confirming clips exist, so empty types don't
+ # leak into ``self.cond_dict`` / ``_compute_max_joints_and_depth``.
+ self.cond_dict[object_type] = cond_data
+ meta = self._precompute_object_type_meta(object_type, cond_data)
+
+ loaded_count = 0
+ for motion_name in tqdm(
+ object_motions, total=len(object_motions),
+ desc=f'Loading {dataset_type.capitalize()} motions',
+ ):
+ entry = self._load_motion_file(
+ motion_dir, motion_name, dataset_type, meta, captions,
+ )
+ if entry is None:
+ continue
+ prefixed_name = f'{object_type}_{motion_name}'
+ motion_dict[prefixed_name] = entry
+ selected_object_types.add(object_type)
+ name_list.append(prefixed_name)
+ loaded_count += 1
+
+ self.dataset_object_count[dataset_type][object_type] = loaded_count
+ self._log_dataset_loaded(dataset_type, loaded_count, len(object_motions), 1)
+
+ # ------------------------------------------------------------------
+ # Dataset interface
+ # ------------------------------------------------------------------
+
+ def __len__(self):
+ return len(self.train_name_list)
+
+ def __getitem__(self, idx):
+ data = self.train_motion_dict[self.train_name_list[idx]]
+ dataset_type = data['dataset_type']
+ object_type = data['object_type']
+
+ mean, std = self._get_normalization_stats(data, dataset_type) # (J, D)
+ aug = self._apply_augmentations(data, mean, std)
+
+ augmented_motion = aug['motion']
+ mean, std = aug['mean'], aug['std']
+
+ assert augmented_motion.ndim == 3
+ assert mean.shape == std.shape == augmented_motion.shape[1:]
+
+ # Augmentations rewrite both position and rotation channels; RIC and
+ # FK independently decode the same pose from each view, so divergence
+ # signals a broken aug op (addition/removal/pooling/perturbation).
+ if self.debug_validate_aug:
+ valid, reason = _validate_motion(
+ augmented_motion,
+ parents=aug['parents'],
+ offsets=aug['offsets'],
+ cross_check=True,
+ )
+ if not valid:
+ logger.warning(
+ f"[debug_validate_aug] {object_type} idx={idx}: {reason}"
+ )
+
+ augmented_motion, start_idx = apply_cropping(
+ augmented_motion, self.topology_condition_type, self.max_motion_length,
+ )
+
+ # Re-align clips when cropping moved frame-0 forward, so the
+ # new frame-0 facing direction is identity (matches training-time
+ # invariant assumed by the feature pipeline).
+ if self.realign_feature and start_idx > 0:
+ augmented_motion = realign_unimate_clip(augmented_motion, aug['parents'])
+
+ # Pad tpos (J, 3) to motion feature dim (J, 12): identity 6D
+ # rotation + zero velocity, matching the layout of motion features.
+ tpos = aug['tpos']
+ if tpos.shape[-1] < self.feature_len:
+ J = tpos.shape[0]
+ identity_6d = Quaternions.id(1).rotation_matrix(cont6d=True)[0] # (6,)
+ pad = np.zeros((J, self.feature_len - 3))
+ pad[:, :6] = identity_6d
+ tpos = np.concatenate([tpos, pad], axis=-1)
+
+ conds = extract_conditions(
+ augmented_motion, tpos, self.topology_condition_type,
+ )
+ motion = conds['motion']
+ tpos_first_frame = conds['tpos_first_frame']
+
+ motion = apply_normalization(motion, mean, std)
+ tpos_first_frame = apply_normalization(tpos_first_frame, mean, std)
+ motion, motion_length = apply_padding(motion, self.max_motion_length)
+
+ parents = aug['parents']
+ parent_feats = build_parent_features(tpos_first_frame, parents)
+
+ results = {
+ 'motion': motion,
+ 'max_motion_length': self.max_motion_length,
+ 'motion_length': motion_length,
+ 'max_joints': self.max_joints,
+ 'parents': parents,
+ 'edge_indexs': aug['edge_indexs'],
+ 'tpos_first_frame': tpos_first_frame,
+ 'tpos_first_frame_parents': parent_feats['tpos_first_frame_parents'],
+ 'offsets': aug['offsets'],
+ 'joint_graph_dist': aug['joint_graph_dist'],
+ 'joint_relations': aug['joint_relations'],
+ 'joint_depths': aug['joint_depths'],
+ 'spectral_feats': aug['spectral_feats'],
+ 'joint_names_emb': aug['joint_names_emb'],
+ 'object_type': object_type,
+ 'start_idx': start_idx,
+ 'mean': mean,
+ 'std': std,
+ }
+ results['caption'] = data['caption']
+ results['caption_emb'] = data['caption_emb']
+ results['caption_tokens'] = data['caption_tokens']
+
+ return results
+
+ # ------------------------------------------------------------------
+ # Augmentation pipeline
+ # ------------------------------------------------------------------
+ # Aug ops live in ``augmentations.py`` as plain functions; this wrapper
+ # builds the aug dict and threads ``max_freqs`` through.
+
+ @staticmethod
+ def _extract_aug_dict(data, mean, std):
+ """Copy of a motion_dict entry + stats so augs can mutate freely."""
+ return {
+ 'motion': data['motion'].copy(),
+ 'parents': data['parents'].copy(),
+ 'edge_indexs': data['edge_indexs'].copy(),
+ 'joint_graph_dist': data['joint_graph_dist'].copy(),
+ 'joint_relations': data['joint_relations'].copy(),
+ 'joint_depths': data['joint_depths'].copy(),
+ 'spectral_feats': data['spectral_feats'].copy(),
+ 'tpos': data['tpos'].copy(),
+ 'offsets': data['offsets'].copy(),
+ 'joint_names_emb': data['joint_names_emb'].copy(),
+ 'mean': mean.copy(),
+ 'std': std.copy(),
+ }
+
+ def _apply_augmentations(self, data, mean, std):
+ """Apply at most one enabled augmentation to a copy of ``data``.
+
+ A no-op is always a candidate, so augmentation probability scales
+ inversely with the number of enabled flags.
+ """
+ aug = self._extract_aug_dict(data, mean, std)
+
+ candidates = [
+ ('addition', self.use_addition_aug, self._aug_addition),
+ ('removal', self.use_removal_aug, self._aug_removal),
+ ('pooling', self.use_pooling_aug, self._aug_pooling),
+ ('perturbation', self.use_perturbation_aug, self._aug_perturbation),
+ ]
+ ops = [None] + [fn for _, enabled, fn in candidates if enabled]
+ if len(ops) == 1:
+ return aug
+
+ op = random.choice(ops)
+ return aug if op is None else op(aug)
+
+ def _aug_addition(self, aug):
+ return aug_ops.apply_joint_addition_ellipsoid(aug, self.max_freqs)
+
+ def _aug_removal(self, aug):
+ rate = random.uniform(0.05, 0.15)
+ return aug_ops.apply_joint_removal(aug, rate, self.max_freqs)
+
+ def _aug_pooling(self, aug):
+ rate = random.uniform(0.1, 0.3)
+ return aug_ops.apply_skeleton_pooling(aug, rate, self.max_freqs)
+
+ def _aug_perturbation(self, aug):
+ return aug_ops.apply_joint_perturbation(aug, max_scale=0.1)
+
+ # ------------------------------------------------------------------
+ # Max joints computation
+ # ------------------------------------------------------------------
+
+ def _compute_max_joints_and_depth(self):
+ """Scan loaded skeletons for max_joints / max_depth, apply
+ augmentation headroom, and clamp depth to the config cap.
+ """
+ max_joints_by_dataset = {}
+ max_depths_by_dataset = {}
+ for dataset_type, object_types in self.dataset_object_count.items():
+ for object_type in object_types:
+ cond_data = self.cond_dict[object_type]
+ n_joints = len(cond_data['parents'])
+ depth = int(np.max(cond_data['joint_depths']))
+ max_joints_by_dataset[dataset_type] = max(
+ max_joints_by_dataset.get(dataset_type, 0), n_joints)
+ max_depths_by_dataset[dataset_type] = max(
+ max_depths_by_dataset.get(dataset_type, 0), depth)
+
+ data_max_joints = max(max_joints_by_dataset.values())
+ data_max_depths = max(max_depths_by_dataset.values())
+
+ for dt in max_joints_by_dataset:
+ logger.info(f'{dt.capitalize()} max_joints={max_joints_by_dataset[dt]} '
+ f'max_depths={max_depths_by_dataset[dt]}')
+ logger.info(f'Data max_joints={data_max_joints} | max_depths={data_max_depths}')
+
+ # Headroom: joint-addition aug can add 1 joint.
+ if self.use_addition_aug:
+ data_max_joints += 1
+
+ if self.config_max_depth > 0 and data_max_depths > self.config_max_depth:
+ logger.info(f'Clamping max_depths from {data_max_depths} to {self.config_max_depth}')
+ data_max_depths = self.config_max_depth
+
+ return data_max_joints, data_max_depths
+
+ # ------------------------------------------------------------------
+ # Normalization & statistics
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _split_names(name_list, motion_dict, test_ratio, seed,
+ split_mode_by_dataset=None, explicit_eval_objects=None):
+ """Per-dataset train/eval split. Deterministic for (seed, names).
+
+ Per-dataset selection rule:
+ 1. If ``explicit_eval_objects[dataset_type]`` is non-empty โ†’ use
+ that fixed object_type list as eval (``test_ratio`` ignored).
+ 2. Else if ``test_ratio > 0`` โ†’ use ``split_mode_by_dataset`` mode:
+ - ``'clip'`` : hold out ``round(n * test_ratio)`` clips
+ per object_type (โ‰ฅ1 train clip kept).
+ - ``'object_type'`` : hold out ``round(n_types * test_ratio)``
+ whole object_types (โ‰ฅ1 train type kept).
+ 3. Else โ†’ that dataset contributes 0 eval clips.
+
+ Returns (train_names, eval_names) preserving original ordering within
+ each split.
+ """
+ explicit_eval_objects = {
+ dt: set(v) for dt, v in (explicit_eval_objects or {}).items() if v
+ }
+ if test_ratio <= 0.0 and not explicit_eval_objects:
+ return list(name_list), []
+ if test_ratio > 0.0 and not 0.0 < test_ratio < 1.0:
+ raise ValueError(f"test_split_ratio must be in [0, 1), got {test_ratio}")
+
+ split_mode_by_dataset = split_mode_by_dataset or {}
+
+ by_dataset_obj = defaultdict(lambda: defaultdict(list))
+ for nm in name_list:
+ entry = motion_dict[nm]
+ by_dataset_obj[entry['dataset_type']][entry['object_type']].append(nm)
+
+ rng = random.Random(seed)
+ eval_set = set()
+
+ for dataset_type in sorted(by_dataset_obj.keys()):
+ obj_to_clips = by_dataset_obj[dataset_type]
+ explicit = explicit_eval_objects.get(dataset_type)
+
+ if explicit:
+ eval_set.update(MotionDataset._eval_clips_explicit(
+ dataset_type, explicit, obj_to_clips,
+ ))
+ continue
+ if test_ratio <= 0.0:
+ continue
+
+ mode = split_mode_by_dataset.get(dataset_type, 'clip')
+ if mode == 'object_type':
+ eval_set.update(MotionDataset._eval_clips_by_object_type(
+ dataset_type, obj_to_clips, test_ratio, rng,
+ ))
+ elif mode == 'clip':
+ eval_set.update(MotionDataset._eval_clips_by_clip(
+ obj_to_clips, test_ratio, rng,
+ ))
+ else:
+ raise ValueError(
+ f"Unknown split mode {mode!r} for dataset_type={dataset_type!r}"
+ )
+
+ train_names = [nm for nm in name_list if nm not in eval_set]
+ eval_names = [nm for nm in name_list if nm in eval_set]
+ return train_names, eval_names
+
+ @staticmethod
+ def _eval_clips_explicit(dataset_type, explicit, obj_to_clips):
+ """Eval = all clips of the listed object_types (test_ratio ignored)."""
+ available = set(obj_to_clips.keys())
+ eval_types = sorted(explicit & available)
+ missing = sorted(explicit - available)
+ if missing:
+ logger.warning(
+ f"[{dataset_type}] explicit eval objects not loaded "
+ f"(filtered out or missing motion files): {missing}"
+ )
+ if not eval_types:
+ logger.warning(
+ f"[{dataset_type}] explicit eval list given but no matching "
+ f"object types found in loaded data; skipping eval split"
+ )
+ return set()
+ # Refuse to drain a dataset: at least one object_type must remain in
+ # train, otherwise per-dataset stats and sampling break downstream.
+ if len(eval_types) >= len(obj_to_clips):
+ raise ValueError(
+ f"[{dataset_type}] explicit test_objects.txt holds out ALL "
+ f"{len(obj_to_clips)} loaded object types โ€” would leave 0 "
+ f"train clips for this dataset."
+ )
+ eval_clips = set()
+ for ot in eval_types:
+ eval_clips.update(obj_to_clips[ot])
+ logger.info(
+ f"[{dataset_type}] explicit object_type split: holding out "
+ f"{len(eval_types)}/{len(obj_to_clips)} types as eval ({eval_types})"
+ )
+ return eval_clips
+
+ @staticmethod
+ def _eval_clips_by_object_type(dataset_type, obj_to_clips, test_ratio, rng):
+ """Eval = all clips of ``round(n_types * test_ratio)`` random types.
+ Guarantees at least 1 train type (eval may be 0 when n_types == 1).
+ """
+ object_types = sorted(obj_to_clips.keys())
+ n_types = len(object_types)
+ n_eval_types = int(round(n_types * test_ratio))
+ n_eval_types = min(n_eval_types, max(0, n_types - 1))
+ if n_eval_types == 0:
+ return set()
+ rng.shuffle(object_types)
+ eval_clips = set()
+ for ot in object_types[:n_eval_types]:
+ eval_clips.update(obj_to_clips[ot])
+ logger.info(
+ f"[{dataset_type}] object_type split: holding out "
+ f"{n_eval_types}/{n_types} types as eval"
+ )
+ return eval_clips
+
+ @staticmethod
+ def _eval_clips_by_clip(obj_to_clips, test_ratio, rng):
+ """Eval = ``round(n * test_ratio)`` random clips per object_type."""
+ eval_clips = set()
+ for obj_type in sorted(obj_to_clips.keys()):
+ clips = sorted(obj_to_clips[obj_type])
+ n = len(clips)
+ n_eval = int(round(n * test_ratio))
+ n_eval = min(n_eval, max(0, n - 1))
+ if n_eval == 0:
+ continue
+ rng.shuffle(clips)
+ eval_clips.update(clips[:n_eval])
+ return eval_clips
+
+ def _get_normalization_stats(self, data, dataset_type):
+ """Return (mean, std) arrays shaped (J, D). Raises ``KeyError`` if
+ the dataset_type has no recorded stats (no training frames).
+ """
+ stats = self.dataset_stats[dataset_type]
+ J, D = data['motion'].shape[1], data['motion'].shape[2]
+ mean = np.zeros((J, D))
+ std = np.zeros((J, D))
+ mean[0, :], std[0, :] = stats['mean_root'], stats['std_root']
+ mean[1:, :], std[1:, :] = stats['mean_local'], stats['std_local']
+ return mean, std
+
+ def _calculate_dataset_stats(self):
+ """Compute normalization statistics keyed by ``dataset_type``.
+
+ Axes:
+ - ``use_dataset_stats``: per-dataset pools (True) vs one global pool
+ shared across all dataset_type keys (False).
+ - ``balanced_stats``: frame-weighted (False, default) vs object-type
+ balanced via the law of total variance (True).
+
+ Root (joint 0) and local (joints 1+) are always split โ€” root encodes
+ global velocity/orientation, locals encode parent-relative transforms.
+
+ Short-circuits to disk load when ``stats_path`` is set.
+ """
+ if self._stats_path is not None:
+ logger.info(f"Loading saved dataset stats from {self._stats_path}")
+ self.dataset_stats = np.load(self._stats_path, allow_pickle=True).item()
+ return
+
+ mode = "object-type balanced" if self.balanced_stats else "frame-weighted"
+ scope = "per-dataset" if self.use_dataset_stats else "global"
+ logger.info(f"Calculating dataset statistics ({mode}, {scope})...")
+
+ compute = self._stats_balanced if self.balanced_stats else self._stats_frame_weighted
+ dataset_types = list(self.dataset_object_count.keys())
+
+ if self.use_dataset_stats:
+ jobs = [(d, d) for d in dataset_types]
+ else:
+ jobs = [('<all>', None)]
+
+ for label, filter_d in jobs:
+ mean_root, std_root, mean_local, std_local = compute(filter_d)
+ if mean_root is None:
+ logger.warning(
+ f"No frames for '{label}'; skipping dataset-level stats."
+ )
+ continue
+
+ if self.tie_std:
+ std_root[:3] = std_root[:3].mean()
+ std_root[3:9] = std_root[3:9].mean()
+ std_local[:3] = std_local[:3].mean()
+ std_local[3:9] = std_local[3:9].mean()
+ if self.feature_len >= 12:
+ std_root[9:12] = std_root[9:12].mean()
+ std_local[9:12] = std_local[9:12].mean()
+
+ assert np.all(std_root > 0) and np.all(std_local > 0)
+
+ stats = {
+ 'mean_root': mean_root, 'std_root': std_root,
+ 'mean_local': mean_local, 'std_local': std_local,
+ }
+ # Global mode broadcasts the single result across all dataset_type
+ # keys so downstream lookups remain uniform.
+ targets = [label] if self.use_dataset_stats else dataset_types
+ for t in targets:
+ self.dataset_stats[t] = stats
+
+ with np.printoptions(precision=4, suppress=True, linewidth=200):
+ logger.info(
+ f"[{label}] stats ({mode}):\n"
+ f" mean_root = {mean_root}\n"
+ f" std_root = {std_root}\n"
+ f" mean_local = {mean_local}\n"
+ f" std_local = {std_local}\n"
+ f" std_root range=[{std_root.min():.4g}, {std_root.max():.4g}]"
+ f" std_local range=[{std_local.min():.4g}, {std_local.max():.4g}]"
+ )
+
+ logger.info("Dataset statistics calculation finished.")
+
+ def _stats_frame_weighted(self, d_type=None):
+ """Pool all frames equally. ``d_type=None`` pools across all dataset types."""
+ sum_root = np.zeros(self.feature_len)
+ sq_sum_root = np.zeros(self.feature_len)
+ sum_local = np.zeros(self.feature_len)
+ sq_sum_local = np.zeros(self.feature_len)
+ n_root, n_local = 0, 0
+
+ for m_data in self.train_motion_dict.values():
+ if d_type is not None and m_data['dataset_type'] != d_type:
+ continue
+ motion = m_data['motion'] # (T, J, D)
+ T, J, D = motion.shape
+
+ root = motion[:, 0, :]
+ sum_root += root.sum(axis=0)
+ sq_sum_root += (root ** 2).sum(axis=0)
+ n_root += T
+
+ local = motion[:, 1:J, :].reshape(-1, D)
+ sum_local += local.sum(axis=0)
+ sq_sum_local += (local ** 2).sum(axis=0)
+ n_local += T * (J - 1)
+
+ if n_root == 0:
+ return None, None, None, None
+
+ mean_root = sum_root / n_root
+ std_root = np.maximum(
+ np.sqrt(np.maximum(sq_sum_root / n_root - mean_root ** 2, 0.0)),
+ 1e-8,
+ )
+ mean_local = sum_local / n_local
+ std_local = np.maximum(
+ np.sqrt(np.maximum(sq_sum_local / n_local - mean_local ** 2, 0.0)),
+ 1e-8,
+ )
+ return mean_root, std_root, mean_local, std_local
+
+ def _stats_balanced(self, d_type=None):
+ """Equal-weight per-object-type stats via law of total variance:
+ ``Var(X) = E_k[Var_k(X)] + Var_k[E_k(X)]``. ``d_type=None`` pools
+ across all dataset types.
+ """
+ obj_to_motions = defaultdict(list)
+ for m_data in self.train_motion_dict.values():
+ if d_type is not None and m_data['dataset_type'] != d_type:
+ continue
+ obj_to_motions[m_data['object_type']].append(m_data['motion'])
+
+ if not obj_to_motions:
+ return None, None, None, None
+
+ obj_means_root, obj_vars_root = [], []
+ obj_means_local, obj_vars_local = [], []
+
+ for motions in obj_to_motions.values():
+ sum_root = np.zeros(self.feature_len)
+ sq_sum_root = np.zeros(self.feature_len)
+ sum_local = np.zeros(self.feature_len)
+ sq_sum_local = np.zeros(self.feature_len)
+ total_f, total_local = 0, 0
+
+ for motion in motions:
+ T, J, D = motion.shape
+ total_f += T
+ total_local += T * (J - 1)
+
+ root = motion[:, 0, :]
+ sum_root += root.sum(axis=0)
+ sq_sum_root += (root ** 2).sum(axis=0)
+
+ local = motion[:, 1:, :].reshape(-1, D)
+ sum_local += local.sum(axis=0)
+ sq_sum_local += (local ** 2).sum(axis=0)
+
+ mean_r = sum_root / total_f
+ mean_l = sum_local / total_local
+ obj_means_root.append(mean_r)
+ obj_vars_root.append(
+ np.maximum(sq_sum_root / total_f - mean_r ** 2, 0.0)
+ )
+ obj_means_local.append(mean_l)
+ obj_vars_local.append(
+ np.maximum(sq_sum_local / total_local - mean_l ** 2, 0.0)
+ )
+
+ # Law of total variance: E[Var] + Var[E]
+ mean_root = np.mean(obj_means_root, axis=0)
+ within_var_root = np.mean(obj_vars_root, axis=0)
+ between_var_root = np.var(obj_means_root, axis=0)
+ std_root = np.maximum(
+ np.sqrt(np.maximum(within_var_root + between_var_root, 0.0)),
+ 1e-8,
+ )
+
+ mean_local = np.mean(obj_means_local, axis=0)
+ within_var_local = np.mean(obj_vars_local, axis=0)
+ between_var_local = np.var(obj_means_local, axis=0)
+ std_local = np.maximum(
+ np.sqrt(np.maximum(within_var_local + between_var_local, 0.0)),
+ 1e-8,
+ )
+
+ return mean_root, std_root, mean_local, std_local
+
+ # ------------------------------------------------------------------
+ # Text encoding
+ # ------------------------------------------------------------------
+
+ # ------------------------------------------------------------------
+ # Persistence
+ # ------------------------------------------------------------------
+
+ def save_dataset_stats(self, path):
+ """Persist ``self.dataset_stats`` as a pickled .npy. Inference
+ reloads with ``np.load(path, allow_pickle=True).item()``.
+ """
+ if os.path.dirname(path):
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ np.save(path, self.dataset_stats, allow_pickle=True)
+ logger.info(f"Saved dataset stats to {path}")
+
+
+# ---------------------------------------------------------------------------
+# MixtureSampler โ€” balanced sampling across skeleton types
+# ---------------------------------------------------------------------------
+
+class MixtureSampler(data.Sampler):
+ """Power-law balanced sampling across skeleton types.
+
+ Per object type k with n_k motions, total sampling probability โˆ n_k^(1-alpha).
+ Per sample within type k, weight โˆ n_k^(-alpha).
+
+ alpha=0.0 : uniform per sample (data-rich types dominate)
+ alpha=0.5 : square-root balanced (default โ€” good compromise)
+ alpha=1.0 : uniform per type (ignores motion count entirely)
+
+ This is a plain Sampler (not DistributedSampler) that yields all indices.
+ Accelerate's BatchSamplerShard handles per-rank sharding automatically.
+ """
+
+ def __init__(self, data_source, alpha: float = 0.5):
+ super().__init__(data_source)
+
+ name_list = data_source.motion_dataset.train_name_list
+ motion_dict = data_source.motion_dataset.train_motion_dict
+ total_samples = len(name_list)
+
+ indices_by_object = defaultdict(list)
+ for i, name in enumerate(name_list):
+ indices_by_object[motion_dict[name]['object_type']].append(i)
+
+ # w_i = n_k^(-alpha) for sample i in type k, giving type k total
+ # probability โˆ n_k * n_k^(-alpha) = n_k^(1-alpha).
+ weights = np.zeros(total_samples)
+ for indices in indices_by_object.values():
+ n_k = len(indices)
+ weights[indices] = n_k ** (-alpha)
+
+ weights /= weights.sum()
+ type_probs = {
+ object_type: weights[indices].sum()
+ for object_type, indices in indices_by_object.items()
+ }
+ sorted_types = sorted(type_probs.items(), key=lambda x: x[1], reverse=True)
+ logger.info(f'MixtureSampler (alpha={alpha}): {len(sorted_types)} object types')
+ for name, prob in sorted_types[:5]:
+ logger.info(f' top: {name} โ€” n={len(indices_by_object[name])}, p={prob:.4f}')
+ if len(sorted_types) > 10:
+ logger.info(' ...')
+ for name, prob in sorted_types[-5:]:
+ logger.info(f' bot: {name} โ€” n={len(indices_by_object[name])}, p={prob:.4f}')
+
+ self.weights = torch.as_tensor(weights, dtype=torch.double)
+ self.total_samples = total_samples
+ self.epoch = 0
+
+ def set_epoch(self, epoch):
+ self.epoch = epoch
+
+ def __iter__(self):
+ g = torch.Generator()
+ g.manual_seed(self.epoch)
+ indices = torch.multinomial(
+ self.weights, self.total_samples, replacement=True, generator=g
+ ).tolist()
+ return iter(indices)
+
+ def __len__(self):
+ return self.total_samples
+
+
+# ---------------------------------------------------------------------------
+# Mixture โ€” top-level dataset used by the dataloader factory
+# ---------------------------------------------------------------------------
+
+class Mixture(data.Dataset):
+ """Wrapper that loads condition files, filters subsets, then builds MotionDataset."""
+
+ def __init__(
+ self,
+ data_configs: dict,
+ topology_condition_type: str,
+ max_motion_length: int,
+ max_joints: int = 65,
+ min_joints: int = 8,
+ max_depth: int = 0,
+ feature_len: int = 12,
+ text_encoder_type: str = "t5",
+ text_encoder_version: str = "t5-base",
+ use_dataset_stats: bool = True,
+ balanced_stats: bool = False,
+ tie_std: bool = False,
+ use_addition_aug: bool = False,
+ use_removal_aug: bool = False,
+ use_pooling_aug: bool = False,
+ use_perturbation_aug: bool = False,
+ test_split_ratio: float = 0.0,
+ split_seed: int = 42,
+ max_freqs: int = 8,
+ debug_validate_aug: bool = False,
+ ground_motion_height: bool = True,
+ realign_feature: bool = True,
+ prebuilt_max_joints: int = 0,
+ prebuilt_max_depth: int = 0,
+ target_object_types: Optional[Set[str]] = None,
+ target_clip_stems: Optional[Set[str]] = None,
+ stats_path: Optional[str] = None,
+ ):
+ logger.info(f'Initializing Mixture Dataset with datasets: {list(data_configs.keys())}')
+ data_dict = {
+ dataset_config.type: self._build_dataset_entry(
+ dataset_config, min_joints, max_joints,
+ )
+ for _, dataset_config in data_configs.items()
+ }
+
+ self.motion_dataset = MotionDataset(
+ data_dict=data_dict,
+ topology_condition_type=topology_condition_type,
+ max_motion_length=max_motion_length,
+ config_max_depth=max_depth,
+ feature_len=feature_len,
+ text_encoder_type=text_encoder_type,
+ text_encoder_version=text_encoder_version,
+ use_dataset_stats=use_dataset_stats,
+ balanced_stats=balanced_stats,
+ tie_std=tie_std,
+ use_addition_aug=use_addition_aug,
+ use_removal_aug=use_removal_aug,
+ use_pooling_aug=use_pooling_aug,
+ use_perturbation_aug=use_perturbation_aug,
+ test_split_ratio=test_split_ratio,
+ split_seed=split_seed,
+ max_freqs=max_freqs,
+ debug_validate_aug=debug_validate_aug,
+ ground_motion_height=ground_motion_height,
+ realign_feature=realign_feature,
+ prebuilt_max_joints=prebuilt_max_joints,
+ prebuilt_max_depth=prebuilt_max_depth,
+ target_object_types=target_object_types,
+ target_clip_stems=target_clip_stems,
+ stats_path=stats_path,
+ )
+ if target_object_types is None:
+ # Training only: inference can produce a tiny (even empty) split.
+ assert len(self.motion_dataset) > 1, 'You loaded an empty dataset!'
+
+ self.max_joints = self.motion_dataset.max_joints
+ self.max_depth = self.motion_dataset.max_depth
+
+ # ------------------------------------------------------------------
+ # Per-dataset entry construction
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _build_dataset_entry(dataset_config, min_joints, max_joints):
+ """Build the ``data_dict`` entry for one dataset: load cond / captions
+ / test_objects, apply dataset-specific and joint-count filters.
+ """
+ root_dir = dataset_config.path
+ dataset_type = dataset_config.type
+ motion_dir = pjoin(root_dir, 'motions')
+ assert os.path.exists(motion_dir), f"Motion directory {motion_dir} does not exist."
+
+ cond_dict = Mixture._load_cond_dict(root_dir)
+ captions = Mixture._load_captions(root_dir, dataset_type)
+ test_objects = Mixture._load_test_objects(root_dir, dataset_type)
+
+ cond_dict = Mixture._apply_dataset_filters(cond_dict, dataset_config, root_dir)
+ cond_dict = Mixture._filter_by_joint_count(cond_dict, dataset_type, min_joints, max_joints)
+
+ return {
+ 'root_dir': root_dir, # where the text-embedding cache lives
+ 'motion_dir': motion_dir,
+ 'cond_dict': cond_dict,
+ 'captions': captions,
+ 'test_objects': test_objects,
+ }
+
+ @staticmethod
+ def _load_cond_dict(root_dir):
+ cond_file = pjoin(root_dir, 'cond.npy')
+ assert os.path.exists(cond_file), f"Cond file {cond_file} does not exist."
+ return np.load(cond_file, allow_pickle=True).item()
+
+ @staticmethod
+ def _load_captions(root_dir, dataset_type):
+ """Load the flat ``{clip_stem: caption}`` dict from ``captions.json``.
+
+ The feature-extraction stage writes it whenever any clip has a
+ caption; a missing file means the dataset is caption-free.
+ """
+ captions_file = pjoin(root_dir, 'captions.json')
+ if not os.path.exists(captions_file):
+ logger.info(f'{dataset_type.capitalize()}: no captions.json in '
+ f'{root_dir} (caption-free dataset)')
+ return {}
+ with open(captions_file) as f:
+ captions = json.load(f)
+ logger.info(
+ f'{dataset_type.capitalize()}: loaded captions from '
+ f'{captions_file} ({len(captions)} entries)'
+ )
+ return captions
+
+ @staticmethod
+ def _load_test_objects(root_dir, dataset_type):
+ """Explicit eval object_type list from ``test_objects.txt``.
+ Skipped for mixamo (single object_type โ†’ empty train).
+ """
+ if dataset_type == 'mixamo':
+ return []
+ test_objects_file = pjoin(root_dir, 'test_objects.txt')
+ if not os.path.exists(test_objects_file):
+ return []
+ with open(test_objects_file) as f:
+ test_objects = sorted({line.strip() for line in f if line.strip()})
+ logger.info(
+ f'{dataset_type.capitalize()}: loaded {len(test_objects)} '
+ f'test object types from {test_objects_file}'
+ )
+ return test_objects
+
+ @staticmethod
+ def _apply_dataset_filters(cond_dict, dataset_config, root_dir):
+ """Dispatch to per-dataset filter (subset / object filter / count cap)."""
+ if dataset_config.type == 'truebones':
+ return Mixture._filter_truebones(cond_dict, dataset_config, root_dir)
+ if dataset_config.type == 'objaverse':
+ return Mixture._filter_objaverse(cond_dict, dataset_config, root_dir)
+ return cond_dict
+
+ @staticmethod
+ def _filter_truebones(cond_dict, dataset_config, root_dir):
+ """Keep only object types in ``dataset_config.objects_subset`` (or all)."""
+ subset_key = dataset_config.objects_subset
+ if subset_key == 'all':
+ subset = sorted(cond_dict.keys())
+ else:
+ category_groups_path = pjoin(root_dir, 'category_groups.json')
+ assert os.path.exists(category_groups_path), \
+ f"category_groups.json not found at {category_groups_path}"
+ with open(category_groups_path) as f:
+ category_groups = json.load(f)
+ if subset_key not in category_groups:
+ raise ValueError(
+ f"Unknown objects_subset: {subset_key!r}, "
+ f"available: {list(category_groups.keys())}")
+ subset = category_groups[subset_key]
+ cond_dict = {k: cond_dict[k] for k in subset if k in cond_dict}
+ logger.info(f'Truebones Dataset has {len(cond_dict)} object types')
+ return cond_dict
+
+ @staticmethod
+ def _filter_objaverse(cond_dict, dataset_config, root_dir):
+ """Apply objaverse-specific filters: filter_object + objects_num cap."""
+ if dataset_config.filter_object:
+ filter_path = pjoin(root_dir, 'filtered_objects.txt')
+ if os.path.exists(filter_path):
+ with open(filter_path) as f:
+ excluded = {line.strip() for line in f if line.strip()}
+ before = len(cond_dict)
+ cond_dict = {k: v for k, v in cond_dict.items() if k not in excluded}
+ logger.info(
+ f'Objaverse: filter_object removed {before - len(cond_dict)} '
+ f'of {before} object types via {filter_path}'
+ )
+ else:
+ logger.info(
+ f'Objaverse: filter_object=True but no filtered_objects.txt '
+ f'at {filter_path}; skipping filtering.'
+ )
+ objects_num = dataset_config.objects_num
+ if objects_num > 0:
+ keys = sorted(cond_dict.keys())[:objects_num]
+ cond_dict = {k: cond_dict[k] for k in keys}
+ logger.info(f'Objaverse Dataset has {len(cond_dict)} object types')
+ return cond_dict
+
+ @staticmethod
+ def _filter_by_joint_count(cond_dict, dataset_type, min_joints, max_joints):
+ """Drop object types outside ``[min_joints, max_joints]`` (inclusive)."""
+ skipped = {
+ k: len(v['parents']) for k, v in cond_dict.items()
+ if len(v['parents']) > max_joints or len(v['parents']) < min_joints
+ }
+ cond_dict = {k: v for k, v in cond_dict.items() if k not in skipped}
+ if skipped:
+ logger.info(
+ f'{dataset_type.capitalize()}: skipped {len(skipped)} object types '
+ f'outside [{min_joints}, {max_joints}] joints'
+ )
+ for name, nj in sorted(skipped.items(), key=lambda x: x[1], reverse=True)[:5]:
+ logger.info(f' {name}: {nj} joints')
+ return cond_dict
+
+ # ------------------------------------------------------------------
+ # Dataset interface
+ # ------------------------------------------------------------------
+
+ def __getitem__(self, item):
+ return self.motion_dataset[item]
+
+ def __len__(self):
+ return len(self.motion_dataset)
+
+ def save_dataset_stats(self, path):
+ self.motion_dataset.save_dataset_stats(path)
diff --git a/unimate/dataset/transforms.py b/unimate/dataset/transforms.py
new file mode 100644
index 0000000..9b60be1
--- /dev/null
+++ b/unimate/dataset/transforms.py
@@ -0,0 +1,144 @@
+"""Shared per-sample processing for training and inference.
+
+Cropping, condition extraction, normalization, padding, and parent-feature
+construction used by both ``mixture/dataset.py`` (training samples) and
+``conditioning.py`` (sampling / inference batches).
+"""
+
+import random
+
+import numpy as np
+
+
+# ---------------------------------------------------------------------------
+# Cropping
+# ---------------------------------------------------------------------------
+
+def apply_cropping(
+ augmented_motion, topology_condition_type, max_motion_length, start_idx=None,
+):
+ """Crop augmented_motion before condition extraction.
+
+ For 'first_frame' the first frame is split off as the condition, so the
+ crop length is ``max_motion_length + 1``. For 'tpos' the full sequence is
+ the motion, so the crop length is ``max_motion_length``.
+
+ Start-index policy:
+ * ``start_idx`` provided: slice ``[start_idx, start_idx + target_len]``
+ verbatim. When fewer than ``target_len`` frames remain after
+ ``start_idx`` the returned tensor is shorter โ€” downstream
+ ``apply_padding`` zero-fills the tail, and the caller's
+ valid-length signal trims the saved output back.
+ * ``start_idx is None``: 'first_frame' uses 0 (continuity with the
+ global first frame); 'tpos' picks a uniform random start.
+
+ Returns:
+ (cropped_motion, start_idx)
+ """
+ n_frames = augmented_motion.shape[0]
+
+ if topology_condition_type == 'first_frame':
+ target_len = max_motion_length + 1 # +1 for the first-frame condition
+ else: # 'tpos'
+ target_len = max_motion_length
+
+ if start_idx is not None:
+ if start_idx < 0:
+ raise ValueError(f"start_idx must be >= 0, got {start_idx}.")
+ if start_idx >= n_frames:
+ raise ValueError(
+ f"start_idx={start_idx} is >= clip length {n_frames}."
+ )
+ return augmented_motion[start_idx:start_idx + target_len], start_idx
+
+ start_idx = 0
+ if n_frames > target_len:
+ if topology_condition_type == 'first_frame':
+ start_idx = 0
+ else: # 'tpos'
+ start_idx = random.randint(0, n_frames - target_len)
+ augmented_motion = augmented_motion[start_idx:start_idx + target_len]
+
+ return augmented_motion, start_idx
+
+
+# ---------------------------------------------------------------------------
+# Condition extraction
+# ---------------------------------------------------------------------------
+
+def extract_conditions(augmented_motion, tpos, topology_condition_type):
+ """Split augmented_motion into motion and condition arrays.
+
+ Returns a dict with keys:
+ - ``motion``: the motion frames (first frame removed for 'first_frame')
+ - ``tpos_first_frame``: T-pose or first-frame condition (J, D)
+ """
+ if topology_condition_type == 'first_frame':
+ return {
+ 'tpos_first_frame': augmented_motion[0].copy(),
+ 'motion': augmented_motion[1:].copy(),
+ }
+ elif topology_condition_type == 'tpos':
+ return {
+ 'tpos_first_frame': tpos.copy(),
+ 'motion': augmented_motion.copy(),
+ }
+ else:
+ raise ValueError(f"Invalid topology_condition_type: {topology_condition_type}")
+
+
+# ---------------------------------------------------------------------------
+# Normalization
+# ---------------------------------------------------------------------------
+
+def apply_normalization(motion, mean, std):
+ """Normalize motion and replace NaN with zero.
+
+ Assumes ``std`` is strictly positive (enforced upstream by a variance
+ floor in ``_calculate_dataset_stats``), so no epsilon is added here โ€”
+ keeping the forward op exact lets denormalization invert it cleanly.
+ """
+ if motion.ndim == 3:
+ motion = (motion - mean[None, :]) / std[None, :]
+ elif motion.ndim == 2:
+ motion = (motion - mean) / std
+ else:
+ raise ValueError("Motion data must be 2D or 3D.")
+ return np.nan_to_num(motion)
+
+
+# ---------------------------------------------------------------------------
+# Padding
+# ---------------------------------------------------------------------------
+
+def apply_padding(motion, max_motion_length):
+ """Pad motion to max_motion_length if shorter.
+
+ Returns:
+ (padded_motion, original_motion_length)
+ """
+ motion_length = motion.shape[0]
+ if motion_length < max_motion_length:
+ pad = np.zeros((max_motion_length - motion_length, *motion.shape[1:]))
+ motion = np.concatenate([motion, pad], axis=0)
+ return motion, motion_length
+
+
+# ---------------------------------------------------------------------------
+# Parent-feature maps
+# ---------------------------------------------------------------------------
+
+def build_parent_features(tpos_first_frame, parents):
+ """Compute parent-copied feature array for tpos_first_frame.
+
+ For each joint j with parent p (!= -1), copies the parent's features.
+
+ Returns a dict with:
+ - ``tpos_first_frame_parents``: (J, D)
+ """
+ tpos_first_frame_parents = tpos_first_frame.copy()
+ for j_idx, p_idx in enumerate(parents):
+ if p_idx != -1:
+ tpos_first_frame_parents[j_idx] = tpos_first_frame[p_idx]
+
+ return {'tpos_first_frame_parents': tpos_first_frame_parents}
diff --git a/unimate/inference/__init__.py b/unimate/inference/__init__.py
new file mode 100644
index 0000000..65e0396
--- /dev/null
+++ b/unimate/inference/__init__.py
@@ -0,0 +1 @@
+"""Inference entry points: sampling, in-betweening, motion editing, and expansion."""
diff --git a/unimate/inference/generate.py b/unimate/inference/generate.py
new file mode 100644
index 0000000..5a44305
--- /dev/null
+++ b/unimate/inference/generate.py
@@ -0,0 +1,127 @@
+"""Sampling utilities for diffusion / flow-matching generation."""
+
+import torch
+import torch.nn as nn
+
+from unimate.utils.logger import get_logger
+
+logger = get_logger(file_name=__file__)
+
+
+class ClassifierFreeSampleModel(nn.Module):
+ """Wrapper that applies classifier-free guidance during sampling.
+
+ Runs the model twice (conditional + unconditional) and interpolates
+ outputs using the guidance scale: out = out_uncond + scale * (out_cond - out_uncond).
+
+ Reference: Ho & Salimans, "Classifier-Free Diffusion Guidance", 2022.
+ https://arxiv.org/abs/2207.12598
+
+ Args:
+ model: Diffusion model (must have cond_mask_prob > 0 from training).
+ cfg_scale: Classifier-free guidance scale (1.0 = no guidance).
+ """
+
+ def __init__(self, model, cfg_scale=1.0):
+ super().__init__()
+ self.model = model
+ self.cfg_scale = cfg_scale
+
+ assert self.model.cond_mask_prob > 0, \
+ 'Cannot run guided diffusion on a model not trained with conditional dropout'
+
+ def forward(self, x, timesteps, cond=None):
+ out = self.model(x, timesteps, cond)
+ out_uncond = self.model(x, timesteps, cond, force_mask=True)
+
+ return out_uncond + (self.cfg_scale * (out - out_uncond))
+
+
+def generate_samples(
+ model,
+ cond,
+ motion_shape,
+ diff_model,
+ diffusion,
+ gen_diffusion=None,
+ device=None,
+ cfg_scale=1.0,
+ x1_known=None,
+ keep_mask=None,
+):
+ """Run the generative model to produce motion samples.
+
+ Shared between training-time visualization and standalone inference.
+
+ Args:
+ model: The denoising network (unwrapped, in eval mode).
+ cond: Conditioning dict (tensors already on device).
+ motion_shape: Tuple (B, J, D, T) for the output motion.
+ diff_model: ``"flow"`` or ``"diffusion"``.
+ diffusion: The diffusion schedule (Gaussian DDPM or flow transport).
+ gen_diffusion: ``Sampler`` wrapper for flow transport (required when
+ ``diff_model == "flow"``).
+ device: Target device for noise tensor. Inferred from model if None.
+ cfg_scale: Classifier-free guidance scale (1.0 = no guidance).
+ x1_known: optional ``(B, J, D, T)`` normalized clean motion for
+ in-betweening. When set, ``keep_mask`` must also be set, and
+ ``diff_model`` must be ``"flow"``.
+ keep_mask: optional ``(B, 1, 1, T)`` bool mask โ€” True for frames
+ held fixed at ``x1_known`` during sampling.
+
+ Returns:
+ samples: Tensor of shape ``motion_shape``.
+ """
+ if device is None:
+ device = next(model.parameters()).device
+
+ # Optional classifier-free guidance wrapper. The cfg_scale is logged once
+ # by the caller (sample.py); skip a per-chunk log here to avoid flooding
+ # the output during multi-rep / multi-chunk runs.
+ if cfg_scale > 1.0:
+ sample_model = ClassifierFreeSampleModel(model, cfg_scale=cfg_scale)
+ else:
+ sample_model = model
+
+ inbetween = x1_known is not None or keep_mask is not None
+ if inbetween:
+ if x1_known is None or keep_mask is None:
+ raise ValueError("x1_known and keep_mask must both be set for in-betweening.")
+ if diff_model != "flow":
+ raise NotImplementedError(
+ "In-betweening currently supports diff_model='flow' only."
+ )
+ # Imported lazily so non-inbetween code paths don't pull torchdiffeq
+ # dependencies twice or fail on import errors here.
+ from unimate.inference.motion_inbetweening import inbetween_sample_ode
+ assert gen_diffusion is not None, "gen_diffusion (Sampler) required for flow sampling"
+ return inbetween_sample_ode(
+ sample_model=sample_model,
+ transport=gen_diffusion.transport,
+ cond=cond,
+ x1_known=x1_known,
+ keep_mask=keep_mask,
+ motion_shape=motion_shape,
+ device=device,
+ )
+
+ model_kwargs = dict(cond=cond)
+ noise = torch.randn(motion_shape, device=device)
+
+ if diff_model == "flow":
+ assert gen_diffusion is not None, "gen_diffusion (Sampler) required for flow sampling"
+ model_fn = gen_diffusion.sample_ode()
+ samples = model_fn(noise, sample_model, **model_kwargs)[-1]
+ elif diff_model == "diffusion":
+ samples = diffusion.p_sample_loop(
+ model=sample_model,
+ shape=motion_shape,
+ noise=noise,
+ clip_denoised=False,
+ model_kwargs=model_kwargs,
+ progress=False,
+ )
+ else:
+ raise ValueError(f"Unknown diff_model: {diff_model!r}")
+
+ return samples
diff --git a/unimate/inference/motion_editing.py b/unimate/inference/motion_editing.py
new file mode 100644
index 0000000..ec42b2d
--- /dev/null
+++ b/unimate/inference/motion_editing.py
@@ -0,0 +1,160 @@
+"""Text-guided motion editing via replacement-style flow-matching inference.
+
+Given a clean ground-truth motion ``x1_known`` and a list of joint names to
+hold fixed, clamp those joints to GT for all frames while letting the flow
+ODE denoise the remaining joints under a new text prompt. Example: fix the
+lower body of a walking clip and ask the model to add an upper-body action
+("walking while waving").
+
+Mask shape is ``(B, J, 1, 1)`` โ€” broadcasts uniformly over feature dim D and
+time T, since whole joints are kept across the entire clip. The underlying
+ODE sampler (``inbetween_sample_ode``) is shape-agnostic, so the replacement
+math is the same as in-betweening; only the mask differs.
+
+Joint names are resolved per-case against
+``motion_dataset.cond_dict[object_type]``, matching **either** vocabulary:
+the rig's own bone names (``Bip01_L_Thigh``) or the cleaned ones stage 3
+produces (``Left Thigh``). Cleaning is a per-element string transform that
+preserves joint order, so an index found through either list points at the
+same joint row the model was conditioned on via ``joint_names_emb`` (which
+is built from the cleaned names โ€” see ``dataset.model_joint_names``).
+"""
+
+from typing import List, Sequence
+
+import torch
+
+from unimate.utils.logger import get_logger
+
+logger = get_logger(file_name=__file__)
+
+
+# ---------------------------------------------------------------------------
+# Keep-joint spec parsing
+# ---------------------------------------------------------------------------
+
+
+def parse_keep_joints(spec: str) -> List[str]:
+ """Parse a comma-separated list of joint name strings.
+
+ Whitespace around each name is stripped; empty tokens are skipped so
+ ``"Hips, LeftUpLeg ,LeftLeg"`` and ``"Hips,LeftUpLeg,LeftLeg"`` are
+ equivalent. Resolution against per-skeleton joint lists is deferred to
+ :func:`build_joint_keep_mask`.
+ """
+ if not spec.strip():
+ raise ValueError("keep_joints spec is empty.")
+ out: List[str] = []
+ for tok in spec.split(','):
+ tok = tok.strip()
+ if tok:
+ out.append(tok)
+ if not out:
+ raise ValueError(f"keep_joints spec parsed to empty list: {spec!r}.")
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Joint-name lookup
+# ---------------------------------------------------------------------------
+
+
+def get_joint_names(dataset, object_type: str) -> List[str]:
+ """Return per-joint name *aliases* for ``object_type``, in model-index order.
+
+ Each entry is ``"<raw>|<clean>"`` when the two differ, so ``--keep_joints``
+ matches either vocabulary: the source rig's own names (``Bip01_Pelvis``,
+ ``Wing1.L``), which is what someone looking at the asset knows, and the
+ canonicalized ones this repo produces in stage 3 (``Hips``), which is what
+ the T-pose visualizations, the captions and the model's own
+ ``joint_names_emb`` all use. Matching only the raw list made every cleaned
+ name silently miss.
+
+ Safe to conflate because cleaning is a per-element string transform: it
+ preserves joint *order*, so index ``j`` is the same joint row either way.
+ """
+ md = dataset.motion_dataset
+ cond_entry = md.cond_dict[object_type]
+ raw = cond_entry.get('joint_names')
+ clean = cond_entry.get('clean_joint_names')
+ if (raw is None or len(raw) == 0) and (clean is None or len(clean) == 0):
+ raise KeyError(
+ f"cond_dict[{object_type!r}] has neither 'joint_names' nor "
+ f"'clean_joint_names'."
+ )
+ # ``cond_entry`` values are sometimes numpy arrays of strings; coerce so
+ # downstream membership checks behave like plain Python strings.
+ raw = [str(n) for n in (raw if raw is not None else [])]
+ clean = [str(n) for n in (clean if clean is not None else [])]
+ if not raw:
+ return clean
+ if len(clean) != len(raw):
+ return raw
+ return [r if r == c else f'{r}|{c}' for r, c in zip(raw, clean)]
+
+
+# ---------------------------------------------------------------------------
+# Spatial keep-mask
+# ---------------------------------------------------------------------------
+
+
+def build_joint_keep_mask(
+ joint_names_per_sample: Sequence[Sequence[str]],
+ keep_names: List[str],
+ max_joints: int,
+ device: torch.device,
+) -> torch.Tensor:
+ """Build a ``(B, J, 1, 1)`` bool mask: True for joints whose name appears
+ in ``keep_names`` (case-insensitive). Padding joints past the per-sample
+ joint count are left False.
+
+ A joint entry may carry several ``|``-separated aliases (see
+ :func:`get_joint_names`); matching any one of them selects the joint.
+
+ Logs a warning per sample for any ``keep_names`` entries that don't
+ match a joint in that skeleton โ€” a single keep list is typically applied
+ across heterogeneous skeletons (different topology, different naming),
+ so partial matches are expected and shouldn't fail the run.
+
+ Args:
+ joint_names_per_sample: per-sample lists of joint name strings,
+ ordered to match the model's joint-index axis.
+ keep_names: user-supplied target joint names.
+ max_joints: padded joint-axis size (``cond["joint_mask"]`` width).
+ device: target device.
+ """
+ keep_lower = {n.lower() for n in keep_names}
+ B = len(joint_names_per_sample)
+ mask = torch.zeros((B, max_joints, 1, 1), dtype=torch.bool, device=device)
+
+ total_hits = 0
+ for i, names in enumerate(joint_names_per_sample):
+ if len(names) > max_joints:
+ # Should not happen โ€” ``max_joints`` is derived from the loaded
+ # skeletons โ€” but be defensive: truncating silently here would
+ # clamp the wrong indices.
+ raise ValueError(
+ f"Sample {i}: skeleton has {len(names)} joints > max_joints={max_joints}."
+ )
+ hit_lower = set()
+ for j, nm in enumerate(names):
+ aliases = {a.strip().lower() for a in str(nm).split('|') if a.strip()}
+ matched = aliases & keep_lower
+ if matched:
+ mask[i, j, 0, 0] = True
+ hit_lower |= matched
+ total_hits += 1
+ misses = sorted(keep_lower - hit_lower)
+ if misses:
+ logger.warning(
+ f"Sample {i} ({len(names)} joints): {len(misses)} keep_joints "
+ f"unmatched โ€” {misses}"
+ )
+
+ if total_hits == 0:
+ raise ValueError(
+ f"build_joint_keep_mask: no keep_joints matched any skeleton in "
+ f"the batch (keep_names={keep_names}). Check spelling against the "
+ f"clip's joint_names or clean_joint_names."
+ )
+ return mask
diff --git a/unimate/inference/motion_expansion.py b/unimate/inference/motion_expansion.py
new file mode 100644
index 0000000..1e27d41
--- /dev/null
+++ b/unimate/inference/motion_expansion.py
@@ -0,0 +1,146 @@
+"""Motion expansion: chain text-conditioned generations into a long motion.
+
+Given a list of N text prompts and a target skeleton, generate:
+
+ * ``seg_1``: free generation under ``prompt_1`` (no GT clamp).
+ * ``seg_i`` for ``i in [2, N]``: replacement-style sampling under
+ ``prompt_i`` with ``x1_known[:, :, :, :overlap] = seg_{i-1}[:, :, :, -overlap:]``
+ and a ``(B, 1, 1, T)`` keep_mask True for the first ``overlap`` frames.
+
+The concatenated output stitches segments at the overlap seam:
+
+ ``chain = [seg_1, seg_2[overlap:], seg_3[overlap:], ..., seg_N[overlap:]]``
+
+so the seam frames appear once and motion continuity is enforced by the
+flow ODE's clamping (same machinery as in-betweening โ€” only the mask
+construction differs).
+
+Total length: ``max_T + (max_T - overlap) * (N - 1)``.
+"""
+
+from typing import List
+
+import torch
+
+from unimate.utils.logger import get_logger
+from unimate.inference.generate import generate_samples
+
+logger = get_logger(file_name=__file__)
+
+
+# ---------------------------------------------------------------------------
+# Mask + seed helpers
+# ---------------------------------------------------------------------------
+
+
+def build_overlap_keep_mask(
+ batch_size: int, overlap: int, max_T: int, device: torch.device,
+) -> torch.Tensor:
+ """``(B, 1, 1, T)`` bool mask: True for the first ``overlap`` frames.
+
+ Broadcasts uniformly over the joint and feature axes โ€” same shape
+ convention as :func:`unimate.inference.motion_inbetweening.build_keep_mask`, so the
+ shared ``inbetween_sample_ode`` clamps without per-axis logic.
+ """
+ mask = torch.zeros((batch_size, 1, 1, max_T), dtype=torch.bool, device=device)
+ mask[:, :, :, :overlap] = True
+ return mask
+
+
+def seed_expansion_x1(
+ prev_seq: torch.Tensor, overlap: int, motion_shape, device: torch.device,
+) -> torch.Tensor:
+ """Build ``x1_known`` for the next segment.
+
+ Frames ``[0, overlap)`` are copied from ``prev_seq[..., -overlap:]``;
+ the remaining slots are zero. Only the kept slice is read by the
+ sampler, so the zero tail is inert.
+ """
+ x1 = torch.zeros(motion_shape, device=device)
+ x1[:, :, :, :overlap] = prev_seq[:, :, :, -overlap:]
+ return x1
+
+
+# ---------------------------------------------------------------------------
+# Chain generation
+# ---------------------------------------------------------------------------
+
+
+def expand_motion_chain(
+ cond_per_segment: List[dict],
+ motion_shape,
+ overlap: int,
+ sample_model,
+ diff_model: str,
+ diffusion,
+ gen_diffusion,
+ cfg_scale: float,
+ device: torch.device,
+) -> torch.Tensor:
+ """Generate a chain of motion segments and concatenate at the seam.
+
+ Args:
+ cond_per_segment: per-segment conditioning dicts (already on
+ device). All entries must share the same skeleton fields
+ (``tpos_first_frame``, ``parents``, ``mean``/``std``, etc.) โ€”
+ only ``caption_emb`` (and ``caption`` for logging) should
+ differ across entries.
+ motion_shape: ``(B, J, D, max_T)`` for each segment generation.
+ overlap: number of frames pinned between consecutive segments.
+ Must be in ``(0, max_T)``.
+ sample_model: denoising network. CFG-wrapping handled inside
+ ``generate_samples`` based on ``cfg_scale``.
+ diff_model, diffusion, gen_diffusion, cfg_scale, device: forwarded
+ to ``generate_samples``.
+
+ Returns:
+ ``(B, J, D, T_total)`` concatenated chain, where
+ ``T_total = max_T + (max_T - overlap) * (N - 1)``.
+ """
+ max_T = motion_shape[3]
+ if overlap <= 0 or overlap >= max_T:
+ raise ValueError(
+ f"overlap must be in (0, max_T={max_T}), got {overlap}."
+ )
+ if not cond_per_segment:
+ raise ValueError("cond_per_segment is empty โ€” need at least one prompt.")
+
+ segments: List[torch.Tensor] = []
+ prev_seq = None
+ for i, cond in enumerate(cond_per_segment):
+ if prev_seq is None:
+ x1_known = None
+ keep_mask = None
+ else:
+ x1_known = seed_expansion_x1(prev_seq, overlap, motion_shape, device)
+ keep_mask = build_overlap_keep_mask(
+ motion_shape[0], overlap, max_T, device,
+ )
+
+ sample = generate_samples(
+ model=sample_model,
+ cond=cond,
+ motion_shape=motion_shape,
+ diff_model=diff_model,
+ diffusion=diffusion,
+ gen_diffusion=gen_diffusion,
+ device=device,
+ cfg_scale=cfg_scale,
+ x1_known=x1_known,
+ keep_mask=keep_mask,
+ )
+ segments.append(sample)
+ prev_seq = sample
+ logger.info(
+ f"motion_expansion: segment {i + 1}/{len(cond_per_segment)} done "
+ f"(T={sample.shape[-1]})."
+ )
+
+ parts = [segments[0]]
+ for seg in segments[1:]:
+ parts.append(seg[:, :, :, overlap:])
+ chain = torch.cat(parts, dim=-1)
+ logger.info(
+ f"motion_expand: chained {len(segments)} segments โ†’ total T={chain.shape[-1]}."
+ )
+ return chain
diff --git a/unimate/inference/motion_inbetweening.py b/unimate/inference/motion_inbetweening.py
new file mode 100644
index 0000000..eba8b43
--- /dev/null
+++ b/unimate/inference/motion_inbetweening.py
@@ -0,0 +1,199 @@
+"""Motion in-betweening via replacement-style flow-matching inference.
+
+Given a clean ground-truth motion ``x1_known`` and a temporal ``keep_mask``
+marking which frames to hold fixed, run the flow ODE on the remaining frames
+while pinning the kept slice to the analytical interpolant
+``(1 - t) * eps + t * x1_known`` at every step. With a linear interpolant
+(``path.ICPlan``) and a velocity-prediction model this is exact: at ``t = 1``
+the kept frames equal ``x1_known``.
+
+Mirrors RePaint (Lugmayr et al. 2022) for diffusion, but for flow matching
+the analytic interpolant removes the need for forward/back resampling loops โ€”
+one pass of fixed-step Euler with replacement is sufficient.
+
+Only supports ``diff_model == "flow"`` with ``ModelType.VELOCITY`` and
+``PathType.LINEAR`` โ€” i.e. every current config in this repo. Diffusion-model
+in-betweening would need a separate RePaint variant.
+"""
+
+from typing import List, Optional, Sequence, Tuple
+
+import torch
+
+from unimate.utils.logger import get_logger
+
+logger = get_logger(file_name=__file__)
+
+
+# ---------------------------------------------------------------------------
+# Keep-frame spec parsing
+# ---------------------------------------------------------------------------
+
+
+def parse_keep_frames(spec: str) -> List[int]:
+ """Parse a comma-separated list of signed integer indices.
+
+ Negative indices are kept as-is here and resolved against the per-clip
+ valid frame count in :func:`build_keep_mask`. Duplicates are de-duplicated
+ after resolution, not at parse time (a user listing ``0,-1`` for a 1-frame
+ clip should still produce a single kept index, not an error).
+
+ Examples:
+ ``"0,-1"`` โ†’ ``[0, -1]`` (first + last frame)
+ ``"0,1,-2,-1"`` โ†’ ``[0, 1, -2, -1]`` (first two + last two)
+ """
+ if not spec.strip():
+ raise ValueError("keep_frames spec is empty.")
+ out: List[int] = []
+ for tok in spec.split(','):
+ tok = tok.strip()
+ if not tok:
+ continue
+ try:
+ out.append(int(tok))
+ except ValueError as e:
+ raise ValueError(
+ f"keep_frames: cannot parse {tok!r} as integer ({spec!r})."
+ ) from e
+ if not out:
+ raise ValueError(f"keep_frames spec parsed to empty list: {spec!r}.")
+ return out
+
+
+def build_keep_mask(
+ motion_lengths: torch.Tensor,
+ keep_indices: List[int],
+ max_T: int,
+ device: torch.device,
+ labels: Optional[Sequence[str]] = None,
+) -> Tuple[torch.Tensor, List[int]]:
+ """Build a ``(B, 1, 1, T)`` boolean keep-mask plus the resolved indices.
+
+ Indices resolve against ``max_T`` (so ``-1`` is always the last
+ generation slot, e.g. frame 59 when ``max_T = 60``) and clamp to
+ ``[0, max_T - 1]``. The mask is identical across the batch โ€” the only
+ per-sample concern is that some clips are shorter than ``max_T`` and
+ need their ``x1_known`` patched so the kept slot โ‰ฅ ``T_i`` holds the
+ clip's last real frame; that patch lives in the caller (sample.py).
+
+ Args:
+ motion_lengths: ``(B,)`` long tensor of per-sample valid frame counts.
+ Only used here for logging โ€” the resolution itself uses ``max_T``.
+ keep_indices: signed indices; negatives count from ``max_T``.
+ max_T: padded temporal length (``cond["lengths_mask"]`` width).
+ device: target device.
+ labels: optional per-sample labels (clip names) for logging.
+
+ Returns:
+ ``(mask, resolved_indices)``. ``resolved_indices`` is the sorted list
+ of absolute positions to clamp; callers use it to fix up ``x1_known``
+ for short clips.
+ """
+ B = motion_lengths.shape[0]
+ resolved = sorted({
+ max(0, min(k if k >= 0 else max_T + k, max_T - 1))
+ for k in keep_indices
+ })
+ mask = torch.zeros((B, 1, 1, max_T), dtype=torch.bool, device=device)
+ for idx in resolved:
+ mask[:, 0, 0, idx] = True
+
+ for i in range(B):
+ T_i = int(motion_lengths[i].item())
+ out_of_gt = [idx for idx in resolved if idx >= T_i]
+ label = labels[i] if labels is not None else f"sample[{i}]"
+ note = (f" (slots {out_of_gt} โ‰ฅ T_i clamp to GT's last frame)"
+ if out_of_gt else "")
+ logger.info(
+ f"build_keep_mask: {label} โ†’ valid_length={T_i}, "
+ f"keep_indices={resolved}{note}"
+ )
+ return mask, resolved
+
+
+# ---------------------------------------------------------------------------
+# Replacement-style ODE sampler
+# ---------------------------------------------------------------------------
+
+
+def inbetween_sample_ode(
+ sample_model,
+ transport,
+ cond: dict,
+ x1_known: torch.Tensor,
+ keep_mask: torch.Tensor,
+ motion_shape,
+ *,
+ num_steps: int = 50,
+ device: torch.device,
+) -> torch.Tensor:
+ """Fixed-step Euler ODE with per-step replacement of the kept slice.
+
+ Mask-shape-agnostic: the sampler clamps whatever ``keep_mask`` selects,
+ so the same routine handles temporal in-betweening (``(B, 1, 1, T)``
+ mask), spatial motion editing (``(B, J, 1, 1)`` mask), or any
+ combination as long as the mask broadcasts to ``(B, J, D, T)``.
+
+ Args:
+ sample_model: denoising network (already CFG-wrapped if cfg > 1).
+ transport: the ``Transport`` instance from the ``Sampler`` (needed
+ for the integration interval ``[t0, t1]``).
+ cond: conditioning dict (tensors already on device). Forwarded to
+ ``sample_model`` as the ``cond=`` keyword at every step.
+ x1_known: ``(B, J, D, T)`` normalized ground-truth motion. Values
+ outside ``keep_mask`` are ignored.
+ keep_mask: bool tensor broadcastable to ``(B, J, D, T)``; True where
+ the GT is pinned. Common shapes:
+ * ``(B, 1, 1, T)`` โ€” temporal in-betweening (keep frames).
+ * ``(B, J, 1, 1)`` โ€” spatial motion editing (keep joints).
+ motion_shape: ``(B, J, D, T)`` โ€” output shape (used to sample noise).
+ num_steps: number of Euler steps. Replacement needs a fixed-step
+ solver โ€” the kept slice has to be re-pinned at each known ``t``,
+ which an adaptive solver's internal stages do not expose โ€” so
+ this path does NOT use ``Sampler.sample_ode``'s default
+ ``dopri5``. The three application modes therefore integrate the
+ same ODE with a different (lower-order, fixed) discretization
+ than plain text-conditioned sampling does.
+ device: target device.
+
+ Returns:
+ ``(B, J, D, T)`` final sample. Positions selected by ``keep_mask``
+ equal ``x1_known`` (modulo the epsilon end-stop).
+ """
+ t0, t1 = transport.check_interval(
+ transport.train_eps,
+ transport.sample_eps,
+ sde=False, eval=True, reverse=False, last_step_size=0.0,
+ )
+
+ # Fixed noise โ€” both the initial state and the per-step interpolant
+ # reuse the same eps so kept frames trace the exact training-time path
+ # x_t = (1-t) eps + t x_1.
+ eps = torch.randn(motion_shape, device=device)
+ x = eps.clone()
+
+ # Mask must broadcast to (B, J, D, T). The replacement math is identical
+ # whichever axes the mask collapses on โ€” see inbetween (keep frames) vs.
+ # motion editing (keep joints) for the two common cases.
+ mask = keep_mask
+
+ def _replace(x_t, t_scalar):
+ t_blend = (1.0 - t_scalar) * eps + t_scalar * x1_known
+ return torch.where(mask, t_blend, x_t)
+
+ # Initial state: pin the kept frames to their t=t0 interpolant value.
+ x = _replace(x, t0)
+
+ ts = torch.linspace(t0, t1, num_steps + 1, device=device)
+
+ for i in range(num_steps):
+ t_cur = ts[i]
+ t_next = ts[i + 1]
+ dt = t_next - t_cur
+
+ t_batch = torch.full((x.size(0),), t_cur.item(), device=device, dtype=x.dtype)
+ v = sample_model(x, t_batch, cond=cond)
+ x = x + dt * v
+ x = _replace(x, t_next)
+
+ return x
diff --git a/unimate/inference/sample.py b/unimate/inference/sample.py
new file mode 100644
index 0000000..4b76965
--- /dev/null
+++ b/unimate/inference/sample.py
@@ -0,0 +1,1199 @@
+"""Inference entry point: generate motion samples from a trained model."""
+import dataclasses
+import gc
+import glob
+import json
+import os
+import re
+import time
+import warnings
+from typing import Dict, List, Optional, Tuple
+
+import numpy as np
+import torch
+import torch.nn as nn
+import tyro
+from accelerate.utils import set_seed
+
+warnings.filterwarnings("ignore")
+
+from unimate.configs.schema import MainConfig
+from unimate.dataset.conditioning import create_sample_condition
+from unimate.dataset.factory import create_dataset
+from unimate.inference.motion_inbetweening import build_keep_mask, parse_keep_frames
+from unimate.inference.motion_editing import (
+ build_joint_keep_mask,
+ get_joint_names,
+ parse_keep_joints,
+)
+from unimate.inference.motion_expansion import expand_motion_chain
+from unimate.models.flow.transport import Sampler
+from unimate.models.factory import create_diffusion, create_model, create_transport
+from unimate.training.ema import EMAModel
+from unimate.models.text_encoder.factory import create_text_encoder
+from unimate.utils.logger import get_logger
+from unimate.inference.generate import generate_samples
+from unimate.utils.text_emb_cache import pool, sequences_from_hidden
+from unimate.utils.visualization import visualize_and_save_motions
+
+logger = get_logger(file_name=__file__)
+
+# (case_id_for_filename, object_type, caption_text, caption_enc, clip_name).
+# ``caption_enc`` is the encoded prompt as ``{'caption_emb': (D,),
+# 'caption_tokens': (T, D)}`` โ€” the pooled vector text_cond='adaln' reads and
+# the token sequence text_cond='cross_attn' attends, mirroring what the data
+# loader hands the model at training time. ``clip_name`` is None unless an
+# in-betweening / motion-editing run pins a specific clip, whose GT motion is
+# then clamped during sampling.
+CaptionEnc = Dict[str, np.ndarray]
+TestCase = Tuple[str, str, str, CaptionEnc, Optional[str]]
+
+
+class InferenceArgs:
+ """Command-line arguments for inference (parsed by tyro)."""
+ exp_dir: str
+ model_path: Optional[str] = None
+ seed: Optional[int] = None
+ output_dir: Optional[str] = None
+ num_repetitions: int = 1
+ cfg_scale: Optional[float] = None
+ # JSON of {"<object_type>-<case_id>": caption}; used when cfg_scale > 1.0.
+ # When None, every clip in the dataset is enumerated as a test case.
+ test_cases_json: Optional[str] = None
+ # Plain-text object_types (one per line) for unconditional sampling at
+ # cfg_scale == 1.0. '#' starts a comment.
+ test_cases_txt: Optional[str] = None
+ # Per-chunk inference batch size โ€” caps GPU memory regardless of total count.
+ batch_size: int = 64
+ # Skip mp4/PNG renders; write only the .npy motion features.
+ only_save_motion: bool = False
+ # Skip the RIC-recovered mp4 (FK render + T-pose still saved).
+ # Defaults to False at inference: RIC is largely redundant with FK.
+ save_ric: bool = False
+ # Motion in-betweening: clamp the specified frames to ground truth and
+ # let the flow ODE denoise only the rest. Requires either
+ # --test_cases_json (with keys '<object_type>-<clip_id>' resolvable in
+ # train or eval motion_dict) or the dataset's eval split.
+ inbetween: bool = False
+ # Comma-separated signed temporal indices to hold clean. Negatives count
+ # from the per-clip valid length. Default keeps first + last frame.
+ keep_frames: str = "0,-1"
+ # Text-guided motion editing: clamp the listed joints to GT for all
+ # frames and let the model denoise the rest under a new caption (e.g.,
+ # fix the lower body, change the upper body action). Same clip-pinning
+ # requirement as --inbetween; mutually exclusive with it.
+ motion_edit: bool = False
+ # Comma-separated joint names to hold clean (matched case-insensitive
+ # against the per-skeleton ``clean_joint_names`` / ``joint_names``).
+ keep_joints: str = ""
+ # When set, the GT clip is cropped starting at this absolute frame index
+ # (instead of the default 'tpos' random window). Up to max_motion_length
+ # frames are taken from start_idx; if fewer remain, the GT is trimmed
+ # and the model still generates over the full ODE window but saved
+ # outputs (and the GT-clamp signal) are trimmed back via valid_lengths.
+ # Most useful with --motion_edit / --inbetween for deterministic, user-
+ # chosen edit windows.
+ gt_start_frame: Optional[int] = None
+ # Motion expansion: chain multiple text-conditioned generations into one
+ # long motion. Requires --test_cases_json whose values are *lists* of
+ # prompts (one segment per prompt). Each segment after the first pins
+ # its first `expand_overlap` frames to the previous segment's last
+ # `expand_overlap` frames via replacement-style sampling. Mutually
+ # exclusive with --inbetween / --motion_edit.
+ motion_expand: bool = False
+ # Number of frames overlapped (clamped) between consecutive expansion
+ # segments. Must satisfy 0 < expand_overlap < max_motion_length.
+ expand_overlap: int = 10
+
+
+class _UnconditionalWrapper(nn.Module):
+ """Force ``force_mask=True`` so the caption embedding is always zeroed.
+
+ Used at cfg_scale == 1.0 to mirror training-time CFG dropout while
+ preserving topology conditioning.
+ """
+
+ def __init__(self, model):
+ super().__init__()
+ self.model = model
+
+ def forward(self, x, timesteps, cond=None):
+ return self.model(x, timesteps, cond, force_mask=True)
+
+
+# ---------------------------------------------------------------------------
+# Setup helpers
+# ---------------------------------------------------------------------------
+
+
+def _resolve_exp_paths(exp_dir: str, model_path: Optional[str]) -> Tuple[str, str]:
+ """Locate config + highest-step checkpoint inside ``exp_dir``."""
+ config_path = os.path.join(exp_dir, "config.json")
+ if not os.path.isfile(config_path):
+ raise FileNotFoundError(f"No config.json in {exp_dir!r}")
+
+ if model_path is not None:
+ return config_path, model_path
+
+ ckpt_dir = os.path.join(exp_dir, "checkpoints")
+ candidates = glob.glob(os.path.join(ckpt_dir, "checkpoint_step_*.pt"))
+ if not candidates:
+ raise FileNotFoundError(f"No checkpoint_step_*.pt files in {ckpt_dir!r}")
+
+ step_re = re.compile(r"checkpoint_step_(\d+)\.pt$")
+
+ def _step(p):
+ m = step_re.search(os.path.basename(p))
+ return int(m.group(1)) if m else -1
+
+ return config_path, max(candidates, key=_step)
+
+
+def _build_diffusion(config: MainConfig):
+ """Return ``(diffusion, gen_diffusion)`` based on ``training.diff_model``."""
+ if config.training.diff_model == 'flow':
+ diffusion = create_transport(training_config=config.training)
+ return diffusion, Sampler(diffusion)
+ if config.training.diff_model == 'diffusion':
+ diffusion = create_diffusion(
+ scheduler_config=config.scheduler,
+ training_config=config.training,
+ )
+ return diffusion, None
+ raise ValueError(f"Unknown diff_model: {config.training.diff_model!r}")
+
+
+def _load_checkpoint(model, model_path: str, config: MainConfig):
+ """Load weights into ``model`` in place; apply EMA shadow if available."""
+ state_dict = torch.load(model_path, map_location='cpu')
+ model.load_state_dict(state_dict.get('model_state_dict', state_dict))
+
+ if config.training.use_ema and 'ema_state_dict' in state_dict:
+ logger.info("Loading EMA weights into model parameters.")
+ ema_model = EMAModel(
+ parameters=model.parameters(),
+ decay=config.training.ema_decay,
+ use_ema_warmup=True,
+ )
+ ema_model.load_state_dict(state_dict['ema_state_dict'])
+ ema_model.copy_to(model.parameters())
+ else:
+ logger.info("Using standard model weights (no EMA).")
+
+
+# ---------------------------------------------------------------------------
+# Test-case loaders
+# ---------------------------------------------------------------------------
+
+
+def _known_object_types(dataset) -> set:
+ """Object types with at least one train or eval clip โ€” only these can
+ realize a test case (otherwise no reference clip is available)."""
+ md = dataset.motion_dataset
+ return {
+ ot for ot in md.cond_dict.keys()
+ if md.train_object_motions_map.get(ot) or md.eval_object_motions_map.get(ot)
+ }
+
+
+def _make_text_encoder(config: MainConfig, device: torch.device):
+ # pool=False so a prompt yields its token sequence; ``_encode_prompt``
+ # derives the pooled vector from it, the same rule the data loader uses.
+ return create_text_encoder(
+ encoder_type=config.model.text_encoder_type,
+ encoder_version=config.model.text_encoder_version,
+ device=str(device),
+ pool=False,
+ )
+
+
+def _encode_prompt(encoder, text: str) -> CaptionEnc:
+ """Encode one prompt -> ``{'caption_emb': (D,), 'caption_tokens': (T, D)}``.
+
+ Padding is dropped by the attention mask, so the mean over the kept rows
+ is exactly the encoder's own pooled output โ€” including for the empty
+ prompt, whose mask is all zeros and which therefore pools to the zero
+ vector the unconditional reference has always been.
+ """
+ with torch.no_grad():
+ inputs = encoder.tokenize(text)
+ hidden = encoder(inputs) # (1, T, D)
+ tokens = sequences_from_hidden(hidden.detach().cpu(),
+ inputs['attention_mask'].cpu())[0]
+ return {'caption_emb': pool(tokens), 'caption_tokens': tokens}
+
+
+def _release_gpu():
+ gc.collect()
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+
+
+def _resolve_inference_scope(args: InferenceArgs) -> Tuple[Optional[set], Optional[set]]:
+ """Return ``(target_object_types, target_clip_stems)`` extracted from the
+ test-case spec, or ``(None, None)`` when neither file is supplied.
+
+ ``target_clip_stems`` is populated only for in-betweening / motion
+ editing โ€” they pin specific GT clips that must actually be on disk.
+ """
+ object_types: Optional[set] = None
+ clip_stems: Optional[set] = None
+
+ if args.test_cases_json is not None:
+ with open(args.test_cases_json) as f:
+ raw_cases = json.load(f)
+ object_types = set()
+ if args.inbetween or args.motion_edit:
+ clip_stems = set()
+ for case_key in raw_cases:
+ obj_type, _, clip_id = case_key.partition('-')
+ if obj_type:
+ object_types.add(obj_type)
+ if clip_stems is not None and clip_id:
+ # On-disk file stem is "{obj_type}-{clip_id}" for
+ # Truebones/Objaverse and "{obj_type}_{clip_id}" for Mixamo
+ # (prefixed at load). Also keep the literal clip_id for
+ # users who already supply the full stem in case_key.
+ clip_stems.add(clip_id)
+ clip_stems.add(f"{obj_type}-{clip_id}")
+ clip_stems.add(f"{obj_type}_{clip_id}")
+ logger.info(
+ f"Inference scope from {args.test_cases_json}: "
+ f"{len(object_types)} object types"
+ + (f", {len(clip_stems)} pinned clip stems" if clip_stems else '')
+ )
+
+ if args.test_cases_txt is not None:
+ if object_types is None:
+ object_types = set()
+ with open(args.test_cases_txt) as f:
+ for line in f:
+ s = line.strip()
+ if s and not s.startswith('#'):
+ object_types.add(s)
+ logger.info(
+ f"Inference scope augmented from {args.test_cases_txt}: "
+ f"{len(object_types)} object types total."
+ )
+
+ return object_types, clip_stems
+
+
+def _resolve_stats_path(exp_dir: str) -> Optional[str]:
+ """Return path to ``dataset_stats.npy`` in ``exp_dir``, or ``None``."""
+ candidate = os.path.join(exp_dir, "dataset_stats.npy")
+ if os.path.isfile(candidate):
+ return candidate
+ logger.warning(
+ f"No dataset_stats.npy at {candidate} โ€” stats will be recomputed from "
+ f"the loaded clips, which may not match training-time normalization."
+ )
+ return None
+
+
+def _resolve_clip_name(dataset, obj_type: str, clip_id: str) -> Optional[str]:
+ """Find the dataset key whose stem matches ``clip_id`` for ``obj_type``.
+
+ Motion-dict keys are filenames (typically with a ``.npz`` extension);
+ user-supplied case ids omit the extension. We search train then eval โ€”
+ same priority as :func:`create_sample_condition` โ€” and verify the
+ ``object_type`` so a clip-id collision across types can't pin the wrong
+ skeleton.
+ """
+ md = dataset.motion_dataset
+ # Accept either the suffix-only form (``clip_id``) or one of the prefixed
+ # forms that match motion_dict keys: Truebones/Objaverse stems are
+ # "{obj_type}-{clip_id}", Mixamo prefixed stems are "{obj_type}_{clip_id}".
+ candidates = {clip_id, f"{obj_type}-{clip_id}", f"{obj_type}_{clip_id}"}
+ for source in (md.train_motion_dict, md.eval_motion_dict):
+ for clip_name in source:
+ stem = os.path.splitext(clip_name)[0]
+ if stem in candidates and source[clip_name].get('object_type') == obj_type:
+ return clip_name
+ return None
+
+
+def _load_test_cases_json(
+ json_path: str,
+ config: MainConfig,
+ dataset,
+ device: torch.device,
+ resolve_clip: bool = False,
+) -> List[TestCase]:
+ """Caption-conditioned cases from {"<object_type>-<id>": caption} JSON.
+
+ When ``resolve_clip`` is True (in-betweening), the ``<id>`` portion is
+ treated as a dataset clip stem and must resolve to an actual clip in
+ train or eval motion_dict โ€” otherwise the case is dropped, since
+ in-betweening has nothing to clamp against. When False, ``<id>`` is a
+ free-form tag and only ``<object_type>`` needs to exist.
+ """
+ with open(json_path) as f:
+ raw_cases: Dict[str, str] = json.load(f)
+
+ known = _known_object_types(dataset)
+ cases: List[Tuple[str, str, str, Optional[str]]] = []
+ for case_key, caption in raw_cases.items():
+ obj_type, _, clip_id = case_key.partition('-')
+ if obj_type not in known:
+ logger.warning(
+ f"Test case {case_key!r}: object_type={obj_type!r} not in dataset; skipping."
+ )
+ continue
+ # An empty caption at cfg>1 collapses to ~unconditional output and
+ # is almost always a data-entry mistake; skip rather than silently
+ # generating garbage.
+ if not caption or not caption.strip():
+ logger.warning(f"Test case {case_key!r}: empty caption; skipping.")
+ continue
+
+ resolved_clip: Optional[str] = None
+ if resolve_clip:
+ if not clip_id:
+ logger.warning(
+ f"Test case {case_key!r}: in-betweening requires "
+ f"'<object_type>-<clip_id>' format with a non-empty id; skipping."
+ )
+ continue
+ resolved_clip = _resolve_clip_name(dataset, obj_type, clip_id)
+ if resolved_clip is None:
+ logger.warning(
+ f"Test case {case_key!r}: clip_id={clip_id!r} not found in "
+ f"train or eval motion_dict for object_type={obj_type!r}; skipping."
+ )
+ continue
+
+ cases.append((case_key, obj_type, caption, resolved_clip))
+
+ if not cases:
+ raise ValueError(
+ f"No usable test cases in {json_path}: object_types not present in dataset."
+ )
+ logger.info(f"Loaded {len(cases)} test cases from {json_path}")
+
+ encoder = _make_text_encoder(config, device)
+ encoded: List[TestCase] = []
+ for case_key, obj_type, caption, clip_name in cases:
+ encoded.append((case_key, obj_type, caption,
+ _encode_prompt(encoder, caption), clip_name))
+ del encoder
+ _release_gpu()
+ return encoded
+
+
+def _load_test_cases_txt(
+ txt_path: str,
+ config: MainConfig,
+ dataset,
+ device: torch.device,
+) -> List[TestCase]:
+ """Unconditional cases โ€” one object_type per line.
+
+ The empty-string embedding is a shape-only placeholder; ``_UnconditionalWrapper``
+ zeroes it inside the model at sample time.
+ """
+ with open(txt_path) as f:
+ object_types = [
+ line.strip() for line in f
+ if line.strip() and not line.lstrip().startswith('#')
+ ]
+
+ known = _known_object_types(dataset)
+ cases = []
+ for ot in object_types:
+ if ot not in known:
+ logger.warning(f"object_type={ot!r} not in dataset; skipping.")
+ continue
+ cases.append(ot)
+
+ if not cases:
+ raise ValueError(
+ f"No usable test cases in {txt_path}: object_types not present in dataset."
+ )
+ logger.info(f"Loaded {len(cases)} unconditional test cases from {txt_path}")
+
+ encoder = _make_text_encoder(config, device)
+ null_emb = _encode_prompt(encoder, "")
+ del encoder
+ _release_gpu()
+
+ # case_id == object_type since txt rows have no per-case suffix.
+ return [(ot, ot, "", null_emb, None) for ot in cases]
+
+
+def _load_test_cases_from_dataset(dataset) -> List[TestCase]:
+ """Enumerate test cases from the dataset, prioritised by data-loader source.
+
+ Three regimes, in priority order:
+
+ 1. **eval split populated by ``test_objects.txt``** (data loader saw an
+ explicit object-type holdout list): per-clip enumeration, no dedup.
+ Every clip in the listed object_types becomes its own test case.
+ This is the default for quantitative evaluation.
+
+ 2. **eval split populated by ``test_split_ratio > 0``** (no
+ ``test_objects.txt``, but a random clip-level split exists):
+ per-clip enumeration, no dedup. Same as (1) but the eval-set
+ composition came from the random-split logic in the dataloader.
+
+ 3. **no eval split** (``test_objects.txt`` absent and ratio == 0):
+ dedup'd unique ``(object_type, caption)`` enumeration on the train
+ split โ€” a visualization sweep with no held-out set.
+
+ Captions reuse pre-encoded embeddings โ€” no text encoder needed.
+ """
+ md = dataset.motion_dataset
+
+ if md.eval_motion_dict:
+ source, split, dedup = md.eval_motion_dict, 'eval', False
+ if any(v for v in md.explicit_eval_objects.values()):
+ origin = "test_objects.txt (explicit object_type holdout)"
+ else:
+ origin = "test_split_ratio (random clip holdout)"
+ else:
+ source, split, dedup = md.train_motion_dict, 'train', True
+ origin = "fallback โ€” no eval split (test_objects.txt absent, ratio=0)"
+
+ seen = set()
+ encoded: List[TestCase] = []
+ per_object_count: Dict[str, int] = {}
+ for clip_name in sorted(source.keys()):
+ entry = source[clip_name]
+ if 'caption_emb' not in entry:
+ continue
+ ot = entry['object_type']
+ caption = entry['caption']
+ if dedup:
+ key = (ot, caption)
+ if key in seen:
+ continue
+ seen.add(key)
+ per_object_count[ot] = per_object_count.get(ot, 0) + 1
+ case_id = os.path.splitext(clip_name)[0]
+ # Dataset entries carry both views already (the loader built them).
+ enc = {'caption_emb': entry['caption_emb']}
+ if 'caption_tokens' in entry:
+ enc['caption_tokens'] = entry['caption_tokens']
+ encoded.append((case_id, ot, caption, enc, clip_name))
+
+ if not encoded:
+ raise ValueError(
+ "No usable test cases in dataset: no clips have a pre-encoded caption."
+ )
+ mode = 'unique (object_type, caption)' if dedup else 'per-clip'
+ summary = ', '.join(f'{ot}={n}' for ot, n in sorted(per_object_count.items()))
+ logger.info(
+ f"Auto-enumerated {len(encoded)} {mode} test cases from {split} split "
+ f"[source: {origin}] [{summary}]."
+ )
+ return encoded
+
+
+def _load_expand_test_cases(
+ json_path: str,
+ config: MainConfig,
+ dataset,
+ device: torch.device,
+) -> List[Tuple[str, str, List[str], List[np.ndarray]]]:
+ """Motion-expand cases from {"<object_type>-<label>": [prompt, ...]} JSON.
+
+ Each value must be a non-empty list of non-empty strings. The list
+ order is the segment order: prompt[0] drives the free first segment,
+ prompt[i>0] drives a follow-up segment whose first ``expand_overlap``
+ frames are clamped to the previous segment's last ``expand_overlap``
+ frames.
+
+ Returns ``[(case_id, object_type, [prompts], [caption_embs])]``.
+ Unlike motion-edit / in-betweening, no GT clip is pinned โ€” only the
+ skeleton from ``<object_type>`` is needed.
+ """
+ with open(json_path) as f:
+ raw_cases = json.load(f)
+
+ known = _known_object_types(dataset)
+ cases: List[Tuple[str, str, List[str]]] = []
+ for case_key, prompts in raw_cases.items():
+ obj_type, _, _ = case_key.partition('-')
+ if obj_type not in known:
+ logger.warning(
+ f"Test case {case_key!r}: object_type={obj_type!r} not in dataset; skipping."
+ )
+ continue
+ if not isinstance(prompts, list):
+ logger.warning(
+ f"Test case {case_key!r}: value must be a list of prompts for "
+ f"--motion_expand (got {type(prompts).__name__}); skipping."
+ )
+ continue
+ valid = [p.strip() for p in prompts if isinstance(p, str) and p.strip()]
+ if len(valid) != len(prompts):
+ logger.warning(
+ f"Test case {case_key!r}: {len(prompts) - len(valid)} prompt(s) "
+ f"empty or non-string; keeping {len(valid)}/{len(prompts)}."
+ )
+ if not valid:
+ logger.warning(f"Test case {case_key!r}: no usable prompts; skipping.")
+ continue
+ cases.append((case_key, obj_type, valid))
+
+ if not cases:
+ raise ValueError(
+ f"No usable motion-expand test cases in {json_path}."
+ )
+ logger.info(f"Loaded {len(cases)} motion-expand test cases from {json_path}.")
+
+ encoder = _make_text_encoder(config, device)
+ encoded: List[Tuple[str, str, List[str], List[np.ndarray]]] = []
+ for case_key, obj_type, prompts in cases:
+ embs = [_encode_prompt(encoder, p) for p in prompts]
+ encoded.append((case_key, obj_type, prompts, embs))
+ del encoder
+ _release_gpu()
+ return encoded
+
+
+def _select_test_cases(
+ args: InferenceArgs,
+ cfg_scale: float,
+ config: MainConfig,
+ dataset,
+ device: torch.device,
+ resolve_clip: bool = False,
+) -> List[TestCase]:
+ """Test-case selection at cfg > 1.0, in priority order:
+
+ 1. ``--test_cases_json`` provided
+ โ†’ use the JSON's ``{object_type-id: prompt}`` map verbatim
+ (curated prompts).
+ 2. dataset's eval split populated by ``test_objects.txt``
+ โ†’ per-clip enumeration over the listed object_types (eval mode).
+ 3. dataset's eval split populated by ``test_split_ratio > 0``
+ โ†’ per-clip enumeration over the random eval clips (eval mode).
+ 4. no JSON, no eval split
+ โ†’ dedup'd unique ``(object_type, caption)`` prompts from the train
+ split (visualization sweep).
+
+ Cases 2/3/4 are all handled by ``_load_test_cases_from_dataset``, which
+ introspects the dataloader's split state and logs which source it used.
+
+ At cfg == 1.0 the function always returns unconditional test cases from
+ ``--test_cases_txt`` (one ``object_type`` per line, null caption emb).
+ """
+ if cfg_scale > 1.0:
+ if args.test_cases_json is not None:
+ return _load_test_cases_json(
+ args.test_cases_json, config, dataset, device,
+ resolve_clip=resolve_clip,
+ )
+ return _load_test_cases_from_dataset(dataset)
+ return _load_test_cases_txt(args.test_cases_txt, config, dataset, device)
+
+
+# ---------------------------------------------------------------------------
+# Sampling
+# ---------------------------------------------------------------------------
+
+
+def _validate_cfg_inputs(cfg_scale: float, args: InferenceArgs):
+ if cfg_scale < 1.0:
+ raise ValueError(f"cfg_scale must be >= 1.0, got {cfg_scale}.")
+ if args.inbetween and args.motion_edit:
+ raise ValueError(
+ "--inbetween and --motion_edit are mutually exclusive (different "
+ "mask axes โ€” frames vs. joints)."
+ )
+ if args.motion_expand and (args.inbetween or args.motion_edit):
+ raise ValueError(
+ "--motion_expand is mutually exclusive with --inbetween / --motion_edit."
+ )
+ if (args.inbetween or args.motion_edit) and cfg_scale <= 1.0:
+ # cfg==1.0 uses --test_cases_txt (no clip pinning), so there's no
+ # GT motion to clamp known frames/joints against.
+ mode = '--inbetween' if args.inbetween else '--motion_edit'
+ raise ValueError(
+ f"{mode} requires cfg_scale > 1.0 so test cases come from "
+ f"--test_cases_json or the dataset eval split (both pin a clip)."
+ )
+ if args.motion_expand and cfg_scale <= 1.0:
+ raise ValueError(
+ "--motion_expand requires cfg_scale > 1.0 and a --test_cases_json "
+ "whose values are lists of prompts (one per segment)."
+ )
+ if args.motion_expand and args.test_cases_json is None:
+ raise ValueError(
+ "--motion_expand requires --test_cases_json with per-case prompt lists."
+ )
+ if args.motion_edit and not args.keep_joints.strip():
+ raise ValueError(
+ "--motion_edit requires --keep_joints (comma-separated joint names)."
+ )
+ if cfg_scale > 1.0:
+ if args.test_cases_json is None:
+ logger.info(
+ f"cfg_scale={cfg_scale} > 1.0 with no --test_cases_json: "
+ f"enumerating the dataset's test split (per-clip if eval split "
+ f"is non-empty, else dedup-fallback on train)."
+ )
+ if args.test_cases_txt is not None:
+ logger.warning(
+ "--test_cases_txt is ignored at cfg > 1.0 โ€” the dataset's "
+ "test_objects.txt drives the eval split at data-loading time."
+ )
+ else: # cfg_scale == 1.0
+ if args.test_cases_txt is None:
+ raise ValueError("cfg_scale=1.0 requires --test_cases_txt.")
+ if args.test_cases_json is not None:
+ logger.warning("--test_cases_json ignored because cfg_scale == 1.0.")
+
+
+def _wrap_for_cfg(model, cfg_scale: float):
+ """Pass-through at cfg > 1.0; force unconditional inference at cfg == 1.0."""
+ if cfg_scale > 1.0:
+ return model
+ if not (getattr(model, 'cond_mask_prob', 0) > 0):
+ logger.warning(
+ "Unconditional sampling requested but model was trained with "
+ "cond_mask_prob == 0; sample quality may be poor."
+ )
+ logger.info("Wrapping model in _UnconditionalWrapper (force_mask=True).")
+ return _UnconditionalWrapper(model)
+
+
+def _gt_valid_lengths(dataset, clip_names, gt_offset: int, max_T: int,
+ device: torch.device) -> torch.Tensor:
+ """Per-clip usable GT frame counts, as a ``(B,)`` long tensor.
+
+ Lengths come from the source motion_dict (``cond["motion_length"]``
+ reports the padded length at inference, which would resolve ``-1`` to a
+ zero-padded frame instead of the clip's true last frame). When the GT was
+ cropped from ``gt_offset`` (``--gt_start_frame``), the usable length is
+ ``n - gt_offset``; everything is clamped to ``[0, max_T]``.
+ """
+ md = dataset.motion_dataset
+ return torch.tensor(
+ [
+ max(0, min(
+ (md.train_motion_dict.get(cn)
+ or md.eval_motion_dict[cn])['motion'].shape[0] - gt_offset,
+ max_T,
+ ))
+ for cn in clip_names
+ ],
+ dtype=torch.long, device=device,
+ )
+
+
+def _run_sampling(
+ config: MainConfig,
+ sample_model,
+ dataset,
+ test_cases: List[TestCase],
+ diffusion,
+ gen_diffusion,
+ cfg_scale: float,
+ device: torch.device,
+ args: InferenceArgs,
+ output_dir: str,
+):
+ """Generate ``num_repetitions`` samples per test case, in chunks of
+ ``args.batch_size``. ``no_grad`` keeps the ODE rollout from accumulating
+ autograd graphs across denoising steps.
+
+ When ``args.inbetween`` is set, ``create_sample_condition`` returns the
+ normalized GT motion (because ``test_case_captions`` now includes the
+ pinned clip_name). That GT plus a keep_mask are passed to
+ ``generate_samples`` which routes to the replacement-style sampler.
+ Each case's GT is also saved as ``<case_id>-gt.npy`` for side-by-side
+ rendering.
+ """
+ # Only pin the reference clip when in-betweening or motion-editing (the
+ # clip's GT motion is what the sampler clamps against). Other runs let
+ # create_sample_condition pick a random clip of the same object_type,
+ # since only the skeleton is needed.
+ needs_gt = args.inbetween or args.motion_edit
+ if needs_gt:
+ test_case_captions = [
+ (ot, cap, emb, clip) for _, ot, cap, emb, clip in test_cases
+ ]
+ else:
+ test_case_captions = [
+ (ot, cap, emb) for _, ot, cap, emb, _ in test_cases
+ ]
+ case_ids = [case_id for case_id, *_ in test_cases]
+ captions_text = [caption for _, _, caption, _, _ in test_cases]
+ total = len(test_cases)
+ chunk_size = max(1, args.batch_size)
+ use_cuda_sync = device.type == 'cuda'
+
+ keep_frame_indices = parse_keep_frames(args.keep_frames) if args.inbetween else None
+ keep_joint_names = parse_keep_joints(args.keep_joints) if args.motion_edit else None
+ if args.inbetween:
+ logger.info(f"In-betweening: keep_frames={keep_frame_indices}.")
+ if args.motion_edit:
+ logger.info(f"Motion editing: keep_joints={keep_joint_names}.")
+
+ # ``captions.json`` mirrors the motion-feature filenames written by
+ # ``visualize_and_save_motions``: keys are ``<case_id>-rep_<rep>-<idx>.npy``,
+ # values are the prompt used to condition each sample. Rewritten after
+ # every chunk so a partial run still leaves a valid index on disk.
+ captions_path = os.path.join(output_dir, 'captions.json')
+ captions_map: Dict[str, str] = {}
+
+ logger.info(
+ f"Starting sampling: {total} test cases ร— {args.num_repetitions} reps "
+ f"in chunks of {chunk_size}."
+ )
+
+ with torch.no_grad():
+ for rep_i in range(args.num_repetitions):
+ logger.info(f'--- rep #{rep_i} ---')
+ for chunk_start in range(0, total, chunk_size):
+ chunk_end = min(chunk_start + chunk_size, total)
+ # test_case_captions drives selection here, one reference
+ # clip per case, so create_sample_condition's own sampling
+ # (num_samples) never applies.
+ gt_motion, cond = create_sample_condition(
+ config=config,
+ data=dataset,
+ test_case_captions=test_case_captions[chunk_start:chunk_end],
+ gt_start_frame=args.gt_start_frame,
+ )
+ cond = {
+ k: v.to(device) if torch.is_tensor(v) else v
+ for k, v in cond.items()
+ }
+ bsz = cond["n_joints"].shape[0]
+ motion_shape = (
+ bsz,
+ config.dataset.max_joints,
+ config.dataset.feature_len,
+ config.dataset.max_motion_length,
+ )
+
+ # Replacement-style sampling for in-betweening or motion
+ # editing. Both branches share the same GT-clamping sampler
+ # (only the mask differs); ``generate_samples`` routes on the
+ # presence of x1_known + keep_mask.
+ x1_known = None
+ keep_mask = None
+ gt_valid_lengths = None # per-sample lengths for trimming saved GT
+ sample_valid_lengths = None # same, for the generated sample (motion_edit only)
+ if args.inbetween:
+ chunk_clip_names = [
+ c for _, _, _, _, c in test_cases[chunk_start:chunk_end]
+ ]
+ max_T = config.dataset.max_motion_length
+ valid_lengths = _gt_valid_lengths(
+ dataset, chunk_clip_names, args.gt_start_frame or 0,
+ max_T, device,
+ )
+ keep_mask, resolved_keep = build_keep_mask(
+ valid_lengths, keep_frame_indices, max_T, device,
+ labels=chunk_clip_names,
+ )
+ x1_known = gt_motion.to(device)
+ # For clips shorter than the padded ODE window, copy the
+ # clip's actual last frame into any keep slot beyond T_i
+ # so the generation endpoint (e.g. frame 59) clamps to a
+ # real GT pose instead of the zero-padded slot.
+ for i in range(bsz):
+ T_i = int(valid_lengths[i].item())
+ if T_i >= max_T:
+ continue
+ last_gt = x1_known[i, :, :, T_i - 1].clone()
+ for idx in resolved_keep:
+ if idx >= T_i:
+ x1_known[i, :, :, idx] = last_gt
+ gt_valid_lengths = valid_lengths
+ elif args.motion_edit:
+ # Per-sample joint names come from the (already-loaded)
+ # cond_dict โ€” same source the model used at training to
+ # build joint_names_emb, so indices align.
+ chunk_object_types = cond["object_type"]
+ joint_names_per_sample = [
+ get_joint_names(dataset, ot) for ot in chunk_object_types
+ ]
+ keep_mask = build_joint_keep_mask(
+ joint_names_per_sample,
+ keep_joint_names,
+ config.dataset.max_joints,
+ device,
+ )
+ x1_known = gt_motion.to(device)
+ # Motion-edit operates on the clip's actual frames only;
+ # the model still generates 60 padded frames, but anything
+ # past T_i is meaningless (no GT to compare against), so
+ # trim both the sample and the GT to the per-clip length
+ # at save time.
+ chunk_clip_names = [
+ c for _, _, _, _, c in test_cases[chunk_start:chunk_end]
+ ]
+ max_T = config.dataset.max_motion_length
+ valid_lengths = _gt_valid_lengths(
+ dataset, chunk_clip_names, args.gt_start_frame or 0,
+ max_T, device,
+ )
+ # The joint-keep mask is (B, J, 1, 1) โ€” broadcasts over
+ # the temporal axis โ€” so kept joints get clamped to GT
+ # at every frame. For samples whose cropped GT is shorter
+ # than max_T (short clips, or ``--gt_start_frame`` near
+ # the clip's end), the zero-padded tail would clamp kept
+ # joints to a zero pose during denoising. Hold the last
+ # real frame instead so the constraint stays
+ # geometrically sensible; the tail is trimmed at save
+ # time via ``valid_lengths``.
+ for i in range(bsz):
+ T_i = int(valid_lengths[i].item())
+ if 0 < T_i < max_T:
+ x1_known[i, :, :, T_i:] = x1_known[i, :, :, T_i - 1:T_i]
+ gt_valid_lengths = valid_lengths
+ sample_valid_lengths = valid_lengths
+ for cn, T_i in zip(chunk_clip_names, valid_lengths.tolist()):
+ logger.info(
+ f"motion_edit: {cn} โ†’ valid_length={T_i} "
+ f"(sample + GT will be saved at this length)."
+ )
+
+ if use_cuda_sync:
+ torch.cuda.synchronize(device)
+ t_start = time.perf_counter()
+
+ samples = generate_samples(
+ model=sample_model,
+ cond=cond,
+ motion_shape=motion_shape,
+ diff_model=config.training.diff_model,
+ diffusion=diffusion,
+ gen_diffusion=gen_diffusion,
+ device=device,
+ cfg_scale=cfg_scale,
+ x1_known=x1_known,
+ keep_mask=keep_mask,
+ )
+
+ if use_cuda_sync:
+ torch.cuda.synchronize(device)
+ elapsed = time.perf_counter() - t_start
+ logger.info(
+ f'rep#{rep_i} chunk[{chunk_start}:{chunk_end}] '
+ f'{elapsed:.2f}s for batch={bsz} ({elapsed / bsz:.3f}s/motion).'
+ )
+
+ # ``rep_{rep_i}`` prefixes every saved file so repetitions of
+ # the same test case never collide.
+ chunk_case_ids = case_ids[chunk_start:chunk_end]
+ visualize_and_save_motions(
+ config=config,
+ cond=cond,
+ samples=samples,
+ save_dir=output_dir,
+ prefix=f'rep_{rep_i}',
+ case_ids=chunk_case_ids,
+ only_save_motion=args.only_save_motion,
+ save_ric=args.save_ric,
+ valid_lengths=sample_valid_lengths,
+ )
+
+ # Save GT under a per-rep "gt_rep_<i>" prefix. Per-rep rather
+ # than once-only because ``apply_cropping`` picks a random
+ # start_idx for ``topology_condition_type='tpos'``, so each
+ # rep clamps against a different windowed GT.
+ # NOTE the two files can differ in length: motion_edit trims
+ # sample and GT alike (``sample_valid_lengths``), while
+ # in-betweening trims only the GT โ€” the model is asked for the
+ # whole ODE window there, so its output stays max_motion_length
+ # even when the reference clip is shorter. Align on frame 0
+ # before diffing them.
+ # ``gt_valid_lengths`` (set for inbetween and motion_edit)
+ # trims the saved GT to the clip's true length rather than
+ # the padded ODE window.
+ if needs_gt:
+ visualize_and_save_motions(
+ config=config,
+ cond=cond,
+ samples=x1_known,
+ save_dir=output_dir,
+ prefix=f'gt_rep_{rep_i}',
+ case_ids=chunk_case_ids,
+ only_save_motion=args.only_save_motion,
+ save_ric=args.save_ric,
+ valid_lengths=gt_valid_lengths,
+ )
+
+ for object_idx, case_id in enumerate(chunk_case_ids):
+ npy_name = f'{case_id}-rep_{rep_i}-{object_idx}.npy'
+ captions_map[npy_name] = captions_text[chunk_start + object_idx]
+ with open(captions_path, 'w') as f:
+ json.dump(captions_map, f, indent=2, ensure_ascii=False)
+
+ # Drop chunk-scoped tensors before the next batch so peak GPU
+ # memory tracks per-batch, not per-run, usage.
+ del cond, samples
+ if x1_known is not None:
+ del x1_known
+ _release_gpu()
+
+
+def _run_expansion_sampling(
+ config: MainConfig,
+ sample_model,
+ dataset,
+ expand_cases: List[Tuple[str, str, List[str], List[np.ndarray]]],
+ diffusion,
+ gen_diffusion,
+ cfg_scale: float,
+ device: torch.device,
+ args: InferenceArgs,
+ output_dir: str,
+):
+ """Per-case chain generation: each case produces one concatenated motion
+ of length ``max_T + (max_T - overlap) * (N - 1)``.
+
+ Each case is processed independently (no cross-case batching) because
+ prompt-list lengths can differ. Within a case, the cond dict is set up
+ once via ``create_sample_condition`` and the per-segment cond is built
+ by swapping in the segment's pre-encoded ``caption_emb`` โ€” ``caption_emb``
+ is a fixed-shape ``(B, text_dim)`` tensor (see ``mixture_batch_collate``)
+ so the swap is a single tensor assignment.
+ """
+ overlap = args.expand_overlap
+ max_T = config.dataset.max_motion_length
+ if overlap <= 0 or overlap >= max_T:
+ raise ValueError(
+ f"--expand_overlap must be in (0, max_motion_length={max_T}), "
+ f"got {overlap}."
+ )
+
+ captions_path = os.path.join(output_dir, 'captions.json')
+ captions_map: Dict[str, str] = {}
+
+ logger.info(
+ f"Starting motion-expand sampling: {len(expand_cases)} case(s) ร— "
+ f"{args.num_repetitions} rep(s); overlap={overlap}, max_T={max_T}."
+ )
+
+ motion_shape = (
+ 1,
+ config.dataset.max_joints,
+ config.dataset.feature_len,
+ max_T,
+ )
+
+ with torch.no_grad():
+ for rep_i in range(args.num_repetitions):
+ logger.info(f'--- rep #{rep_i} ---')
+ for case_idx, (case_id, obj_type, prompts, embs) in enumerate(expand_cases):
+ # Bootstrap the skeleton cond using the first prompt; the
+ # caption is overwritten per segment below.
+ _, cond = create_sample_condition(
+ config=config,
+ data=dataset,
+ test_case_captions=[(obj_type, prompts[0], embs[0])],
+ )
+ cond = {
+ k: v.to(device) if torch.is_tensor(v) else v
+ for k, v in cond.items()
+ }
+ if 'caption_emb' not in cond:
+ raise RuntimeError(
+ "caption_emb missing from cond โ€” --motion_expand requires "
+ "a text-conditioned model (cond_mode='text')."
+ )
+
+ # Per-segment cond dicts share every skeleton field; only the
+ # caption and its encodings change. Shallow copy is enough โ€”
+ # the tensor reassignment doesn't leak across segments.
+ cond_per_segment: List[Dict] = []
+ dtype = cond['caption_emb'].dtype
+ for prompt, enc in zip(prompts, embs):
+ seg_cond = dict(cond)
+ seg_cond['caption_emb'] = torch.from_numpy(
+ enc['caption_emb']).to(device=device, dtype=dtype).unsqueeze(0)
+ if 'caption_tokens' in enc:
+ toks = torch.from_numpy(enc['caption_tokens']).to(
+ device=device, dtype=dtype).unsqueeze(0) # (1, T, D)
+ seg_cond['caption_tokens'] = toks
+ seg_cond['caption_mask'] = torch.ones(
+ toks.shape[:2], dtype=torch.bool, device=device)
+ seg_cond['caption'] = [prompt]
+ cond_per_segment.append(seg_cond)
+
+ t_start = time.perf_counter()
+ chain = expand_motion_chain(
+ cond_per_segment=cond_per_segment,
+ motion_shape=motion_shape,
+ overlap=overlap,
+ sample_model=sample_model,
+ diff_model=config.training.diff_model,
+ diffusion=diffusion,
+ gen_diffusion=gen_diffusion,
+ cfg_scale=cfg_scale,
+ device=device,
+ )
+ elapsed = time.perf_counter() - t_start
+ logger.info(
+ f'rep#{rep_i} case[{case_idx}] {case_id!r}: '
+ f'{len(prompts)} segments โ†’ T_total={chain.shape[-1]} '
+ f'({elapsed:.2f}s).'
+ )
+
+ # Stitch the prompts into a single caption for the saved
+ # video title; the model never sees this โ€” segment captions
+ # were used individually during generation.
+ joined_caption = " | ".join(prompts)
+ viz_cond = dict(cond)
+ viz_cond['caption'] = [joined_caption]
+
+ visualize_and_save_motions(
+ config=config,
+ cond=viz_cond,
+ samples=chain,
+ save_dir=output_dir,
+ prefix=f'rep_{rep_i}',
+ case_ids=[case_id],
+ only_save_motion=args.only_save_motion,
+ save_ric=args.save_ric,
+ )
+
+ npy_name = f'{case_id}-rep_{rep_i}-0.npy'
+ captions_map[npy_name] = joined_caption
+ with open(captions_path, 'w') as f:
+ json.dump(captions_map, f, indent=2, ensure_ascii=False)
+
+ del cond, cond_per_segment, chain
+ _release_gpu()
+
+
+# ---------------------------------------------------------------------------
+# Entry point
+# ---------------------------------------------------------------------------
+
+
+def main(args: InferenceArgs):
+ # Read config first so CLI-omitted fields can fall back to the saved
+ # ``sampling`` block (mirrors the cfg_scale fallback below).
+ config_path = os.path.join(args.exp_dir, "config.json")
+ if not os.path.isfile(config_path):
+ raise FileNotFoundError(f"No config.json in {args.exp_dir!r}")
+ config = MainConfig.from_json(config_path)
+
+ model_path_arg = args.model_path or config.sampling.model_path
+ config_path, model_path = _resolve_exp_paths(args.exp_dir, model_path_arg)
+ logger.info(f"Using config: [{config_path}]")
+ logger.info(f"Using checkpoint: [{model_path}]")
+
+ cfg_scale = args.cfg_scale if args.cfg_scale is not None else config.sampling.cfg_scale
+ _validate_cfg_inputs(cfg_scale, args)
+
+ base_output = args.output_dir or os.path.join(args.exp_dir, "samples")
+ # Inbetween / motion-edit / motion-expand write to a sibling subdir so
+ # GT/output pairs don't collide with vanilla sampling artifacts from
+ # the same exp_dir.
+ if args.inbetween:
+ output_dir = os.path.join(base_output, "inbetween")
+ elif args.motion_edit:
+ output_dir = os.path.join(base_output, "motion_edit")
+ elif args.motion_expand:
+ output_dir = os.path.join(base_output, "motion_expand")
+ else:
+ output_dir = base_output
+ os.makedirs(output_dir, exist_ok=True)
+
+ if args.inbetween:
+ keep_indices = parse_keep_frames(args.keep_frames)
+ ledger_path = os.path.join(output_dir, "inbetween_keep.json")
+ with open(ledger_path, "w") as f:
+ json.dump({"keep_frames": keep_indices}, f, indent=2)
+ elif args.motion_edit:
+ # Record the user-supplied names; the actual per-skeleton matches
+ # (and any misses) are logged by build_joint_keep_mask at run time.
+ keep_names = parse_keep_joints(args.keep_joints)
+ ledger_path = os.path.join(output_dir, "motion_edit_keep.json")
+ with open(ledger_path, "w") as f:
+ json.dump({"keep_joints": keep_names}, f, indent=2)
+ elif args.motion_expand:
+ ledger_path = os.path.join(output_dir, "motion_expand.json")
+ with open(ledger_path, "w") as f:
+ json.dump({"expand_overlap": args.expand_overlap}, f, indent=2)
+
+ if args.seed is not None:
+ set_seed(args.seed)
+ logger.info(f"Set random seed to [{args.seed}]")
+
+ target_object_types, target_clip_stems = _resolve_inference_scope(args)
+ stats_path = _resolve_stats_path(args.exp_dir)
+
+ dataset = create_dataset(
+ dataset_config=config.dataset,
+ model_config=config.model,
+ inference=True,
+ target_object_types=target_object_types,
+ target_clip_stems=target_clip_stems,
+ stats_path=stats_path,
+ )
+
+ logger.info("Creating model and diffusion...")
+ model = create_model(
+ dataset_config=config.dataset,
+ model_config=config.model,
+ )
+ diffusion, gen_diffusion = _build_diffusion(config)
+
+ logger.info(f"Loading checkpoints from [{model_path}]...")
+ _load_checkpoint(model, model_path, config)
+
+ device = torch.device(config.sampling.device)
+
+ # Encode test cases before moving the diffusion model to device, so the
+ # text encoder and diffusion model don't coexist on GPU. Motion-expand
+ # has a distinct test-case structure (per-case prompt lists), so it
+ # uses its own loader + runner.
+ if args.motion_expand:
+ expand_cases = _load_expand_test_cases(
+ args.test_cases_json, config, dataset, device,
+ )
+ test_cases = None
+ else:
+ expand_cases = None
+ test_cases = _select_test_cases(
+ args, cfg_scale, config, dataset, device,
+ resolve_clip=args.inbetween or args.motion_edit,
+ )
+
+ model.to(device)
+ model.eval()
+
+ logger.info(f"Using cfg_scale={cfg_scale}")
+ sample_model = _wrap_for_cfg(model, cfg_scale)
+
+ if args.motion_expand:
+ _run_expansion_sampling(
+ config=config,
+ sample_model=sample_model,
+ dataset=dataset,
+ expand_cases=expand_cases,
+ diffusion=diffusion,
+ gen_diffusion=gen_diffusion,
+ cfg_scale=cfg_scale,
+ device=device,
+ args=args,
+ output_dir=output_dir,
+ )
+ else:
+ _run_sampling(
+ config=config,
+ sample_model=sample_model,
+ dataset=dataset,
+ test_cases=test_cases,
+ diffusion=diffusion,
+ gen_diffusion=gen_diffusion,
+ cfg_scale=cfg_scale,
+ device=device,
+ args=args,
+ output_dir=output_dir,
+ )
+
+
+if __name__ == "__main__":
+ main(tyro.cli(InferenceArgs))
diff --git a/unimate/models/__init__.py b/unimate/models/__init__.py
new file mode 100644
index 0000000..9b7a055
--- /dev/null
+++ b/unimate/models/__init__.py
@@ -0,0 +1 @@
+"""Denoising models, generation schedules, and text encoders."""
diff --git a/unimate/models/denoiser/__init__.py b/unimate/models/denoiser/__init__.py
new file mode 100644
index 0000000..5e99cf0
--- /dev/null
+++ b/unimate/models/denoiser/__init__.py
@@ -0,0 +1,34 @@
+"""Denoising backbones โ€” topology-agnostic motion transformers.
+
+One class per point on the two orthogonal axes the config exposes,
+``model.attention`` x ``model.text_cond``; the module names spell out the
+pair, and :mod:`unimate.models.factory` is what maps a config onto them:
+
+=================== ========================== ==================
+attention/text_cond module class
+=================== ========================== ==================
+``full``/``adaln`` :mod:`.full_adaln` UniMateFullAdaLN
+``full``/``cross`` :mod:`.full_cross_attn` UniMateFullCrossAttn
+``graph``/``adaln`` :mod:`.graph_adaln` UniMateGraphAdaLN
+``graph``/``cross`` :mod:`.graph_cross_attn` UniMateGraphCrossAttn
+=================== ========================== ==================
+
+All four subclass :class:`~.base.UniMateDenoiserBase`, which owns everything
+the axes do not touch: config, conditioning embedders, adaLN-Zero init and
+classifier-free-guidance masking. The attention blocks they assemble live in
+:mod:`.blocks`, positional encodings in :mod:`.rope`.
+"""
+
+from unimate.models.denoiser.base import UniMateDenoiserBase
+from unimate.models.denoiser.full_adaln import UniMateFullAdaLN
+from unimate.models.denoiser.full_cross_attn import UniMateFullCrossAttn
+from unimate.models.denoiser.graph_adaln import UniMateGraphAdaLN
+from unimate.models.denoiser.graph_cross_attn import UniMateGraphCrossAttn
+
+__all__ = [
+ "UniMateDenoiserBase",
+ "UniMateFullAdaLN",
+ "UniMateFullCrossAttn",
+ "UniMateGraphAdaLN",
+ "UniMateGraphCrossAttn",
+]
diff --git a/unimate/models/denoiser/base.py b/unimate/models/denoiser/base.py
new file mode 100644
index 0000000..ef538ea
--- /dev/null
+++ b/unimate/models/denoiser/base.py
@@ -0,0 +1,394 @@
+"""Shared base class for the denoiser variants.
+
+The four variants differ only along the two config axes โ€” ``attention``
+(full flattened vs. factored spatio-temporal) and ``text_cond`` (adaLN vs. a
+cross-attention stage). Everything else โ€” configuration, conditioning
+embedders, optional token embeddings, adaLN-Zero weight init, CFG masking โ€”
+is identical and lives here.
+
+Subclass contract (order matters so a fixed seed reproduces identical
+initial weights):
+
+1. ``super().__init__(...)`` โ€” stashes config and builds the shared
+ embedders (cond / timestep / input layer / tpos pool / joint-name /
+ graph / depth).
+2. Build positional-encoding modules (``_build_axis_ropes`` for the
+ factored variants) and ``self.transformer_blocks``.
+3. ``self._finish_build()`` โ€” builds ``self.final_layer`` and runs
+ ``initialize_weights``.
+"""
+
+import torch
+import torch.nn as nn
+
+from torch_geometric.nn import GCNConv
+
+from unimate.models.denoiser.blocks import (
+ TimestepEmbedder,
+ InputLayer,
+ FinalLayer,
+ TposPool,
+)
+from unimate.models.denoiser.rope import RopeND, SpectralJointRoPE
+
+
+class UniMateDenoiserBase(nn.Module):
+ """Configuration, conditioning, and initialization shared by all UniMate variants."""
+
+ #: Subclasses that feed the caption in as cross-attention K/V set this,
+ #: so the base only builds the parts that variant actually uses.
+ uses_text_cross = False
+
+ def __init__(
+ self,
+ feature_len,
+ max_motion_length=60,
+ max_joints=24,
+ max_depth=0,
+ latent_dim=256,
+ ff_size=1024,
+ num_layers=4,
+ num_heads=4,
+ dropout=0.0,
+ use_spectral_rope=False,
+ max_freqs=8,
+ use_signnet=True,
+ cond_mode='no_cond',
+ cond_mask_prob=0.0,
+ text_dim=512,
+ use_joint_name_emb=False,
+ use_graph_emb=False,
+ use_depth_emb=False,
+ concat_parent_features=False,
+ num_tpos_queries=0,
+ inject_tpos_to_adaln=False,
+ ):
+ super().__init__()
+
+ self.max_motion_length = max_motion_length
+ self.max_joints = max_joints
+ self.feature_len = feature_len
+ self.latent_dim = latent_dim
+ self.ff_size = ff_size
+ self.num_layers = num_layers
+ self.num_heads = num_heads
+ self.dropout = dropout
+
+ self.text_dim = text_dim
+ self.cond_mode = cond_mode
+ self.cond_mask_prob = cond_mask_prob
+
+ self.use_spectral_rope = use_spectral_rope
+ self.max_freqs = max_freqs
+ self.use_signnet = use_signnet
+
+ self.use_joint_name_emb = use_joint_name_emb
+ self.use_graph_emb = use_graph_emb
+ self.use_depth_emb = use_depth_emb
+ self.concat_parent_features = concat_parent_features
+ self.num_tpos_queries = num_tpos_queries
+ self.inject_tpos_to_adaln = inject_tpos_to_adaln
+ # One conditioning frame (tpos / first-frame tokens) prepended to the
+ # temporal axis; stripped again after the final layer.
+ self.n_prefix = 1
+
+ # Caption embedding โ†’ latent (text mode) or identity (no_cond).
+ if self.cond_mode == 'text':
+ self.cond_embedder = nn.Linear(self.text_dim, self.latent_dim)
+ # Learnable unconditional caption โ€” only for variants that route
+ # text through cross-attention. Creating it unconditionally would
+ # leave the adaLN variants with a parameter that never receives a
+ # gradient, which DDP rejects at its default
+ # find_unused_parameters=False.
+ # Zeroing the text memory instead would leave attention with
+ # softmax(qยท0) over an all-zero V โ€” the value bias, one constant
+ # with no capacity โ€” so the unconditional branch that CFG
+ # extrapolates from could not be shaped at all. PixArt-alpha's
+ # CaptionEmbedder carries the same idea (its ``y_embedding`` null
+ # sequence), including this initialisation scale. The adaLN path
+ # keeps zeroing its vector: there a zero really is "no signal"
+ # added to the modulation, which is well defined.
+ if self.uses_text_cross:
+ self.null_caption = nn.Parameter(
+ torch.randn(1, 1, self.text_dim) / self.text_dim ** 0.5)
+ elif self.cond_mode == 'no_cond':
+ self.cond_embedder = nn.Identity()
+ else:
+ raise ValueError(f"Unknown cond_mode: {self.cond_mode}")
+
+ # Timestep embedder
+ self.time_embedder = TimestepEmbedder(hidden_size=self.latent_dim)
+
+ # Input layer (root/joint split, MLP encoding)
+ self.input_layer = InputLayer(
+ feature_len=self.feature_len,
+ latent_dim=self.latent_dim,
+ max_joints=self.max_joints,
+ concat_parent_features=self.concat_parent_features,
+ )
+
+ # Tpos pooling โ†’ adaLN conditioning (only instantiated if enabled)
+ if self.inject_tpos_to_adaln:
+ self.tpos_pool = TposPool(self.latent_dim, num_queries=self.num_tpos_queries)
+
+ # Joint name embedding
+ if self.use_joint_name_emb:
+ self.joint_name_embedder = nn.Linear(self.text_dim, self.latent_dim)
+ self.joint_name_dropout = nn.Dropout(self.dropout)
+
+ # Graph embedding
+ if self.use_graph_emb:
+ self.graph_conv = GCNConv(self.latent_dim, self.latent_dim)
+
+ # Kinematic depth embedding
+ if self.use_depth_emb:
+ # max_depth is auto-computed from data; fallback to max_joints if not provided
+ self.max_depth = max_depth if max_depth > 0 else max_joints
+ self.depth_embedding = nn.Embedding(self.max_depth + 1, self.latent_dim)
+
+ # ------------------------------------------------------------------
+ # Construction helpers (called from subclass __init__)
+ # ------------------------------------------------------------------
+
+ def _build_axis_ropes(self):
+ """Per-axis RoPE for the factored (Graph / Cross) variants.
+
+ Spatial (joint) axis: spectral RoPE when ``use_spectral_rope``,
+ otherwise 1D sinusoidal with integer joint indices. Temporal axis:
+ always sinusoidal. Position-id buffers are non-persistent (they are
+ pure index tables).
+ """
+ head_dim = self.latent_dim // self.num_heads
+ max_frames = self.max_motion_length + self.n_prefix
+
+ if self.use_spectral_rope:
+ self.rope_j = SpectralJointRoPE(
+ head_dim=head_dim,
+ num_eigvecs=self.max_freqs,
+ use_signnet=self.use_signnet,
+ )
+ else:
+ self.rope_j = RopeND(
+ head_dim=head_dim, nd=1, nd_split=[1], max_lens=[self.max_joints],
+ )
+ self.register_buffer(
+ 'spatial_position_ids',
+ torch.arange(self.max_joints).unsqueeze(0),
+ persistent=False,
+ )
+
+ self.rope_t = RopeND(
+ head_dim=head_dim, nd=1, nd_split=[1], max_lens=[max_frames],
+ )
+ self.register_buffer(
+ 'temporal_position_ids',
+ torch.arange(max_frames).unsqueeze(0),
+ persistent=False,
+ )
+
+ def _finish_build(self):
+ """Build the output layer and initialize weights. Call last in __init__."""
+ self.final_layer = FinalLayer(
+ hidden_size=self.latent_dim, output_size=self.feature_len,
+ joint=self.max_joints,
+ )
+ self.initialize_weights()
+
+ # ------------------------------------------------------------------
+ # Weight initialization (adaLN-Zero)
+ # ------------------------------------------------------------------
+
+ def initialize_weights(self):
+ def _basic_init(module):
+ if isinstance(module, nn.Linear):
+ torch.nn.init.xavier_uniform_(module.weight)
+ if module.bias is not None:
+ nn.init.constant_(module.bias, 0)
+
+ self.apply(_basic_init)
+
+ # Initialize timestep embedding MLP:
+ nn.init.normal_(self.time_embedder.mlp[0].weight, std=0.02)
+ nn.init.normal_(self.time_embedder.mlp[2].weight, std=0.02)
+
+ # Caption projection: the same std=0.02 normal DiT and PixArt-alpha
+ # give their conditioning embedders, rather than the xavier default
+ # _basic_init would leave (0.0395 for 768->512, twice the variance).
+ # An embedding projection sets how loud the conditioning signal is
+ # relative to the backbone's activations at step 0, which matters most
+ # for text_cond='cross_attn' where it feeds the attention K/V directly.
+ if self.cond_mode == 'text':
+ nn.init.normal_(self.cond_embedder.weight, std=0.02)
+ nn.init.constant_(self.cond_embedder.bias, 0)
+
+ # Zero-out adaLN modulation layers in UniMate blocks:
+ for block in self.transformer_blocks:
+ nn.init.constant_(block.adaLN_modulation[-1].weight, 0)
+ nn.init.constant_(block.adaLN_modulation[-1].bias, 0)
+
+ # Zero-out output layers:
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)
+ nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)
+ for out_mlp in [self.final_layer.root_out, self.final_layer.joint_out]:
+ nn.init.constant_(out_mlp[-1].weight, 0)
+ nn.init.constant_(out_mlp[-1].bias, 0)
+ # Zero-init cross-attention output so residual starts as identity
+ nn.init.constant_(self.final_layer.root_cross_attn.out_proj.weight, 0)
+ nn.init.constant_(self.final_layer.root_cross_attn.out_proj.bias, 0)
+
+ # Zero-init the tpos cross-attention pool's output projection so its
+ # contribution to the adaLN driver `y` starts at zero โ€” same adaLN-Zero
+ # pattern used for adaLN_modulation / final-layer outputs above. Without
+ # this, randomly-initialized tpos_pool feeds noise into y from step 0,
+ # destabilizing the adaLN modulation magnitudes.
+ if self.inject_tpos_to_adaln and self.num_tpos_queries > 0:
+ nn.init.constant_(self.tpos_pool.pool.out_proj.weight, 0)
+ nn.init.constant_(self.tpos_pool.pool.out_proj.bias, 0)
+
+ # ------------------------------------------------------------------
+ # Shared forward pieces
+ # ------------------------------------------------------------------
+
+ def _caption_vector(self, bs, cond, dtype, device, force_mask):
+ """CFG-masked caption embedding vector (pre ``cond_embedder``).
+
+ Returns ``(B, text_dim)`` in text mode (zeros when the batch has no
+ captions) or ``(B, latent_dim)`` zeros in no_cond mode โ€” matching
+ what ``cond_embedder`` (Linear vs. Identity) expects.
+ """
+ if self.cond_mode == 'text':
+ # Missing key โ†’ whole batch had no captions; treat as unconditional.
+ cond_vector = cond.get('caption_emb')
+ if cond_vector is None:
+ cond_vector = torch.zeros(bs, self.text_dim, dtype=dtype, device=device)
+ else: # 'no_cond' (validated in __init__)
+ cond_vector = torch.zeros(bs, self.latent_dim, dtype=dtype, device=device)
+ return self.mask_cond(cond_vector, force_mask=force_mask)
+
+ def _caption_tokens(self, bs, cond, dtype, device, force_mask):
+ """CFG-masked caption token sequence + validity mask for cross-attn.
+
+ Returns ``((B, T, text_dim), (B, T) bool)``. A CFG-dropped sample gets
+ the learnable null caption as a one-token memory; its mask keeps only
+ that position, so no row is ever fully masked (which would make
+ scaled_dot_product_attention return NaN).
+ """
+ tokens = cond.get('caption_tokens') if self.cond_mode == 'text' else None
+ if tokens is None and self.cond_mode == 'text':
+ # A caller that only produced the pooled vector (the inference
+ # paths encode one prompt at a time) still conditions the model,
+ # as a one-token memory. Falling through to zeros here would make
+ # cross-attention silently unconditional.
+ pooled = cond.get('caption_emb')
+ if pooled is not None:
+ tokens = pooled.unsqueeze(1) # (B, 1, D)
+ if tokens is None:
+ # no_cond, or a text batch with no captions at all. In text mode
+ # the null caption is the unconditional representation the model
+ # was trained on, so use it rather than zeros โ€” and referencing it
+ # here keeps it in the graph on this path too.
+ if self.cond_mode == 'text':
+ tokens = self.null_caption.to(dtype).expand(bs, 1, -1)
+ else:
+ tokens = torch.zeros(bs, 1, self.text_dim, dtype=dtype, device=device)
+ return tokens, torch.ones(bs, 1, dtype=torch.bool, device=device)
+
+ tokens = tokens.to(dtype)
+ mask = cond.get('caption_mask')
+ if mask is None:
+ mask = torch.ones(tokens.shape[:2], dtype=torch.bool, device=tokens.device)
+
+ # Same dropout decision as ``mask_cond``, but a dropped sample is
+ # replaced by the learnable null caption rather than zeroed: its memory
+ # becomes that single token, and its mask attends only that position.
+ # Every row keeps one attendable position, so SDPA never sees a fully
+ # masked row (which returns NaN).
+ if force_mask:
+ drop = torch.ones(tokens.shape[0], dtype=torch.bool, device=tokens.device)
+ elif self.training and self.cond_mask_prob > 0.:
+ drop = torch.bernoulli(
+ torch.ones(tokens.shape[0], device=tokens.device) * self.cond_mask_prob
+ ).to(torch.bool)
+ else:
+ drop = None
+
+ if drop is not None:
+ # torch.where rather than indexing the dropped rows: it keeps
+ # null_caption in the graph for every sample, so the parameter
+ # still receives a (zero) gradient on steps where nothing was
+ # dropped. Indexing would leave it unused on those steps, and DDP
+ # at its default find_unused_parameters=False errors out on that.
+ # PixArt-alpha's CaptionEmbedder.token_drop does the same.
+ null = self.null_caption.to(dtype).expand(tokens.shape[0], 1, -1)
+ head = torch.where(drop[:, None, None], null, tokens[:, :1])
+ tokens = torch.cat([head, tokens[:, 1:]], dim=1)
+ only_first = torch.zeros_like(mask)
+ only_first[:, 0] = True
+ mask = torch.where(drop[:, None], only_first, mask)
+ return tokens, mask
+
+ def _build_adaln_y(self, x, timesteps, cond, force_mask):
+ """adaLN driver ``y = timestep_emb + caption_emb`` (``text_cond='adaln'``)."""
+ timesteps_emb = self.time_embedder(timesteps, dtype=x.dtype) # (B, latent_dim)
+ cond_vector = self._caption_vector(
+ x.shape[0], cond, x.dtype, x.device, force_mask,
+ )
+ return timesteps_emb + self.cond_embedder(cond_vector) # (B, latent_dim)
+
+ def _apply_token_embeddings(self, x, cond):
+ """Add the optional graph / depth / joint-name embeddings to the tokens.
+
+ Args:
+ x: (B, F+1, J, latent_dim) embedded tokens (tpos frame prepended).
+ cond: conditioning dict.
+ """
+ device = x.device
+
+ # Graph embedding (per-sample GCN over the skeleton edges)
+ if self.use_graph_emb:
+ x_graph_emb = []
+ for i in range(x.shape[0]):
+ edge_index = cond['edge_indexs'][i].to(device) # [2, E]
+ x_graph_emb.append(self.graph_conv(x[i], edge_index)) # (F+1, J, D)
+ x = x + torch.stack(x_graph_emb, dim=0) # (B, F+1, J, latent_dim)
+
+ # Kinematic depth embedding
+ if self.use_depth_emb:
+ joint_depths = cond['joint_depths'].long().clamp(max=self.max_depth) # (B, J)
+ depth_emb = self.depth_embedding(joint_depths) # (B, J, latent_dim)
+ x = x + depth_emb.unsqueeze(1) # (B, F+1, J, latent_dim)
+
+ # Joint name embedding
+ if self.use_joint_name_emb:
+ joint_names_emb = cond['joint_names_emb'] # (B, J, text_dim)
+ joint_name_embedded = self.joint_name_dropout(
+ self.joint_name_embedder(joint_names_emb)
+ ) # (B, J, latent_dim)
+ x = x + joint_name_embedded.unsqueeze(1) # (B, F+1, J, latent_dim)
+
+ return x
+
+ def _spatial_position_ids(self, njoints):
+ """Spatial position ids for the factored variants (None when spectral
+ RoPE pulls its coordinates from ``cond['spectral_feats']`` instead)."""
+ if self.use_spectral_rope:
+ return None
+ return self.spatial_position_ids[:, :njoints]
+
+ def mask_cond(self, cond, force_mask=False):
+ """Classifier-free-guidance dropout of the conditioning vector."""
+ bs, d = cond.shape
+ if force_mask:
+ return torch.zeros_like(cond)
+ elif self.training and self.cond_mask_prob > 0.:
+ mask = torch.bernoulli(
+ torch.ones(bs, device=cond.device) * self.cond_mask_prob
+ ).view(bs, 1)
+ return cond * (1. - mask)
+ else:
+ return cond
+
+ @staticmethod
+ def lengths_to_mask(lengths, max_len):
+ return torch.arange(max_len, device=lengths.device).expand(
+ len(lengths), max_len) < lengths.unsqueeze(1)
diff --git a/unimate/models/denoiser/blocks/__init__.py b/unimate/models/denoiser/blocks/__init__.py
new file mode 100644
index 0000000..fd2bbe0
--- /dev/null
+++ b/unimate/models/denoiser/blocks/__init__.py
@@ -0,0 +1,19 @@
+"""Transformer blocks and layers the denoiser variants are built from.
+
+* :mod:`.common` โ€” pieces every variant shares (norms, SwiGLU FFN, adaLN
+ ``modulate``, timestep embedder, input/final layers, tpos pool) plus the
+ full-attention blocks ``DiTBlock`` / ``DiTCrossBlock``.
+* :mod:`.graph` โ€” factored spatial (graph-biased, per-frame) + temporal
+ (per-joint) attention and the ``SpatioTemporalBlock`` around them.
+* :mod:`.cross` โ€” text cross-attention, and the factored block that adds a
+ cross stage.
+
+Everything in ``common`` is re-exported here, so
+``from unimate.models.denoiser import blocks`` is enough for the shared
+pieces; the two attention families are imported from their own modules.
+"""
+
+from unimate.models.denoiser.blocks.common import * # noqa: F401,F403
+from unimate.models.denoiser.blocks.common import __all__ as _common_all
+
+__all__ = list(_common_all)
diff --git a/unimate/models/denoiser/blocks/common.py b/unimate/models/denoiser/blocks/common.py
new file mode 100644
index 0000000..49b4125
--- /dev/null
+++ b/unimate/models/denoiser/blocks/common.py
@@ -0,0 +1,542 @@
+"""Layers and blocks shared by every denoiser variant.
+
+- Primitives: ``modulate`` (adaLN), ``LlamaRMSNorm``, ``SwiGLUFFN``
+- Embedders: ``TimestepEmbedder``, ``InputLayer``, ``TposPool`` /
+ ``TposCrossAttentionPool``
+- Full attention: ``RoPEAttention``, ``DiTBlock`` (adaLN only) and
+ ``DiTCrossBlock`` (adaLN + a text cross-attention stage) โ€” the two blocks
+ the ``attention='full'`` variants stack
+- Output: ``FinalLayer``
+
+The factored (``attention='graph'``) attention lives in
+:mod:`unimate.models.denoiser.blocks.graph`, text cross-attention in
+:mod:`unimate.models.denoiser.blocks.cross`, and the variant classes that
+assemble all of this in :mod:`unimate.models.denoiser`.
+"""
+
+import math
+
+import einops
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from unimate.models.denoiser.rope import GraphRoPE
+
+__all__ = [
+ "modulate",
+ "LlamaRMSNorm",
+ "SwiGLUFFN",
+ "TimestepEmbedder",
+ "TposCrossAttentionPool",
+ "TposPool",
+ "InputLayer",
+ "RoPEAttention",
+ "DiTBlock",
+ "DiTCrossBlock",
+ "FinalLayer",
+]
+
+
+
+# ---------------------------------------------------------------------------
+# Primitives
+# ---------------------------------------------------------------------------
+
+def modulate(x, shift, scale):
+ return x * (1 + scale) + shift
+
+
+class LlamaRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6, **kwargs):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return (self.weight * hidden_states).to(input_dtype)
+
+
+class SwiGLUFFN(nn.Module):
+ def __init__(self, in_features: int, hidden_features, bias: bool = True) -> None:
+ super().__init__()
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
+ self.w3 = nn.Linear(hidden_features, in_features, bias=bias)
+
+ def forward(self, x):
+ x12 = self.w12(x)
+ x1, x2 = x12.chunk(2, dim=-1)
+ hidden = F.silu(x1) * x2
+ return self.w3(hidden)
+
+
+# ---------------------------------------------------------------------------
+# Embedders
+# ---------------------------------------------------------------------------
+
+class TimestepEmbedder(nn.Module):
+ def __init__(self, hidden_size, frequency_embedding_size=256):
+ super().__init__()
+ self.mlp = nn.Sequential(
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
+ nn.SiLU(),
+ nn.Linear(hidden_size, hidden_size, bias=True),
+ )
+ self.frequency_embedding_size = frequency_embedding_size
+
+ @staticmethod
+ def timestep_embedding(t, dim, max_period=10000, dtype=torch.float32):
+ half = dim // 2
+ freqs = torch.exp(
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=dtype) / half
+ ).to(device=t.device, dtype=dtype)
+ args = t[:, None] * freqs[None]
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ if dim % 2:
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
+ return embedding
+
+ def forward(self, t, dtype=torch.bfloat16):
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size, dtype=dtype)
+ t_emb = self.mlp(t_freq)
+ return t_emb
+
+
+class TposCrossAttentionPool(nn.Module):
+ """PMA-style attention pool (Set Transformer / Perceiver Resampler).
+
+ K learnable queries cross-attend to per-joint tpos embeddings, with
+ residual + FFN (both pre-LN), then reduce K queries to one (B, D)
+ vector via mean + RMSNorm + linear projection.
+
+ Design notes:
+ * Residual on the cross-attention output keeps a gradient shortcut so
+ the queries cannot drift wholesale away from initialization.
+ * A post-attention SwiGLU FFN with its own residual gives the standard
+ "attention + FFN" representational power.
+ * The K โ†’ 1 reduction is mean(K) followed by Linear(D โ†’ D) rather than
+ Linear(KยทD โ†’ D), which keeps the parameter count independent of K
+ and bounds the output magnitude.
+ * A final RMSNorm before the projection caps the magnitude flowing
+ into the adaLN driver ``y``.
+ """
+
+ def __init__(self, latent_dim, num_queries=4, num_heads=4, mlp_ratio=2.0):
+ super().__init__()
+ self.num_queries = num_queries
+ self.queries = nn.Parameter(torch.randn(1, num_queries, latent_dim) * 0.02)
+
+ # Cross-attention block (pre-LN + residual).
+ self.norm_q = LlamaRMSNorm(latent_dim, eps=1e-6)
+ self.norm_kv = LlamaRMSNorm(latent_dim, eps=1e-6)
+ self.cross_attn = nn.MultiheadAttention(
+ embed_dim=latent_dim, num_heads=num_heads, batch_first=True,
+ )
+
+ # FFN block (pre-LN + residual).
+ self.norm_ff = LlamaRMSNorm(latent_dim, eps=1e-6)
+ self.ffn = SwiGLUFFN(latent_dim, int(latent_dim * mlp_ratio))
+
+ # K โ†’ 1 reduction (mean across queries, then norm + project).
+ self.norm_out = LlamaRMSNorm(latent_dim, eps=1e-6)
+ self.out_proj = nn.Linear(latent_dim, latent_dim)
+
+ def forward(self, tpos_emb, joints_valid):
+ """
+ Args:
+ tpos_emb: (B, J, latent_dim) per-joint tpos embeddings.
+ joints_valid: (B, J) boolean mask (True = valid joint).
+ Returns:
+ (B, latent_dim) pooled conditioning vector.
+ """
+ B = tpos_emb.shape[0]
+ q = self.queries.expand(B, -1, -1) # (B, K, D)
+
+ # Cross-attention with residual. K/V padding handled via PyTorch's
+ # key_padding_mask (True = ignore). Queries are not padded.
+ key_padding_mask = ~joints_valid # (B, J)
+ kv = self.norm_kv(tpos_emb)
+ attn_out, _ = self.cross_attn(
+ self.norm_q(q), kv, kv, key_padding_mask=key_padding_mask,
+ )
+ q = q + attn_out # (B, K, D)
+
+ # FFN with residual.
+ q = q + self.ffn(self.norm_ff(q)) # (B, K, D)
+
+ # Reduce K โ†’ 1: mean is magnitude-bounded; out_proj is zero-inited
+ # by ``UniMateDenoiserBase.initialize_weights`` so its contribution to ``y`` starts
+ # at zero (adaLN-Zero pattern).
+ pooled = q.mean(dim=1) # (B, D)
+ return self.out_proj(self.norm_out(pooled)) # (B, D)
+
+
+class TposPool(nn.Module):
+ """Pools per-joint tpos embeddings into a single (B, latent_dim) vector.
+
+ num_queries == 0 -> masked mean-pool + linear projection.
+ num_queries > 0 -> cross-attention with K learnable queries.
+ """
+
+ def __init__(self, latent_dim, num_queries=0):
+ super().__init__()
+ self.num_queries = num_queries
+ if num_queries > 0:
+ self.pool = TposCrossAttentionPool(latent_dim, num_queries=num_queries)
+ else:
+ self.proj = nn.Linear(latent_dim, latent_dim)
+
+ def forward(self, tpos_emb, joints_valid):
+ """
+ Args:
+ tpos_emb: (B, J, latent_dim) per-joint tpos embeddings.
+ joints_valid: (B, J) boolean mask (True = valid joint).
+ Returns:
+ (B, latent_dim)
+ """
+ if self.num_queries > 0:
+ return self.pool(tpos_emb, joints_valid)
+ mask = joints_valid.unsqueeze(-1).to(tpos_emb.dtype) # (B, J, 1)
+ token_count = mask.sum(dim=1).clamp(min=1) # (B, 1)
+ pooled = (tpos_emb * mask).sum(dim=1) / token_count # (B, latent_dim)
+ return self.proj(pooled)
+
+
+class InputLayer(nn.Module):
+ """Encodes raw motion and tpos features into latent tokens.
+
+ Handles root/joint separation (root = joint index 0 with global motion,
+ others = local rotations), 2-layer MLP encoding, and tpos+motion
+ concatenation. Tpos pooling (for adaLN conditioning) is handled
+ externally by the optional ``TposPool`` module.
+
+ Args:
+ feature_len: Per-joint feature dimension (12 for the UniMate representation).
+ latent_dim: Transformer hidden dimension.
+ max_joints: Maximum number of joints (for padding / masking).
+ concat_parent_features: If True, non-root joint tpos input is concatenated
+ with parent joint features (2*D input dim). Root joint is unaffected.
+ """
+
+ def __init__(self, feature_len, latent_dim, max_joints,
+ concat_parent_features=False):
+ super().__init__()
+ self.max_joints = max_joints
+ self.concat_parent_features = concat_parent_features
+
+ # Root embedders always take D features (root has no meaningful parent)
+ self.root_tpos_embedder = nn.Sequential(
+ nn.Linear(feature_len, latent_dim), nn.SiLU(), nn.Linear(latent_dim, latent_dim)
+ )
+ self.root_x_embedder = nn.Sequential(
+ nn.Linear(feature_len, latent_dim), nn.SiLU(), nn.Linear(latent_dim, latent_dim)
+ )
+ # Non-root joint embedders
+ self.joint_tpos_embedder = nn.Sequential(
+ nn.Linear(feature_len, latent_dim), nn.SiLU(), nn.Linear(latent_dim, latent_dim)
+ )
+ if concat_parent_features:
+ self.parent_tpos_embedder = nn.Sequential(
+ nn.Linear(feature_len, latent_dim), nn.SiLU(), nn.Linear(latent_dim, latent_dim)
+ )
+ self.tpos_fuse = nn.Sequential(
+ nn.Linear(latent_dim * 2, latent_dim), nn.SiLU(), nn.Linear(latent_dim, latent_dim)
+ )
+ self.joint_x_embedder = nn.Sequential(
+ nn.Linear(feature_len, latent_dim), nn.SiLU(), nn.Linear(latent_dim, latent_dim)
+ )
+
+ def forward(self, x, cond):
+ """
+ Args:
+ x: (B, J, D, F) raw motion tensor.
+ cond: dict with 'tpos_first_frame', 'n_joints',
+ optionally 'tpos_first_frame_parents'.
+
+ Returns:
+ x: (B, F+1, J, latent_dim) embedded tokens (tpos frame prepended).
+ tpos_emb: (B, J, latent_dim) per-joint tpos embeddings (pre-prepend).
+ joints_valid: (B, J) boolean validity mask.
+ """
+ device = x.device
+
+ # --- Tpos encoding ---
+ tpos = cond['tpos_first_frame'].to(device) # (B, J, D)
+ tpos = einops.rearrange(tpos, 'b j d -> b 1 j d') # (B, 1, J, D)
+
+ tpos_root = self.root_tpos_embedder(tpos[:, :, :1, :]) # (B, 1, 1, latent_dim)
+ tpos_joint_proj = self.joint_tpos_embedder(tpos[:, :, 1:, :]) # (B, 1, J-1, latent_dim)
+ if self.concat_parent_features:
+ tpos_parents = cond['tpos_first_frame_parents'].to(device) # (B, J, D)
+ tpos_parents = einops.rearrange(tpos_parents, 'b j d -> b 1 j d')
+ tpos_parent_proj = self.parent_tpos_embedder(tpos_parents[:, :, 1:, :]) # (B, 1, J-1, latent_dim)
+ tpos_joints = self.tpos_fuse(torch.cat([tpos_joint_proj, tpos_parent_proj], dim=-1)) # (B, 1, J-1, latent_dim)
+ else:
+ tpos_joints = tpos_joint_proj # (B, 1, J-1, latent_dim)
+ tpos_emb = torch.cat([tpos_root, tpos_joints], dim=2) # (B, 1, J, latent_dim)
+
+ joints_valid = self._lengths_to_mask(cond['n_joints'], self.max_joints) # (B, J)
+
+ # --- Motion encoding ---
+ x = einops.rearrange(x, 'b j d f -> b f j d') # (B, F, J, D)
+ x_root = self.root_x_embedder(x[:, :, :1, :]) # (B, F, 1, latent_dim)
+ x_joints = self.joint_x_embedder(x[:, :, 1:, :]) # (B, F, J-1, latent_dim)
+ x = torch.cat([x_root, x_joints], dim=2) # (B, F, J, latent_dim)
+
+ # --- Prepend conditioning frame ---
+ x = torch.cat([tpos_emb, x], dim=1) # (B, F+1, J, latent_dim)
+ return x, tpos_emb[:, 0], joints_valid
+
+ @staticmethod
+ def _lengths_to_mask(lengths, max_len):
+ return torch.arange(max_len, device=lengths.device).expand(
+ len(lengths), max_len
+ ) < lengths.unsqueeze(1)
+
+
+# ---------------------------------------------------------------------------
+# Attention
+# ---------------------------------------------------------------------------
+
+class RoPEAttention(nn.Module):
+ def __init__(self, dim, num_heads=8, qkv_bias=True, rope=None, qk_norm=True,
+ attn_drop=0., proj_drop=0., **kwargs):
+ super().__init__()
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.rope = rope
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.proj = nn.Linear(dim, dim)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ if qk_norm:
+ self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
+ self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
+ else:
+ self.q_norm = nn.Identity()
+ self.k_norm = nn.Identity()
+
+ def forward(self, x, position_ids=None, attention_mask=None, cond=None,
+ nframes=None):
+ B, N, C = x.shape
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
+ q, k, v = qkv.unbind(0)
+ q, k = self.q_norm(q), self.k_norm(k)
+
+ if self.rope is not None:
+ # GraphRoPE: spectral coords from cond, plus nframes for native (T*J)
+ if isinstance(self.rope, GraphRoPE):
+ spectral_coords = cond['spectral_feats']
+ q, k = self.rope(q, k, spectral_coords, nframes=nframes)
+ else:
+ q, k = self.rope(q, k, position_ids)
+
+ x = F.scaled_dot_product_attention(
+ q, k, v,
+ attn_mask=attention_mask,
+ dropout_p=self.attn_drop.p if self.training else 0.,
+ )
+ x = x.transpose(1, 2).reshape(B, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+
+# ---------------------------------------------------------------------------
+# Transformer blocks
+# ---------------------------------------------------------------------------
+
+class DiTBlock(nn.Module):
+ """Full-attention transformer block with adaLN-Zero modulation.
+ Operates on flattened tokens: x (B, L, D), c (B, D).
+ """
+ def __init__(self, hidden_size, num_heads, mlp_size=1024, rope=None,
+ qk_norm=True, dropout=0.0):
+ super().__init__()
+ self.norm1 = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.attn = RoPEAttention(hidden_size, num_heads=num_heads, qkv_bias=True,
+ qk_norm=qk_norm, rope=rope,
+ attn_drop=dropout, proj_drop=dropout)
+ self.norm2 = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.mlp = SwiGLUFFN(hidden_size, int(2 / 3 * mlp_size))
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(),
+ nn.Linear(hidden_size, 6 * hidden_size, bias=True)
+ )
+
+ def forward(self, x, c, attention_mask=None, position_ids=None, cond=None,
+ nframes=None):
+ dtype = x.dtype
+ # c: (B, D) โ†’ unsqueeze for broadcasting with (B, L, D)
+ c = c.unsqueeze(1) if c.dim() == 2 else c
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=-1)
+ norm_x1 = self.norm1(x.to(torch.float32)).to(dtype)
+ attn_input_x = modulate(norm_x1, shift_msa, scale_msa)
+ attn_output_x = self.attn(attn_input_x, attention_mask=attention_mask,
+ position_ids=position_ids, cond=cond,
+ nframes=nframes)
+ x = x + gate_msa * attn_output_x
+
+ norm_x2 = self.norm2(x.to(torch.float32)).to(dtype)
+ gate_input_x = modulate(norm_x2, shift_mlp, scale_mlp)
+ gate_output_x = self.mlp(gate_input_x)
+ x = x + gate_mlp * gate_output_x
+ return x
+
+
+# ---------------------------------------------------------------------------
+# Output layers
+# ---------------------------------------------------------------------------
+
+class DiTCrossBlock(nn.Module):
+ """Full-attention block with a text cross-attention stage.
+
+ The ``full`` + ``cross_attn`` pairing: one self-attention over the
+ flattened spatio-temporal tokens, then a stage where every token attends
+ the caption's token sequence as K/V, then the MLP.
+
+ Self-attention and the MLP are adaLN-Zero gated; the cross stage is not.
+ It gets its own norm and is added plainly, which is what Wan 2.1 does
+ (its 6 modulation chunks all go to self-attn and the FFN) and what
+ PixArt-alpha does (no norm either). adaLN here is driven by the timestep
+ alone, so a cross gate could only say "how much text at step t" โ€” a
+ freedom neither reference needs, and one that costs 3*d^2 per layer and
+ invites the failure where a zero gate and a zero output projection
+ deadlock each other. The cross branch instead starts silent through a
+ zero-init ``c_attn.proj``, which stays learnable because nothing
+ multiplies its output by zero.
+
+ Operates on flattened tokens: ``x (B, L, D)``, ``c (B, D)``,
+ ``text_mem (B, T, D)``.
+ """
+
+ def __init__(self, hidden_size, num_heads, mlp_size=1024, rope=None,
+ qk_norm=True, dropout=0.0):
+ super().__init__()
+ from unimate.models.denoiser.blocks.cross import TextCrossAttention
+ self.norm1 = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.attn = RoPEAttention(hidden_size, num_heads=num_heads,
+ qkv_bias=True, qk_norm=qk_norm, rope=rope,
+ attn_drop=dropout, proj_drop=dropout)
+ self.norm_c = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.c_attn = TextCrossAttention(hidden_size, num_heads=num_heads,
+ qkv_bias=True, qk_norm=qk_norm,
+ attn_drop=dropout, proj_drop=dropout)
+ self.norm2 = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.mlp = SwiGLUFFN(hidden_size, int(2 / 3 * mlp_size))
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(),
+ nn.Linear(hidden_size, 6 * hidden_size, bias=True)
+ )
+
+ def forward(self, x, c, text_mem, attention_mask=None, text_mask=None,
+ position_ids=None, cond=None, nframes=None):
+ dtype = x.dtype
+ c = c.unsqueeze(1) if c.dim() == 2 else c
+ (shift_msa, scale_msa, gate_msa,
+ shift_mlp, scale_mlp, gate_mlp) = self.adaLN_modulation(c).chunk(6, dim=-1)
+
+ h = modulate(self.norm1(x.to(torch.float32)).to(dtype), shift_msa, scale_msa)
+ x = x + gate_msa * self.attn(h, attention_mask=attention_mask,
+ position_ids=position_ids, cond=cond,
+ nframes=nframes)
+
+ # TextCrossAttention works on (B, Fr, J, D); the flattened token axis
+ # is fed as a single "frame" so the same module serves both variants.
+ h = self.norm_c(x.to(torch.float32)).to(dtype)
+ x = x + self.c_attn(h.unsqueeze(2), text_mem, text_mask=text_mask).squeeze(2)
+
+ h = modulate(self.norm2(x.to(torch.float32)).to(dtype), shift_mlp, scale_mlp)
+ x = x + gate_mlp * self.mlp(h)
+ return x
+
+
+class FinalLayer(nn.Module):
+ """Output projection shared by all UniMate variants.
+ Accepts x as (B, F, J, D) or (B, F*J, D) and outputs (B, D_out, F, J).
+
+ Mirrors InputLayer's root/joint split: separate 2-layer MLPs for root
+ (global velocity + orientation) and non-root joints (local rotations).
+ Before projection, root tokens aggregate whole-body information from
+ joint tokens via per-frame cross-attention.
+ """
+ def __init__(self, hidden_size, output_size, joint=24, num_heads=4):
+ super().__init__()
+ self.norm_final = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.joint = joint
+
+ # Root aggregation: cross-attention from root (query) to joints (key/value)
+ self.root_cross_attn = nn.MultiheadAttention(
+ embed_dim=hidden_size, num_heads=num_heads, batch_first=True,
+ )
+ self.root_cross_norm_q = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.root_cross_norm_kv = LlamaRMSNorm(hidden_size, eps=1e-6)
+
+ # Separate output heads for root vs non-root joints
+ self.root_out = nn.Sequential(
+ nn.Linear(hidden_size, hidden_size), nn.SiLU(), nn.Linear(hidden_size, output_size),
+ )
+ self.joint_out = nn.Sequential(
+ nn.Linear(hidden_size, hidden_size), nn.SiLU(), nn.Linear(hidden_size, output_size),
+ )
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(),
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True)
+ )
+
+ def forward(self, x, c, joints_valid=None):
+ # c: (B, D)
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=-1)
+
+ if x.dim() == 4:
+ B, Fm, J, D = x.shape
+ x = x.reshape(B, Fm * J, D)
+ elif x.dim() == 3:
+ pass
+ else:
+ raise ValueError("x must be (B,F,J,D) or (B,F*J,D)")
+
+ norm_x = self.norm_final(x.to(torch.float32)).to(x.dtype)
+ shift = shift[:, None, :]
+ scale = scale[:, None, :]
+ x = modulate(norm_x, shift, scale)
+
+ # Unflatten to (B, F, J, D) for root/joint split
+ x = einops.rearrange(x, 'b (f j) d -> b f j d', j=self.joint)
+ B, F, J, D = x.shape
+
+ root_tokens = x[:, :, :1, :] # (B, F, 1, D)
+ joint_tokens = x[:, :, 1:, :] # (B, F, J-1, D)
+
+ # Per-frame cross-attention: root queries joints for whole-body aggregation
+ root_flat = root_tokens.reshape(B * F, 1, D)
+ joints_flat = joint_tokens.reshape(B * F, J - 1, D)
+ # key_padding_mask: True = ignore (PyTorch convention), exclude padding joints
+ if joints_valid is not None:
+ # joints_valid: (B, J) -> exclude root col -> (B, J-1) -> expand per frame -> (B*F, J-1)
+ kv_mask = ~joints_valid[:, 1:] # (B, J-1), True = padding
+ kv_mask = kv_mask.unsqueeze(1).expand(-1, F, -1).reshape(B * F, J - 1)
+ else:
+ kv_mask = None
+ root_agg, _ = self.root_cross_attn(
+ self.root_cross_norm_q(root_flat),
+ self.root_cross_norm_kv(joints_flat),
+ joints_flat,
+ key_padding_mask=kv_mask,
+ )
+ root_tokens = root_tokens + root_agg.reshape(B, F, 1, D)
+
+ root = self.root_out(root_tokens) # (B, F, 1, D_out)
+ joints = self.joint_out(joint_tokens) # (B, F, J-1, D_out)
+ x = torch.cat([root, joints], dim=2) # (B, F, J, D_out)
+
+ x = einops.rearrange(x, 'b f j d -> b d f j')
+ return x
+
+
diff --git a/unimate/models/denoiser/blocks/cross.py b/unimate/models/denoiser/blocks/cross.py
new file mode 100644
index 0000000..e883a69
--- /dev/null
+++ b/unimate/models/denoiser/blocks/cross.py
@@ -0,0 +1,198 @@
+"""Cross-attention variant of the graph spatio-temporal transformer.
+
+Same factored spatial (graph-biased) + temporal attention as
+``blocks_graph``, with an added text cross-attention stage per
+block. Time and tpos still drive AdaLN; text is routed through cross-attn.
+"""
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from unimate.models.denoiser.blocks.common import (
+ LlamaRMSNorm,
+ SwiGLUFFN,
+ modulate,
+)
+from unimate.models.denoiser.blocks.graph import (
+ SpatialGraphSelfAttention,
+ TemporalSelfAttention,
+)
+
+
+# ---------------------------------------------------------------------------
+# Cross-attention (text as K/V)
+# ---------------------------------------------------------------------------
+
+class TextCrossAttention(nn.Module):
+ """Cross-attention with x as query and text memory as key/value.
+
+ x: (B, F, J, D) -> flattened internally to (B, F*J, D).
+ text_mem: (B, L_text, D). No rope; no positional structure on text.
+ """
+ def __init__(self, dim, num_heads=8, qkv_bias=True, qk_norm=True,
+ attn_drop=0., proj_drop=0., **kwargs):
+ super().__init__()
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+
+ self.q_proj = nn.Linear(dim, dim, bias=qkv_bias)
+ self.kv_proj = nn.Linear(dim, dim * 2, bias=qkv_bias)
+ self.proj = nn.Linear(dim, dim)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ if qk_norm:
+ self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
+ self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
+ else:
+ self.q_norm = nn.Identity()
+ self.k_norm = nn.Identity()
+
+ def forward(self, x, text_mem, text_mask=None):
+ B, Fr, J, D = x.shape
+ N = Fr * J
+ L = text_mem.shape[1]
+
+ q = self.q_proj(x.reshape(B, N, D))
+ kv = self.kv_proj(text_mem)
+ q = q.reshape(B, N, self.num_heads, self.head_dim).transpose(1, 2)
+ kv = kv.reshape(B, L, 2, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
+ k, v = kv.unbind(0)
+ q, k = self.q_norm(q), self.k_norm(k)
+
+ # text_mask: (B, L) bool with True = valid. Build SDPA attn_mask where
+ # True = keep, False = mask (PyTorch SDPA convention for bool masks).
+ attn_mask = None
+ if text_mask is not None:
+ attn_mask = text_mask.to(torch.bool)[:, None, None, :] # (B,1,1,L)
+
+ out = F.scaled_dot_product_attention(
+ q, k, v,
+ attn_mask=attn_mask,
+ dropout_p=self.attn_drop.p if self.training else 0.,
+ )
+ out = out.transpose(1, 2).reshape(B, N, D)
+ out = self.proj(out)
+ out = self.proj_drop(out)
+ return out.reshape(B, Fr, J, D)
+
+
+# ---------------------------------------------------------------------------
+# Transformer block
+# ---------------------------------------------------------------------------
+
+class SpatioTemporalCrossBlock(nn.Module):
+ """Spatial (graph) โ†’ Temporal โ†’ Text cross-attn โ†’ MLP.
+ x: (B, F, J, D), c: (B, D), text_mem: (B, L_text, D).
+ """
+ def __init__(self, hidden_size, num_heads, mlp_size=1024,
+ rope_spatial=None, rope_temporal=None,
+ qk_norm=True, max_path_len=5, edge_types=6, dropout=0.0,
+ own_graph_bias=True,
+ gradient_checkpointing=False):
+ super().__init__()
+ self.gradient_checkpointing = gradient_checkpointing
+
+ self.norm_s = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.s_attn = SpatialGraphSelfAttention(
+ hidden_size, num_heads=num_heads, qkv_bias=True,
+ qk_norm=qk_norm, rope=rope_spatial,
+ max_path_len=max_path_len, edge_types=edge_types,
+ attn_drop=dropout, proj_drop=dropout,
+ own_graph_bias=own_graph_bias,
+ )
+
+ self.norm_t = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.t_attn = TemporalSelfAttention(
+ hidden_size, num_heads=num_heads, qkv_bias=True,
+ qk_norm=qk_norm, rope=rope_temporal,
+ attn_drop=dropout, proj_drop=dropout,
+ )
+
+ self.norm_c = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.c_attn = TextCrossAttention(
+ hidden_size, num_heads=num_heads, qkv_bias=True,
+ qk_norm=qk_norm, attn_drop=dropout, proj_drop=dropout,
+ )
+
+ self.norm_mlp = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.mlp = SwiGLUFFN(hidden_size, int(2 / 3 * mlp_size))
+
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(),
+ nn.Linear(hidden_size, 9 * hidden_size, bias=True)
+ )
+
+ def _forward_spatial(self, xs, spatial_mask, position_ids_spatial, cond,
+ graph_bias):
+ return self.s_attn(xs, attention_mask=spatial_mask,
+ position_ids=position_ids_spatial, cond=cond,
+ graph_bias=graph_bias)
+
+ def _forward_temporal(self, xt, temporal_mask, position_ids_temporal):
+ return self.t_attn(xt, attention_mask=temporal_mask,
+ position_ids=position_ids_temporal)
+
+ def _forward_cross(self, xc, text_mem, text_mask):
+ return self.c_attn(xc, text_mem, text_mask=text_mask)
+
+ def forward(self, x, c, text_mem, spatial_mask=None, temporal_mask=None,
+ text_mask=None,
+ position_ids_spatial=None, position_ids_temporal=None, cond=None,
+ graph_bias=None):
+ dtype = x.dtype
+ # The cross stage takes no modulation chunk: it gets its own norm and
+ # is added plainly, as in Wan 2.1 / PixArt-alpha. See DiTCrossBlock.
+ (shift_s, scale_s, gate_s,
+ shift_t, scale_t, gate_t,
+ shift_m, scale_m, gate_m) = self.adaLN_modulation(c).chunk(9, dim=-1)
+
+ def expand_to_x(z):
+ return z[:, None, None, :]
+
+ use_ckpt = self.gradient_checkpointing and self.training
+
+ # spatial attn
+ xs = self.norm_s(x.to(torch.float32)).to(dtype)
+ xs = modulate(xs, expand_to_x(shift_s), expand_to_x(scale_s))
+ if use_ckpt:
+ xs = torch.utils.checkpoint.checkpoint(
+ self._forward_spatial, xs, spatial_mask,
+ position_ids_spatial, cond, graph_bias, use_reentrant=False,
+ )
+ else:
+ xs = self._forward_spatial(xs, spatial_mask, position_ids_spatial,
+ cond, graph_bias)
+ x = x + expand_to_x(gate_s) * xs
+
+ # temporal attn
+ xt = self.norm_t(x.to(torch.float32)).to(dtype)
+ xt = modulate(xt, expand_to_x(shift_t), expand_to_x(scale_t))
+ if use_ckpt:
+ xt = torch.utils.checkpoint.checkpoint(
+ self._forward_temporal, xt, temporal_mask,
+ position_ids_temporal, use_reentrant=False,
+ )
+ else:
+ xt = self._forward_temporal(xt, temporal_mask, position_ids_temporal)
+ x = x + expand_to_x(gate_t) * xt
+
+ # text cross attn
+ xc = self.norm_c(x.to(torch.float32)).to(dtype)
+ if use_ckpt:
+ xc = torch.utils.checkpoint.checkpoint(
+ self._forward_cross, xc, text_mem, text_mask,
+ use_reentrant=False,
+ )
+ else:
+ xc = self._forward_cross(xc, text_mem, text_mask)
+ x = x + xc
+
+ # mlp
+ xm = self.norm_mlp(x.to(torch.float32)).to(dtype)
+ xm = modulate(xm, expand_to_x(shift_m), expand_to_x(scale_m))
+ xm = self.mlp(xm)
+ x = x + expand_to_x(gate_m) * xm
+
+ return x
diff --git a/unimate/models/denoiser/blocks/graph.py b/unimate/models/denoiser/blocks/graph.py
new file mode 100644
index 0000000..7c00ef9
--- /dev/null
+++ b/unimate/models/denoiser/blocks/graph.py
@@ -0,0 +1,343 @@
+"""Graph-aware spatio-temporal transformer blocks for UniMate.
+
+Contains attention modules that incorporate skeleton graph structure
+(distance + edge-type biases) into the spatial attention, plus a
+factored spatial-temporal transformer block.
+"""
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import einops
+
+from unimate.models.denoiser.blocks.common import (
+ LlamaRMSNorm,
+ SwiGLUFFN,
+ modulate,
+)
+from unimate.models.denoiser.rope import SpectralJointRoPE
+
+
+# ---------------------------------------------------------------------------
+# Attention
+# ---------------------------------------------------------------------------
+
+def build_graph_bias_params(module, dim, num_heads, max_path_len=5, edge_types=6):
+ """Register the Graphormer bias tables on *module*, in place.
+
+ A free function rather than a base class so the parameters can live either
+ directly on an attention (their historical home, and the names checkpoints
+ carry) or on a standalone :class:`GraphAttnBias`, with one definition and
+ one registration order either way.
+ """
+ module.graph_dist_embedding = nn.Embedding(max_path_len + 1, dim // 4)
+ module.graph_dist_proj = nn.Linear(dim // 4, num_heads)
+ module.graph_dist_scale = nn.Parameter(torch.ones(1) * 0.02)
+
+ module.graph_rel_embedding = nn.Embedding(edge_types, dim // 4)
+ module.graph_rel_proj = nn.Linear(dim // 4, num_heads)
+ module.graph_rel_scale = nn.Parameter(torch.ones(1) * 0.02)
+
+
+def compute_graph_bias(module, cond, attention_mask):
+ """Masked graph bias at (B, H, J, J) from *module*'s tables.
+
+ ``A_ij = QK^T/sqrt(d) + b_dist(i,j) + b_edge(i,j)`` โ€” Graphormer's spatial
+ and edge encodings, here over the skeleton graph. Shared across frames.
+ """
+ dist_emb = module.graph_dist_proj(
+ module.graph_dist_embedding(cond["graph_dist"])
+ ) * module.graph_dist_scale
+ rel_emb = module.graph_rel_proj(
+ module.graph_rel_embedding(cond["joint_relations"])
+ ) * module.graph_rel_scale
+
+ # (B, J, J, H) -> (B, H, J, J)
+ graph_bias = (dist_emb + rel_emb).permute(0, 3, 1, 2)
+ # Joint validity folded in here rather than applied as a second mask:
+ # attention_mask is (B, 1, 1, J) and broadcasts over the query axis.
+ return graph_bias.masked_fill(~attention_mask.to(torch.bool), float('-inf'))
+
+
+class GraphAttnBias(nn.Module):
+ """The graph bias as a standalone module, for sharing across layers.
+
+ Graphormer itself learns one bias for the whole stack. Held by the model
+ (see ``share_graph_attn_bias``) it is evaluated once per forward and handed
+ to every layer, instead of ``num_layers`` private copies each rebuilding
+ their own. Per-layer copies are the default: more expressive, at
+ ``num_layers`` times these (small) tables.
+ """
+
+ def __init__(self, dim, num_heads, max_path_len=5, edge_types=6):
+ super().__init__()
+ build_graph_bias_params(self, dim, num_heads, max_path_len, edge_types)
+
+ def forward(self, cond, attention_mask):
+ return compute_graph_bias(self, cond, attention_mask)
+
+
+class SpatialGraphSelfAttention(nn.Module):
+ """Spatial self-attention over joints, optionally biased by skeleton graph.
+ Operates per-frame: reshapes (B, F, J, D) โ†’ (B*F, J, D).
+
+ With ``use_graph_attn_bias=True`` (default): adds learned graph-distance
+ and edge-type biases. Bias (B, H, J, J) is shared across frames and
+ broadcast over the frame dim during manual attention, avoiding a full
+ (B*F, H, J, J) copy and keeping the path SDPA-free.
+
+ With ``use_graph_attn_bias=False`` (ablation): plain self-attention via
+ SDPA; the joint validity mask (folded into the bias when on) is supplied
+ as SDPA's attn_mask instead.
+
+ ``own_graph_bias=False`` leaves the bias parameters out of this module: the
+ model then holds a single :class:`GraphAttnBias` for the whole stack and
+ hands the computed ``graph_bias`` to every layer's ``forward``.
+ """
+ def __init__(self, dim, num_heads=8, qkv_bias=True, rope=None, qk_norm=True,
+ max_path_len=5, edge_types=6, attn_drop=0., proj_drop=0.,
+ use_graph_attn_bias=True, own_graph_bias=True, **kwargs):
+ super().__init__()
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.scale = self.head_dim ** -0.5
+ self.rope = rope
+ self.use_graph_attn_bias = use_graph_attn_bias
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.proj = nn.Linear(dim, dim)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ if qk_norm:
+ self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
+ self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
+ else:
+ self.q_norm = nn.Identity()
+ self.k_norm = nn.Identity()
+
+ # Graph distance/edge-type biases โ€” skipped when ablated (the joint mask
+ # then goes through SDPA's attn_mask in forward instead), and skipped
+ # when the model owns one shared bias and passes it into forward. When
+ # we do own them they hang directly off this module, the names and the
+ # registration order existing checkpoints were written with.
+ self.own_graph_bias = self.use_graph_attn_bias and own_graph_bias
+ if self.own_graph_bias:
+ build_graph_bias_params(self, dim, num_heads, max_path_len, edge_types)
+
+ def forward(self, x, attention_mask=None, position_ids=None, cond=None,
+ graph_bias=None):
+ B, Fr, J, _ = x.shape
+ C = self.num_heads * self.head_dim
+
+ # QKV projection for all frames at once
+ x_flat = einops.rearrange(x, 'b f j d -> (b f) j d')
+ qkv = self.qkv(x_flat).reshape(B * Fr, J, 3, self.num_heads, self.head_dim)
+ qkv = qkv.permute(2, 0, 3, 1, 4) # (3, B*F, H, J, D)
+ q, k, v = qkv.unbind(0)
+ q, k = self.q_norm(q), self.k_norm(k)
+
+ if self.rope is not None:
+ if isinstance(self.rope, SpectralJointRoPE):
+ # Spectral rope: angles depend only on (B, J), so the encoder
+ # runs once and the rotation broadcasts across the frame dim.
+ spectral_coords = cond['spectral_feats'] # (B, J, K)
+ q, k = self.rope.forward_per_frame(
+ q, k, spectral_coords, n_frames=Fr,
+ )
+ else:
+ q, k = self.rope(q, k, position_ids)
+
+ if self.use_graph_attn_bias:
+ # Graph bias: (B, H, J, J) โ€” shared across all frames. Supplied by
+ # the model when it owns one bias for every layer, else our own.
+ if graph_bias is None:
+ assert self.own_graph_bias, (
+ 'This attention was built with own_graph_bias=False, so '
+ 'the model must pass the shared graph_bias into forward.')
+ graph_bias = compute_graph_bias(self, cond, attention_mask)
+ # Manual attention with broadcasting: avoid expanding (B,H,J,J) bias
+ # to (B*F,H,J,J) โ€” broadcast over the frame dim instead.
+ q = q.reshape(B, Fr, self.num_heads, J, self.head_dim)
+ k = k.reshape(B, Fr, self.num_heads, J, self.head_dim)
+ v = v.reshape(B, Fr, self.num_heads, J, self.head_dim)
+
+ attn_weights = (q @ k.transpose(-1, -2)) * self.scale # (B, F, H, J, J)
+ attn_weights = attn_weights + graph_bias.unsqueeze(1) # broadcast (B, 1, H, J, J)
+ # Softmax in fp32. This path is hand-rolled rather than SDPA (the
+ # bias cannot broadcast over the frame axis once frames are folded
+ # into the batch), so it does not inherit SDPA's internal fp32
+ # accumulation: under bf16 autocast a bf16 softmax here costs about
+ # an order of magnitude of accuracy against the full-attention
+ # variant, which would skew any comparison between them. Free in
+ # fp32, where .float() is a no-op.
+ attn_weights = attn_weights.float().softmax(dim=-1).to(v.dtype)
+ drop_p = self.attn_drop.p if self.training else 0.
+ if drop_p > 0.:
+ attn_weights = F.dropout(attn_weights, p=drop_p, training=self.training)
+ out = (attn_weights @ v).reshape(B * Fr, self.num_heads, J, self.head_dim)
+ else:
+ # Ablation: no graph bias. Apply joint validity via SDPA's attn_mask
+ # (broadcast across frames) so padded joints are still excluded.
+ attn_mask = einops.repeat(
+ attention_mask, 'b 1 1 j -> (b f) 1 1 j', f=Fr,
+ ).to(torch.bool)
+ out = F.scaled_dot_product_attention(
+ q, k, v,
+ attn_mask=attn_mask,
+ dropout_p=self.attn_drop.p if self.training else 0.,
+ )
+
+ out = out.transpose(1, 2).reshape(B * Fr, J, C)
+ out = self.proj(out)
+ out = self.proj_drop(out)
+
+ out = einops.rearrange(out, '(b f) j d -> b f j d', b=B, f=Fr)
+ return out
+
+
+class TemporalSelfAttention(nn.Module):
+ """Temporal self-attention applied per-joint.
+ Reshapes (B, F, J, D) โ†’ (B*J, F, D).
+ """
+ def __init__(self, dim, num_heads=8, qkv_bias=True, rope=None, qk_norm=True,
+ attn_drop=0., proj_drop=0., **kwargs):
+ super().__init__()
+ self.num_heads = num_heads
+ self.head_dim = dim // num_heads
+ self.rope = rope
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.proj = nn.Linear(dim, dim)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ if qk_norm:
+ self.q_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
+ self.k_norm = LlamaRMSNorm(self.head_dim, eps=1e-6)
+ else:
+ self.q_norm = nn.Identity()
+ self.k_norm = nn.Identity()
+
+ def forward(self, x, attention_mask=None, position_ids=None):
+ B_orig, Fr, J, _ = x.shape
+ x = einops.rearrange(x, 'b f j d -> (b j) f d')
+ attention_mask = einops.repeat(attention_mask, 'b 1 1 f -> (b j) 1 1 f', j=J).to(torch.bool)
+
+ B, N, C = x.shape
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)
+ q, k, v = qkv.unbind(0)
+ q, k = self.q_norm(q), self.k_norm(k)
+
+ if self.rope is not None:
+ q, k = self.rope(q, k, position_ids)
+
+ x = F.scaled_dot_product_attention(
+ q, k, v,
+ attn_mask=attention_mask,
+ dropout_p=self.attn_drop.p if self.training else 0.,
+ )
+ x = x.transpose(1, 2).reshape(B, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+
+ x = einops.rearrange(x, '(b j) f d -> b f j d', b=B_orig, j=J)
+ return x
+
+
+# ---------------------------------------------------------------------------
+# Transformer block
+# ---------------------------------------------------------------------------
+
+class SpatioTemporalBlock(nn.Module):
+ """Spatial self-attn (graph bias optional) โ†’ Temporal self-attn โ†’ MLP.
+ All operate on x: (B, F, J, D), c: (B, D).
+ """
+ def __init__(self, hidden_size, num_heads, mlp_size=1024,
+ rope_spatial=None, rope_temporal=None,
+ qk_norm=True, max_path_len=5, edge_types=6, dropout=0.0,
+ use_graph_attn_bias=True, own_graph_bias=True,
+ gradient_checkpointing=False):
+ super().__init__()
+ self.gradient_checkpointing = gradient_checkpointing
+
+ self.norm_s = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.s_attn = SpatialGraphSelfAttention(
+ hidden_size, num_heads=num_heads, qkv_bias=True,
+ qk_norm=qk_norm, rope=rope_spatial,
+ max_path_len=max_path_len, edge_types=edge_types,
+ attn_drop=dropout, proj_drop=dropout,
+ use_graph_attn_bias=use_graph_attn_bias,
+ own_graph_bias=own_graph_bias,
+ )
+
+ self.norm_t = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.t_attn = TemporalSelfAttention(
+ hidden_size, num_heads=num_heads, qkv_bias=True,
+ qk_norm=qk_norm, rope=rope_temporal,
+ attn_drop=dropout, proj_drop=dropout,
+ )
+
+ self.norm_mlp = LlamaRMSNorm(hidden_size, eps=1e-6)
+ self.mlp = SwiGLUFFN(hidden_size, int(2 / 3 * mlp_size))
+
+ self.adaLN_modulation = nn.Sequential(
+ nn.SiLU(),
+ nn.Linear(hidden_size, 9 * hidden_size, bias=True)
+ )
+
+ def _forward_spatial(self, xs, spatial_mask, position_ids_spatial, cond,
+ graph_bias):
+ return self.s_attn(xs, attention_mask=spatial_mask,
+ position_ids=position_ids_spatial, cond=cond,
+ graph_bias=graph_bias)
+
+ def _forward_temporal(self, xt, temporal_mask, position_ids_temporal):
+ return self.t_attn(xt, attention_mask=temporal_mask,
+ position_ids=position_ids_temporal)
+
+ def forward(self, x, c, spatial_mask=None, temporal_mask=None,
+ position_ids_spatial=None, position_ids_temporal=None, cond=None,
+ graph_bias=None):
+ dtype = x.dtype
+ (shift_s, scale_s, gate_s,
+ shift_t, scale_t, gate_t,
+ shift_m, scale_m, gate_m) = self.adaLN_modulation(c).chunk(9, dim=-1)
+
+ def expand_to_x(z):
+ return z[:, None, None, :]
+
+ use_ckpt = self.gradient_checkpointing and self.training
+
+ # spatial attn
+ xs = self.norm_s(x.to(torch.float32)).to(dtype)
+ xs = modulate(xs, expand_to_x(shift_s), expand_to_x(scale_s))
+ if use_ckpt:
+ xs = torch.utils.checkpoint.checkpoint(
+ self._forward_spatial, xs, spatial_mask,
+ position_ids_spatial, cond, graph_bias, use_reentrant=False,
+ )
+ else:
+ xs = self._forward_spatial(xs, spatial_mask, position_ids_spatial,
+ cond, graph_bias)
+ x = x + expand_to_x(gate_s) * xs
+
+ # temporal attn
+ xt = self.norm_t(x.to(torch.float32)).to(dtype)
+ xt = modulate(xt, expand_to_x(shift_t), expand_to_x(scale_t))
+ if use_ckpt:
+ xt = torch.utils.checkpoint.checkpoint(
+ self._forward_temporal, xt, temporal_mask,
+ position_ids_temporal, use_reentrant=False,
+ )
+ else:
+ xt = self._forward_temporal(xt, temporal_mask, position_ids_temporal)
+ x = x + expand_to_x(gate_t) * xt
+
+ # mlp
+ xm = self.norm_mlp(x.to(torch.float32)).to(dtype)
+ xm = modulate(xm, expand_to_x(shift_m), expand_to_x(scale_m))
+ xm = self.mlp(xm)
+ x = x + expand_to_x(gate_m) * xm
+
+ return x
diff --git a/unimate/models/denoiser/full_adaln.py b/unimate/models/denoiser/full_adaln.py
new file mode 100644
index 0000000..b93d63a
--- /dev/null
+++ b/unimate/models/denoiser/full_adaln.py
@@ -0,0 +1,119 @@
+"""``attention='full'`` + ``text_cond='adaln'`` โ€” the plain DiT pairing."""
+
+import torch
+import einops
+
+from unimate.models.denoiser.rope import RopeND, GraphRoPE
+from unimate.models.denoiser.base import UniMateDenoiserBase
+from unimate.models.denoiser.blocks import DiTBlock
+
+
+class UniMateFullAdaLN(UniMateDenoiserBase):
+ """One attention over the flattened spatio-temporal (T*J) tokens.
+
+ The caption reaches the network only through the adaLN vector, alongside
+ the timestep and the pooled tpos โ€” a single pooled sentence embedding per
+ sample, as in DiT's class conditioning.
+
+ Position encoding is controlled by ``use_spectral_rope``:
+ - True: GraphRoPE (sign-invariant spectral joint + sinusoidal temporal).
+ - False: 2D sinusoidal RopeND with integer (frame, joint) indices.
+ """
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ # Positional Encoding. Either spectral (GraphRoPE) or standard 2D RoPE.
+ head_dim = self.latent_dim // self.num_heads
+ max_frames = self.max_motion_length + self.n_prefix # F + n_prefix
+ if self.use_spectral_rope:
+ self.rope = GraphRoPE(
+ head_dim=head_dim,
+ num_eigvecs=self.max_freqs,
+ use_signnet=self.use_signnet,
+ max_time=max_frames,
+ )
+ else:
+ self.rope = RopeND(
+ head_dim=head_dim, nd=2, nd_split=[1, 1],
+ max_lens=[max_frames, self.max_joints],
+ )
+ pos_ids_f = torch.arange(max_frames).unsqueeze(1).repeat(1, self.max_joints)
+ pos_ids_j = torch.arange(self.max_joints).unsqueeze(0).repeat(max_frames, 1)
+ self.register_buffer(
+ 'position_ids_precompute',
+ torch.stack([pos_ids_f, pos_ids_j], dim=0),
+ persistent=False,
+ )
+
+ # Transformer blocks (the rope module is shared across blocks)
+ self.transformer_blocks = torch.nn.ModuleList(
+ [
+ DiTBlock(
+ hidden_size=self.latent_dim,
+ num_heads=self.num_heads,
+ mlp_size=self.ff_size,
+ rope=self.rope,
+ qk_norm=True,
+ dropout=self.dropout,
+ )
+ for _ in range(self.num_layers)
+ ]
+ )
+
+ self._finish_build()
+
+ def forward(self, x, timesteps, cond=None, force_mask=False):
+ """
+ Args:
+ x: [batch_size, max_joints, nfeats, max_frames], denoted x_t in the paper
+ timesteps: [batch_size] (int)
+ cond: Optional dict with conditioning information
+ Returns:
+ output: [batch_size, max_joints, nfeats, max_frames]
+ """
+ bs, njoints, nfeats, nframes = x.shape
+
+ # adaLN conditioning: timestep + (CFG-masked) caption embedding
+ y = self._build_adaln_y(x, timesteps, cond, force_mask) # (B, latent_dim)
+
+ # Input layer: encode tpos + motion, prepend the conditioning frame
+ x, tpos_emb, joints_valid = self.input_layer(x, cond)
+ if self.inject_tpos_to_adaln:
+ y = y + self.tpos_pool(tpos_emb, joints_valid) # (B, latent_dim)
+
+ # Optional graph / depth / joint-name token embeddings
+ x = self._apply_token_embeddings(x, cond)
+
+ # Flatten spatial-temporal dims for full attention
+ x = einops.rearrange(x, 'b f j d -> b d f j') # (B, latent_dim, F+1, J)
+ x = x.flatten(2).transpose(1, 2) # (B, (F+1)*J, latent_dim)
+
+ # Prepare attention mask
+ # Length must be the batch's own frame count, not the config maximum:
+ # the token axis below is flattened over (nframes + n_prefix), so a
+ # shorter clip would give a mask that no longer lines up with it.
+ temporal_mask = self.lengths_to_mask(cond['motion_length'] + self.n_prefix, nframes + self.n_prefix) # (B, F+n_prefix)
+ attention_mask = temporal_mask.unsqueeze(-1) & joints_valid.unsqueeze(1) # (B, F+n_prefix, J)
+ attention_mask = attention_mask.flatten(1).unsqueeze(1).unsqueeze(1) # (B, 1, 1, (F+n_prefix)*J)
+
+ # Positional encodings: spectral needs nframes; standard needs position_ids
+ if self.use_spectral_rope:
+ rope_nframes = nframes + self.n_prefix
+ position_ids = None
+ else:
+ rope_nframes = None
+ position_ids = self.position_ids_precompute[:, :(nframes + self.n_prefix), :njoints]
+ position_ids = position_ids.flatten(1)
+
+ # Transformer blocks
+ for block in self.transformer_blocks:
+ x = block(x, y, attention_mask, position_ids=position_ids,
+ cond=cond, nframes=rope_nframes)
+
+ # Final layer
+ x = self.final_layer(x, y, joints_valid=joints_valid) # (B, feature_len, F+n_prefix, J)
+ x = einops.rearrange(x, 'b d f j -> b j d f') # (B, J, D, F+n_prefix)
+ x = x[:, :, :, self.n_prefix:] # remove prefix frames (B, J, D, F)
+
+ return x
diff --git a/unimate/models/denoiser/full_cross_attn.py b/unimate/models/denoiser/full_cross_attn.py
new file mode 100644
index 0000000..71164a7
--- /dev/null
+++ b/unimate/models/denoiser/full_cross_attn.py
@@ -0,0 +1,143 @@
+"""``attention='full'`` + ``text_cond='cross_attn'`` โ€” DiT with a text stage."""
+
+import torch
+import torch.nn as nn
+import einops
+
+from unimate.models.denoiser.rope import RopeND, GraphRoPE
+from unimate.models.denoiser.base import UniMateDenoiserBase
+from unimate.models.denoiser.blocks import DiTCrossBlock
+
+
+class UniMateFullCrossAttn(UniMateDenoiserBase):
+ """Full attention over the flattened (T*J) tokens, plus a text stage.
+
+ Same attention stack as :class:`UniMateFullAdaLN`; the caption enters
+ each block as cross-attention K/V instead of through the adaLN vector, so
+ every spatio-temporal token can attend the words it needs. Time and
+ (optionally) pooled tpos still drive adaLN.
+
+ Position encoding is controlled by ``use_spectral_rope``:
+ - True: GraphRoPE (sign-invariant spectral joint + sinusoidal temporal).
+ - False: 2D sinusoidal RopeND with integer (frame, joint) indices.
+ """
+
+ uses_text_cross = True
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ # Positional Encoding. Either spectral (GraphRoPE) or standard 2D RoPE.
+ head_dim = self.latent_dim // self.num_heads
+ max_frames = self.max_motion_length + self.n_prefix # F + n_prefix
+ if self.use_spectral_rope:
+ self.rope = GraphRoPE(
+ head_dim=head_dim,
+ num_eigvecs=self.max_freqs,
+ use_signnet=self.use_signnet,
+ max_time=max_frames,
+ )
+ else:
+ self.rope = RopeND(
+ head_dim=head_dim, nd=2, nd_split=[1, 1],
+ max_lens=[max_frames, self.max_joints],
+ )
+ pos_ids_f = torch.arange(max_frames).unsqueeze(1).repeat(1, self.max_joints)
+ pos_ids_j = torch.arange(self.max_joints).unsqueeze(0).repeat(max_frames, 1)
+ self.register_buffer(
+ 'position_ids_precompute',
+ torch.stack([pos_ids_f, pos_ids_j], dim=0),
+ persistent=False,
+ )
+
+ # Transformer blocks (the rope module is shared across blocks)
+ self.transformer_blocks = torch.nn.ModuleList(
+ [
+ DiTCrossBlock(
+ hidden_size=self.latent_dim,
+ num_heads=self.num_heads,
+ mlp_size=self.ff_size,
+ rope=self.rope,
+ qk_norm=True,
+ dropout=self.dropout,
+ )
+ for _ in range(self.num_layers)
+ ]
+ )
+
+ self._finish_build()
+
+ # Zero-init each block's cross-attn output projection so the text
+ # branch starts silent, as PixArt-alpha does. Safe now that the branch
+ # carries no adaLN gate: d(loss)/d(proj) = upstream * attn_out is
+ # nonzero, so it can leave zero. Zeroing a gate AND the projection
+ # would deadlock both โ€” neither could ever become nonzero and the
+ # whole text path would train at exactly zero gradient.
+ for block in self.transformer_blocks:
+ nn.init.constant_(block.c_attn.proj.weight, 0)
+ nn.init.constant_(block.c_attn.proj.bias, 0)
+
+ def forward(self, x, timesteps, cond=None, force_mask=False):
+ """
+ Args:
+ x: [batch_size, max_joints, nfeats, max_frames], denoted x_t in the paper
+ timesteps: [batch_size] (int)
+ cond: Optional dict with conditioning information
+ Returns:
+ output: [batch_size, max_joints, nfeats, max_frames]
+ """
+ bs, njoints, nfeats, nframes = x.shape
+
+ # Timestep embedding โ†’ adaLN vector y (text is NOT added to y).
+ y = self.time_embedder(timesteps, dtype=x.dtype) # (B, latent_dim)
+
+ # Text memory for cross-attention: the caption's TOKEN sequence.
+ if self.cond_mode == 'text':
+ raw_text, text_mask = self._caption_tokens(
+ bs, cond, x.dtype, x.device, force_mask) # (B, T, text_dim)
+ text_mem = self.cond_embedder(raw_text) # (B, T, latent_dim)
+ else: # 'no_cond'
+ text_mem = torch.zeros(bs, 1, self.latent_dim, dtype=x.dtype, device=x.device)
+ text_mask = torch.ones(bs, 1, dtype=torch.bool, device=x.device)
+
+ # Input layer: encode tpos + motion, prepend the conditioning frame
+ x, tpos_emb, joints_valid = self.input_layer(x, cond)
+ if self.inject_tpos_to_adaln:
+ y = y + self.tpos_pool(tpos_emb, joints_valid) # (B, latent_dim)
+
+ # Optional graph / depth / joint-name token embeddings
+ x = self._apply_token_embeddings(x, cond)
+
+ # Flatten spatial-temporal dims for full attention
+ x = einops.rearrange(x, 'b f j d -> b d f j') # (B, latent_dim, F+1, J)
+ x = x.flatten(2).transpose(1, 2) # (B, (F+1)*J, latent_dim)
+
+ # Prepare attention mask
+ # Length must be the batch's own frame count, not the config maximum:
+ # the token axis below is flattened over (nframes + n_prefix), so a
+ # shorter clip would give a mask that no longer lines up with it.
+ temporal_mask = self.lengths_to_mask(cond['motion_length'] + self.n_prefix, nframes + self.n_prefix) # (B, F+n_prefix)
+ attention_mask = temporal_mask.unsqueeze(-1) & joints_valid.unsqueeze(1) # (B, F+n_prefix, J)
+ attention_mask = attention_mask.flatten(1).unsqueeze(1).unsqueeze(1) # (B, 1, 1, (F+n_prefix)*J)
+
+ # Positional encodings: spectral needs nframes; standard needs position_ids
+ if self.use_spectral_rope:
+ rope_nframes = nframes + self.n_prefix
+ position_ids = None
+ else:
+ rope_nframes = None
+ position_ids = self.position_ids_precompute[:, :(nframes + self.n_prefix), :njoints]
+ position_ids = position_ids.flatten(1)
+
+ # Transformer blocks
+ for block in self.transformer_blocks:
+ x = block(x, y, text_mem, attention_mask=attention_mask,
+ text_mask=text_mask, position_ids=position_ids,
+ cond=cond, nframes=rope_nframes)
+
+ # Final layer
+ x = self.final_layer(x, y, joints_valid=joints_valid) # (B, feature_len, F+n_prefix, J)
+ x = einops.rearrange(x, 'b d f j -> b j d f') # (B, J, D, F+n_prefix)
+ x = x[:, :, :, self.n_prefix:] # remove prefix frames (B, J, D, F)
+
+ return x
diff --git a/unimate/models/denoiser/graph_adaln.py b/unimate/models/denoiser/graph_adaln.py
new file mode 100644
index 0000000..3baf974
--- /dev/null
+++ b/unimate/models/denoiser/graph_adaln.py
@@ -0,0 +1,105 @@
+"""``attention='graph'`` + ``text_cond='adaln'`` โ€” the default pairing."""
+
+import torch.nn as nn
+import einops
+
+from unimate.models.denoiser.base import UniMateDenoiserBase
+from unimate.models.denoiser.blocks.graph import (GraphAttnBias,
+ SpatioTemporalBlock)
+
+
+class UniMateGraphAdaLN(UniMateDenoiserBase):
+ """Factored spatial (per-frame) + temporal (per-joint) attention.
+
+ Spatial attention carries learned graph-distance + edge-type biases
+ (Graphormer-style), so the skeleton's topology enters the attention
+ logits rather than only the token features. The caption reaches the
+ network through the adaLN vector.
+ Position encoding on the joint axis is controlled by ``use_spectral_rope``:
+ - True: SpectralJointRoPE (sign-invariant SignNet on Laplacian eigvecs).
+ - False: 1D sinusoidal RopeND with integer joint indices.
+ Temporal axis always uses sinusoidal RopeND with integer frame indices.
+ """
+
+ def __init__(self, use_graph_attn_bias=True, share_graph_attn_bias=False,
+ gradient_checkpointing=False, **kwargs):
+ super().__init__(**kwargs)
+ self.use_graph_attn_bias = use_graph_attn_bias
+ self.gradient_checkpointing = gradient_checkpointing
+
+ # One bias for the whole stack (Graphormer's arrangement) instead of a
+ # private one per block: built here, evaluated once per forward, and
+ # handed to every layer.
+ self.graph_bias = (
+ GraphAttnBias(self.latent_dim, self.num_heads)
+ if share_graph_attn_bias and use_graph_attn_bias else None
+ )
+
+ # Positional encoding: separate rope module per axis.
+ self._build_axis_ropes()
+
+ # Transformer blocks
+ self.transformer_blocks = nn.ModuleList(
+ [
+ SpatioTemporalBlock(
+ hidden_size=self.latent_dim,
+ num_heads=self.num_heads,
+ mlp_size=self.ff_size,
+ rope_spatial=self.rope_j,
+ rope_temporal=self.rope_t,
+ qk_norm=True,
+ dropout=self.dropout,
+ use_graph_attn_bias=self.use_graph_attn_bias,
+ own_graph_bias=self.graph_bias is None,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ for _ in range(self.num_layers)
+ ]
+ )
+
+ self._finish_build()
+
+ def forward(self, x, timesteps, cond=None, force_mask=False):
+ """
+ Args:
+ x: [batch_size, max_joints, nfeats, max_frames], denoted x_t in the paper
+ timesteps: [batch_size] (int)
+ cond: Optional dict with conditioning information
+ Returns:
+ output: [batch_size, max_joints, nfeats, max_frames]
+ """
+ bs, njoints, nfeats, nframes = x.shape
+
+ # adaLN conditioning: timestep + (CFG-masked) caption embedding
+ y = self._build_adaln_y(x, timesteps, cond, force_mask) # (B, latent_dim)
+
+ # Input layer: encode tpos + motion, prepend the conditioning frame
+ x, tpos_emb, joints_valid = self.input_layer(x, cond)
+ if self.inject_tpos_to_adaln:
+ y = y + self.tpos_pool(tpos_emb, joints_valid) # (B, latent_dim)
+
+ # Optional graph / depth / joint-name token embeddings
+ x = self._apply_token_embeddings(x, cond)
+
+ # Prepare attention masks
+ temporal_valid = self.lengths_to_mask(cond['motion_length'] + self.n_prefix, nframes + self.n_prefix) # (B, F+n_prefix)
+ temporal_mask = temporal_valid.unsqueeze(1).unsqueeze(1) # (B, 1, 1, F+1)
+ joint_mask = joints_valid.unsqueeze(1).unsqueeze(2) # (B, 1, 1, J)
+
+ # Spatial rope: spectral pulls from cond; standard uses integer joint ids.
+ spatial_pos_ids = self._spatial_position_ids(njoints)
+ # Shared graph bias (when enabled): one (B, H, J, J) build for the stack.
+ graph_bias = (self.graph_bias(cond, joint_mask)
+ if self.graph_bias is not None else None)
+ for block in self.transformer_blocks:
+ x = block(x, y, spatial_mask=joint_mask, temporal_mask=temporal_mask,
+ position_ids_spatial=spatial_pos_ids,
+ position_ids_temporal=self.temporal_position_ids[:, :nframes + self.n_prefix],
+ cond=cond, graph_bias=graph_bias)
+
+ # Final layer
+ x = self.final_layer(x, y, joints_valid=joints_valid) # (B, feature_len, F+n_prefix, J)
+ x = einops.rearrange(x, 'b d f j -> b j d f') # (B, J, D, F+n_prefix)
+ x = x[:, :, :, self.n_prefix:] # remove prefix frames (B, J, D, F)
+
+ return x
diff --git a/unimate/models/denoiser/graph_cross_attn.py b/unimate/models/denoiser/graph_cross_attn.py
new file mode 100644
index 0000000..e81886f
--- /dev/null
+++ b/unimate/models/denoiser/graph_cross_attn.py
@@ -0,0 +1,123 @@
+"""``attention='graph'`` + ``text_cond='cross_attn'`` โ€” factored + text stage."""
+
+import torch
+import torch.nn as nn
+import einops
+
+from unimate.models.denoiser.base import UniMateDenoiserBase
+from unimate.models.denoiser.blocks.cross import SpatioTemporalCrossBlock
+from unimate.models.denoiser.blocks.graph import GraphAttnBias
+
+
+class UniMateGraphCrossAttn(UniMateDenoiserBase):
+ """Factored graph attention, with the caption entering as cross-attention.
+
+ Time and (optionally) pooled tpos drive AdaLN. Text enters each block as
+ K/V in a dedicated cross-attention stage โ€” it never contributes to the
+ AdaLN conditioning vector.
+ """
+
+ uses_text_cross = True
+
+ def __init__(self, share_graph_attn_bias=False,
+ gradient_checkpointing=False, **kwargs):
+ super().__init__(**kwargs)
+ self.gradient_checkpointing = gradient_checkpointing
+
+ # One bias for the whole stack (Graphormer's arrangement) instead of a
+ # private one per block: built here, evaluated once per forward, and
+ # handed to every layer.
+ self.graph_bias = (GraphAttnBias(self.latent_dim, self.num_heads)
+ if share_graph_attn_bias else None)
+
+ # Positional encoding: separate rope module per axis.
+ self._build_axis_ropes()
+
+ # Transformer blocks
+ self.transformer_blocks = nn.ModuleList(
+ [
+ SpatioTemporalCrossBlock(
+ hidden_size=self.latent_dim,
+ num_heads=self.num_heads,
+ mlp_size=self.ff_size,
+ rope_spatial=self.rope_j,
+ rope_temporal=self.rope_t,
+ qk_norm=True,
+ dropout=self.dropout,
+ own_graph_bias=self.graph_bias is None,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ for _ in range(self.num_layers)
+ ]
+ )
+
+ self._finish_build()
+
+ def initialize_weights(self):
+ super().initialize_weights()
+ # Zero-init each block's cross-attn output projection so the text
+ # branch starts silent, as PixArt-alpha does. Safe now that the branch
+ # carries no adaLN gate: d(loss)/d(proj) = upstream * attn_out is
+ # nonzero, so it can leave zero. Zeroing a gate AND the projection
+ # would deadlock both โ€” neither could ever become nonzero and the
+ # whole text path would train at exactly zero gradient.
+ for block in self.transformer_blocks:
+ nn.init.constant_(block.c_attn.proj.weight, 0)
+ nn.init.constant_(block.c_attn.proj.bias, 0)
+
+ def forward(self, x, timesteps, cond=None, force_mask=False):
+ """
+ Args:
+ x: [batch_size, max_joints, nfeats, max_frames], denoted x_t in the paper
+ timesteps: [batch_size] (int)
+ cond: Optional dict with conditioning information
+ Returns:
+ output: [batch_size, max_joints, nfeats, max_frames]
+ """
+ bs, njoints, nfeats, nframes = x.shape
+
+ # Timestep embedding โ†’ adaLN vector y (text is NOT added to y).
+ y = self.time_embedder(timesteps, dtype=x.dtype) # (B, latent_dim)
+
+ # Text memory for cross-attention: the caption's TOKEN sequence, so
+ # each joint/frame can attend the words it needs. A pooled vector here
+ # would make this a one-token memory โ€” an adaLN with extra cost.
+ if self.cond_mode == 'text':
+ raw_text, text_mask = self._caption_tokens(
+ bs, cond, x.dtype, x.device, force_mask) # (B, T, text_dim)
+ text_mem = self.cond_embedder(raw_text) # (B, T, latent_dim)
+ else: # 'no_cond'
+ text_mem = torch.zeros(bs, 1, self.latent_dim, dtype=x.dtype, device=x.device)
+ text_mask = torch.ones(bs, 1, dtype=torch.bool, device=x.device)
+
+ # Input layer: encode tpos + motion, prepend the conditioning frame
+ x, tpos_emb, joints_valid = self.input_layer(x, cond)
+ if self.inject_tpos_to_adaln:
+ y = y + self.tpos_pool(tpos_emb, joints_valid) # (B, latent_dim)
+
+ # Optional graph / depth / joint-name token embeddings
+ x = self._apply_token_embeddings(x, cond)
+
+ # Prepare attention masks
+ temporal_valid = self.lengths_to_mask(cond['motion_length'] + self.n_prefix, nframes + self.n_prefix) # (B, F+n_prefix)
+ temporal_mask = temporal_valid.unsqueeze(1).unsqueeze(1) # (B, 1, 1, F+1)
+ joint_mask = joints_valid.unsqueeze(1).unsqueeze(2) # (B, 1, 1, J)
+
+ # Spatial rope: spectral pulls from cond; standard uses integer joint ids.
+ spatial_pos_ids = self._spatial_position_ids(njoints)
+ # Shared graph bias (when enabled): one (B, H, J, J) build for the stack.
+ graph_bias = (self.graph_bias(cond, joint_mask)
+ if self.graph_bias is not None else None)
+ for block in self.transformer_blocks:
+ x = block(x, y, text_mem=text_mem, text_mask=text_mask,
+ spatial_mask=joint_mask, temporal_mask=temporal_mask,
+ position_ids_spatial=spatial_pos_ids,
+ position_ids_temporal=self.temporal_position_ids[:, :nframes + self.n_prefix],
+ cond=cond, graph_bias=graph_bias)
+
+ # Final layer
+ x = self.final_layer(x, y, joints_valid=joints_valid) # (B, feature_len, F+n_prefix, J)
+ x = einops.rearrange(x, 'b d f j -> b j d f') # (B, J, D, F+n_prefix)
+ x = x[:, :, :, self.n_prefix:] # remove prefix frames (B, J, D, F)
+
+ return x
diff --git a/unimate/models/denoiser/rope.py b/unimate/models/denoiser/rope.py
new file mode 100644
index 0000000..aa3995f
--- /dev/null
+++ b/unimate/models/denoiser/rope.py
@@ -0,0 +1,587 @@
+"""Rotary Position Embedding modules.
+
+``RopeND`` โ€” N-dimensional sinusoidal RoPE with per-axis frequency tables.
+Used for integer position indices on regular sequences.
+
+``SpectralJointRoPE`` โ€” joint-axis spectral RoPE. Projects Laplacian
+eigenvectors to rotation angles filling the full head dimension. Used for
+per-frame spatial attention where temporal encoding is handled separately.
+
+``GraphRoPE`` โ€” combined spectral-joint + sinusoidal-temporal RoPE. Splits
+the head dimension between a spectral graph half and a sinusoidal temporal
+half. Used for full attention over flattened ``(T*J)`` tokens.
+
+The spectral modules offer two projection backends, selected by
+``use_signnet``:
+
+ - ``True`` (default): ``SignNetSpectralEncoder`` implements the
+ ``rho([phi(v_k) + phi(-v_k)])`` construction โ€” sign-invariant by
+ design, robust to Laplacian eigenvector sign flips.
+ - ``False``: ``WIRESpectralEncoder`` (learnable frequencies, from *Rotary
+ Position Encodings for Graphs*) โ€” a single unbiased linear projection
+ ``angles = W @ v`` where each row of ``W`` is a learned frequency vector
+ ``ฯ‰_i โˆˆ โ„^m``. Parameter count is ``(d/2) * m`` โ€” the minimal WIRE
+ parameterization. Not sign-invariant on its own.
+"""
+
+import math
+
+import torch
+import torch.nn as nn
+from typing import List, Optional, Tuple
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+def _rotate_half(x: torch.Tensor) -> torch.Tensor:
+ """Swap and negate the two halves of the last dimension."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def _apply_rotary_pos_emb(
+ q: torch.Tensor,
+ k: torch.Tensor,
+ cos: torch.Tensor,
+ sin: torch.Tensor,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Apply rotary embeddings to query and key tensors.
+
+ The last dimension of ``q``/``k`` is rotated as standard RoPE:
+ ``out = x * cos + rotate_half(x) * sin``. Callers must pass ``cos``/``sin``
+ already shaped to broadcast against ``q``/``k`` (no implicit unsqueezing).
+
+ Args:
+ q, k: Same shape. The last dim is rotated, earlier dims are batched.
+ cos, sin: Broadcastable to ``q`` and ``k``.
+ """
+ dtype = q.dtype
+ q_f, k_f = q.float(), k.float()
+ q_out = (q_f * cos) + (_rotate_half(q_f) * sin)
+ k_out = (k_f * cos) + (_rotate_half(k_f) * sin)
+ return q_out.to(dtype), k_out.to(dtype)
+
+
+# ---------------------------------------------------------------------------
+# RopeND
+# ---------------------------------------------------------------------------
+
+class RopeND:
+ """N-dimensional Rotary Position Embedding.
+
+ Args:
+ head_dim: Total dimension per attention head.
+ nd: Number of positional axes.
+ max_lens: Maximum sequence length along each axis.
+ nd_split: Relative dimension allocation per axis (summed then
+ normalised to ``head_dim``).
+ bases: Frequency bases per axis (used when ``auto_base=False``).
+ auto_base: If True, derive bases empirically so that ``cos(theta)``
+ reaches -1 at ~8x the max length (similar to the standard 10k
+ base for length 4096).
+ cache_longer: Multiplier on max_len for the cached frequency table.
+ """
+
+ def __init__(
+ self,
+ head_dim: int = 64,
+ nd: int = 3,
+ max_lens: List[int] = [1024, 64, 64],
+ nd_split: List[int] = [2, 1, 1],
+ bases: List[float] = [1000, 1000, 1000],
+ auto_base: bool = True,
+ cache_longer: int = 1,
+ ):
+ self.nd = nd
+ self.head_dim = head_dim
+ self.max_lens = max_lens
+ self.nd_split = nd_split
+ self.cache_longer = cache_longer
+
+ # Dimension allocation per axis: 2 * ratio * (head_dim // 2 // sum)
+ self.split_dims = [2 * s * (head_dim // 2 // sum(nd_split)) for s in nd_split]
+ assert sum(self.split_dims) == head_dim, (
+ f"split_dims {self.split_dims} do not sum to head_dim={head_dim}"
+ )
+
+ if auto_base:
+ # Empirical rule: base โ‰ˆ 8L / ฯ€ (rounded to nearest 100)
+ self.bases = [(int(8 * L / math.pi) // 100 + 1) * 100 for L in max_lens]
+ else:
+ self.bases = bases
+
+ # ------------------------------------------------------------------
+ # Frequency table generation & caching
+ # ------------------------------------------------------------------
+
+ def _generate_cos_sin(
+ self, max_len: int, dim: int, device: torch.device, base: float,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Build cosine / sine frequency tables of shape ``(max_len, dim)``."""
+ inv_freq = 1.0 / (
+ base ** (torch.arange(0, dim, 2, device=device).float() / dim)
+ )
+ assert inv_freq.size(0) * 2 == dim
+
+ t = torch.arange(max_len * self.cache_longer, device=device).float()
+ freqs = torch.einsum("i,j->ij", t, inv_freq)
+ freqs = torch.cat([freqs, freqs], dim=1)
+ return freqs.cos().float(), freqs.sin().float()
+
+ def _get_pos_embs(
+ self, position_ids: torch.Tensor, device: torch.device,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Look up (or lazily create) per-axis embeddings and concatenate.
+
+ Args:
+ position_ids: ``(nd, L)`` integer position indices per axis.
+ device: Target device for the frequency tables.
+
+ Returns:
+ ``(cos, sin)`` each of shape ``(L, head_dim)``.
+ """
+ if position_ids.dim() == 1:
+ position_ids = position_ids.unsqueeze(0)
+
+ cos_parts, sin_parts = [], []
+ for i in range(self.nd):
+ # Lazy cache per axis; regenerate if device changed
+ cache_key_cos, cache_key_sin = f"cos_{i}", f"sin_{i}"
+ cached_cos = getattr(self, cache_key_cos, None)
+ if cached_cos is None or cached_cos.device != device:
+ c, s = self._generate_cos_sin(
+ self.max_lens[i], self.split_dims[i], device, self.bases[i],
+ )
+ setattr(self, cache_key_cos, c)
+ setattr(self, cache_key_sin, s)
+
+ cos_parts.append(getattr(self, cache_key_cos)[position_ids[i, :], :])
+ sin_parts.append(getattr(self, cache_key_sin)[position_ids[i, :], :])
+
+ return torch.cat(cos_parts, dim=-1), torch.cat(sin_parts, dim=-1)
+
+ # ------------------------------------------------------------------
+ # Forward
+ # ------------------------------------------------------------------
+
+ def __call__(
+ self,
+ q: torch.Tensor,
+ k: torch.Tensor,
+ position_ids: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Apply N-D RoPE to query and key tensors.
+
+ Args:
+ q: ``(B, H, L, C)`` query tensor.
+ k: ``(B, H, L, C)`` key tensor.
+ position_ids: ``(nd, L)`` per-axis position indices.
+
+ Returns:
+ Rotated ``(q, k)`` with the same shapes.
+ """
+ cos_emb, sin_emb = self._get_pos_embs(position_ids, device=q.device)
+ # Shape (L, C) โ†’ (1, 1, L, C) to broadcast over (B, H, L, C)
+ cos_emb = cos_emb.unsqueeze(0).unsqueeze(0)
+ sin_emb = sin_emb.unsqueeze(0).unsqueeze(0)
+ return _apply_rotary_pos_emb(q, k, cos_emb, sin_emb)
+
+
+# ---------------------------------------------------------------------------
+# SignNet sign-invariant spectral encoder
+# ---------------------------------------------------------------------------
+
+class SignNetSpectralEncoder(nn.Module):
+ """Sign-invariant projection from spectral coordinates to angles.
+
+ Implements ``rho([phi(v_k) + phi(-v_k)]_{k=1..K})`` where ``phi`` is a
+ per-frequency scalar MLP and ``rho`` is an aggregation MLP. Because
+ ``phi(v) + phi(-v)`` is unchanged when ``v`` is negated, the output is
+ invariant to the arbitrary sign flips inherent to Laplacian eigenvectors.
+
+ Args:
+ num_eigvecs: Number of spectral frequencies K.
+ hidden_dim: Hidden width of phi and rho.
+ out_dim: Output dimension (typically ``graph_dim // 2`` rotation angles).
+ """
+
+ def __init__(self, num_eigvecs: int, hidden_dim: int, out_dim: int):
+ super().__init__()
+ self.num_eigvecs = num_eigvecs
+
+ # phi: per-frequency scalar -> hidden
+ self.phi = nn.Sequential(
+ nn.Linear(1, hidden_dim),
+ nn.GELU(),
+ nn.Linear(hidden_dim, hidden_dim),
+ )
+
+ # rho: aggregate K frequencies -> out_dim
+ self.rho = nn.Sequential(
+ nn.Linear(num_eigvecs * hidden_dim, hidden_dim),
+ nn.GELU(),
+ nn.Linear(hidden_dim, out_dim),
+ )
+
+ nn.init.normal_(self.rho[-1].weight, std=0.02)
+ nn.init.zeros_(self.rho[-1].bias)
+
+ def forward(self, spectral_coords: torch.Tensor) -> torch.Tensor:
+ """Project spectral coordinates to sign-invariant angles.
+
+ Args:
+ spectral_coords: ``(B, J, K)`` Laplacian eigenvector values.
+
+ Returns:
+ ``(B, J, out_dim)`` rotation angles.
+ """
+ v = spectral_coords.unsqueeze(-1) # (B, J, K, 1)
+ h = self.phi(v) + self.phi(-v) # (B, J, K, hidden)
+ h = h.flatten(start_dim=-2) # (B, J, K * hidden)
+ return self.rho(h) # (B, J, out_dim)
+
+
+# ---------------------------------------------------------------------------
+# WIRE learnable-frequency spectral encoder
+# ---------------------------------------------------------------------------
+
+class WIRESpectralEncoder(nn.Module):
+ """Learnable-frequency spectral encoder from *Rotary Position Encodings
+ for Graphs* (WIRE).
+
+ The only learnable parameters are the frequencies
+ ``(ฯ‰_i)_{i=1..out_dim} โŠ‚ โ„^{num_eigvecs}``, stored as a single
+ ``nn.Parameter`` of shape ``(out_dim, num_eigvecs)``. For spectral
+ coords ``v โˆˆ โ„^{num_eigvecs}`` the output is ``angles[i] = <ฯ‰_i, v>``,
+ giving ``out_dim * num_eigvecs`` parameters total โ€” much smaller than a
+ SignNet head. Not sign-invariant: if Laplacian eigenvectors are
+ sign-flipped, the angles are negated.
+
+ Args:
+ num_eigvecs: Number of spectral frequencies K (= dim of ฯ‰_i).
+ out_dim: Number of rotation angles produced (= head_dim / 2 or
+ graph_dim / 2 depending on the caller).
+ """
+
+ def __init__(self, num_eigvecs: int, out_dim: int):
+ super().__init__()
+ self.num_eigvecs = num_eigvecs
+ self.out_dim = out_dim
+ # Rows are frequency vectors ฯ‰_i โˆˆ โ„^{num_eigvecs}
+ self.frequencies = nn.Parameter(torch.empty(out_dim, num_eigvecs))
+ nn.init.normal_(self.frequencies, std=0.02)
+
+ def forward(self, spectral_coords: torch.Tensor) -> torch.Tensor:
+ """Project spectral coordinates to rotation angles via learned frequencies.
+
+ Args:
+ spectral_coords: ``(B, J, K)`` Laplacian eigenvector values.
+
+ Returns:
+ ``(B, J, out_dim)`` rotation angles ``[<ฯ‰_i, v>]``.
+ """
+ # (B, J, K) @ (K, out_dim) -> (B, J, out_dim)
+ return spectral_coords @ self.frequencies.t()
+
+
+def _build_spectral_encoder(
+ num_eigvecs: int, out_dim: int, use_signnet: bool, signnet_hidden: int,
+) -> nn.Module:
+ """Construct the spectral encoder selected by ``use_signnet``."""
+ if use_signnet:
+ return SignNetSpectralEncoder(
+ num_eigvecs=num_eigvecs,
+ hidden_dim=signnet_hidden,
+ out_dim=out_dim,
+ )
+ return WIRESpectralEncoder(num_eigvecs=num_eigvecs, out_dim=out_dim)
+
+
+# ---------------------------------------------------------------------------
+# SpectralJointRoPE โ€” joint-axis (spectral only) rotary embedding
+# ---------------------------------------------------------------------------
+
+class SpectralJointRoPE(nn.Module):
+ """Spectral rotary embedding for the joint axis only.
+
+ Projects Laplacian eigenvectors to rotation angles covering the entire
+ head dimension. Used for per-frame spatial attention where temporal
+ differentiation is handled separately. The projection backend is
+ selected by ``use_signnet`` (see module docstring).
+
+ Args:
+ head_dim: Total dimension per attention head (must be even).
+ num_eigvecs: Number of Laplacian eigenvectors used as spectral coords.
+ use_signnet: If True, use sign-invariant SignNet encoder. If False,
+ use the minimal WIRE learnable-frequency projection.
+ signnet_hidden: Hidden width of the SignNet phi/rho MLPs. Ignored
+ when ``use_signnet=False``.
+ """
+
+ def __init__(
+ self,
+ head_dim: int = 64,
+ num_eigvecs: int = 8,
+ use_signnet: bool = True,
+ signnet_hidden: int = 64,
+ ):
+ super().__init__()
+ assert head_dim % 2 == 0, f"head_dim must be even, got {head_dim}"
+ self.head_dim = head_dim
+ self.num_eigvecs = num_eigvecs
+ self.use_signnet = use_signnet
+
+ self.spectral_encoder = _build_spectral_encoder(
+ num_eigvecs=num_eigvecs,
+ out_dim=head_dim // 2,
+ use_signnet=use_signnet,
+ signnet_hidden=signnet_hidden,
+ )
+
+ def _compute_cos_sin(
+ self, spectral_coords: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Project spectral coords to cos/sin of rotation angles."""
+ angles = self.spectral_encoder(spectral_coords) # (..., J, C/2)
+ angles = torch.cat([angles, angles], dim=-1) # (..., J, C)
+ return angles.cos(), angles.sin()
+
+ def forward(
+ self,
+ q: torch.Tensor,
+ k: torch.Tensor,
+ spectral_coords: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Apply joint-axis spectral RoPE to query and key.
+
+ Args:
+ q, k: ``(B, H, J, C)`` query/key tensors.
+ spectral_coords: ``(B, J, num_eigvecs)`` Laplacian eigenvectors.
+
+ Returns:
+ Rotated ``(q, k)``.
+ """
+ cos, sin = self._compute_cos_sin(spectral_coords) # (B, J, C)
+ # Shape (B, J, C) โ†’ (B, 1, J, C) to broadcast over H
+ cos = cos.unsqueeze(1)
+ sin = sin.unsqueeze(1)
+ return _apply_rotary_pos_emb(q, k, cos, sin)
+
+ def forward_per_frame(
+ self,
+ q: torch.Tensor,
+ k: torch.Tensor,
+ spectral_coords: torch.Tensor,
+ n_frames: int,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Efficient per-frame variant for use in factored spatial attention.
+
+ The caller has folded the frame dim into the batch: ``q``, ``k``
+ arrive as ``(B*F, H, J, C)``. Spectral coordinates do not depend on
+ the frame, so the encoder runs once on ``(B, J, K)`` and the
+ rotation is broadcast across F via a reshape to ``(B, F, H, J, C)``.
+
+ This avoids:
+ - materializing a ``(B*F, J, K)`` copy of spectral_coords, and
+ - running the SignNet/WIRE encoder F times on identical inputs.
+
+ Args:
+ q, k: ``(B*F, H, J, C)`` query/key tensors.
+ spectral_coords: ``(B, J, num_eigvecs)`` Laplacian eigenvectors.
+ n_frames: F โ€” number of frames folded into the batch.
+
+ Returns:
+ Rotated ``(q, k)`` with the original ``(B*F, H, J, C)`` shape.
+ """
+ B, J = spectral_coords.shape[0], spectral_coords.shape[1]
+ H, C = q.shape[1], q.shape[3]
+
+ cos, sin = self._compute_cos_sin(spectral_coords) # (B, J, C)
+ # Broadcast shape: (B, 1, 1, J, C) โ†’ over F (dim 1) and H (dim 2)
+ cos = cos.view(B, 1, 1, J, C)
+ sin = sin.view(B, 1, 1, J, C)
+
+ # ``reshape`` because q/k are non-contiguous after ``.permute().unbind()``.
+ q = q.reshape(B, n_frames, H, J, C)
+ k = k.reshape(B, n_frames, H, J, C)
+ q, k = _apply_rotary_pos_emb(q, k, cos, sin)
+ return (
+ q.reshape(B * n_frames, H, J, C),
+ k.reshape(B * n_frames, H, J, C),
+ )
+
+
+# ---------------------------------------------------------------------------
+# GraphRoPE โ€” combined spectral-joint + sinusoidal-temporal rotary embedding
+# ---------------------------------------------------------------------------
+
+class GraphRoPE(nn.Module):
+ """Combined spectral-joint + sinusoidal-temporal Rotary Position Embedding.
+
+ Follows *Rotary Position Encodings for Graphs*: the head dimension is
+ split into a graph half and a temporal half. The graph half projects
+ Laplacian eigenvectors to rotation angles (backend selected by
+ ``use_signnet``); the temporal half uses standard sinusoidal RoPE
+ frequencies (rotations depend on frame index). Used for full attention
+ over flattened ``(T*J)`` tokens.
+
+ Args:
+ head_dim: Total dimension per attention head.
+ num_eigvecs: Number of Laplacian eigenvectors K used as spectral
+ coordinates per joint.
+ nd_split: Relative dim allocation ``[graph_ratio, time_ratio]``
+ between the joint and temporal halves. Mirrors ``RopeND``'s
+ ``nd_split`` โ€” ``[1, 1]`` (default) is equal split, ``[2, 1]``
+ gives the joint half twice as many channels as the temporal
+ half, etc. ``sum(nd_split)`` must divide ``head_dim // 2`` so
+ each half gets an even number of channels.
+ use_signnet: If True, use sign-invariant SignNet encoder. If False,
+ use the minimal WIRE learnable-frequency projection.
+ signnet_hidden: Hidden width of the SignNet phi/rho MLPs. Ignored
+ when ``use_signnet=False``.
+ max_time: Maximum temporal sequence length. Used both to size the
+ precomputed cos/sin table and to derive ``time_base`` when
+ ``time_base`` is None.
+ time_base: Frequency base for the temporal RoPE axis. ``None``
+ selects the RopeND auto rule ``8ยทmax_time/ฯ€`` rounded up to the
+ nearest 100, which matches ``RopeND``'s ``auto_base=True``.
+ """
+
+ def __init__(
+ self,
+ head_dim: int = 64,
+ num_eigvecs: int = 8,
+ nd_split: List[int] = [1, 1],
+ use_signnet: bool = True,
+ signnet_hidden: int = 64,
+ max_time: int = 1024,
+ time_base: Optional[float] = None,
+ ):
+ super().__init__()
+ self.head_dim = head_dim
+ self.num_eigvecs = num_eigvecs
+ self.use_signnet = use_signnet
+ self.max_time = max_time
+
+ # Split head_dim between the two axes, following RopeND's rule.
+ # Each axis gets `2 * ratio * (head_dim // 2 // sum(nd_split))`
+ # channels, which guarantees each axis has an even count (required
+ # by rotate_half) as long as sum(nd_split) | head_dim // 2.
+ assert len(nd_split) == 2, f"nd_split must be length 2, got {nd_split}"
+ self.nd_split = list(nd_split)
+ split_dims = [
+ 2 * s * (head_dim // 2 // sum(nd_split)) for s in nd_split
+ ]
+ assert sum(split_dims) == head_dim, (
+ f"split_dims {split_dims} do not sum to head_dim={head_dim}. "
+ f"Ensure sum(nd_split)={sum(nd_split)} divides head_dim//2={head_dim//2}."
+ )
+ self.graph_dim, self.time_dim = split_dims
+
+ self.spectral_encoder = _build_spectral_encoder(
+ num_eigvecs=num_eigvecs,
+ out_dim=self.graph_dim // 2,
+ use_signnet=use_signnet,
+ signnet_hidden=signnet_hidden,
+ )
+
+ # Temporal sinusoidal RoPE โ€” mirrors RopeND for consistency.
+ #
+ # Auto-derive the base using the same rule as RopeND(auto_base=True):
+ # base โ‰ˆ 8ยทL/ฯ€, rounded up to the nearest 100
+ # This guarantees the lowest-frequency channel rotates a meaningful
+ # fraction of a turn across max_time without wrapping.
+ if time_base is None:
+ time_base = float((int(8 * max_time / math.pi) // 100 + 1) * 100)
+ self.time_base = time_base
+
+ # Pre-compute the full cos/sin table up to max_time. Registered as
+ # non-persistent buffers so they follow the module across devices /
+ # dtypes automatically (analogous to RopeND's lazy per-axis cache,
+ # but always-on since max_time is known at construction).
+ inv_freq = 1.0 / (
+ time_base ** (torch.arange(0, self.time_dim, 2).float() / self.time_dim)
+ )
+ t = torch.arange(max_time).float()
+ freqs = torch.einsum("i,j->ij", t, inv_freq) # (max_time, time_dim/2)
+ freqs = torch.cat([freqs, freqs], dim=-1) # (max_time, time_dim)
+ self.register_buffer("t_cos_cache", freqs.cos(), persistent=False)
+ self.register_buffer("t_sin_cache", freqs.sin(), persistent=False)
+
+ def _compute_graph_cos_sin(
+ self, spectral_coords: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Project spectral coordinates to rotation angles via spectral encoder."""
+ angles = self.spectral_encoder(spectral_coords) # (B, J, graph_dim // 2)
+ angles = torch.cat([angles, angles], dim=-1) # (B, J, graph_dim)
+ return angles.cos(), angles.sin()
+
+ def _compute_time_cos_sin(
+ self, nframes: int,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Look up cached temporal frequencies (matches RopeND cache style)."""
+ assert nframes <= self.max_time, (
+ f"nframes={nframes} exceeds max_time={self.max_time}"
+ )
+ return self.t_cos_cache[:nframes], self.t_sin_cache[:nframes]
+
+ def forward(
+ self,
+ q: torch.Tensor,
+ k: torch.Tensor,
+ spectral_coords: torch.Tensor,
+ nframes: int,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Apply combined graph + temporal RoPE to query and key.
+
+ Axis-wise rotation: split head_dim into graph_dim + time_dim, then
+ apply a proper 2D RoPE independently within each half. The cos/sin
+ tensors are never materialized to the full ``(B, T*J, C)`` shape โ€”
+ broadcasting over the reshaped ``(B, H, T, J, C)`` view handles it.
+
+ Args:
+ q, k: ``(B, H, T*J, C)`` query/key over flattened spatio-temporal tokens.
+ spectral_coords: ``(B, J, num_eigvecs)`` Laplacian eigenvectors.
+ nframes: T (number of frames).
+
+ Returns:
+ Rotated ``(q, k)`` with the same shapes.
+ """
+ B, H, L, C = q.shape
+ njoints = spectral_coords.shape[1]
+ assert L == nframes * njoints, (
+ f"L={L} != nframes*njoints={nframes}*{njoints}"
+ )
+ assert C == self.head_dim, f"C={C} != head_dim={self.head_dim}"
+
+ # Per-axis angles (no expansion โ€” broadcasting only).
+ g_cos, g_sin = self._compute_graph_cos_sin(spectral_coords) # (B, J, graph_dim)
+ t_cos, t_sin = self._compute_time_cos_sin(nframes) # (T, time_dim)
+
+ # Unflatten tokens so T and J are separate axes for broadcasting.
+ # ``reshape`` (not ``view``) because q/k come from ``.permute().unbind()``
+ # in RoPEAttention and may be non-contiguous.
+ q = q.reshape(B, H, nframes, njoints, C)
+ k = k.reshape(B, H, nframes, njoints, C)
+
+ # Split channels โ€” each half gets its own proper RoPE rotation.
+ q_g, q_t = q[..., :self.graph_dim], q[..., self.graph_dim:]
+ k_g, k_t = k[..., :self.graph_dim], k[..., self.graph_dim:]
+
+ # Graph rotation: (B, J, graph_dim) โ†’ (B, 1, 1, J, graph_dim)
+ g_cos = g_cos.unsqueeze(1).unsqueeze(2)
+ g_sin = g_sin.unsqueeze(1).unsqueeze(2)
+ q_g, k_g = _apply_rotary_pos_emb(q_g, k_g, g_cos, g_sin)
+
+ # Temporal rotation: (T, time_dim) โ†’ (1, 1, T, 1, time_dim)
+ t_cos = t_cos.view(1, 1, nframes, 1, self.time_dim)
+ t_sin = t_sin.view(1, 1, nframes, 1, self.time_dim)
+ q_t, k_t = _apply_rotary_pos_emb(q_t, k_t, t_cos, t_sin)
+
+ # Concatenate channels back and restore flat token layout.
+ q = torch.cat([q_g, q_t], dim=-1).reshape(B, H, L, C)
+ k = torch.cat([k_g, k_t], dim=-1).reshape(B, H, L, C)
+ return q, k
\ No newline at end of file
diff --git a/unimate/models/diffusion/__init__.py b/unimate/models/diffusion/__init__.py
new file mode 100644
index 0000000..4e22a60
--- /dev/null
+++ b/unimate/models/diffusion/__init__.py
@@ -0,0 +1 @@
+"""Gaussian diffusion (DDPM) schedule, adapted from guided-diffusion."""
diff --git a/unimate/models/diffusion/gaussian_diffusion.py b/unimate/models/diffusion/gaussian_diffusion.py
new file mode 100644
index 0000000..6075a2e
--- /dev/null
+++ b/unimate/models/diffusion/gaussian_diffusion.py
@@ -0,0 +1,1514 @@
+# This code is based on https://github.com/openai/guided-diffusion
+"""
+This code started out as a PyTorch port of Ho et al's diffusion models:
+https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py
+
+Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules.
+"""
+
+import enum
+import math
+import numpy as np
+import torch
+import torch as th
+from copy import deepcopy
+from unimate.models.diffusion.nn import mean_flat, sum_flat
+from unimate.models.diffusion.losses import normal_kl, discretized_gaussian_log_likelihood
+from unimate.utils.geo_utils import geodesic_distance
+from unimate.utils.rotation_conversions import rotation_6d_to_matrix_safe
+
+def get_named_beta_schedule(schedule_name, num_diffusion_timesteps, scale_betas=1.):
+ """
+ Get a pre-defined beta schedule for the given name.
+
+ The beta schedule library consists of beta schedules which remain similar
+ in the limit of num_diffusion_timesteps.
+ Beta schedules may be added, but should not be removed or changed once
+ they are committed to maintain backwards compatibility.
+ """
+ if schedule_name == "linear":
+ # Linear schedule from Ho et al, extended to work for any number of
+ # diffusion steps.
+ scale = scale_betas * 1000 / num_diffusion_timesteps
+ beta_start = scale * 0.0001
+ beta_end = scale * 0.02
+ return np.linspace(
+ beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64
+ )
+ elif schedule_name == "cosine":
+ return betas_for_alpha_bar(
+ num_diffusion_timesteps,
+ lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
+ )
+ else:
+ raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
+
+
+def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
+ """
+ Create a beta schedule that discretizes the given alpha_t_bar function,
+ which defines the cumulative product of (1-beta) over time from t = [0,1].
+
+ :param num_diffusion_timesteps: the number of betas to produce.
+ :param alpha_bar: a lambda that takes an argument t from 0 to 1 and
+ produces the cumulative product of (1-beta) up to that
+ part of the diffusion process.
+ :param max_beta: the maximum beta to use; use values lower than 1 to
+ prevent singularities.
+ """
+ betas = []
+ for i in range(num_diffusion_timesteps):
+ t1 = i / num_diffusion_timesteps
+ t2 = (i + 1) / num_diffusion_timesteps
+ betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
+ return np.array(betas)
+
+
+class ModelMeanType(enum.Enum):
+ """
+ Which type of output the model predicts.
+ """
+
+ PREVIOUS_X = enum.auto() # the model predicts x_{t-1}
+ START_X = enum.auto() # the model predicts x_0
+ EPSILON = enum.auto() # the model predicts epsilon
+
+
+class ModelVarType(enum.Enum):
+ """
+ What is used as the model's output variance.
+
+ The LEARNED_RANGE option has been added to allow the model to predict
+ values between FIXED_SMALL and FIXED_LARGE, making its job easier.
+ """
+
+ LEARNED = enum.auto()
+ FIXED_SMALL = enum.auto()
+ FIXED_LARGE = enum.auto()
+ LEARNED_RANGE = enum.auto()
+
+
+class LossType(enum.Enum):
+ MSE = enum.auto() # use raw MSE loss (and KL when learning variances)
+ RESCALED_MSE = (
+ enum.auto()
+ ) # use raw MSE loss (with RESCALED_KL when learning variances)
+ KL = enum.auto() # use the variational lower-bound
+ RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB
+
+ def is_vb(self):
+ return self == LossType.KL or self == LossType.RESCALED_KL
+
+
+class GaussianDiffusion:
+ """
+ Utilities for training and sampling diffusion models.
+
+ Ported directly from here, and then adapted over time to further experimentation.
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42
+
+ :param betas: a 1-D numpy array of betas for each diffusion timestep,
+ starting at T and going to 1.
+ :param model_mean_type: a ModelMeanType determining what the model outputs.
+ :param model_var_type: a ModelVarType determining how variance is output.
+ :param loss_type: a LossType determining the loss function to use.
+ :param rescale_timesteps: if True, pass floating point timesteps into the
+ model so that they are always scaled like in the
+ original paper (0 to 1000).
+ """
+
+ def __init__(
+ self,
+ *,
+ betas,
+ model_mean_type,
+ model_var_type,
+ loss_type,
+ rescale_timesteps=False,
+ lambda_geo=0.,
+ ):
+ self.model_mean_type = model_mean_type
+ self.model_var_type = model_var_type
+ self.loss_type = loss_type
+ self.rescale_timesteps = rescale_timesteps
+ self.lambda_geo = lambda_geo
+
+ # Use float64 for accuracy.
+ betas = np.array(betas, dtype=np.float64)
+ self.betas = betas
+ assert len(betas.shape) == 1, "betas must be 1-D"
+ assert (betas > 0).all() and (betas <= 1).all()
+
+ self.num_timesteps = int(betas.shape[0])
+
+ alphas = 1.0 - betas
+ self.alphas_cumprod = np.cumprod(alphas, axis=0)
+ self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1])
+ self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0)
+ assert self.alphas_cumprod_prev.shape == (self.num_timesteps,)
+
+ # calculations for diffusion q(x_t | x_{t-1}) and others
+ self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod)
+ self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod)
+ self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod)
+ self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod)
+ self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)
+
+ # calculations for posterior q(x_{t-1} | x_t, x_0)
+ self.posterior_variance = (
+ betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
+ )
+ # log calculation clipped because the posterior variance is 0 at the
+ # beginning of the diffusion chain.
+ self.posterior_log_variance_clipped = np.log(
+ np.append(self.posterior_variance[1], self.posterior_variance[1:])
+ )
+ self.posterior_mean_coef1 = (
+ betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)
+ )
+ self.posterior_mean_coef2 = (
+ (1.0 - self.alphas_cumprod_prev)
+ * np.sqrt(alphas)
+ / (1.0 - self.alphas_cumprod)
+ )
+
+ self.l2_loss = lambda a, b: (a - b) ** 2 # element-wise; masks are applied afterwards
+
+ def temporal_spatial_masked_l2(self, target, pred, temp_mask, spat_mask, lengths, n_joints):
+ """Compute masked L2 loss over temporal and spatial dimensions.
+ Args:
+ target, pred: (bs, n_joints, feat_dim, n_frames)
+ temp_mask: (bs, 1, 1, n_frames)
+ spat_mask: (bs, 1, 1, n_joints)
+ lengths, n_joints: (bs,) number of valid frames, number of valid joints
+ Returns:
+ mse_loss_val: (bs,) MSE loss values for each sample in the batch
+ """
+ loss = self.l2_loss(target, pred)
+
+ temp_masked_loss = loss * temp_mask.float()
+ spat_temp_masked_loss = (temp_masked_loss * spat_mask.float().transpose(1,3))
+ loss = sum_flat(spat_temp_masked_loss) # gives \sigma_euclidean over unmasked elements
+ non_zero_elements = lengths * n_joints * target.size(2)
+ mse_loss_val = loss / non_zero_elements
+ return mse_loss_val
+
+ def geodesic_loss(self, target, pred, temp_mask, spat_mask, lengths, n_joints):
+ """Compute masked geodesic loss over temporal and spatial dimensions.
+ Args:
+ target, pred: (bs, n_joints, feat_dim, n_frames)
+ temp_mask: (bs, 1, 1, n_frames)
+ spat_mask: (bs, 1, 1, n_joints)
+ lengths, n_joints: (bs,) number of valid frames, number of valid joints
+ Returns:
+ loss_val: (bs,) geodesic loss values for each sample in the batch
+ """
+ rots_target = rotation_6d_to_matrix_safe(target.permute(0, 3, 1, 2)[..., 3:9]) # (bs, F, J, 3, 3)
+ rots_pred = rotation_6d_to_matrix_safe(pred.permute(0, 3, 1, 2)[..., 3:9]) # (bs, F, J, 3, 3)
+
+ loss = geodesic_distance(rots_pred, rots_target).permute(0, 2, 3, 1) # (bs, J, 1, F)
+ temp_masked_loss = loss * temp_mask.float()
+ spat_temp_masked_loss = (temp_masked_loss * spat_mask.float().transpose(1,3))
+ loss = sum_flat(spat_temp_masked_loss) # gives \sigma_euclidean over unmasked elements
+ non_zero_elements = lengths * n_joints # (bs,) number of non-masked joints * frames
+ loss_val = loss / non_zero_elements # (bs,)
+ return loss_val
+
+ def q_mean_variance(self, x_start, t):
+ """
+ Get the distribution q(x_t | x_0).
+
+ :param x_start: the [N x C x ...] tensor of noiseless inputs.
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
+ :return: A tuple (mean, variance, log_variance), all of x_start's shape.
+ """
+ mean = (
+ _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
+ )
+ variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
+ log_variance = _extract_into_tensor(
+ self.log_one_minus_alphas_cumprod, t, x_start.shape
+ )
+ return mean, variance, log_variance
+
+ def q_sample(self, x_start, t, noise=None):
+ """
+ Diffuse the dataset for a given number of diffusion steps.
+
+ In other words, sample from q(x_t | x_0).
+
+ :param x_start: the initial dataset batch.
+ :param t: the number of diffusion steps (minus 1). Here, 0 means one step.
+ :param noise: if specified, the split-out normal noise.
+ :return: A noisy version of x_start.
+ """
+ if noise is None:
+ noise = th.randn_like(x_start)
+ assert noise.shape == x_start.shape
+ return (
+ _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
+ + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
+ * noise
+ )
+
+ def q_posterior_mean_variance(self, x_start, x_t, t):
+ """
+ Compute the mean and variance of the diffusion posterior:
+
+ q(x_{t-1} | x_t, x_0)
+
+ """
+ assert x_start.shape == x_t.shape
+ posterior_mean = (
+ _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start
+ + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
+ )
+ posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape)
+ posterior_log_variance_clipped = _extract_into_tensor(
+ self.posterior_log_variance_clipped, t, x_t.shape
+ )
+ assert (
+ posterior_mean.shape[0]
+ == posterior_variance.shape[0]
+ == posterior_log_variance_clipped.shape[0]
+ == x_start.shape[0]
+ )
+ return posterior_mean, posterior_variance, posterior_log_variance_clipped
+
+ def p_mean_variance(
+ self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None, get_layer_activation=-1
+ ):
+ """
+ Apply the model to get p(x_{t-1} | x_t), as well as a prediction of
+ the initial x, x_0.
+
+ :param model: the model, which takes a signal and a batch of timesteps
+ as input.
+ :param x: the [N x C x ...] tensor at time t.
+ :param t: a 1-D Tensor of timesteps.
+ :param clip_denoised: if True, clip the denoised signal into [-1, 1].
+ :param denoised_fn: if not None, a function which applies to the
+ x_start prediction before it is used to sample. Applies before
+ clip_denoised.
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
+ pass to the model. This can be used for conditioning.
+ :return: a dict with the following keys:
+ - 'mean': the model mean output.
+ - 'variance': the model variance output.
+ - 'log_variance': the log of 'variance'.
+ - 'pred_xstart': the prediction for x_0.
+ """
+ if model_kwargs is None:
+ model_kwargs = {}
+
+ B, C = x.shape[:2]
+ assert t.shape == (B,)
+ if get_layer_activation > -1 and get_layer_activation < model.model.num_layers :
+ model_output, activations = model(x, self._scale_timesteps(t), get_layer_activation=get_layer_activation, **model_kwargs)
+ else:
+ model_output = model(x, self._scale_timesteps(t), **model_kwargs)
+
+ if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]:
+ assert model_output.shape == (B, C * 2, *x.shape[2:])
+ model_output, model_var_values = th.split(model_output, C, dim=1)
+ if self.model_var_type == ModelVarType.LEARNED:
+ model_log_variance = model_var_values
+ model_variance = th.exp(model_log_variance)
+ else:
+ min_log = _extract_into_tensor(
+ self.posterior_log_variance_clipped, t, x.shape
+ )
+ max_log = _extract_into_tensor(np.log(self.betas), t, x.shape)
+ # The model_var_values is [-1, 1] for [min_var, max_var].
+ frac = (model_var_values + 1) / 2
+ model_log_variance = frac * max_log + (1 - frac) * min_log
+ model_variance = th.exp(model_log_variance)
+ else:
+ model_variance, model_log_variance = {
+ # for fixedlarge, we set the initial (log-)variance like so
+ # to get a better decoder log likelihood.
+ ModelVarType.FIXED_LARGE: (
+ np.append(self.posterior_variance[1], self.betas[1:]),
+ np.log(np.append(self.posterior_variance[1], self.betas[1:])),
+ ),
+ ModelVarType.FIXED_SMALL: (
+ self.posterior_variance,
+ self.posterior_log_variance_clipped,
+ ),
+ }[self.model_var_type]
+
+
+ model_variance = _extract_into_tensor(model_variance, t, x.shape)
+ model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)
+
+ def process_xstart(x):
+ if denoised_fn is not None:
+ x = denoised_fn(x)
+ if clip_denoised:
+ return x.clamp(-1, 1)
+ return x
+
+ if self.model_mean_type == ModelMeanType.PREVIOUS_X:
+ pred_xstart = process_xstart(
+ self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output)
+ )
+ model_mean = model_output
+ elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]: # THIS IS US!
+ if self.model_mean_type == ModelMeanType.START_X:
+ pred_xstart = process_xstart(model_output)
+ else:
+ pred_xstart = process_xstart(
+ self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
+ )
+ model_mean, _, _ = self.q_posterior_mean_variance(
+ x_start=pred_xstart, x_t=x, t=t
+ )
+ else:
+ raise NotImplementedError(self.model_mean_type)
+
+ assert (
+ model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
+ )
+ if get_layer_activation > -1 and get_layer_activation < model.model.num_layers:
+ return {
+ "mean": model_mean,
+ "variance": model_variance,
+ "log_variance": model_log_variance,
+ "pred_xstart": pred_xstart,
+ "activations": activations
+ }
+ else:
+ return {
+ "mean": model_mean,
+ "variance": model_variance,
+ "log_variance": model_log_variance,
+ "pred_xstart": pred_xstart,
+ }
+
+ def _predict_xstart_from_eps(self, x_t, t, eps):
+ assert x_t.shape == eps.shape
+ return (
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
+ - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
+ )
+
+ def _predict_xstart_from_xprev(self, x_t, t, xprev):
+ assert x_t.shape == xprev.shape
+ return ( # (xprev - coef2*x_t) / coef1
+ _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev
+ - _extract_into_tensor(
+ self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape
+ )
+ * x_t
+ )
+
+ def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
+ return (
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
+ - pred_xstart
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
+
+ def _scale_timesteps(self, t):
+ if self.rescale_timesteps:
+ return t.float() * (1000.0 / self.num_timesteps)
+ return t
+
+ def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
+ """
+ Compute the mean for the previous step, given a function cond_fn that
+ computes the gradient of a conditional log probability with respect to
+ x. In particular, cond_fn computes grad(log(p(y|x))), and we want to
+ condition on y.
+
+ This uses the conditioning strategy from Sohl-Dickstein et al. (2015).
+ """
+ gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs)
+ new_mean = (
+ p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float()
+ )
+ return new_mean
+
+ def condition_mean_with_grad(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
+ """
+ Compute the mean for the previous step, given a function cond_fn that
+ computes the gradient of a conditional log probability with respect to
+ x. In particular, cond_fn computes grad(log(p(y|x))), and we want to
+ condition on y.
+
+ This uses the conditioning strategy from Sohl-Dickstein et al. (2015).
+ """
+ gradient = cond_fn(x, t, p_mean_var, **model_kwargs)
+ new_mean = (
+ p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float()
+ )
+ return new_mean
+
+ def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
+ """
+ Compute what the p_mean_variance output would have been, should the
+ model's score function be conditioned by cond_fn.
+
+ See condition_mean() for details on cond_fn.
+
+ Unlike condition_mean(), this instead uses the conditioning strategy
+ from Song et al (2020).
+ """
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
+
+ eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
+ eps = eps - (1 - alpha_bar).sqrt() * cond_fn(
+ x, self._scale_timesteps(t), **model_kwargs
+ )
+
+ out = p_mean_var.copy()
+ out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps)
+ out["mean"], _, _ = self.q_posterior_mean_variance(
+ x_start=out["pred_xstart"], x_t=x, t=t
+ )
+ return out
+
+ def condition_score_with_grad(self, cond_fn, p_mean_var, x, t, model_kwargs=None):
+ """
+ Compute what the p_mean_variance output would have been, should the
+ model's score function be conditioned by cond_fn.
+
+ See condition_mean() for details on cond_fn.
+
+ Unlike condition_mean(), this instead uses the conditioning strategy
+ from Song et al (2020).
+ """
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
+
+ eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"])
+ eps = eps - (1 - alpha_bar).sqrt() * cond_fn(
+ x, t, p_mean_var, **model_kwargs
+ )
+
+ out = p_mean_var.copy()
+ out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps)
+ out["mean"], _, _ = self.q_posterior_mean_variance(
+ x_start=out["pred_xstart"], x_t=x, t=t
+ )
+ return out
+
+ def p_sample(
+ self,
+ model,
+ x,
+ t,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ const_noise=False,
+ ):
+ """
+ Sample x_{t-1} from the model at the given timestep.
+
+ :param model: the model to sample from.
+ :param x: the current tensor at x_{t-1}.
+ :param t: the value of t, starting at 0 for the first diffusion step.
+ :param clip_denoised: if True, clip the x_start prediction to [-1, 1].
+ :param denoised_fn: if not None, a function which applies to the
+ x_start prediction before it is used to sample.
+ :param cond_fn: if not None, this is a gradient function that acts
+ similarly to the model.
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
+ pass to the model. This can be used for conditioning.
+ :return: a dict containing the following keys:
+ - 'sample': a random sample from the model.
+ - 'pred_xstart': a prediction of x_0.
+ """
+ out = self.p_mean_variance(
+ model,
+ x,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ model_kwargs=model_kwargs,
+ )
+ noise = th.randn_like(x)
+ if const_noise:
+ noise = noise[[0]].repeat(x.shape[0], 1, 1, 1)
+
+ nonzero_mask = (
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
+ ) # no noise when t == 0
+ if cond_fn is not None:
+ out["mean"] = self.condition_mean(
+ cond_fn, out, x, t, model_kwargs=model_kwargs
+ )
+ sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
+ return {"sample": sample, "pred_xstart": out["pred_xstart"]}
+
+ def p_sample_dift(
+ self,
+ model,
+ x,
+ t,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ const_noise=False,
+ get_layer_activation = -1
+ ):
+ """
+ Sample x_{t-1} from the model at the given timestep.
+
+ :param model: the model to sample from.
+ :param x: the current tensor at x_{t-1}.
+ :param t: the value of t, starting at 0 for the first diffusion step.
+ :param clip_denoised: if True, clip the x_start prediction to [-1, 1].
+ :param denoised_fn: if not None, a function which applies to the
+ x_start prediction before it is used to sample.
+ :param cond_fn: if not None, this is a gradient function that acts
+ similarly to the model.
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
+ pass to the model. This can be used for conditioning.
+ :return: a dict containing the following keys:
+ - 'sample': a random sample from the model.
+ - 'pred_xstart': a prediction of x_0.
+ """
+ out = self.p_mean_variance(
+ model,
+ x,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ model_kwargs=model_kwargs,
+ get_layer_activation=get_layer_activation
+ )
+ noise = th.randn_like(x)
+ if const_noise:
+ noise = noise[[0]].repeat(x.shape[0], 1, 1, 1)
+
+ nonzero_mask = (
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
+ ) # no noise when t == 0
+ if cond_fn is not None:
+ out["mean"] = self.condition_mean(
+ cond_fn, out, x, t, model_kwargs=model_kwargs
+ )
+ sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
+ if get_layer_activation > -1:
+ return {"sample": sample, "pred_xstart": out["pred_xstart"], "activations": out["activations"]}
+ else:
+ return {"sample": sample, "pred_xstart": out["pred_xstart"]}
+
+ def p_sample_with_grad(
+ self,
+ model,
+ x,
+ t,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ ):
+ """
+ Sample x_{t-1} from the model at the given timestep.
+
+ :param model: the model to sample from.
+ :param x: the current tensor at x_{t-1}.
+ :param t: the value of t, starting at 0 for the first diffusion step.
+ :param clip_denoised: if True, clip the x_start prediction to [-1, 1].
+ :param denoised_fn: if not None, a function which applies to the
+ x_start prediction before it is used to sample.
+ :param cond_fn: if not None, this is a gradient function that acts
+ similarly to the model.
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
+ pass to the model. This can be used for conditioning.
+ :return: a dict containing the following keys:
+ - 'sample': a random sample from the model.
+ - 'pred_xstart': a prediction of x_0.
+ """
+ with th.enable_grad():
+ x = x.detach().requires_grad_()
+ out = self.p_mean_variance(
+ model,
+ x,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ model_kwargs=model_kwargs,
+ )
+ noise = th.randn_like(x)
+ nonzero_mask = (
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
+ ) # no noise when t == 0
+ if cond_fn is not None:
+ out["mean"] = self.condition_mean_with_grad(
+ cond_fn, out, x, t, model_kwargs=model_kwargs
+ )
+ sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise
+ return {"sample": sample, "pred_xstart": out["pred_xstart"].detach()}
+
+ def p_sample_loop(
+ self,
+ model,
+ shape,
+ noise=None,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ device=None,
+ progress=False,
+ skip_timesteps=0,
+ init_image=None,
+ randomize_class=False,
+ cond_fn_with_grad=False,
+ dump_steps=None,
+ const_noise=False,
+ get_activations={"layer": -1, "timestep": -1},
+ ):
+ """
+ Generate samples from the model.
+
+ :param model: the model module.
+ :param shape: the shape of the samples, (N, C, H, W).
+ :param noise: if specified, the noise from the encoder to sample.
+ Should be of the same shape as `shape`.
+ :param clip_denoised: if True, clip x_start predictions to [-1, 1].
+ :param denoised_fn: if not None, a function which applies to the
+ x_start prediction before it is used to sample.
+ :param cond_fn: if not None, this is a gradient function that acts
+ similarly to the model.
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
+ pass to the model. This can be used for conditioning.
+ :param device: if specified, the device to create the samples on.
+ If not specified, use a model parameter's device.
+ :param progress: if True, show a tqdm progress bar.
+ :param const_noise: If True, will noise all samples with the same noise throughout sampling
+ :return: a non-differentiable batch of samples.
+ """
+ final = None
+ if dump_steps is not None:
+ dump = []
+ sample_loop = self.p_sample_loop_progressive
+ for i, sample in enumerate(sample_loop(
+ model,
+ shape,
+ noise=noise,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ cond_fn=cond_fn,
+ model_kwargs=model_kwargs,
+ device=device,
+ progress=progress,
+ skip_timesteps=skip_timesteps,
+ init_image=init_image,
+ randomize_class=randomize_class,
+ cond_fn_with_grad=cond_fn_with_grad,
+ const_noise=const_noise,
+ )):
+ final = sample
+ if dump_steps is not None and i in dump_steps:
+ dump.append(deepcopy(sample["sample"]))
+
+ if dump_steps is not None:
+ return dump
+ return final["sample"]
+
+ def p_sample_single_timestep(
+ self,
+ model,
+ shape,
+ noise=None,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ device=None,
+ init_image=None,
+ randomize_class=False,
+ const_noise=False,
+ get_activations={"layer": -1, "timestep": -1},
+ ):
+ """
+ Generate samples from the model.
+
+ :param model: the model module.
+ :param shape: the shape of the samples, (N, C, H, W).
+ :param t: diffusion timestep.
+ :param noise: if specified, the noise from the encoder to sample.
+ Should be of the same shape as `shape`.
+ :param clip_denoised: if True, clip x_start predictions to [-1, 1].
+ :param denoised_fn: if not None, a function which applies to the
+ x_start prediction before it is used to sample.
+ :param cond_fn: if not None, this is a gradient function that acts
+ similarly to the model.
+ :param model_kwargs: if not None, a dict of extra keyword arguments to
+ pass to the model. This can be used for conditioning.
+ :param device: if specified, the device to create the samples on.
+ If not specified, use a model parameter's device.
+ :param progress: if True, show a tqdm progress bar.
+ :param const_noise: If True, will noise all samples with the same noise throughout sampling
+ :return: a non-differentiable batch of samples.
+ """
+ activations_dict=dict()
+ if device is None:
+ device = next(model.parameters()).device
+ assert isinstance(shape, (tuple, list))
+ if noise is None:
+ noise = th.randn(*shape, device=device)
+ img = th.randn(*shape, device=device)
+ t = get_activations["timestep"]
+ t_tnsr = th.tensor([t] * shape[0], device=device)
+ if init_image is not None:
+ # randomize the initial image to timestep t for dift extractrion
+ img = self.q_sample(init_image, t_tnsr, noise)
+ with th.no_grad():
+ out = self.p_sample_dift(
+ model,
+ img,
+ t_tnsr,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ cond_fn=cond_fn,
+ model_kwargs=model_kwargs,
+ const_noise=const_noise,
+ get_layer_activation=get_activations["layer"]
+ )
+
+ if get_activations["timestep"] == t:
+ activations_dict[t] = out["activations"]
+
+ if get_activations["timestep"] == t:
+ return out["sample"], activations_dict
+ return out["sample"]
+
+ def p_sample_loop_progressive(
+ self,
+ model,
+ shape,
+ noise=None,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ device=None,
+ progress=False,
+ skip_timesteps=0,
+ init_image=None,
+ randomize_class=False,
+ cond_fn_with_grad=False,
+ const_noise=False,
+ get_activations=None# dummy
+ ):
+ """
+ Generate samples from the model and yield intermediate samples from
+ each timestep of diffusion.
+
+ Arguments are the same as p_sample_loop().
+ Returns a generator over dicts, where each dict is the return value of
+ p_sample().
+ """
+ if device is None:
+ device = next(model.parameters()).device
+ assert isinstance(shape, (tuple, list))
+ if noise is not None:
+ img = noise
+ else:
+ img = th.randn(*shape, device=device)
+
+ if skip_timesteps and init_image is None:
+ init_image = th.zeros_like(img)
+
+ indices = list(range(self.num_timesteps - skip_timesteps))[::-1]
+
+ if init_image is not None:
+ my_t = th.ones([shape[0]], device=device, dtype=th.long) * indices[0]
+ img = self.q_sample(init_image, my_t, img)
+
+ if progress:
+ # Lazy import so that we don't depend on tqdm.
+ from tqdm.auto import tqdm
+
+ indices = tqdm(indices)
+
+ for i in indices:
+ t = th.tensor([i] * shape[0], device=device)
+ with th.no_grad():
+ sample_fn = self.p_sample_with_grad if cond_fn_with_grad else self.p_sample
+ out = sample_fn(
+ model,
+ img,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ cond_fn=cond_fn,
+ model_kwargs=model_kwargs,
+ const_noise=const_noise,
+ )
+ yield out
+ img = out["sample"]
+
+ def p_sample_loop_for_dift(
+ self,
+ model,
+ shape,
+ noise=None,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ device=None,
+ progress=False,
+ skip_timesteps=0,
+ init_image=None,
+ randomize_class=False,
+ cond_fn_with_grad=False,
+ const_noise=False,
+ get_activations={"layer": -1, "timestep": -1}
+
+ ):
+ """
+ Generate samples from the model and yield intermediate samples from
+ each timestep of diffusion.
+
+ Arguments are the same as p_sample_loop().
+ Returns a generator over dicts, where each dict is the return value of
+ p_sample().
+ """
+ if device is None:
+ device = next(model.parameters()).device
+ assert isinstance(shape, (tuple, list))
+ if noise is not None:
+ noise = th.randn(*shape, device=device)
+ img = th.randn(*shape, device=device)
+ indices = list(range(self.num_timesteps - skip_timesteps))[::-1]
+ if progress:
+ # Lazy import so that we don't depend on tqdm.
+ from tqdm.auto import tqdm
+
+ indices = tqdm(indices)
+
+ for i in indices:
+ get_layer_activation = -1
+ if get_activations["timestep"] == i:
+ get_layer_activation = get_activations["layer"]
+ t = th.tensor([i] * shape[0], device=device)
+ if init_image is not None:
+ # randomize the initial image to timestep t for dift extractrion
+ img = self.q_sample(init_image, t, noise)
+
+ with th.no_grad():
+ sample_fn = self.p_sample_dift
+ out = sample_fn(
+ model,
+ img,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ cond_fn=cond_fn,
+ model_kwargs=model_kwargs,
+ const_noise=const_noise,
+ get_layer_activation = get_layer_activation
+ )
+ yield out
+ img = out["sample"]
+
+ def ddim_sample(
+ self,
+ model,
+ x,
+ t,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ eta=0.0,
+ ):
+ """
+ Sample x_{t-1} from the model using DDIM.
+
+ Same usage as p_sample().
+ """
+ out_orig = self.p_mean_variance(
+ model,
+ x,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ model_kwargs=model_kwargs,
+ )
+ if cond_fn is not None:
+ out = self.condition_score(cond_fn, out_orig, x, t, model_kwargs=model_kwargs)
+ else:
+ out = out_orig
+
+ # Usually our model outputs epsilon, but we re-derive it
+ # in case we used x_start or x_prev prediction.
+ eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
+
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
+ alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
+ sigma = (
+ eta
+ * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
+ * th.sqrt(1 - alpha_bar / alpha_bar_prev)
+ )
+ # Equation 12.
+ noise = th.randn_like(x)
+ mean_pred = (
+ out["pred_xstart"] * th.sqrt(alpha_bar_prev)
+ + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
+ )
+ nonzero_mask = (
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
+ ) # no noise when t == 0
+ sample = mean_pred + nonzero_mask * sigma * noise
+ return {"sample": sample, "pred_xstart": out_orig["pred_xstart"]}
+
+ def ddim_sample_with_grad(
+ self,
+ model,
+ x,
+ t,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ eta=0.0,
+ ):
+ """
+ Sample x_{t-1} from the model using DDIM.
+
+ Same usage as p_sample().
+ """
+ with th.enable_grad():
+ x = x.detach().requires_grad_()
+ out_orig = self.p_mean_variance(
+ model,
+ x,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ model_kwargs=model_kwargs,
+ )
+ if cond_fn is not None:
+ out = self.condition_score_with_grad(cond_fn, out_orig, x, t,
+ model_kwargs=model_kwargs)
+ else:
+ out = out_orig
+
+ out["pred_xstart"] = out["pred_xstart"].detach()
+
+ # Usually our model outputs epsilon, but we re-derive it
+ # in case we used x_start or x_prev prediction.
+ eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
+
+ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
+ alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
+ sigma = (
+ eta
+ * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
+ * th.sqrt(1 - alpha_bar / alpha_bar_prev)
+ )
+ # Equation 12.
+ noise = th.randn_like(x)
+ mean_pred = (
+ out["pred_xstart"] * th.sqrt(alpha_bar_prev)
+ + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
+ )
+ nonzero_mask = (
+ (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
+ ) # no noise when t == 0
+ sample = mean_pred + nonzero_mask * sigma * noise
+ return {"sample": sample, "pred_xstart": out_orig["pred_xstart"].detach()}
+
+ def ddim_reverse_sample(
+ self,
+ model,
+ x,
+ t,
+ clip_denoised=True,
+ denoised_fn=None,
+ model_kwargs=None,
+ eta=0.0,
+ ):
+ """
+ Sample x_{t+1} from the model using DDIM reverse ODE.
+ """
+ assert eta == 0.0, "Reverse ODE only for deterministic path"
+ out = self.p_mean_variance(
+ model,
+ x,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ model_kwargs=model_kwargs,
+ )
+ # Usually our model outputs epsilon, but we re-derive it
+ # in case we used x_start or x_prev prediction.
+ eps = (
+ _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
+ - out["pred_xstart"]
+ ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
+ alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape)
+
+ # Equation 12. reversed
+ mean_pred = (
+ out["pred_xstart"] * th.sqrt(alpha_bar_next)
+ + th.sqrt(1 - alpha_bar_next) * eps
+ )
+
+ return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]}
+
+ def ddim_sample_loop(
+ self,
+ model,
+ shape,
+ noise=None,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ device=None,
+ progress=False,
+ eta=0.0,
+ skip_timesteps=0,
+ init_image=None,
+ randomize_class=False,
+ cond_fn_with_grad=False,
+ dump_steps=None,
+ const_noise=False,
+ ):
+ """
+ Generate samples from the model using DDIM.
+
+ Same usage as p_sample_loop().
+ """
+ if dump_steps is not None:
+ raise NotImplementedError()
+ if const_noise == True:
+ raise NotImplementedError()
+
+ final = None
+ for sample in self.ddim_sample_loop_progressive(
+ model,
+ shape,
+ noise=noise,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ cond_fn=cond_fn,
+ model_kwargs=model_kwargs,
+ device=device,
+ progress=progress,
+ eta=eta,
+ skip_timesteps=skip_timesteps,
+ init_image=init_image,
+ randomize_class=randomize_class,
+ cond_fn_with_grad=cond_fn_with_grad,
+ ):
+ final = sample
+ return final["sample"]
+
+ def ddim_sample_loop_progressive(
+ self,
+ model,
+ shape,
+ noise=None,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ device=None,
+ progress=False,
+ eta=0.0,
+ skip_timesteps=0,
+ init_image=None,
+ randomize_class=False,
+ cond_fn_with_grad=False,
+ ):
+ """
+ Use DDIM to sample from the model and yield intermediate samples from
+ each timestep of DDIM.
+
+ Same usage as p_sample_loop_progressive().
+ """
+ if device is None:
+ device = next(model.parameters()).device
+ assert isinstance(shape, (tuple, list))
+ if noise is not None:
+ img = noise
+ else:
+ img = th.randn(*shape, device=device)
+
+ if skip_timesteps and init_image is None:
+ init_image = th.zeros_like(img)
+
+ indices = list(range(self.num_timesteps - skip_timesteps))[::-1]
+
+ if init_image is not None:
+ my_t = th.ones([shape[0]], device=device, dtype=th.long) * indices[0]
+ img = self.q_sample(init_image, my_t, img)
+
+ if progress:
+ # Lazy import so that we don't depend on tqdm.
+ from tqdm.auto import tqdm
+
+ indices = tqdm(indices)
+
+ for i in indices:
+ t = th.tensor([i] * shape[0], device=device)
+ with th.no_grad():
+ sample_fn = self.ddim_sample_with_grad if cond_fn_with_grad else self.ddim_sample
+ out = sample_fn(
+ model,
+ img,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ cond_fn=cond_fn,
+ model_kwargs=model_kwargs,
+ eta=eta,
+ )
+ yield out
+ img = out["sample"]
+
+ def plms_sample(
+ self,
+ model,
+ x,
+ t,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ cond_fn_with_grad=False,
+ order=2,
+ old_out=None,
+ ):
+ """
+ Sample x_{t-1} from the model using Pseudo Linear Multistep.
+
+ Same usage as p_sample().
+ """
+ if not int(order) or not 1 <= order <= 4:
+ raise ValueError('order is invalid (should be int from 1-4).')
+
+ def get_model_output(x, t):
+ with th.set_grad_enabled(cond_fn_with_grad and cond_fn is not None):
+ x = x.detach().requires_grad_() if cond_fn_with_grad else x
+ out_orig = self.p_mean_variance(
+ model,
+ x,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ model_kwargs=model_kwargs,
+ )
+ if cond_fn is not None:
+ if cond_fn_with_grad:
+ out = self.condition_score_with_grad(cond_fn, out_orig, x, t, model_kwargs=model_kwargs)
+ x = x.detach()
+ else:
+ out = self.condition_score(cond_fn, out_orig, x, t, model_kwargs=model_kwargs)
+ else:
+ out = out_orig
+
+ # Usually our model outputs epsilon, but we re-derive it
+ # in case we used x_start or x_prev prediction.
+ eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
+ return eps, out, out_orig
+
+ alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)
+ eps, out, out_orig = get_model_output(x, t)
+
+ if order > 1 and old_out is None:
+ # Pseudo Improved Euler
+ old_eps = [eps]
+ mean_pred = out["pred_xstart"] * th.sqrt(alpha_bar_prev) + th.sqrt(1 - alpha_bar_prev) * eps
+ eps_2, _, _ = get_model_output(mean_pred, t - 1)
+ eps_prime = (eps + eps_2) / 2
+ pred_prime = self._predict_xstart_from_eps(x, t, eps_prime)
+ mean_pred = pred_prime * th.sqrt(alpha_bar_prev) + th.sqrt(1 - alpha_bar_prev) * eps_prime
+ else:
+ # Pseudo Linear Multistep (Adams-Bashforth)
+ old_eps = old_out["old_eps"]
+ old_eps.append(eps)
+ cur_order = min(order, len(old_eps))
+ if cur_order == 1:
+ eps_prime = old_eps[-1]
+ elif cur_order == 2:
+ eps_prime = (3 * old_eps[-1] - old_eps[-2]) / 2
+ elif cur_order == 3:
+ eps_prime = (23 * old_eps[-1] - 16 * old_eps[-2] + 5 * old_eps[-3]) / 12
+ elif cur_order == 4:
+ eps_prime = (55 * old_eps[-1] - 59 * old_eps[-2] + 37 * old_eps[-3] - 9 * old_eps[-4]) / 24
+ else:
+ raise RuntimeError('cur_order is invalid.')
+ pred_prime = self._predict_xstart_from_eps(x, t, eps_prime)
+ mean_pred = pred_prime * th.sqrt(alpha_bar_prev) + th.sqrt(1 - alpha_bar_prev) * eps_prime
+
+ if len(old_eps) >= order:
+ old_eps.pop(0)
+
+ nonzero_mask = (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
+ sample = mean_pred * nonzero_mask + out["pred_xstart"] * (1 - nonzero_mask)
+
+ return {"sample": sample, "pred_xstart": out_orig["pred_xstart"], "old_eps": old_eps}
+
+ def plms_sample_loop(
+ self,
+ model,
+ shape,
+ noise=None,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ device=None,
+ progress=False,
+ skip_timesteps=0,
+ init_image=None,
+ randomize_class=False,
+ cond_fn_with_grad=False,
+ order=2,
+ ):
+ """
+ Generate samples from the model using Pseudo Linear Multistep.
+
+ Same usage as p_sample_loop().
+ """
+ final = None
+ for sample in self.plms_sample_loop_progressive(
+ model,
+ shape,
+ noise=noise,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ cond_fn=cond_fn,
+ model_kwargs=model_kwargs,
+ device=device,
+ progress=progress,
+ skip_timesteps=skip_timesteps,
+ init_image=init_image,
+ randomize_class=randomize_class,
+ cond_fn_with_grad=cond_fn_with_grad,
+ order=order,
+ ):
+ final = sample
+ return final["sample"]
+
+ def plms_sample_loop_progressive(
+ self,
+ model,
+ shape,
+ noise=None,
+ clip_denoised=True,
+ denoised_fn=None,
+ cond_fn=None,
+ model_kwargs=None,
+ device=None,
+ progress=False,
+ skip_timesteps=0,
+ init_image=None,
+ randomize_class=False,
+ cond_fn_with_grad=False,
+ order=2,
+ ):
+ """
+ Use PLMS to sample from the model and yield intermediate samples from each
+ timestep of PLMS.
+
+ Same usage as p_sample_loop_progressive().
+ """
+ if device is None:
+ device = next(model.parameters()).device
+ assert isinstance(shape, (tuple, list))
+ if noise is not None:
+ img = noise
+ else:
+ img = th.randn(*shape, device=device)
+
+ if skip_timesteps and init_image is None:
+ init_image = th.zeros_like(img)
+
+ indices = list(range(self.num_timesteps - skip_timesteps))[::-1]
+
+ if init_image is not None:
+ my_t = th.ones([shape[0]], device=device, dtype=th.long) * indices[0]
+ img = self.q_sample(init_image, my_t, img)
+
+ if progress:
+ # Lazy import so that we don't depend on tqdm.
+ from tqdm.auto import tqdm
+
+ indices = tqdm(indices)
+
+ old_out = None
+
+ for i in indices:
+ t = th.tensor([i] * shape[0], device=device)
+ with th.no_grad():
+ out = self.plms_sample(
+ model,
+ img,
+ t,
+ clip_denoised=clip_denoised,
+ denoised_fn=denoised_fn,
+ cond_fn=cond_fn,
+ model_kwargs=model_kwargs,
+ cond_fn_with_grad=cond_fn_with_grad,
+ order=order,
+ old_out=old_out,
+ )
+ yield out
+ old_out = out
+ img = out["sample"]
+
+ def _vb_terms_bpd(
+ self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None
+ ):
+ """
+ Get a term for the variational lower-bound.
+
+ The resulting units are bits (rather than nats, as one might expect).
+ This allows for comparison to other papers.
+
+ :return: a dict with the following keys:
+ - 'output': a shape [N] tensor of NLLs or KLs.
+ - 'pred_xstart': the x_0 predictions.
+ """
+ true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance(
+ x_start=x_start, x_t=x_t, t=t
+ )
+ out = self.p_mean_variance(
+ model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs
+ )
+ kl = normal_kl(
+ true_mean, true_log_variance_clipped, out["mean"], out["log_variance"]
+ )
+ kl = mean_flat(kl) / np.log(2.0)
+
+ decoder_nll = -discretized_gaussian_log_likelihood(
+ x_start, means=out["mean"], log_scales=0.5 * out["log_variance"]
+ )
+ assert decoder_nll.shape == x_start.shape
+ decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
+
+ # At the first timestep return the decoder NLL,
+ # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
+ output = th.where((t == 0), decoder_nll, kl)
+ return {"output": output, "pred_xstart": out["pred_xstart"]}
+
+ def training_losses(self, model, x_start, t, model_kwargs=None, noise=None):
+ """
+ Compute training losses for a single timestep.
+
+ :param model: the model to compute losses for.
+ :param x_start: the [N x J x D x F] tensor of original inputs.
+ :param t: a batch of timestep indices.
+ :param model_kwargs: extra model keyword arguments; ``model_kwargs["cond"]``
+ holds the conditioning dict (masks, lengths, normalization stats).
+ :param noise: the noise that was added to x_start to produce x_t.
+ :return: a dict with the key "loss" containing a tensor of shape [N].
+ Some mean or variance settings may also have other keys.
+ """
+ if model_kwargs is None:
+ model_kwargs = {}
+
+ temp_mask = model_kwargs['cond']['lengths_mask'] # (bs, 1, 1, F)
+ gt_n_frames = model_kwargs['cond']['motion_length'] # (bs,)
+ joint_mask = model_kwargs['cond']['joint_mask'] # (bs, 1, 1, J)
+ gt_n_joints = model_kwargs['cond']['n_joints'] # (bs,)
+
+ if noise is None:
+ noise = th.randn_like(x_start) # (bs, J, D, F)
+ x_t = self.q_sample(x_start, t, noise=noise) # (bs, J, D, F)
+
+ terms = {}
+
+ if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL:
+ terms["loss"] = self._vb_terms_bpd(
+ model=model,
+ x_start=x_start,
+ x_t=x_t,
+ t=t,
+ clip_denoised=False,
+ model_kwargs=model_kwargs,
+ )["output"]
+ if self.loss_type == LossType.RESCALED_KL:
+ terms["loss"] *= self.num_timesteps
+ elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE:
+ model_output = model(x_t, self._scale_timesteps(t), **model_kwargs)
+
+ if self.model_var_type in [
+ ModelVarType.LEARNED,
+ ModelVarType.LEARNED_RANGE,
+ ]:
+ B, C = x_t.shape[:2]
+ assert model_output.shape == (B, C * 2, *x_t.shape[2:])
+ model_output, model_var_values = th.split(model_output, C, dim=1)
+ # Learn the variance using the variational bound, but don't let
+ # it affect our mean prediction.
+ frozen_out = th.cat([model_output.detach(), model_var_values], dim=1)
+ terms["vb"] = self._vb_terms_bpd(
+ model=lambda *args, r=frozen_out: r,
+ x_start=x_start,
+ x_t=x_t,
+ t=t,
+ clip_denoised=False,
+ )["output"]
+ if self.loss_type == LossType.RESCALED_MSE:
+ # Divide by 1000 for equivalence with initial implementation.
+ # Without a factor of 1/1000, the VB term hurts the MSE term.
+ terms["vb"] *= self.num_timesteps / 1000.0
+
+ target = {
+ ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance(
+ x_start=x_start, x_t=x_t, t=t
+ )[0],
+ ModelMeanType.START_X: x_start,
+ ModelMeanType.EPSILON: noise,
+ }[self.model_mean_type]
+ assert model_output.shape == target.shape == x_start.shape # [bs, njoints, nfeats, nframes]
+ terms["l_simple"] = self.temporal_spatial_masked_l2(
+ target=target,
+ pred=model_output,
+ temp_mask=temp_mask,
+ spat_mask=joint_mask,
+ lengths=gt_n_frames,
+ n_joints=gt_n_joints
+ )
+ terms["loss"] = terms["l_simple"].clone()
+
+ # Geodesic loss requires denormalized predictions
+ if self.lambda_geo > 0.:
+ mean = model_kwargs['cond']['mean'][..., None] # (bs, J, D, 1)
+ std = model_kwargs['cond']['std'][..., None] # (bs, J, D, 1)
+ target_denorm = (target * std) + mean
+ output_denorm = (model_output * std) + mean
+
+ terms["geodesic_loss"] = self.geodesic_loss(
+ target=target_denorm,
+ pred=output_denorm,
+ temp_mask=temp_mask,
+ spat_mask=joint_mask,
+ lengths=gt_n_frames,
+ n_joints=gt_n_joints
+ )
+ terms["loss"] = terms["loss"] + self.lambda_geo * terms["geodesic_loss"]
+
+ else:
+ raise NotImplementedError(self.loss_type)
+ return terms
+
+
+def _extract_into_tensor(arr, timesteps, broadcast_shape):
+ """
+ Extract values from a 1-D numpy array for a batch of indices.
+ :param arr: the 1-D numpy array.
+ :param timesteps: a tensor of indices into the array to extract.
+ :param broadcast_shape: a larger shape of K dimensions with the batch
+ dimension equal to the length of timesteps.
+ :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.
+ """
+ res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float()
+ while len(res.shape) < len(broadcast_shape):
+ res = res[..., None]
+ return res.expand(broadcast_shape)
diff --git a/unimate/models/diffusion/losses.py b/unimate/models/diffusion/losses.py
new file mode 100644
index 0000000..e3fded1
--- /dev/null
+++ b/unimate/models/diffusion/losses.py
@@ -0,0 +1,77 @@
+# This code is based on https://github.com/openai/guided-diffusion
+"""
+Helpers for various likelihood-based losses. These are ported from the original
+Ho et al. diffusion models codebase:
+https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py
+"""
+
+import numpy as np
+import torch as th
+
+
+def normal_kl(mean1, logvar1, mean2, logvar2):
+ """
+ Compute the KL divergence between two gaussians.
+
+ Shapes are automatically broadcasted, so batches can be compared to
+ scalars, among other use cases.
+ """
+ tensor = None
+ for obj in (mean1, logvar1, mean2, logvar2):
+ if isinstance(obj, th.Tensor):
+ tensor = obj
+ break
+ assert tensor is not None, "at least one argument must be a Tensor"
+
+ # Force variances to be Tensors. Broadcasting helps convert scalars to
+ # Tensors, but it does not work for th.exp().
+ logvar1, logvar2 = [
+ x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor)
+ for x in (logvar1, logvar2)
+ ]
+
+ return 0.5 * (
+ -1.0
+ + logvar2
+ - logvar1
+ + th.exp(logvar1 - logvar2)
+ + ((mean1 - mean2) ** 2) * th.exp(-logvar2)
+ )
+
+
+def approx_standard_normal_cdf(x):
+ """
+ A fast approximation of the cumulative distribution function of the
+ standard normal.
+ """
+ return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3))))
+
+
+def discretized_gaussian_log_likelihood(x, *, means, log_scales):
+ """
+ Compute the log-likelihood of a Gaussian distribution discretizing to a
+ given image.
+
+ :param x: the target images. It is assumed that this was uint8 values,
+ rescaled to the range [-1, 1].
+ :param means: the Gaussian mean Tensor.
+ :param log_scales: the Gaussian log stddev Tensor.
+ :return: a tensor like x of log probabilities (in nats).
+ """
+ assert x.shape == means.shape == log_scales.shape
+ centered_x = x - means
+ inv_stdv = th.exp(-log_scales)
+ plus_in = inv_stdv * (centered_x + 1.0 / 255.0)
+ cdf_plus = approx_standard_normal_cdf(plus_in)
+ min_in = inv_stdv * (centered_x - 1.0 / 255.0)
+ cdf_min = approx_standard_normal_cdf(min_in)
+ log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12))
+ log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12))
+ cdf_delta = cdf_plus - cdf_min
+ log_probs = th.where(
+ x < -0.999,
+ log_cdf_plus,
+ th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))),
+ )
+ assert log_probs.shape == x.shape
+ return log_probs
diff --git a/unimate/models/diffusion/nn.py b/unimate/models/diffusion/nn.py
new file mode 100644
index 0000000..2f4189c
--- /dev/null
+++ b/unimate/models/diffusion/nn.py
@@ -0,0 +1,16 @@
+# This code is based on https://github.com/openai/guided-diffusion
+"""Tensor reduction helpers shared by the diffusion and flow-matching losses."""
+
+
+def mean_flat(tensor):
+ """
+ Take the mean over all non-batch dimensions.
+ """
+ return tensor.mean(dim=list(range(1, len(tensor.shape))))
+
+
+def sum_flat(tensor):
+ """
+ Take the sum over all non-batch dimensions.
+ """
+ return tensor.sum(dim=list(range(1, len(tensor.shape))))
diff --git a/unimate/models/diffusion/respace.py b/unimate/models/diffusion/respace.py
new file mode 100644
index 0000000..a270253
--- /dev/null
+++ b/unimate/models/diffusion/respace.py
@@ -0,0 +1,123 @@
+# This code is based on https://github.com/openai/guided-diffusion
+import numpy as np
+import torch as th
+
+from unimate.models.diffusion.gaussian_diffusion import GaussianDiffusion
+
+
+def space_timesteps(num_timesteps, section_counts):
+ """
+ Create a list of timesteps to use from an original diffusion process,
+ given the number of timesteps we want to take from equally-sized portions
+ of the original process.
+
+ For example, if there's 300 timesteps and the section counts are [10,15,20]
+ then the first 100 timesteps are strided to be 10 timesteps, the second 100
+ are strided to be 15 timesteps, and the final 100 are strided to be 20.
+
+ If the stride is a string starting with "ddim", then the fixed striding
+ from the DDIM paper is used, and only one section is allowed.
+
+ :param num_timesteps: the number of diffusion steps in the original
+ process to divide up.
+ :param section_counts: either a list of numbers, or a string containing
+ comma-separated numbers, indicating the step count
+ per section. As a special case, use "ddimN" where N
+ is a number of steps to use the striding from the
+ DDIM paper.
+ :return: a set of diffusion steps from the original process to use.
+ """
+ if isinstance(section_counts, str):
+ if section_counts.startswith("ddim"):
+ desired_count = int(section_counts[len("ddim") :])
+ for i in range(1, num_timesteps):
+ if len(range(0, num_timesteps, i)) == desired_count:
+ return set(range(0, num_timesteps, i))
+ raise ValueError(
+ f"cannot create exactly {num_timesteps} steps with an integer stride"
+ )
+ section_counts = [int(x) for x in section_counts.split(",")]
+ size_per = num_timesteps // len(section_counts)
+ extra = num_timesteps % len(section_counts)
+ start_idx = 0
+ all_steps = []
+ for i, section_count in enumerate(section_counts):
+ size = size_per + (1 if i < extra else 0)
+ if size < section_count:
+ raise ValueError(
+ f"cannot divide section of {size} steps into {section_count}"
+ )
+ if section_count <= 1:
+ frac_stride = 1
+ else:
+ frac_stride = (size - 1) / (section_count - 1)
+ cur_idx = 0.0
+ taken_steps = []
+ for _ in range(section_count):
+ taken_steps.append(start_idx + round(cur_idx))
+ cur_idx += frac_stride
+ all_steps += taken_steps
+ start_idx += size
+ return set(all_steps)
+
+
+class SpacedDiffusion(GaussianDiffusion):
+ """
+ A diffusion process which can skip steps in a base diffusion process.
+
+ :param use_timesteps: a collection (sequence or set) of timesteps from the original diffusion process to retain.
+ :param kwargs: the kwargs to create the base diffusion process.
+ """
+
+ def __init__(self, use_timesteps, **kwargs):
+ self.use_timesteps = set(use_timesteps)
+ self.timestep_map = []
+ self.original_num_steps = len(kwargs["betas"])
+
+ base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa
+ last_alpha_cumprod = 1.0
+ new_betas = []
+ for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod):
+ if i in self.use_timesteps:
+ new_betas.append(1 - alpha_cumprod / last_alpha_cumprod)
+ last_alpha_cumprod = alpha_cumprod
+ self.timestep_map.append(i)
+ kwargs["betas"] = np.array(new_betas)
+ super().__init__(**kwargs)
+
+ def p_mean_variance(
+ self, model, *args, **kwargs
+ ): # pylint: disable=signature-differs
+ return super().p_mean_variance(self._wrap_model(model), *args, **kwargs)
+
+ def condition_mean(self, cond_fn, *args, **kwargs):
+ return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs)
+
+ def condition_score(self, cond_fn, *args, **kwargs):
+ return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs)
+
+ def _wrap_model(self, model):
+ if isinstance(model, _WrappedModel):
+ return model
+ return _WrappedModel(
+ model, self.timestep_map, self.rescale_timesteps, self.original_num_steps
+ )
+
+ def _scale_timesteps(self, t):
+ # Scaling is done by the wrapped model.
+ return t
+
+
+class _WrappedModel:
+ def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps):
+ self.model = model
+ self.timestep_map = timestep_map
+ self.rescale_timesteps = rescale_timesteps
+ self.original_num_steps = original_num_steps
+
+ def __call__(self, x, ts, **kwargs):
+ map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype)
+ new_ts = map_tensor[ts]
+ if self.rescale_timesteps:
+ new_ts = new_ts.float() * (1000.0 / self.original_num_steps)
+ return self.model(x, new_ts, **kwargs)
diff --git a/unimate/models/factory.py b/unimate/models/factory.py
new file mode 100644
index 0000000..7d131d5
--- /dev/null
+++ b/unimate/models/factory.py
@@ -0,0 +1,197 @@
+"""Factories for the denoising model and its generation schedule.
+
+``create_model`` โ€” builds the denoiser variant selected by the two
+ orthogonal axes ``model_config.attention``
+ (``'full'`` / ``'graph'``) and ``model_config.text_cond``
+ (``'adaln'`` / ``'cross_attn'``).
+``create_diffusion`` โ€” Gaussian DDPM schedule (``training.diff_model == 'diffusion'``).
+``create_transport`` โ€” flow-matching transport (``training.diff_model == 'flow'``,
+ used by all current configs).
+"""
+
+from unimate.models.denoiser import (UniMateFullAdaLN, UniMateFullCrossAttn,
+ UniMateGraphAdaLN, UniMateGraphCrossAttn)
+from unimate.models.diffusion import gaussian_diffusion as gd
+from unimate.models.diffusion.respace import SpacedDiffusion, space_timesteps
+from unimate.models.flow.transport import Transport, ModelType, WeightType, PathType
+from unimate.models.text_encoder.factory import get_text_encoder_dim
+
+
+# (attention, text_cond) -> model class. All four pairs are implemented; the
+# two axes are genuinely independent.
+_MODEL_BY_AXES = {
+ ('full', 'adaln'): UniMateFullAdaLN,
+ ('full', 'cross_attn'): UniMateFullCrossAttn,
+ ('graph', 'adaln'): UniMateGraphAdaLN,
+ ('graph', 'cross_attn'): UniMateGraphCrossAttn,
+}
+
+
+def create_model(dataset_config, model_config):
+ """Build the denoiser for a config.
+
+ Selected by ``attention`` ('full' | 'graph') x ``text_cond``
+ ('adaln' | 'cross_attn'); see :data:`_MODEL_BY_AXES`.
+ """
+ axes = (model_config.attention, model_config.text_cond)
+ model_cls = _MODEL_BY_AXES.get(axes)
+ if model_cls is None:
+ raise ValueError(
+ f"Unsupported model axes: attention={model_config.attention!r}, "
+ f"text_cond={model_config.text_cond!r}. Available: "
+ + ', '.join(f'{a}+{t}' for a, t in sorted(_MODEL_BY_AXES)))
+
+ text_dim = get_text_encoder_dim(
+ model_config.text_encoder_type,
+ model_config.text_encoder_version,
+ )
+
+ # Shared kwargs for all variants, grouped by purpose.
+ model_kwargs = dict(
+ # Dataset-derived shape
+ feature_len=dataset_config.feature_len,
+ max_motion_length=dataset_config.max_motion_length,
+ max_joints=dataset_config.max_joints,
+ max_depth=dataset_config.max_depth,
+ # Architecture
+ latent_dim=model_config.latent_dim,
+ ff_size=model_config.ff_size,
+ num_layers=model_config.num_layers,
+ num_heads=model_config.num_heads,
+ dropout=model_config.dropout,
+ # Positional encoding
+ use_spectral_rope=model_config.use_spectral_rope,
+ max_freqs=model_config.max_freqs,
+ use_signnet=model_config.use_signnet,
+ # Conditioning
+ cond_mode=model_config.cond_mode,
+ cond_mask_prob=model_config.cond_mask_prob,
+ text_dim=text_dim,
+ # Embeddings
+ use_joint_name_emb=model_config.use_joint_name_emb,
+ use_graph_emb=model_config.use_graph_emb,
+ use_depth_emb=model_config.use_depth_emb,
+ concat_parent_features=model_config.concat_parent_features,
+ num_tpos_queries=model_config.num_tpos_queries,
+ inject_tpos_to_adaln=model_config.inject_tpos_to_adaln,
+ )
+
+ # Knobs only the factored (attention='graph') variants accept. The
+ # cross_attn one always uses the graph bias, so it takes the sharing
+ # switch but not the on/off ablation.
+ if model_cls is UniMateGraphAdaLN:
+ model_kwargs.update(
+ use_graph_attn_bias=model_config.use_graph_attn_bias,
+ share_graph_attn_bias=model_config.share_graph_attn_bias,
+ gradient_checkpointing=model_config.gradient_checkpointing,
+ )
+ elif model_cls is UniMateGraphCrossAttn:
+ model_kwargs.update(
+ share_graph_attn_bias=model_config.share_graph_attn_bias,
+ gradient_checkpointing=model_config.gradient_checkpointing,
+ )
+
+ return model_cls(**model_kwargs)
+
+
+def create_diffusion(scheduler_config, training_config):
+ betas = gd.get_named_beta_schedule(
+ scheduler_config.noise_schedule,
+ scheduler_config.diffusion_steps,
+ scheduler_config.scale_beta
+ )
+ loss_type = gd.LossType.MSE
+ timestep_respacing = scheduler_config.timestep_respacing or [scheduler_config.diffusion_steps]
+
+ diffusion = SpacedDiffusion(
+ use_timesteps=space_timesteps(
+ scheduler_config.diffusion_steps,
+ timestep_respacing
+ ),
+ betas=betas,
+ model_mean_type=(
+ gd.ModelMeanType.EPSILON if not scheduler_config.predict_xstart else gd.ModelMeanType.START_X
+ ),
+ model_var_type=(
+ (
+ gd.ModelVarType.FIXED_LARGE
+ if not scheduler_config.sigma_small
+ else gd.ModelVarType.FIXED_SMALL
+ )
+ if not scheduler_config.learn_sigma
+ else gd.ModelVarType.LEARNED_RANGE
+ ),
+ loss_type=loss_type,
+ rescale_timesteps=scheduler_config.rescale_timesteps,
+ lambda_geo=training_config.lambda_geo,
+ )
+
+ return diffusion
+
+
+def create_transport(
+ path_type='Linear',
+ prediction="velocity",
+ loss_weight=None,
+ train_eps=None,
+ sample_eps=None,
+ training_config=None,
+):
+ """Create a flow-matching :class:`Transport`.
+
+ Args:
+ path_type: interpolant family โ€” 'Linear' (default), 'GVP', or 'VP'.
+ prediction: model parameterization โ€” 'velocity' (default), 'noise',
+ or 'score'.
+ loss_weight: loss weighting โ€” None (default), 'velocity', or
+ 'likelihood'. Only affects noise/score prediction.
+ train_eps / sample_eps: interval-clipping epsilons; None selects a
+ path-dependent default (0 for the stable velocity + Linear/GVP
+ combination used by all current configs).
+ training_config: supplies ``lambda_geo`` / ``lambda_smooth`` for the
+ auxiliary losses.
+ """
+
+ if prediction == "noise":
+ model_type = ModelType.NOISE
+ elif prediction == "score":
+ model_type = ModelType.SCORE
+ else:
+ model_type = ModelType.VELOCITY
+
+ if loss_weight == "velocity":
+ loss_type = WeightType.VELOCITY
+ elif loss_weight == "likelihood":
+ loss_type = WeightType.LIKELIHOOD
+ else:
+ loss_type = WeightType.NONE
+
+ path_choice = {
+ "Linear": PathType.LINEAR,
+ "GVP": PathType.GVP,
+ "VP": PathType.VP,
+ }
+
+ path_type = path_choice[path_type]
+
+ if path_type in [PathType.VP]:
+ train_eps = 1e-5 if train_eps is None else train_eps
+ sample_eps = 1e-3 if sample_eps is None else sample_eps
+ elif path_type in [PathType.GVP, PathType.LINEAR] and model_type != ModelType.VELOCITY:
+ train_eps = 1e-3 if train_eps is None else train_eps
+ sample_eps = 1e-3 if sample_eps is None else sample_eps
+ else: # velocity & [GVP, LINEAR] is stable everywhere
+ train_eps = 0
+ sample_eps = 0
+
+ state = Transport(
+ model_type=model_type,
+ path_type=path_type,
+ loss_type=loss_type,
+ train_eps=train_eps,
+ sample_eps=sample_eps,
+ lambda_geo=training_config.lambda_geo,
+ lambda_smooth=training_config.lambda_smooth,
+ )
+
+ return state
\ No newline at end of file
diff --git a/unimate/models/flow/__init__.py b/unimate/models/flow/__init__.py
new file mode 100644
index 0000000..8779273
--- /dev/null
+++ b/unimate/models/flow/__init__.py
@@ -0,0 +1 @@
+"""Flow-matching transport, interpolant paths, and ODE/SDE integrators, adapted from SiT."""
diff --git a/unimate/models/flow/integrators.py b/unimate/models/flow/integrators.py
new file mode 100644
index 0000000..44dbc13
--- /dev/null
+++ b/unimate/models/flow/integrators.py
@@ -0,0 +1,111 @@
+# Adapted from SiT: https://github.com/willisma/SiT (MIT License)
+"""Numerical integrators for SDE and ODE sampling.
+
+Provides ``sde`` (Euler-Maruyama / Heun) and ``ode`` (via ``torchdiffeq``)
+solvers used by :class:`transport.Sampler`.
+"""
+
+import torch as th
+from torchdiffeq import odeint
+
+
+# ------------------------------------------------------------------
+# SDE Solver
+# ------------------------------------------------------------------
+
+class sde:
+ """Forward-time SDE integrator (Euler-Maruyama or Heun)."""
+
+ def __init__(self, drift, diffusion, *, t0, t1, num_steps, sampler_type):
+ assert t0 < t1, "SDE sampler requires forward time (t0 < t1)"
+
+ self.num_timesteps = num_steps
+ self.t = th.linspace(t0, t1, num_steps)
+ self.dt = self.t[1] - self.t[0]
+ self.drift = drift
+ self.diffusion = diffusion
+ self.sampler_type = sampler_type
+
+ def __Euler_Maruyama_step(self, x, mean_x, t, model, **model_kwargs):
+ w_cur = th.randn(x.size()).to(x)
+ t = th.ones(x.size(0)).to(x) * t
+ dw = w_cur * th.sqrt(self.dt)
+ drift = self.drift(x, t, model, **model_kwargs)
+ diffusion = self.diffusion(x, t)
+ mean_x = x + drift * self.dt
+ x = mean_x + th.sqrt(2 * diffusion) * dw
+ return x, mean_x
+
+ def __Heun_step(self, x, _, t, model, **model_kwargs):
+ w_cur = th.randn(x.size()).to(x)
+ dw = w_cur * th.sqrt(self.dt)
+ t_cur = th.ones(x.size(0)).to(x) * t
+ diffusion = self.diffusion(x, t_cur)
+ xhat = x + th.sqrt(2 * diffusion) * dw
+ K1 = self.drift(xhat, t_cur, model, **model_kwargs)
+ xp = xhat + self.dt * K1
+ K2 = self.drift(xp, t_cur + self.dt, model, **model_kwargs)
+ # At the last time point we skip the Heun correction
+ return xhat + 0.5 * self.dt * (K1 + K2), xhat
+
+ def __forward_fn(self):
+ """Select the step function based on ``sampler_type``."""
+ sampler_dict = {
+ "Euler": self.__Euler_Maruyama_step,
+ "Heun": self.__Heun_step,
+ }
+ try:
+ sampler = sampler_dict[self.sampler_type]
+ except KeyError:
+ raise NotImplementedError(f"Sampler type '{self.sampler_type}' not implemented.")
+ return sampler
+
+ def sample(self, init, model, **model_kwargs):
+ """Run the forward SDE loop and collect samples at each step."""
+ x = init
+ mean_x = init
+ samples = []
+ sampler = self.__forward_fn()
+ for ti in self.t[:-1]:
+ with th.no_grad():
+ x, mean_x = sampler(x, mean_x, ti, model, **model_kwargs)
+ samples.append(x)
+ return samples
+
+
+# ------------------------------------------------------------------
+# ODE Solver
+# ------------------------------------------------------------------
+
+class ode:
+ """ODE integrator wrapping ``torchdiffeq.odeint``."""
+
+ def __init__(self, drift, *, t0, t1, sampler_type, num_steps, atol, rtol):
+ assert t0 < t1, "ODE sampler requires forward time (t0 < t1)"
+
+ self.drift = drift
+ self.t = th.linspace(t0, t1, num_steps)
+ self.atol = atol
+ self.rtol = rtol
+ self.sampler_type = sampler_type
+
+ def sample(self, x, model, **model_kwargs):
+ """Integrate the ODE from t0 to t1."""
+ device = x[0].device if isinstance(x, tuple) else x.device
+
+ def _fn(t, x):
+ batch_t = (
+ th.ones(x[0].size(0)).to(device) * t
+ if isinstance(x, tuple)
+ else th.ones(x.size(0)).to(device) * t
+ )
+ return self.drift(x, batch_t, model, **model_kwargs)
+
+ t = self.t.to(device)
+ atol = [self.atol] * len(x) if isinstance(x, tuple) else [self.atol]
+ rtol = [self.rtol] * len(x) if isinstance(x, tuple) else [self.rtol]
+ samples = odeint(
+ _fn, x, t,
+ method=self.sampler_type, atol=atol, rtol=rtol,
+ )
+ return samples
\ No newline at end of file
diff --git a/unimate/models/flow/path.py b/unimate/models/flow/path.py
new file mode 100644
index 0000000..39934a4
--- /dev/null
+++ b/unimate/models/flow/path.py
@@ -0,0 +1,198 @@
+# Adapted from SiT: https://github.com/willisma/SiT (MIT License)
+"""Interpolant paths (coupling plans) for flow matching.
+
+Each plan defines how to interpolate between noise x0 and data x1 over time,
+providing coefficients alpha_t (data) and sigma_t (noise), along with drift
+and diffusion terms for the corresponding SDE.
+
+Supported plans:
+ - ``ICPlan`` โ€” Linear interpolation (identity coupling)
+ - ``VPCPlan`` โ€” Variance-preserving path
+ - ``GVPCPlan`` โ€” Geodesic variance-preserving path
+"""
+
+import numpy as np
+import torch as th
+
+
+def expand_t_like_x(t, x):
+ """Reshape time vector ``t`` to be broadcastable with data ``x``.
+
+ Args:
+ t: (B,) time vector.
+ x: (B, ...) data tensor.
+ """
+ dims = [1] * (len(x.size()) - 1)
+ t = t.view(t.size(0), *dims)
+ return t
+
+
+# ------------------------------------------------------------------
+# Linear Coupling Plan (base class)
+# ------------------------------------------------------------------
+
+class ICPlan:
+ """Linear (identity coupling) interpolant: x_t = t * x1 + (1-t) * x0."""
+
+ def __init__(self, sigma=0.0):
+ self.sigma = sigma
+
+ def compute_alpha_t(self, t):
+ """Data coefficient alpha_t and its time derivative."""
+ return t, 1
+
+ def compute_sigma_t(self, t):
+ """Noise coefficient sigma_t and its time derivative."""
+ return 1 - t, -1
+
+ def compute_d_alpha_alpha_ratio_t(self, t):
+ """d(alpha_t)/dt / alpha_t, numerically stable form."""
+ return 1 / t
+
+ def compute_drift(self, x, t):
+ """SDE drift (score parameterization). Returns (-drift, diffusion)."""
+ t = expand_t_like_x(t, x)
+ alpha_ratio = self.compute_d_alpha_alpha_ratio_t(t)
+ sigma_t, d_sigma_t = self.compute_sigma_t(t)
+ drift = alpha_ratio * x
+ diffusion = alpha_ratio * (sigma_t ** 2) - sigma_t * d_sigma_t
+ return -drift, diffusion
+
+ def compute_diffusion(self, x, t, form="constant", norm=1.0):
+ """SDE diffusion coefficient under various functional forms."""
+ t = expand_t_like_x(t, x)
+ choices = {
+ "constant": norm,
+ "SBDM": norm * self.compute_drift(x, t)[1],
+ "sigma": norm * self.compute_sigma_t(t)[0],
+ "linear": norm * (1 - t),
+ "decreasing": 0.25 * (norm * th.cos(np.pi * t) + 1) ** 2,
+ "increasing-decreasing": norm * th.sin(np.pi * t) ** 2,
+ }
+
+ try:
+ diffusion = choices[form]
+ except KeyError:
+ raise NotImplementedError(f"Diffusion form {form} not implemented")
+
+ return diffusion
+
+ # --- Conversion between model parameterizations ---
+
+ def get_score_from_velocity(self, velocity, x, t):
+ """Convert velocity prediction to score."""
+ t = expand_t_like_x(t, x)
+ alpha_t, d_alpha_t = self.compute_alpha_t(t)
+ sigma_t, d_sigma_t = self.compute_sigma_t(t)
+ mean = x
+ reverse_alpha_ratio = alpha_t / d_alpha_t
+ var = sigma_t ** 2 - reverse_alpha_ratio * d_sigma_t * sigma_t
+ score = (reverse_alpha_ratio * velocity - mean) / var
+ return score
+
+ def get_noise_from_velocity(self, velocity, x, t):
+ """Convert velocity prediction to noise (denoiser)."""
+ t = expand_t_like_x(t, x)
+ alpha_t, d_alpha_t = self.compute_alpha_t(t)
+ sigma_t, d_sigma_t = self.compute_sigma_t(t)
+ mean = x
+ reverse_alpha_ratio = alpha_t / d_alpha_t
+ var = reverse_alpha_ratio * d_sigma_t - sigma_t
+ noise = (reverse_alpha_ratio * velocity - mean) / var
+ return noise
+
+ def get_velocity_from_score(self, score, x, t):
+ """Convert score prediction to velocity."""
+ t = expand_t_like_x(t, x)
+ drift, var = self.compute_drift(x, t)
+ velocity = var * score - drift
+ return velocity
+
+ # --- Interpolation and planning ---
+
+ def compute_mu_t(self, t, x0, x1):
+ """Mean of the time-dependent density p_t."""
+ t = expand_t_like_x(t, x1)
+ alpha_t, _ = self.compute_alpha_t(t)
+ sigma_t, _ = self.compute_sigma_t(t)
+ return alpha_t * x1 + sigma_t * x0
+
+ def compute_xt(self, t, x0, x1):
+ """Sample x_t from p_t (deterministic for zero sigma)."""
+ return self.compute_mu_t(t, x0, x1)
+
+ def compute_ut(self, t, x0, x1, xt):
+ """Conditional vector field u_t corresponding to p_t."""
+ t = expand_t_like_x(t, x1)
+ _, d_alpha_t = self.compute_alpha_t(t)
+ _, d_sigma_t = self.compute_sigma_t(t)
+ return d_alpha_t * x1 + d_sigma_t * x0
+
+ def plan(self, t, x0, x1):
+ """Compute (t, x_t, u_t) for a batch of (noise, data) pairs."""
+ xt = self.compute_xt(t, x0, x1)
+ ut = self.compute_ut(t, x0, x1, xt)
+ return t, xt, ut
+
+
+# ------------------------------------------------------------------
+# Variance-Preserving Coupling Plan
+# ------------------------------------------------------------------
+
+class VPCPlan(ICPlan):
+ """VP (variance-preserving) path for flow matching."""
+
+ def __init__(self, sigma_min=0.1, sigma_max=20.0):
+ self.sigma_min = sigma_min
+ self.sigma_max = sigma_max
+ self.log_mean_coeff = (
+ lambda t: -0.25 * ((1 - t) ** 2) * (self.sigma_max - self.sigma_min)
+ - 0.5 * (1 - t) * self.sigma_min
+ )
+ self.d_log_mean_coeff = (
+ lambda t: 0.5 * (1 - t) * (self.sigma_max - self.sigma_min)
+ + 0.5 * self.sigma_min
+ )
+
+ def compute_alpha_t(self, t):
+ alpha_t = th.exp(self.log_mean_coeff(t))
+ d_alpha_t = alpha_t * self.d_log_mean_coeff(t)
+ return alpha_t, d_alpha_t
+
+ def compute_sigma_t(self, t):
+ p_sigma_t = 2 * self.log_mean_coeff(t)
+ sigma_t = th.sqrt(1 - th.exp(p_sigma_t))
+ d_sigma_t = th.exp(p_sigma_t) * (2 * self.d_log_mean_coeff(t)) / (-2 * sigma_t)
+ return sigma_t, d_sigma_t
+
+ def compute_d_alpha_alpha_ratio_t(self, t):
+ return self.d_log_mean_coeff(t)
+
+ def compute_drift(self, x, t):
+ t = expand_t_like_x(t, x)
+ beta_t = self.sigma_min + (1 - t) * (self.sigma_max - self.sigma_min)
+ return -0.5 * beta_t * x, beta_t / 2
+
+
+# ------------------------------------------------------------------
+# Geodesic Variance-Preserving Coupling Plan
+# ------------------------------------------------------------------
+
+class GVPCPlan(ICPlan):
+ """GVP (geodesic variance-preserving) path with trigonometric coefficients."""
+
+ def __init__(self, sigma=0.0):
+ super().__init__(sigma)
+
+ def compute_alpha_t(self, t):
+ alpha_t = th.sin(t * np.pi / 2)
+ d_alpha_t = np.pi / 2 * th.cos(t * np.pi / 2)
+ return alpha_t, d_alpha_t
+
+ def compute_sigma_t(self, t):
+ sigma_t = th.cos(t * np.pi / 2)
+ d_sigma_t = -np.pi / 2 * th.sin(t * np.pi / 2)
+ return sigma_t, d_sigma_t
+
+ def compute_d_alpha_alpha_ratio_t(self, t):
+ return np.pi / (2 * th.tan(t * np.pi / 2))
\ No newline at end of file
diff --git a/unimate/models/flow/transport.py b/unimate/models/flow/transport.py
new file mode 100644
index 0000000..afe9318
--- /dev/null
+++ b/unimate/models/flow/transport.py
@@ -0,0 +1,556 @@
+# Adapted from SiT: https://github.com/willisma/SiT (MIT License)
+"""Flow-matching transport for training and sampling generative models.
+
+Supports three model parameterizations (velocity, noise, score) and three
+interpolant paths (linear, GVP, VP). The primary training path for this
+project uses ``ModelType.VELOCITY`` with ``PathType.LINEAR``.
+"""
+
+import enum
+
+import numpy as np
+import torch as th
+
+from . import path
+from .integrators import ode, sde
+
+from unimate.models.diffusion.nn import mean_flat, sum_flat
+from unimate.utils.rotation_conversions import rotation_6d_to_matrix_safe
+from unimate.utils.geo_utils import geodesic_distance
+
+
+# ------------------------------------------------------------------
+# Enums
+# ------------------------------------------------------------------
+
+class ModelType(enum.Enum):
+ """What the model predicts."""
+ NOISE = enum.auto() # epsilon
+ SCORE = enum.auto() # nabla log p(x)
+ VELOCITY = enum.auto() # v(x)
+
+
+class PathType(enum.Enum):
+ """Interpolant path family."""
+ LINEAR = enum.auto()
+ GVP = enum.auto()
+ VP = enum.auto()
+
+
+class WeightType(enum.Enum):
+ """Loss weighting strategy."""
+ NONE = enum.auto()
+ VELOCITY = enum.auto()
+ LIKELIHOOD = enum.auto()
+
+
+# ------------------------------------------------------------------
+# Transport
+# ------------------------------------------------------------------
+
+class Transport:
+ """Core transport object pairing a path sampler with a model type.
+
+ Args:
+ model_type: prediction parameterization (velocity / noise / score).
+ path_type: interpolant family (linear / GVP / VP).
+ loss_type: loss weighting strategy.
+ train_eps / sample_eps: epsilon for numerical stability.
+ lambda_geo: weight for the auxiliary geodesic rotation loss.
+ lambda_smooth: weight for the auxiliary velocity smoothness loss
+ (penalizes ฮ” on the local-velocity channels of the predicted x1).
+ """
+
+ def __init__(
+ self,
+ *,
+ model_type,
+ path_type,
+ loss_type,
+ train_eps,
+ sample_eps,
+ lambda_geo=0.0,
+ lambda_smooth=0.0,
+ ):
+ path_options = {
+ PathType.LINEAR: path.ICPlan,
+ PathType.GVP: path.GVPCPlan,
+ PathType.VP: path.VPCPlan,
+ }
+
+ self.loss_type = loss_type
+ self.model_type = model_type
+ self.path_sampler = path_options[path_type]()
+ self.train_eps = train_eps
+ self.sample_eps = sample_eps
+ self.lambda_geo = lambda_geo
+ self.lambda_smooth = lambda_smooth
+
+ self.l2_loss = lambda a, b: (a - b) ** 2
+
+ # ------------------------------------------------------------------
+ # Loss helpers
+ # ------------------------------------------------------------------
+
+ def temporal_spatial_masked_l2(self, target, pred, temp_mask, spat_mask, lengths, n_joints):
+ """Masked L2 loss over temporal and spatial dimensions.
+
+ Args:
+ target, pred: (B, J, D, T)
+ temp_mask: (B, 1, 1, T)
+ spat_mask: (B, 1, 1, J)
+ lengths: (B,) valid frame counts
+ n_joints: (B,) valid joint counts
+ Returns:
+ (B,) per-sample MSE values.
+ """
+ loss = self.l2_loss(target, pred)
+ temp_masked_loss = loss * temp_mask.float()
+ spat_temp_masked_loss = temp_masked_loss * spat_mask.float().transpose(1, 3)
+ loss = sum_flat(spat_temp_masked_loss)
+ non_zero_elements = lengths * n_joints * target.size(2)
+ return loss / non_zero_elements
+
+ def geodesic_loss(self, target, pred, temp_mask, spat_mask, lengths, n_joints):
+ """Masked geodesic (rotation angle) loss.
+
+ Extracts 6D rotation features (channels 3โ€“9), converts to matrices,
+ then computes the angular distance.
+
+ Args/Returns: same shape convention as :meth:`temporal_spatial_masked_l2`.
+ """
+ # (B, J, D, T) โ†’ (B, T, J, D) โ†’ extract 6D โ†’ (B, T, J, 3, 3)
+ rots_target = rotation_6d_to_matrix_safe(target.permute(0, 3, 1, 2)[..., 3:9])
+ rots_pred = rotation_6d_to_matrix_safe(pred.permute(0, 3, 1, 2)[..., 3:9])
+
+ loss = geodesic_distance(rots_pred, rots_target).permute(0, 2, 3, 1) # (B, J, 1, T)
+ temp_masked_loss = loss * temp_mask.float()
+ spat_temp_masked_loss = temp_masked_loss * spat_mask.float().transpose(1, 3)
+ loss = sum_flat(spat_temp_masked_loss)
+ non_zero_elements = lengths * n_joints
+ return loss / non_zero_elements
+
+ def velocity_smoothness_loss(self, pred, temp_mask, spat_mask, lengths, n_joints):
+ """Masked smoothness penalty on the local-velocity channels.
+
+ Penalizes per-frame finite differences on channels [-3:] of the
+ predicted clean motion x1 โ€” i.e., regularizes the acceleration of
+ the UniMate ``local_velocity`` block (channels [9:12] in the
+ 12-dim layout). Pure regularization on the prediction; no GT.
+
+ Args:
+ pred: (B, J, D, T) predicted clean motion (denormalized).
+ temp_mask: (B, 1, 1, T)
+ spat_mask: (B, 1, 1, J)
+ lengths: (B,) valid frame counts.
+ n_joints: (B,) valid joint counts.
+ Returns:
+ (B,) per-sample smoothness penalty.
+ """
+ v = pred[:, :, -3:, :] # (B, J, 3, T)
+ dv = v[..., 1:] - v[..., :-1] # (B, J, 3, T-1)
+ pair_mask = temp_mask[..., 1:].float() * temp_mask[..., :-1].float() # (B,1,1,T-1)
+ loss = (dv ** 2) * pair_mask
+ loss = loss * spat_mask.float().transpose(1, 3)
+ loss = sum_flat(loss)
+ denom = th.clamp(lengths - 1, min=1) * n_joints * 3
+ return loss / denom
+
+ # ------------------------------------------------------------------
+ # Sampling & interval helpers
+ # ------------------------------------------------------------------
+
+ def prior_logp(self, z):
+ """Log-probability under standard multivariate normal."""
+ shape = th.tensor(z.size())
+ N = th.prod(shape[1:])
+ _fn = lambda x: -N / 2.0 * np.log(2 * np.pi) - th.sum(x ** 2) / 2.0
+ return th.vmap(_fn)(z)
+
+ def check_interval(
+ self,
+ train_eps,
+ sample_eps,
+ *,
+ diffusion_form="SBDM",
+ sde=False,
+ reverse=False,
+ eval=False,
+ last_step_size=0.0,
+ ):
+ """Compute integration interval [t0, t1] with epsilon clipping."""
+ t0 = 0
+ t1 = 1
+ eps = train_eps if not eval else sample_eps
+
+ if type(self.path_sampler) in [path.VPCPlan]:
+ t1 = 1 - eps if (not sde or last_step_size == 0) else 1 - last_step_size
+
+ elif (type(self.path_sampler) in [path.ICPlan, path.GVPCPlan]
+ and (self.model_type != ModelType.VELOCITY or sde)):
+ # Avoid numerical issues with a semi-implicit first step
+ t0 = eps if (diffusion_form == "SBDM" and sde) or self.model_type != ModelType.VELOCITY else 0
+ t1 = 1 - eps if (not sde or last_step_size == 0) else 1 - last_step_size
+
+ if reverse:
+ t0, t1 = 1 - t0, 1 - t1
+
+ return t0, t1
+
+ def sample(self, x1):
+ """Sample noise x0 and time t for training.
+
+ Args:
+ x1: data point, shape (B, *dim).
+ Returns:
+ (t, x0, x1) where x0 ~ N(0, I), t ~ U[t0, t1].
+ """
+ x0 = th.randn_like(x1)
+ t0, t1 = self.check_interval(self.train_eps, self.sample_eps)
+ t = th.rand((x1.shape[0],)) * (t1 - t0) + t0
+ t = t.to(x1)
+ return t, x0, x1
+
+ # ------------------------------------------------------------------
+ # Training loss
+ # ------------------------------------------------------------------
+
+ def training_losses(self, model, x1, model_kwargs=None):
+ """Compute training loss for the flow-matching model.
+
+ Args:
+ model: denoising network (velocity / noise / score predictor).
+ x1: clean data, shape (B, J, D, T).
+ model_kwargs: dict with ``cond`` key containing masks, lengths, etc.
+ Returns:
+ dict of per-sample loss tensors keyed by name.
+ """
+ if model_kwargs is None:
+ model_kwargs = {}
+
+ # Extract masks from conditioning
+ cond = model_kwargs.get("cond", {})
+ temp_mask = cond["lengths_mask"] # (B, 1, 1, T)
+ gt_n_frames = cond["motion_length"] # (B,)
+ joint_mask = cond["joint_mask"] # (B, 1, 1, J)
+ gt_n_joints = cond["n_joints"] # (B,)
+
+ # Sample noise and interpolate
+ t, x0, x1 = self.sample(x1)
+ t, xt, ut = self.path_sampler.plan(t, x0, x1)
+
+ model_output = model(xt, t, **model_kwargs)
+ B, *_, C = xt.shape
+ assert model_output.size() == (B, *xt.size()[1:-1], C)
+
+ terms = {}
+
+ if self.model_type == ModelType.VELOCITY:
+ # --- Velocity prediction loss ---
+ terms["diff_loss"] = self.temporal_spatial_masked_l2(
+ target=ut, pred=model_output,
+ temp_mask=temp_mask, spat_mask=joint_mask,
+ lengths=gt_n_frames, n_joints=gt_n_joints,
+ )
+ terms["loss"] = terms["diff_loss"].clone()
+
+ # Reconstruct x1 from velocity (then denormalize) for any
+ # auxiliary loss that operates in data space.
+ if self.lambda_geo > 0 or self.lambda_smooth > 0:
+ # x1 = xt + (1-t)ยทv holds for the linear interpolant only
+ # (xt = tยทx1 + (1-t)ยทx0, ut = x1 - x0).
+ assert type(self.path_sampler) is path.ICPlan, (
+ "geo/smooth aux losses assume PathType.LINEAR")
+ pred_x1 = model_output * (1 - t).view(-1, 1, 1, 1) + xt
+ mean = cond["mean"][..., None] # (B, J, D, 1)
+ std = cond["std"][..., None]
+ pred_x1_denorm = pred_x1 * std + mean
+
+ # Optional geodesic rotation loss
+ if self.lambda_geo > 0:
+ target_x1 = x1 * std + mean
+
+ terms["geo_loss"] = self.geodesic_loss(
+ target=target_x1, pred=pred_x1_denorm,
+ temp_mask=temp_mask, spat_mask=joint_mask,
+ lengths=gt_n_frames, n_joints=gt_n_joints,
+ )
+ terms["loss"] = terms["loss"] + self.lambda_geo * terms["geo_loss"]
+
+ # Optional velocity smoothness regularizer
+ if self.lambda_smooth > 0:
+ terms["smooth_loss"] = self.velocity_smoothness_loss(
+ pred=pred_x1_denorm,
+ temp_mask=temp_mask, spat_mask=joint_mask,
+ lengths=gt_n_frames, n_joints=gt_n_joints,
+ )
+ terms["loss"] = terms["loss"] + self.lambda_smooth * terms["smooth_loss"]
+
+ else:
+ # --- Noise / score prediction loss (weighted) ---
+ _, drift_var = self.path_sampler.compute_drift(xt, t)
+ sigma_t, _ = self.path_sampler.compute_sigma_t(path.expand_t_like_x(t, xt))
+
+ if self.loss_type in [WeightType.VELOCITY]:
+ weight = (drift_var / sigma_t) ** 2
+ elif self.loss_type in [WeightType.LIKELIHOOD]:
+ weight = drift_var / (sigma_t ** 2)
+ elif self.loss_type in [WeightType.NONE]:
+ weight = 1
+ else:
+ raise NotImplementedError(f"Unknown loss type: {self.loss_type}")
+
+ if self.model_type == ModelType.NOISE:
+ terms["loss"] = mean_flat(weight * ((model_output - x0) ** 2))
+ else:
+ terms["loss"] = mean_flat(weight * ((model_output * sigma_t + x0) ** 2))
+
+ return terms
+
+ # ------------------------------------------------------------------
+ # Drift & score for ODE/SDE sampling
+ # ------------------------------------------------------------------
+
+ def get_drift(self):
+ """Return the drift function for the probability flow ODE."""
+
+ def score_ode(x, t, model, **model_kwargs):
+ drift_mean, drift_var = self.path_sampler.compute_drift(x, t)
+ model_output = model(x, t, **model_kwargs)
+ return -drift_mean + drift_var * model_output
+
+ def noise_ode(x, t, model, **model_kwargs):
+ drift_mean, drift_var = self.path_sampler.compute_drift(x, t)
+ sigma_t, _ = self.path_sampler.compute_sigma_t(path.expand_t_like_x(t, x))
+ model_output = model(x, t, **model_kwargs)
+ score = model_output / -sigma_t
+ return -drift_mean + drift_var * score
+
+ def velocity_ode(x, t, model, **model_kwargs):
+ return model(x, t, **model_kwargs)
+
+ if self.model_type == ModelType.NOISE:
+ drift_fn = noise_ode
+ elif self.model_type == ModelType.SCORE:
+ drift_fn = score_ode
+ else:
+ drift_fn = velocity_ode
+
+ def body_fn(x, t, model, **model_kwargs):
+ model_output = drift_fn(x, t, model, **model_kwargs)
+ assert model_output.shape == x.shape, "Output shape from ODE solver must match input shape"
+ return model_output
+
+ return body_fn
+
+ def get_score(self):
+ """Return the score function: nabla log p_t(x_t)."""
+ if self.model_type == ModelType.NOISE:
+ score_fn = lambda x, t, model, **kwargs: (
+ model(x, t, **kwargs) / -self.path_sampler.compute_sigma_t(path.expand_t_like_x(t, x))[0]
+ )
+ elif self.model_type == ModelType.SCORE:
+ score_fn = lambda x, t, model, **kwargs: model(x, t, **kwargs)
+ elif self.model_type == ModelType.VELOCITY:
+ score_fn = lambda x, t, model, **kwargs: (
+ self.path_sampler.get_score_from_velocity(model(x, t, **kwargs), x, t)
+ )
+ else:
+ raise NotImplementedError()
+
+ return score_fn
+
+
+# ------------------------------------------------------------------
+# Sampler
+# ------------------------------------------------------------------
+
+class Sampler:
+ """Wraps a :class:`Transport` to provide ODE and SDE sampling methods.
+
+ Args:
+ transport: a Transport object specifying model type and interpolant.
+ """
+
+ def __init__(self, transport):
+ self.transport = transport
+ self.drift = self.transport.get_drift()
+ self.score = self.transport.get_score()
+
+ # ------------------------------------------------------------------
+ # SDE sampling
+ # ------------------------------------------------------------------
+
+ def __get_sde_diffusion_and_drift(self, *, diffusion_form="SBDM", diffusion_norm=1.0):
+ """Build SDE drift and diffusion coefficient functions."""
+
+ def diffusion_fn(x, t):
+ return self.transport.path_sampler.compute_diffusion(
+ x, t, form=diffusion_form, norm=diffusion_norm
+ )
+
+ sde_drift = lambda x, t, model, **kwargs: (
+ self.drift(x, t, model, **kwargs)
+ + diffusion_fn(x, t) * self.score(x, t, model, **kwargs)
+ )
+ return sde_drift, diffusion_fn
+
+ def __get_last_step(self, sde_drift, *, last_step, last_step_size):
+ """Build the final denoising step function for SDE sampling."""
+ if last_step is None:
+ return lambda x, t, model, **model_kwargs: x
+ elif last_step == "Mean":
+ return lambda x, t, model, **model_kwargs: (
+ x + sde_drift(x, t, model, **model_kwargs) * last_step_size
+ )
+ elif last_step == "Tweedie":
+ alpha = self.transport.path_sampler.compute_alpha_t
+ sigma = self.transport.path_sampler.compute_sigma_t
+ return lambda x, t, model, **model_kwargs: (
+ x / alpha(t)[0][0]
+ + (sigma(t)[0][0] ** 2) / alpha(t)[0][0] * self.score(x, t, model, **model_kwargs)
+ )
+ elif last_step == "Euler":
+ return lambda x, t, model, **model_kwargs: (
+ x + self.drift(x, t, model, **model_kwargs) * last_step_size
+ )
+ else:
+ raise NotImplementedError(f"Unknown last_step: {last_step}")
+
+ def sample_sde(
+ self,
+ *,
+ sampling_method="Euler",
+ diffusion_form="SBDM",
+ diffusion_norm=1.0,
+ last_step="Mean",
+ last_step_size=0.04,
+ num_steps=250,
+ ):
+ """Return a sampling function using SDE integration.
+
+ Args:
+ sampling_method: "Euler" or "Heun".
+ diffusion_form: diffusion coefficient form.
+ diffusion_norm: diffusion coefficient magnitude.
+ last_step: final step type ("Mean", "Tweedie", "Euler", or None).
+ last_step_size: step size for the final step.
+ num_steps: total integration steps.
+ """
+ if last_step is None:
+ last_step_size = 0.0
+
+ sde_drift, sde_diffusion = self.__get_sde_diffusion_and_drift(
+ diffusion_form=diffusion_form, diffusion_norm=diffusion_norm,
+ )
+
+ t0, t1 = self.transport.check_interval(
+ self.transport.train_eps, self.transport.sample_eps,
+ diffusion_form=diffusion_form,
+ sde=True, eval=True, reverse=False,
+ last_step_size=last_step_size,
+ )
+
+ _sde = sde(
+ sde_drift, sde_diffusion,
+ t0=t0, t1=t1, num_steps=num_steps, sampler_type=sampling_method,
+ )
+ last_step_fn = self.__get_last_step(
+ sde_drift, last_step=last_step, last_step_size=last_step_size,
+ )
+
+ def _sample(init, model, **model_kwargs):
+ xs = _sde.sample(init, model, **model_kwargs)
+ ts = th.ones(init.size(0), device=init.device) * t1
+ x = last_step_fn(xs[-1], ts, model, **model_kwargs)
+ xs.append(x)
+ assert len(xs) == num_steps, "Samples does not match the number of steps"
+ return xs
+
+ return _sample
+
+ # ------------------------------------------------------------------
+ # ODE sampling
+ # ------------------------------------------------------------------
+
+ def sample_ode(
+ self,
+ *,
+ sampling_method="dopri5",
+ num_steps=50,
+ atol=1e-6,
+ rtol=1e-3,
+ reverse=False,
+ ):
+ """Return a sampling function using ODE integration.
+
+ Args:
+ sampling_method: "dopri5" (adaptive) or "euler"/"heun" (fixed).
+ num_steps: integration steps (fixed) or saved datapoints (adaptive).
+ atol / rtol: error tolerances for adaptive solvers.
+ reverse: if True, integrate from data to noise.
+ """
+ if reverse:
+ drift = lambda x, t, model, **kwargs: self.drift(x, th.ones_like(t) * (1 - t), model, **kwargs)
+ else:
+ drift = self.drift
+
+ t0, t1 = self.transport.check_interval(
+ self.transport.train_eps, self.transport.sample_eps,
+ sde=False, eval=True, reverse=reverse, last_step_size=0.0,
+ )
+
+ _ode = ode(
+ drift=drift, t0=t0, t1=t1,
+ sampler_type=sampling_method, num_steps=num_steps,
+ atol=atol, rtol=rtol,
+ )
+ return _ode.sample
+
+ # ------------------------------------------------------------------
+ # Likelihood
+ # ------------------------------------------------------------------
+
+ def sample_ode_likelihood(
+ self,
+ *,
+ sampling_method="dopri5",
+ num_steps=50,
+ atol=1e-6,
+ rtol=1e-3,
+ ):
+ """Return a function that computes log-likelihood via the instantaneous
+ change-of-variables formula (Hutchinson trace estimator)."""
+
+ def _likelihood_drift(x, t, model, **model_kwargs):
+ x, _ = x
+ eps = th.randint(2, x.size(), dtype=th.float, device=x.device) * 2 - 1
+ t = th.ones_like(t) * (1 - t)
+ with th.enable_grad():
+ x.requires_grad = True
+ grad = th.autograd.grad(th.sum(self.drift(x, t, model, **model_kwargs) * eps), x)[0]
+ logp_grad = th.sum(grad * eps, dim=tuple(range(1, len(x.size()))))
+ drift = self.drift(x, t, model, **model_kwargs)
+ return (-drift, logp_grad)
+
+ t0, t1 = self.transport.check_interval(
+ self.transport.train_eps, self.transport.sample_eps,
+ sde=False, eval=True, reverse=False, last_step_size=0.0,
+ )
+
+ _ode = ode(
+ drift=_likelihood_drift, t0=t0, t1=t1,
+ sampler_type=sampling_method, num_steps=num_steps,
+ atol=atol, rtol=rtol,
+ )
+
+ def _sample_fn(x, model, **model_kwargs):
+ init_logp = th.zeros(x.size(0)).to(x)
+ input = (x, init_logp)
+ drift, delta_logp = _ode.sample(input, model, **model_kwargs)
+ drift, delta_logp = drift[-1], delta_logp[-1]
+ prior_logp = self.transport.prior_logp(drift)
+ logp = prior_logp - delta_logp
+ return logp, drift
+
+ return _sample_fn
\ No newline at end of file
diff --git a/unimate/models/text_encoder/__init__.py b/unimate/models/text_encoder/__init__.py
new file mode 100644
index 0000000..1de0ff7
--- /dev/null
+++ b/unimate/models/text_encoder/__init__.py
@@ -0,0 +1 @@
+"""Text encoders (T5, CLIP, BERT) behind a unified tokenize/forward interface."""
diff --git a/unimate/models/text_encoder/factory.py b/unimate/models/text_encoder/factory.py
new file mode 100644
index 0000000..dbcb02a
--- /dev/null
+++ b/unimate/models/text_encoder/factory.py
@@ -0,0 +1,201 @@
+"""Unified text encoder factory.
+
+Provides :func:`create_text_encoder` which returns a text encoder with a
+consistent interface (``tokenize`` + ``forward`` -> ``(B, D)`` mean-pooled
+embeddings) for any supported backend (T5, CLIP, BERT).
+
+Joint-name cleaning is handled upstream by the data-processing pipeline
+(the ``clean_joint_names`` field of ``cond.npy``), so text encoders receive
+already-cleaned text and encode it as-is.
+"""
+
+from typing import Dict, List, Optional, Union
+
+import torch
+from torch import nn
+
+from unimate.models.text_encoder.t5 import T5Conditioner
+from unimate.utils.logger import get_logger
+
+logger = get_logger(file_name=__file__)
+
+
+# ---------------------------------------------------------------------------
+# Embedding dimension lookup tables
+# ---------------------------------------------------------------------------
+
+# T5 dims live in `T5Conditioner.MODELS_DIMS` (single source of truth).
+T5_MODEL_DIM = T5Conditioner.MODELS_DIMS
+
+CLIP_MODEL_DIM = {
+ "ViT-B/32": 512,
+ "ViT-B/16": 512,
+ "ViT-L/14": 768,
+ "ViT-L/14@336px": 768,
+}
+
+BERT_MODEL_DIM = {
+ "distilbert/distilbert-base-uncased": 768,
+ "distilbert-base-uncased": 768,
+ "bert-base-uncased": 768,
+ "bert-large-uncased": 1024,
+}
+
+
+# ---------------------------------------------------------------------------
+# CLIP Conditioner
+# ---------------------------------------------------------------------------
+
+class CLIPConditioner(nn.Module):
+ """CLIP text encoder with unified ``tokenize`` / ``forward`` interface."""
+
+ def __init__(self, version: str = "ViT-B/32", device: str = "cpu",
+ pool: bool = True):
+ super().__init__()
+ if not pool:
+ # CLIP's encode_text returns the EOS-token projection only โ€”
+ # exposing per-token features needs a custom forward through the
+ # text transformer. Not implemented; raise instead of silently
+ # returning pooled features.
+ raise NotImplementedError(
+ "CLIPConditioner only supports pool=True. Use T5 or BERT for "
+ "token-level features."
+ )
+ import clip as clip_lib
+ self.device = device
+ self.version = version
+ self.pool = pool
+ self.clip_model, _ = clip_lib.load(version, device=device, jit=False)
+ clip_lib.model.convert_weights(self.clip_model)
+ self.clip_model.eval()
+ for p in self.clip_model.parameters():
+ p.requires_grad = False
+
+ self.dim = CLIP_MODEL_DIM.get(version, 512)
+ self._clip_lib = clip_lib
+
+ def tokenize(self, x: Union[str, List[Optional[str]]]) -> Dict[str, torch.Tensor]:
+ if isinstance(x, str):
+ x = [x]
+ entries = [xi if xi is not None else "" for xi in x]
+ tokens = self._clip_lib.tokenize(entries).to(self.device)
+ return {"tokens": tokens}
+
+ def forward(self, inputs: Dict[str, torch.Tensor]) -> torch.Tensor:
+ with torch.no_grad():
+ features = self.clip_model.encode_text(inputs["tokens"]) # (B, D)
+ return features.float()
+
+
+# ---------------------------------------------------------------------------
+# BERT Conditioner
+# ---------------------------------------------------------------------------
+
+class BERTConditioner(nn.Module):
+ """BERT text encoder with unified ``tokenize`` / ``forward`` interface."""
+
+ def __init__(self, model_path: str = "distilbert/distilbert-base-uncased",
+ device: str = "cpu", pool: bool = True):
+ super().__init__()
+ import os
+ from transformers import AutoTokenizer, AutoModel, logging
+ logging.set_verbosity_error()
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+
+ self.device = device
+ self.pool = pool
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path)
+ self.text_model = AutoModel.from_pretrained(model_path).to(device)
+ self.text_model.eval()
+ for p in self.text_model.parameters():
+ p.requires_grad = False
+
+ self.dim = self.text_model.config.hidden_size
+
+ def tokenize(self, x: Union[str, List[Optional[str]]]) -> Dict[str, torch.Tensor]:
+ if isinstance(x, str):
+ x = [x]
+ entries = [xi if xi is not None else "" for xi in x]
+ inputs = self.tokenizer(entries, return_tensors="pt", padding=True).to(self.device)
+ return inputs
+
+ def forward(self, inputs: Dict[str, torch.Tensor]) -> torch.Tensor:
+ """Return ``(B, D)`` mean-pooled features (default) or raw ``(B, T, D)``
+ token-level features when ``self.pool`` is False โ€” caller can read
+ the padding mask from ``inputs["attention_mask"]``."""
+ with torch.no_grad():
+ hidden = self.text_model(**inputs).last_hidden_state # (B, T, D)
+ if not self.pool:
+ return hidden
+ mask = inputs["attention_mask"]
+ token_count = mask.sum(dim=-1, keepdim=True).clamp(min=1)
+ embeds = (hidden * mask.unsqueeze(-1).float()).sum(dim=-2) / token_count
+ return embeds
+
+
+# ---------------------------------------------------------------------------
+# Factory
+# ---------------------------------------------------------------------------
+
+def get_text_encoder_dim(encoder_type: str, encoder_version: str) -> int:
+ """Return the embedding dimension for a given encoder type and version."""
+ _dim_tables = {
+ "t5": T5_MODEL_DIM,
+ "clip": CLIP_MODEL_DIM,
+ "bert": BERT_MODEL_DIM,
+ }
+ table = _dim_tables.get(encoder_type)
+ if table is None:
+ raise ValueError(f"Unknown text_encoder_type: {encoder_type}")
+ if encoder_version not in table:
+ raise ValueError(
+ f"Unknown {encoder_type} version '{encoder_version}'. "
+ f"Known versions: {list(table.keys())}"
+ )
+ return table[encoder_version]
+
+
+def create_text_encoder(
+ encoder_type: str,
+ encoder_version: str,
+ device: str = "cpu",
+ pool: bool = True,
+):
+ """Create a text encoder with unified interface.
+
+ All returned encoders support::
+
+ tokens = encoder.tokenize(texts)
+ embeddings = encoder(tokens)
+ # pool=True -> (B, D) mean-pooled
+ # pool=False -> (B, T, D) per-token (T5/BERT only)
+
+ Args:
+ encoder_type: One of 'clip', 'bert', 't5'.
+ encoder_version: Model identifier (e.g. 't5-base', 'ViT-B/32').
+ device: Target device.
+ pool: If True (default), the encoder mean-pools over non-padding
+ tokens. If False, returns raw token-level features ``(B, T, D)``.
+ Not supported for CLIP (raises ``NotImplementedError``).
+
+ Returns:
+ A text encoder module.
+ """
+ if encoder_type == "t5":
+ logger.info(f"Creating T5 text encoder: {encoder_version} (pool={pool})")
+ return T5Conditioner(
+ name=encoder_version,
+ finetune=False,
+ word_dropout=0.0,
+ normalize_text=False,
+ device=device,
+ pool=pool,
+ )
+ elif encoder_type == "clip":
+ logger.info(f"Creating CLIP text encoder: {encoder_version} (pool={pool})")
+ return CLIPConditioner(version=encoder_version, device=device, pool=pool)
+ elif encoder_type == "bert":
+ logger.info(f"Creating BERT text encoder: {encoder_version} (pool={pool})")
+ return BERTConditioner(model_path=encoder_version, device=device, pool=pool)
+ else:
+ raise ValueError(f"Unknown text_encoder_type: {encoder_type}")
diff --git a/unimate/models/text_encoder/t5.py b/unimate/models/text_encoder/t5.py
new file mode 100644
index 0000000..a84c43b
--- /dev/null
+++ b/unimate/models/text_encoder/t5.py
@@ -0,0 +1,291 @@
+# Adapted from the T5 conditioner in AudioCraft (Meta Platforms, Inc., MIT License):
+# https://github.com/facebookresearch/audiocraft
+"""T5-based text conditioner.
+
+Provides :class:`T5Conditioner` which encodes text (joint names, captions,
+categories) into dense vectors via a frozen (or fine-tuned) T5 encoder.
+Joint-name cleaning is handled upstream during data preprocessing.
+"""
+
+import hashlib
+import logging
+import random
+import re
+from typing import Any, Dict, List, Optional, Tuple, Union, no_type_check
+import warnings
+from copy import deepcopy
+
+import torch
+from torch import nn
+from torch.nn.utils.rnn import pad_sequence
+from transformers import T5EncoderModel, T5Tokenizer
+
+from unimate.utils.logger import get_logger
+
+logger = get_logger(file_name=__file__)
+
+# Type aliases
+ConditionType = Tuple[torch.Tensor, torch.Tensor] # (embedding, mask)
+
+
+# ---------------------------------------------------------------------------
+# Utilities
+# ---------------------------------------------------------------------------
+
+class TorchAutocast:
+ """Context manager wrapping ``torch.autocast`` with graceful no-op."""
+
+ def __init__(self, enabled: bool, *args, **kwargs):
+ self.autocast = torch.autocast(*args, **kwargs) if enabled else None
+
+ def __enter__(self):
+ if self.autocast is not None:
+ self.autocast.__enter__()
+
+ def __exit__(self, *args, **kwargs):
+ if self.autocast is not None:
+ self.autocast.__exit__(*args, **kwargs)
+
+
+def _hash_trick(word: str, vocab_size: int) -> int:
+ """Map *word* to an index in ``[0, vocab_size)`` via SHA-256."""
+ h = int(hashlib.sha256(word.encode("utf-8")).hexdigest(), 16)
+ return h % vocab_size
+
+
+def _length_to_mask(lengths: torch.Tensor, max_len: Optional[int] = None) -> torch.Tensor:
+ """Convert a 1-D lengths tensor to a boolean mask.
+
+ Example: ``[3, 5]`` โ†’ ``[[1,1,1,0,0],[1,1,1,1,1]]``
+ """
+ assert lengths.dim() == 1
+ final = lengths.max().item() if max_len is None else max_len
+ final = max(final, 1)
+ return torch.arange(final, device=lengths.device)[None, :] < lengths[:, None]
+
+
+# ---------------------------------------------------------------------------
+# Tokenizers (used only when normalize_text=True)
+# ---------------------------------------------------------------------------
+
+class WhiteSpaceTokenizer:
+ """Hash-based tokenizer with optional lemmatization and stopword removal.
+
+ Used internally by :class:`T5Conditioner` when ``normalize_text=True``.
+ """
+
+ PUNCTUATION = "?:!.,;"
+
+ def __init__(
+ self,
+ n_bins: int,
+ pad_idx: int = 0,
+ language: str = "en_core_web_sm",
+ lemma: bool = True,
+ stopwords: bool = True,
+ ):
+ self.n_bins = n_bins
+ self.pad_idx = pad_idx
+ self.lemma = lemma
+ self.stopwords = stopwords
+ try:
+ import spacy
+ self.nlp = spacy.load(language)
+ except IOError:
+ import spacy
+ spacy.cli.download(language) # type: ignore
+ self.nlp = spacy.load(language)
+
+ @no_type_check
+ def __call__(
+ self,
+ texts: List[Optional[str]],
+ return_text: bool = False,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ from num2words import num2words
+
+ output, lengths = [], []
+ texts = deepcopy(texts)
+ for i, text in enumerate(texts):
+ if text is None:
+ output.append(torch.Tensor([self.pad_idx]))
+ lengths.append(0)
+ continue
+
+ text = re.sub(r"(\d+)", lambda m: num2words(int(m.group(0))), text)
+ text = self.nlp(text)
+ if self.stopwords:
+ text = [w for w in text if not w.is_stop]
+ text = [w for w in text if w.text not in self.PUNCTUATION]
+ text = [getattr(t, "lemma_" if self.lemma else "text") for t in text]
+
+ texts[i] = " ".join(text)
+ lengths.append(len(text))
+ tokens = torch.Tensor([_hash_trick(w, self.n_bins) for w in text])
+ output.append(tokens)
+
+ mask = _length_to_mask(torch.IntTensor(lengths)).int()
+ padded = pad_sequence(output, padding_value=self.pad_idx).int().t()
+ if return_text:
+ return padded, mask, texts
+ return padded, mask
+
+
+# ---------------------------------------------------------------------------
+# Base conditioner
+# ---------------------------------------------------------------------------
+
+class BaseConditioner(nn.Module):
+ """Abstract base for text conditioners."""
+
+ def __init__(self, dim: int):
+ super().__init__()
+ self.dim = dim
+
+ def tokenize(self, *args, **kwargs) -> Any:
+ raise NotImplementedError
+
+ def forward(self, inputs: Any) -> ConditionType:
+ raise NotImplementedError
+
+
+# ---------------------------------------------------------------------------
+# T5 Conditioner
+# ---------------------------------------------------------------------------
+
+class T5Conditioner(BaseConditioner):
+ """Encode text into dense vectors via a frozen (or fine-tuned) T5 encoder.
+
+ The T5 encoder output is mean-pooled over non-padding tokens to produce
+ a single ``(B, D)`` embedding per input string.
+
+ Args:
+ name: HuggingFace T5 model identifier.
+ finetune: Whether to keep T5 gradients during training.
+ device: Target device (``"cuda"`` or ``"cpu"``).
+ autocast_dtype: Dtype string for mixed precision (or None to disable).
+ word_dropout: Probability of dropping each word during training.
+ normalize_text: If True, apply lemmatization / stopword removal.
+ pool: If True (default), mean-pool over non-padding tokens and return
+ ``(B, D)``. If False, return raw token-level features
+ ``(B, T, D)`` โ€” caller can read the padding mask from
+ ``inputs["attention_mask"]`` returned by :meth:`tokenize`.
+ """
+
+ # Supported T5 / Flan-T5 models and their encoder hidden sizes; also
+ # consumed by ``text_encoder.factory`` so the table lives in one place.
+ # Flan-T5's large variants are published as ``-xl`` / ``-xxl``.
+ MODELS_DIMS = {
+ "t5-small": 512,
+ "t5-base": 768,
+ "t5-large": 1024,
+ "t5-3b": 1024,
+ "t5-11b": 1024,
+ "google/flan-t5-small": 512,
+ "google/flan-t5-base": 768,
+ "google/flan-t5-large": 1024,
+ "google/flan-t5-xl": 2048,
+ "google/flan-t5-xxl": 4096,
+ }
+
+ def __init__(
+ self,
+ name: str,
+ finetune: bool,
+ device: str,
+ autocast_dtype: Optional[str] = "float32",
+ word_dropout: float = 0.0,
+ normalize_text: bool = False,
+ pool: bool = True,
+ ):
+ if name not in self.MODELS_DIMS:
+ raise ValueError(
+ f"Unknown T5 model: {name!r}. Known: {list(self.MODELS_DIMS)}"
+ )
+ super().__init__(self.MODELS_DIMS[name])
+ self.device = device
+ self.name = name
+ self.finetune = finetune
+ self.word_dropout = word_dropout
+ self.normalize_text = normalize_text
+ self.pool = pool
+
+ # --- Autocast setup ---
+ if autocast_dtype is None or device == "cpu":
+ self.autocast = TorchAutocast(enabled=False)
+ else:
+ dtype = getattr(torch, autocast_dtype)
+ assert isinstance(dtype, torch.dtype)
+ logger.info(f"T5 autocast dtype: {autocast_dtype}")
+ self.autocast = TorchAutocast(enabled=True, device_type=device, dtype=dtype)
+
+ # --- Load T5 (suppress noisy HF warnings) ---
+ prev_level = logging.root.manager.disable
+ logging.disable(logging.ERROR)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ try:
+ self.t5_tokenizer = T5Tokenizer.from_pretrained(name)
+ t5 = T5EncoderModel.from_pretrained(name).train(mode=finetune)
+ finally:
+ logging.disable(prev_level)
+
+ if finetune:
+ self.t5 = t5
+ else:
+ # Store outside nn.Module state so it's excluded from checkpoints
+ self.__dict__["t5"] = t5.to(device)
+
+ if normalize_text:
+ self.text_normalizer = WhiteSpaceTokenizer(1, lemma=True, stopwords=True)
+
+ # ------------------------------------------------------------------
+ # Tokenize & forward
+ # ------------------------------------------------------------------
+
+ def tokenize(
+ self,
+ x: Union[str, List[Optional[str]]],
+ ) -> Dict[str, torch.Tensor]:
+ """Tokenize text via T5 BPE.
+
+ Args:
+ x: Single string or list of strings to encode.
+ """
+ if isinstance(x, str):
+ x = [x]
+
+ entries = [xi if xi is not None else "" for xi in x]
+
+ if self.normalize_text:
+ _, _, entries = self.text_normalizer(entries, return_text=True)
+
+ if self.word_dropout > 0.0 and self.training:
+ entries = [
+ " ".join(w for w in e.split() if random.random() >= self.word_dropout)
+ for e in entries
+ ]
+
+ empty_idx = torch.LongTensor([i for i, e in enumerate(entries) if e == ""])
+
+ inputs = self.t5_tokenizer(entries, return_tensors="pt", padding=True).to(self.device)
+ inputs["attention_mask"][empty_idx, :] = 0
+ return inputs
+
+ def forward(self, inputs: Dict[str, torch.Tensor]) -> torch.Tensor:
+ """Encode tokenized inputs.
+
+ Returns:
+ ``(B, D)`` mean-pooled embeddings if ``self.pool`` is True,
+ otherwise raw token-level features ``(B, T, D)`` (padded; mask
+ is in ``inputs["attention_mask"]``).
+ """
+ mask = inputs["attention_mask"]
+ with torch.set_grad_enabled(self.finetune), self.autocast:
+ hidden = self.t5(**inputs).last_hidden_state # (B, T, D)
+ if not self.pool:
+ return hidden
+ # Mean-pool over non-padding tokens (avoid division by zero)
+ token_count = mask.sum(dim=-1, keepdim=True).clamp(min=1) # (B, 1)
+ embeds = (hidden * mask.unsqueeze(-1)).sum(dim=-2) / token_count
+ return embeds
diff --git a/unimate/tools/__init__.py b/unimate/tools/__init__.py
new file mode 100644
index 0000000..c1c469c
--- /dev/null
+++ b/unimate/tools/__init__.py
@@ -0,0 +1 @@
+"""Offline utilities that prepare data for training and inference."""
diff --git a/unimate/tools/precompute_text_emb.py b/unimate/tools/precompute_text_emb.py
new file mode 100644
index 0000000..e1be30d
--- /dev/null
+++ b/unimate/tools/precompute_text_emb.py
@@ -0,0 +1,245 @@
+"""Pre-encode a feature directory's text into an on-disk feature cache.
+
+The mixture dataset encodes every unique caption and joint name when it is
+constructed: a text encoder is loaded onto the GPU, run once, and thrown away โ€”
+on every training run, every sampling run, and once per worker. This tool does
+that work once and writes the result next to the features, after which the
+dataset loads the embeddings and never instantiates the encoder at all.
+
+One file per source, each keyed the way the dataset looks it up:
+
+ * ``captions.json`` -> ``caption_emb_cache.npz`` one entry per CLIP KEY (the
+ keys of captions.json), so a clip's features are a
+ direct lookup; two clips sharing a caption each get
+ their own entry
+ * ``cond.npy`` -> ``joint_emb_cache.npz`` one entry per UNIQUE joint
+ name, taken from the cleaned vocabulary
+ ``clean_joint_names`` (see
+ ``dataset.model_joint_names``)
+
+A caption key gets an embedding and a mask โ€” right-padded to the file's
+longest, the mask marking the real tokens. Joint names are stored pooled, one
+vector per name, because that is all the model reads of them
+(``joint_names_emb`` is one vector per joint).
+
+Repeated caption strings are still encoded only once โ€” the dedupe happens
+before the forward pass, not in the file.
+
+Captions are stored per token because ``text_cond='cross_attn'`` attends the
+sequence; the pooled vector ``adaLN`` uses is the mean over the same rows,
+derived by the data loader. The encoder is recorded in each file's metadata and
+checked on load, so a cache built with one encoder is never read by a run
+using another.
+
+Usage (from the repo root)::
+
+ # every dataset/features/* with the config's encoder
+ python -m unimate.tools.precompute_text_emb --config configs/uniml3d_90frames.json
+
+ # one input folder (positional or --input_dir), encoder given explicitly
+ python -m unimate.tools.precompute_text_emb --input_dir dataset/features/truebones \\
+ --encoder_type t5 --encoder_version google/flan-t5-base
+
+ # re-encode even if a cache is already there
+ python -m unimate.tools.precompute_text_emb --config <cfg> --overwrite
+
+Re-run it after regenerating captions or joint names: entries the cache does
+not cover are encoded at load time anyway, so a stale cache costs speed rather
+than correctness, but a fresh one keeps the encoder out of the run entirely.
+"""
+
+import argparse
+import glob
+import json
+import os
+from os.path import join as pjoin
+
+import numpy as np
+import torch
+from tqdm import tqdm
+
+from unimate.configs.schema import MainConfig
+from unimate.dataset.mixture.dataset import model_joint_names
+from unimate.models.text_encoder.factory import create_text_encoder
+from unimate.utils.logger import get_logger
+from unimate.utils.text_emb_cache import (KINDS, cache_path, load_cache,
+ pooled_from_hidden, save_cache,
+ sequences_from_hidden)
+
+logger = get_logger(file_name=__file__)
+
+DEFAULT_GLOB = 'dataset/features/*'
+
+
+# ---------------------------------------------------------------------------
+# Collecting the strings a feature directory needs embedded
+# ---------------------------------------------------------------------------
+
+def collect_texts(root_dir):
+ """What each source needs encoded -> ``{kind: {key: text}}``.
+
+ ``'caption'`` maps every clip key to its caption; ``'joint'`` maps each
+ unique joint name to itself. A source with no file simply does not appear.
+ """
+ out = {}
+
+ captions_path = pjoin(root_dir, 'captions.json')
+ if os.path.isfile(captions_path):
+ with open(captions_path) as f:
+ captions = json.load(f)
+ out['caption'] = {clip: cap for clip, cap in captions.items() if cap}
+
+ cond_path = pjoin(root_dir, 'cond.npy')
+ if os.path.isfile(cond_path):
+ cond = np.load(cond_path, allow_pickle=True).item()
+ # Same rule the dataset applies (cleaned vocabulary, raw only as a
+ # loud fallback) โ€” a different rule here would leave the lookups the
+ # dataset actually performs uncovered by this cache.
+ out['joint'] = {
+ name: name
+ for ot, entry in cond.items()
+ for name in model_joint_names(entry, ot)
+ if name
+ }
+
+ return {k: v for k, v in out.items() if v}
+
+
+# ---------------------------------------------------------------------------
+# Encoding
+# ---------------------------------------------------------------------------
+
+def encode_texts(texts, encoder, chunk_size, label):
+ """Encode *texts* in chunks -> ``({text: (T_i, D)}, {text: (D,) pooled})``.
+
+ The encoder is built with ``pool=False``, so each chunk comes back as
+ ``(B, T, D)`` padded to the chunk's longest text; ``sequences_from_hidden``
+ slices every row back to its own token count, so no padding is stored and
+ the result does not depend on how the texts were chunked. Chunking bounds
+ peak GPU memory the same way the dataset's own pre-encoding does.
+ """
+ seqs_out, pooled_out = {}, {}
+ n_chunks = (len(texts) + chunk_size - 1) // chunk_size
+ for i in tqdm(range(0, len(texts), chunk_size), total=n_chunks,
+ desc=f'Encoding {label}'):
+ chunk = texts[i:i + chunk_size]
+ with torch.no_grad():
+ inputs = encoder.tokenize(chunk)
+ hidden = encoder(inputs) # (B, T, D)
+ # Pool on the encoder's own terms, before anything moves to CPU, so
+ # the adaLN path reads exactly what a pool=True encoder would return.
+ pooled = pooled_from_hidden(hidden, inputs['attention_mask'])
+ seqs = sequences_from_hidden(hidden.detach().cpu(),
+ inputs['attention_mask'].cpu())
+ seqs_out.update(dict(zip(chunk, seqs)))
+ pooled_out.update({t: pooled[j] for j, t in enumerate(chunk)})
+ return seqs_out, pooled_out
+
+
+# ---------------------------------------------------------------------------
+# Entry point
+# ---------------------------------------------------------------------------
+
+def resolve_roots(inputs):
+ """Feature directories from explicit paths or the default glob."""
+ if inputs:
+ roots = list(inputs)
+ else:
+ roots = sorted(p for p in glob.glob(DEFAULT_GLOB) if os.path.isdir(p))
+ missing = [r for r in roots if not os.path.isdir(r)]
+ if missing:
+ raise SystemExit(f'Not a directory: {", ".join(missing)}')
+ return roots
+
+
+def parse_args():
+ ap = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
+ ap.add_argument('inputs', nargs='*', metavar='INPUT_DIR',
+ help='Feature directory / directories to process, e.g. '
+ 'dataset/features/truebones. Same as --input_dir.')
+ ap.add_argument('--input_dir', action='append', default=[], metavar='DIR',
+ help='Feature directory to process; repeatable. With '
+ f'neither form given, every {DEFAULT_GLOB} is done.')
+ ap.add_argument('--config', default=None,
+ help='Training config to take the encoder type / version '
+ 'from; --encoder_type / --encoder_version override it')
+ ap.add_argument('--encoder_type', default=None, help="'t5', 'clip', 'bert'")
+ ap.add_argument('--encoder_version', default=None,
+ help="e.g. 'google/flan-t5-base' (None = the type's default)")
+ ap.add_argument('--chunk_size', type=int, default=256,
+ help='Texts per forward pass (default: 256)')
+ ap.add_argument('--device', default='cuda' if torch.cuda.is_available() else 'cpu')
+ ap.add_argument('--overwrite', action='store_true',
+ help='Re-encode everything instead of extending the cache')
+ return ap.parse_args()
+
+
+def main():
+ args = parse_args()
+
+ encoder_type, encoder_version = args.encoder_type, args.encoder_version
+ if args.config:
+ cfg = MainConfig.from_json(args.config)
+ encoder_type = encoder_type or cfg.model.text_encoder_type
+ encoder_version = encoder_version or cfg.model.text_encoder_version
+ if not encoder_type:
+ raise SystemExit('Give --encoder_type or --config')
+
+ roots = resolve_roots(list(args.inputs) + list(args.input_dir))
+ logger.info(f'Encoder: {encoder_type} / {encoder_version} on {args.device}')
+
+ # The encoder is built on the first directory that actually needs it, so a
+ # run where every cache is already complete never loads it.
+ encoder = None
+ for root in roots:
+ by_kind = collect_texts(root)
+ if not by_kind:
+ logger.info(f'[{root}] no captions.json / cond.npy; skipped')
+ continue
+
+ for kind, text_by_key in by_kind.items():
+ hit = ({} if args.overwrite
+ else load_cache(root, kind, encoder_type, encoder_version))
+ # A sequence kind loads as (tokens, pooled) pairs; split them so
+ # both views survive an incremental re-run.
+ if KINDS[kind][1]:
+ cached, cached_pooled = dict(hit), {}
+ else:
+ cached = {k: v[0] for k, v in hit.items()}
+ cached_pooled = {k: v[1] for k, v in hit.items()}
+ todo_keys = [k for k in text_by_key if k not in cached]
+ path = cache_path(root, kind)
+ if not todo_keys:
+ logger.info(f'[{root}] {kind}: {len(text_by_key)} keys already '
+ f'cached in {os.path.basename(path)}; nothing to do')
+ continue
+
+ # Encode each distinct string once even when several keys share it
+ # (a caption repeated across clips), then fan the result back out.
+ unique = sorted({text_by_key[k] for k in todo_keys})
+ logger.info(f'[{root}] {kind}: {len(text_by_key)} keys, '
+ f'{len(todo_keys)} to encode over {len(unique)} distinct '
+ f'strings, {len(cached)} reused')
+ if encoder is None:
+ # pool=False: the cache stores token sequences; pooling for the
+ # adaLN path happens in the data loader.
+ encoder = create_text_encoder(encoder_type=encoder_type,
+ encoder_version=encoder_version,
+ device=args.device, pool=False)
+ by_text, pooled_by_text = encode_texts(
+ unique, encoder, args.chunk_size,
+ f'{os.path.basename(root.rstrip("/"))}/{kind}')
+ cached.update({k: by_text[text_by_key[k]] for k in todo_keys})
+ cached_pooled.update({k: pooled_by_text[text_by_key[k]]
+ for k in todo_keys})
+ n = save_cache(path, cached, kind, encoder_type, encoder_version,
+ pooled_by_key=cached_pooled)
+ what = 'pooled vectors' if KINDS[kind][1] else 'token sequences'
+ logger.info(f'[{root}] wrote {n} {what} -> {path}')
+
+ if encoder is None:
+ logger.info('Every cache was already complete; the encoder was never loaded.')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/unimate/training/__init__.py b/unimate/training/__init__.py
new file mode 100644
index 0000000..7b1a9dc
--- /dev/null
+++ b/unimate/training/__init__.py
@@ -0,0 +1 @@
+"""Training loop, trainer, EMA, and progress tracking."""
diff --git a/unimate/training/base_trainer.py b/unimate/training/base_trainer.py
new file mode 100644
index 0000000..2fcd24c
--- /dev/null
+++ b/unimate/training/base_trainer.py
@@ -0,0 +1,51 @@
+"""Base trainer class providing a loss interface.
+
+Subclasses must implement :meth:`compute_loss`. Checkpoint I/O is handled
+directly via ``accelerator.save`` in the training loop for distributed
+compatibility.
+"""
+
+from abc import ABC, abstractmethod
+from typing import Dict, Optional, Tuple
+
+import torch
+import torch.nn as nn
+
+
+class BaseTrainer(ABC, nn.Module):
+ """Abstract base trainer wrapping a generative model.
+
+ Inherits ``nn.Module`` so that subclasses can register buffers or
+ sub-modules (e.g. an EMA model) if needed.
+ """
+
+ def __init__(self, checkpoint_dir: Optional[str] = None):
+ super().__init__()
+ self.checkpoint_dir = checkpoint_dir
+
+ # ------------------------------------------------------------------
+ # Abstract interface
+ # ------------------------------------------------------------------
+
+ @abstractmethod
+ def compute_loss(
+ self, batch: Dict[str, torch.Tensor], **kwargs
+ ) -> Tuple[torch.Tensor, Dict[str, float]]:
+ """Compute training loss.
+
+ Returns:
+ (total_loss, loss_dict) โ€” scalar for backprop and a dict of
+ named component values (floats) for logging.
+ """
+
+ # ------------------------------------------------------------------
+ # Helpers
+ # ------------------------------------------------------------------
+
+ def get_num_parameters(self) -> int:
+ """Total number of trainable parameters in the wrapped model.
+
+ Subclasses that store the model as an attribute (rather than as
+ a registered sub-module) should override this.
+ """
+ return sum(p.numel() for p in self.parameters() if p.requires_grad)
diff --git a/unimate/training/ema.py b/unimate/training/ema.py
new file mode 100644
index 0000000..5064752
--- /dev/null
+++ b/unimate/training/ema.py
@@ -0,0 +1,118 @@
+"""Exponential Moving Average (EMA) of model weights."""
+
+import torch
+from typing import Iterator
+
+
+class EMAModel:
+ """Exponential Moving Average of model weights.
+
+ With ``use_ema_warmup`` the decay follows the standard warmup schedule
+ ``decay = (1 + n) / (10 + n)``, where *n* counts EMA updates in units of
+ 100 optimizer steps; each optimizer step applies the 100th root of that
+ value so the smoothing is spread evenly across steps while preserving
+ the same half-life. The result is clamped to ``[min_decay, decay]``.
+ """
+
+ def __init__(
+ self,
+ parameters: Iterator[torch.nn.Parameter],
+ decay: float = 0.9999,
+ min_decay: float = 0.0,
+ update_after_step: int = 0,
+ use_ema_warmup: bool = False,
+ ):
+ parameters = list(parameters)
+ self.shadow_params = [p.clone().detach() for p in parameters if p.requires_grad]
+
+ self.decay = decay
+ self.min_decay = min_decay
+ self.update_after_step = update_after_step
+ self.use_ema_warmup = use_ema_warmup
+ self.optimization_step = 0
+ self.cur_decay_value = None
+
+ # ------------------------------------------------------------------
+ # Decay schedule
+ # ------------------------------------------------------------------
+
+ def get_decay(self, optimization_step: int) -> float:
+ """Compute the EMA decay factor for the current step."""
+ step = max(0, optimization_step - self.update_after_step - 1)
+ if step <= 0:
+ return 0.0
+
+ if self.use_ema_warmup:
+ # Per-step equivalent of an every-100-steps update with
+ # decay = (1 + n) / (10 + n): take the 100th root.
+ n = step / 100.0
+ cur_decay_value = ((1 + n) / (10 + n)) ** 0.01
+ else:
+ cur_decay_value = (1 + step) / (10 + step)
+
+ return max(min(cur_decay_value, self.decay), self.min_decay)
+
+ # ------------------------------------------------------------------
+ # Update
+ # ------------------------------------------------------------------
+
+ @torch.no_grad()
+ def step(self, parameters: Iterator[torch.nn.Parameter]) -> None:
+ """Update shadow params toward *parameters* with current decay."""
+ parameters = [p for p in parameters if p.requires_grad]
+ self.optimization_step += 1
+
+ decay = self.get_decay(self.optimization_step)
+ self.cur_decay_value = decay
+ one_minus_decay = 1 - decay
+
+ for s_param, param in zip(self.shadow_params, parameters):
+ if param.dtype != s_param.dtype:
+ param = param.to(s_param.dtype)
+ s_param.sub_(one_minus_decay * (s_param - param))
+
+ # ------------------------------------------------------------------
+ # Copy / store / restore
+ # ------------------------------------------------------------------
+
+ def copy_to(self, parameters: Iterator[torch.nn.Parameter]) -> None:
+ """Copy shadow (averaged) params into *parameters*."""
+ parameters = [p for p in parameters if p.requires_grad]
+ for s_param, param in zip(self.shadow_params, parameters):
+ param.data.copy_(s_param.data)
+
+ def store(self, parameters: Iterator[torch.nn.Parameter]) -> None:
+ """Snapshot current model params so they can be restored later."""
+ self.collected_params = [p.clone() for p in parameters if p.requires_grad]
+
+ def restore(self, parameters: Iterator[torch.nn.Parameter]) -> None:
+ """Restore params saved by :meth:`store`."""
+ parameters = [p for p in parameters if p.requires_grad]
+ for c_param, param in zip(self.collected_params, parameters):
+ param.data.copy_(c_param.data)
+
+ # ------------------------------------------------------------------
+ # Serialization
+ # ------------------------------------------------------------------
+
+ def state_dict(self) -> dict:
+ return {
+ "decay": self.decay,
+ "min_decay": self.min_decay,
+ "optimization_step": self.optimization_step,
+ "update_after_step": self.update_after_step,
+ "use_ema_warmup": self.use_ema_warmup,
+ "shadow_params": self.shadow_params,
+ }
+
+ def load_state_dict(self, state_dict: dict) -> None:
+ self.decay = state_dict["decay"]
+ self.min_decay = state_dict.get("min_decay", 0.0)
+ self.optimization_step = state_dict["optimization_step"]
+ self.update_after_step = state_dict["update_after_step"]
+ self.use_ema_warmup = state_dict.get("use_ema_warmup", False)
+ self.shadow_params = state_dict["shadow_params"]
+
+ def to(self, device=None, dtype=None) -> None:
+ """Move shadow params to the given device / dtype."""
+ self.shadow_params = [p.to(device=device, dtype=dtype) for p in self.shadow_params]
\ No newline at end of file
diff --git a/unimate/training/tracker.py b/unimate/training/tracker.py
new file mode 100644
index 0000000..b5a000e
--- /dev/null
+++ b/unimate/training/tracker.py
@@ -0,0 +1,96 @@
+"""Lightweight tracker for step-based or epoch-based training loops.
+
+Provides a single object that tracks current step/epoch, determines when
+training is finished, and formats progress descriptions for ``tqdm``.
+
+Usage::
+
+ tracker = TrainingTracker(max_steps=100_000, steps_per_epoch=500)
+ while not tracker.training_finished():
+ for batch in dataloader:
+ ...
+ tracker.step()
+ tracker.next_epoch()
+"""
+
+
+class TrainingTracker:
+ """Track training progress for step-based or epoch-based training.
+
+ Exactly one of *max_steps* or *max_epochs* must be provided.
+
+ Args:
+ max_epochs: Stop after this many full passes through the dataset.
+ max_steps: Stop after this many optimizer steps.
+ steps_per_epoch: Number of batches per epoch (``len(dataloader)``).
+ Used to estimate epochs from steps (or vice versa).
+ """
+
+ def __init__(self, max_epochs=None, max_steps=None, steps_per_epoch=None):
+ if max_steps is None and max_epochs is None:
+ raise ValueError("Either max_epochs or max_steps must be specified")
+ if max_steps is not None and max_epochs is not None:
+ raise ValueError("Only one of max_epochs or max_steps should be specified")
+
+ self.steps_per_epoch = steps_per_epoch
+ self.current_step = 0
+ self.current_epoch = 0
+
+ if max_steps is not None:
+ self.mode = "steps"
+ self.max_steps = max_steps
+ self.max_epochs = None
+ self.estimated_epochs = (
+ (max_steps + steps_per_epoch - 1) // steps_per_epoch
+ if steps_per_epoch else None
+ )
+ else:
+ self.mode = "epochs"
+ self.max_epochs = max_epochs
+ self.max_steps = (
+ max_epochs * steps_per_epoch if steps_per_epoch else None
+ )
+ self.estimated_epochs = max_epochs
+
+ # -------------------------------------------------------------------
+ # Progress
+ # -------------------------------------------------------------------
+
+ @property
+ def total_steps(self):
+ """Total number of optimizer steps (exact or estimated)."""
+ if self.mode == "steps":
+ return self.max_steps
+ return self.max_epochs * self.steps_per_epoch
+
+ def step(self):
+ """Record one optimizer step."""
+ self.current_step += 1
+
+ def next_epoch(self):
+ """Record the start of a new epoch."""
+ self.current_epoch += 1
+
+ def training_finished(self):
+ """Return True when the training budget is exhausted."""
+ if self.mode == "steps":
+ return self.current_step >= self.max_steps
+ return self.current_epoch >= self.max_epochs
+
+ # -------------------------------------------------------------------
+ # Display helpers
+ # -------------------------------------------------------------------
+
+ def get_progress_desc(self):
+ """Return a short string for ``tqdm.set_description``."""
+ if self.mode == "steps":
+ return f"Step {self.current_step}/{self.max_steps} (Epoch {self.current_epoch})"
+ return f"Epoch {self.current_epoch}/{self.max_epochs}"
+
+ def get_duration_str(self):
+ """Return a human-readable summary of the training duration."""
+ spe = self.steps_per_epoch
+ if self.mode == "steps":
+ return f"Steps: {self.max_steps:,} ({spe} steps/epoch)"
+ total = self.max_epochs * spe
+ return f"Epochs: {self.max_epochs} ({spe} steps/epoch, {total:,} total steps)"
diff --git a/unimate/training/train.py b/unimate/training/train.py
new file mode 100644
index 0000000..414ecd1
--- /dev/null
+++ b/unimate/training/train.py
@@ -0,0 +1,441 @@
+"""Train a diffusion model on motions for any skeleton topology.
+
+Entry point (usually via ``accelerate launch``, see scripts/)::
+
+ python -m unimate.training.train --config configs/<config>.json
+
+CLI overrides (via tyro): ``--output_dir``, ``--batch_size``, ``--num_workers``,
+``--resume``.
+"""
+
+import os
+import warnings
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+import tyro
+from accelerate import Accelerator, DataLoaderConfiguration
+from accelerate.utils import set_seed
+from torch.utils.tensorboard import SummaryWriter
+from tqdm import tqdm
+from transformers.optimization import get_cosine_with_min_lr_schedule_with_warmup
+
+from unimate.configs.schema import MainConfig
+from unimate.dataset.factory import create_train_dataloader
+from unimate.models.factory import create_model
+from unimate.training.trainer import DiffusionTrainer
+from unimate.training.tracker import TrainingTracker
+from unimate.utils.logger import get_logger
+
+warnings.filterwarnings("ignore")
+logger = get_logger(file_name=__file__)
+
+
+# ===================================================================
+# CLI arguments
+# ===================================================================
+
+@dataclass
+class TrainingArgs:
+ """CLI arguments parsed by tyro (override config values)."""
+ config: str
+ output_dir: Optional[str] = None
+ batch_size: Optional[int] = None
+ num_workers: Optional[int] = None
+ resume: Optional[str] = None # path to checkpoint .pt file to resume from
+
+
+# ===================================================================
+# Training loop
+# ===================================================================
+
+def train_diffusion(args: TrainingArgs, config: MainConfig,
+ accelerator: Accelerator):
+ """End-to-end training: setup, loop, checkpoint, visualize."""
+
+ is_main = accelerator.is_main_process
+
+ # ---- Output directories ----
+ output_dir = args.output_dir or config.experiment.output_dir
+ checkpoint_dir = os.path.join(output_dir, "checkpoints")
+ log_dir = os.path.join(output_dir, "logs")
+ debug_dir = os.path.join(output_dir, "debug")
+ for d in [checkpoint_dir, log_dir, debug_dir]:
+ os.makedirs(d, exist_ok=True)
+
+ # ---- Reproducibility ----
+ if config.training.seed is not None:
+ # device_specific: seed += process_index. Without it every rank draws
+ # the SAME flow-matching t and the same x0 noise (both come from the
+ # global RNG), so an 8-GPU step sees one batch's worth of distinct
+ # (t, noise) pairs instead of eight โ€” and the same CFG caption-dropout
+ # pattern on every rank. Model init may now differ per rank, which is
+ # harmless: DDP broadcasts rank 0's parameters when it wraps the model.
+ set_seed(config.training.seed, device_specific=True)
+ logger.info(
+ f"Set random seed to {config.training.seed} (device-specific)")
+
+ # ---- Dataset ----
+ logger.info("Creating dataset loader...")
+ batch_size = args.batch_size or config.training.batch_size
+ num_workers = args.num_workers or config.training.num_workers
+ dataloader = create_train_dataloader(
+ dataset_config=config.dataset,
+ model_config=config.model,
+ balanced=config.training.balanced,
+ batch_size=batch_size,
+ num_workers=num_workers,
+ )
+
+ # ---- Persist config (after dataset so auto-computed max_joints /
+ # max_depth are written; inference reads these back to rebuild the
+ # exact same model architecture). ----
+ if is_main:
+ config_path = os.path.join(output_dir, "config.json")
+ config.to_json(config_path)
+ logger.info(f"Saved config to {config_path}")
+
+ # Persist normalization stats so inference normalizes identically.
+ stats_path = os.path.join(output_dir, "dataset_stats.npy")
+ dataloader.dataset.save_dataset_stats(stats_path)
+
+ # ---- Model ----
+ logger.info("Creating model and diffusion...")
+ model = create_model(
+ dataset_config=config.dataset,
+ model_config=config.model,
+ )
+
+ # ---- Trainer (wraps model + diffusion/flow for loss & visualization) ----
+ trainer = DiffusionTrainer(
+ config=config,
+ model=model,
+ data=dataloader,
+ checkpoint_dir=checkpoint_dir,
+ )
+
+ # ---- Optimizer & LR schedule ----
+ optimizer = torch.optim.AdamW(
+ model.parameters(),
+ lr=config.training.learning_rate,
+ weight_decay=config.training.weight_decay,
+ betas=(config.training.adam_beta1, config.training.adam_beta2),
+ )
+ lr_scheduler = get_cosine_with_min_lr_schedule_with_warmup(
+ optimizer,
+ num_warmup_steps=int(config.training.warmup_ratio * config.training.num_steps),
+ num_training_steps=config.training.num_steps,
+ min_lr_rate=config.training.min_lr_ratio,
+ num_cycles=0.5,
+ )
+
+ # ---- Accelerate: wrap model, optimizer, dataloader for distributed ----
+ # NOTE: lr_scheduler is NOT wrapped by accelerator. AcceleratedScheduler
+ # with split_batches=False steps num_processes times per call to compensate
+ # for data sharding, but num_training_steps already equals the target number
+ # of optimizer steps, so wrapping would advance the schedule num_gpusร— too fast.
+ model, optimizer, dataloader = accelerator.prepare(
+ model, optimizer, dataloader,
+ )
+ trainer.model = model # point trainer at the wrapped model
+ trainer.initialize_ema(accelerator)
+
+ # ---- TensorBoard ----
+ writer = SummaryWriter(log_dir) if is_main else None
+
+ # ---- Training tracker ----
+ tracker = TrainingTracker(
+ max_epochs=config.training.num_epochs,
+ max_steps=config.training.num_steps,
+ steps_per_epoch=len(dataloader),
+ )
+
+ # ---- Resume from checkpoint (if requested) ----
+ if args.resume:
+ _resume_from_checkpoint(
+ args.resume, accelerator, model, optimizer, lr_scheduler,
+ trainer, tracker,
+ )
+
+ if is_main:
+ logger.info(f"Training for {tracker.get_duration_str()}")
+
+ # ---- Initial visualization (skip if resuming) ----
+ if not args.resume:
+ trainer.eval()
+ if is_main:
+ trainer.visualize_samples(
+ save_dir=debug_dir,
+ prefix="initial_before_training",
+ num_samples=config.sampling.num_samples,
+ cfg_scale=config.sampling.cfg_scale,
+ )
+ torch.cuda.empty_cache()
+
+ trainer.train()
+
+ # ---- Main training loop ----
+ pbar = tqdm(
+ range(tracker.total_steps),
+ desc=tracker.get_progress_desc(),
+ initial=tracker.current_step,
+ disable=not is_main,
+ )
+ grad_norm = None
+
+ while not tracker.training_finished():
+ pbar.set_description(tracker.get_progress_desc())
+
+ # Update sampler epoch so each epoch gets different random indices in DDP
+ _set_sampler_epoch(dataloader, tracker.current_epoch)
+
+ for batch in dataloader:
+ with accelerator.accumulate(model):
+ # Forward pass (mixed precision)
+ with accelerator.autocast():
+ loss, loss_dict = trainer.compute_loss(batch)
+
+ # NaN guard. The decision is reduced across ranks first, so
+ # every rank takes the same branch โ€” a rank-local skip would
+ # desync DDP. A bad micro-batch is dropped by skipping its
+ # backward: earlier micro-batches' gradients survive and are
+ # all-reduced by the group's final backward as usual. Only
+ # when the bad batch IS that final one is there no all-reduce,
+ # and then the group's (rank-local) gradients must be thrown
+ # away rather than stepped on. Backward on a detached zero
+ # would raise 'does not require grad', so never do that.
+ bad_local = (~torch.isfinite(loss)).to(torch.int32)
+ skip_batch = accelerator.reduce(bad_local, reduction="max").item() == 1
+ if skip_batch and is_main:
+ logger.warning(
+ f"[Global skip] non-finite loss at step {tracker.current_step}"
+ )
+
+ # Backward + optimizer step
+ if not skip_batch:
+ accelerator.backward(loss)
+
+ if accelerator.sync_gradients and skip_batch:
+ # No all-reduce ran for this accumulation group.
+ optimizer.zero_grad(set_to_none=True)
+ elif accelerator.sync_gradients:
+ if config.training.max_grad_norm is not None:
+ grad_norm = accelerator.clip_grad_norm_(
+ accelerator.unwrap_model(model).parameters(),
+ config.training.max_grad_norm,
+ )
+
+ optimizer.step()
+ lr_scheduler.step()
+ optimizer.zero_grad()
+
+ # EMA update
+ if trainer.use_ema and trainer.ema_model is not None:
+ trainer.ema_model.step(
+ accelerator.unwrap_model(model).parameters()
+ )
+
+ pbar.update(1)
+ tracker.step()
+
+ # --- Per-effective-step side effects ---
+ step = tracker.current_step
+
+ # Progress bar postfix
+ if is_main:
+ pbar.set_postfix(
+ loss=f"{loss.item():.4f}",
+ lr=f"{lr_scheduler.get_last_lr()[0]:.6f}",
+ )
+
+ # Periodic logging
+ if step > 0 and step % config.training.log_interval == 0 and is_main:
+ _log_metrics(writer, trainer, lr_scheduler, loss_dict,
+ grad_norm, config, step)
+
+ # Periodic checkpoint + visualization
+ if step > 0 and (step % config.training.save_interval == 0
+ or tracker.training_finished()):
+ # Sync all ranks before checkpoint so rank 1+ don't timeout
+ # waiting during rank 0's lengthy ODE visualization.
+ accelerator.wait_for_everyone()
+ if is_main:
+ _save_checkpoint_and_visualize(
+ trainer, accelerator, model, optimizer, lr_scheduler,
+ tracker, config, checkpoint_dir, debug_dir,
+ )
+ accelerator.wait_for_everyone()
+
+ # Sync all GPUs after the very first step
+ if tracker.current_step == 1:
+ accelerator.wait_for_everyone()
+
+ if tracker.training_finished():
+ break
+
+ if not tracker.training_finished():
+ tracker.next_epoch()
+
+ # ---- Cleanup ----
+ if is_main:
+ writer.close()
+ pbar.close()
+
+ accelerator.wait_for_everyone()
+ accelerator.end_training()
+ logger.info("Training completed.")
+
+
+# ===================================================================
+# Helper functions
+# ===================================================================
+
+def _set_sampler_epoch(dataloader, epoch: int):
+ """Call set_epoch on the underlying sampler if it supports it (for DDP).
+
+ After accelerator.prepare(), the chain is:
+ dataloader.batch_sampler โ†’ BatchSamplerShard
+ .batch_sampler โ†’ original BatchSampler
+ .sampler โ†’ MixtureSampler (or DistributedSampler)
+ We walk the chain until we find a sampler with set_epoch.
+ """
+ # Walk batch_sampler chain (Accelerate's BatchSamplerShard wraps the original)
+ bs = getattr(dataloader, 'batch_sampler', None)
+ while bs is not None:
+ sampler = getattr(bs, 'sampler', None)
+ if sampler is not None and hasattr(sampler, 'set_epoch'):
+ sampler.set_epoch(epoch)
+ return
+ # Accelerate's BatchSamplerShard stores the original as .batch_sampler
+ bs = getattr(bs, 'batch_sampler', None)
+
+ # Fallback: direct sampler attribute
+ sampler = getattr(dataloader, 'sampler', None)
+ if hasattr(sampler, 'set_epoch'):
+ sampler.set_epoch(epoch)
+
+
+def _log_metrics(writer, trainer, lr_scheduler, loss_dict, grad_norm,
+ config, step):
+ """Write training scalars to TensorBoard."""
+ for key, value in loss_dict.items():
+ writer.add_scalar(f"train/{key}", value, step)
+
+ if (trainer.use_ema and trainer.ema_model is not None
+ and trainer.ema_model.cur_decay_value is not None):
+ writer.add_scalar("train/ema_decay",
+ trainer.ema_model.cur_decay_value, step)
+
+ writer.add_scalar("train/learning_rate",
+ lr_scheduler.get_last_lr()[0], step)
+
+ if config.training.max_grad_norm is not None and grad_norm is not None:
+ writer.add_scalar("train/grad_norm", grad_norm, step)
+
+
+def _save_checkpoint_and_visualize(trainer, accelerator, model, optimizer,
+ lr_scheduler, tracker, config,
+ checkpoint_dir, debug_dir):
+ """Generate sample visualizations and persist a checkpoint to disk."""
+ trainer.visualize_samples(
+ save_dir=debug_dir,
+ prefix=f"step_{tracker.current_step}",
+ num_samples=config.sampling.num_samples,
+ cfg_scale=config.sampling.cfg_scale,
+ )
+ torch.cuda.empty_cache()
+
+ checkpoint_dict = {
+ "model_state_dict": accelerator.get_state_dict(model),
+ "optimizer_state_dict": optimizer.state_dict(),
+ "lr_scheduler_state_dict": lr_scheduler.state_dict(),
+ "step": tracker.current_step,
+ "epoch": tracker.current_epoch,
+ }
+ if trainer.use_ema and trainer.ema_model is not None:
+ checkpoint_dict["ema_state_dict"] = trainer.ema_model.state_dict()
+
+ checkpoint_path = os.path.join(
+ checkpoint_dir, f"checkpoint_step_{tracker.current_step}.pt"
+ )
+ accelerator.save(checkpoint_dict, checkpoint_path)
+ logger.info(f"Saved checkpoint to {checkpoint_path}")
+
+
+def _resume_from_checkpoint(
+ resume_path, accelerator, model, optimizer, lr_scheduler, trainer, tracker,
+):
+ """Restore all training state from a checkpoint file.
+
+ Loads model weights, optimizer, lr_scheduler, EMA, and fast-forwards the
+ tracker to the saved step/epoch so training continues seamlessly.
+ """
+ logger.info(f"Resuming from checkpoint: {resume_path}")
+ checkpoint = torch.load(resume_path, map_location="cpu")
+
+ # Model weights
+ unwrapped = accelerator.unwrap_model(model)
+ unwrapped.load_state_dict(checkpoint["model_state_dict"])
+
+ # Optimizer
+ if "optimizer_state_dict" in checkpoint:
+ optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
+
+ # LR scheduler
+ if "lr_scheduler_state_dict" in checkpoint:
+ lr_scheduler.load_state_dict(checkpoint["lr_scheduler_state_dict"])
+ else:
+ # Older checkpoint without scheduler state โ€” fast-forward manually
+ for _ in range(checkpoint.get("step", 0)):
+ lr_scheduler.step()
+
+ # EMA
+ if trainer.use_ema and trainer.ema_model is not None:
+ if "ema_state_dict" in checkpoint:
+ trainer.ema_model.load_state_dict(checkpoint["ema_state_dict"])
+ trainer.ema_model.to(accelerator.device)
+ logger.info("Restored EMA state from checkpoint.")
+ else:
+ # No EMA state in checkpoint โ€” rebuild EMA from the just-loaded
+ # model weights so it doesn't lag behind with the pre-resume random init.
+ trainer.initialize_ema(accelerator)
+ logger.warning("No EMA state in checkpoint โ€” EMA re-initialized from loaded model weights.")
+
+ # Tracker
+ resumed_step = checkpoint.get("step", 0)
+ resumed_epoch = checkpoint.get("epoch", 0)
+ tracker.current_step = resumed_step
+ tracker.current_epoch = resumed_epoch
+
+ logger.info(f"Resumed at step={resumed_step}, epoch={resumed_epoch}")
+
+
+# ===================================================================
+# Entry point
+# ===================================================================
+
+def main(args: TrainingArgs):
+ """Parse config and launch training."""
+ config = MainConfig.from_json(args.config)
+
+ accelerator = Accelerator(
+ dataloader_config=DataLoaderConfiguration(
+ use_seedable_sampler=False,
+ dispatch_batches=False,
+ ),
+ gradient_accumulation_steps=config.training.gradient_accumulation_steps,
+ )
+
+ if accelerator.is_main_process:
+ logger.info("Training Pipeline")
+ logger.info(f" Config: {args.config}")
+ logger.info(f" Mixed Precision: {accelerator.mixed_precision}")
+ logger.info(f" Gradient Accumulation Steps: {accelerator.gradient_accumulation_steps}")
+
+ train_diffusion(args, config, accelerator)
+
+
+if __name__ == "__main__":
+ args = tyro.cli(TrainingArgs)
+ main(args)
diff --git a/unimate/training/trainer.py b/unimate/training/trainer.py
new file mode 100644
index 0000000..e685e93
--- /dev/null
+++ b/unimate/training/trainer.py
@@ -0,0 +1,268 @@
+"""Diffusion / flow-matching trainer with EMA and visualization support.
+
+Handles two generation paradigms selected via ``training.diff_model``:
+ * ``"flow"`` โ€” flow matching (ODE-based sampling)
+ * ``"diffusion"`` โ€” Gaussian DDPM (iterative denoising)
+"""
+
+import os
+from typing import Dict, Optional, Tuple
+
+import torch
+import torch.nn as nn
+
+from unimate.configs.schema import MainConfig
+from unimate.dataset.conditioning import create_sample_condition
+from unimate.models.flow.transport import Sampler
+from unimate.models.factory import create_diffusion, create_transport
+from unimate.training.ema import EMAModel
+from unimate.training.base_trainer import BaseTrainer
+from unimate.utils.logger import get_logger
+from unimate.inference.generate import generate_samples
+from unimate.utils.visualization import visualize_and_save_motions
+
+logger = get_logger(file_name=__file__)
+
+
+class DiffusionTrainer(BaseTrainer):
+ """Trainer that pairs a denoising model with a diffusion/flow schedule.
+
+ Owns:
+ - ``model`` โ€” the trainable denoising network
+ - ``diffusion`` โ€” the noise schedule (Gaussian or flow transport)
+ - ``ema_model`` โ€” optional exponential moving average of model weights
+ - ``data`` โ€” reference to the dataloader (used for visualization)
+ """
+
+ def __init__(
+ self,
+ config: MainConfig,
+ model: nn.Module,
+ data: torch.utils.data.DataLoader,
+ checkpoint_dir: Optional[str] = None,
+ ):
+ super().__init__(checkpoint_dir)
+
+ self.config = config
+ self.model = model
+ self.data = data
+
+ self._setup_sdpa_backends()
+ self._setup_diffusion(config)
+ self._setup_ema_config(config)
+
+ logger.info(
+ f"DiffusionTrainer initialized"
+ f" | Parameters: {self.get_num_parameters() / 1e6:.2f}M"
+ f" | EMA: {self.use_ema} (decay={self.ema_decay})"
+ )
+
+ # ------------------------------------------------------------------
+ # Initialization helpers
+ # ------------------------------------------------------------------
+
+ def _setup_diffusion(self, config: MainConfig) -> None:
+ """Create the diffusion or flow-matching schedule."""
+ if config.training.diff_model == "flow":
+ self.diffusion = create_transport(training_config=config.training)
+ self.gen_diffusion = Sampler(self.diffusion)
+ elif config.training.diff_model == "diffusion":
+ self.diffusion = create_diffusion(
+ scheduler_config=config.scheduler,
+ training_config=config.training,
+ )
+ else:
+ raise ValueError(
+ f"Unknown diff_model: {config.training.diff_model!r}"
+ )
+
+ def _setup_ema_config(self, config: MainConfig) -> None:
+ """Store EMA configuration; actual EMA model is created later via
+ :meth:`initialize_ema` (after ``accelerator.prepare``)."""
+ self.use_ema = config.training.use_ema
+ self.ema_decay = config.training.ema_decay
+ self.ema_model: Optional[EMAModel] = None
+
+ @staticmethod
+ def _setup_sdpa_backends() -> None:
+ """Enable Flash Attention and memory-efficient SDPA backends."""
+ logger.info(
+ f"SDPA backends โ€” Flash: {torch.backends.cuda.flash_sdp_enabled()}"
+ f", MemEfficient: {torch.backends.cuda.mem_efficient_sdp_enabled()}"
+ f", Math: {torch.backends.cuda.math_sdp_enabled()}"
+ )
+ if torch.cuda.is_available():
+ try:
+ torch.backends.cuda.enable_flash_sdp(True)
+ torch.backends.cuda.enable_mem_efficient_sdp(True)
+ logger.info("Enabled Flash Attention and Memory Efficient backends")
+ except Exception as e:
+ logger.warning(f"Failed to enable SDPA backends: {e}")
+
+ def initialize_ema(self, accelerator) -> None:
+ """Create the EMA model. Call *after* ``accelerator.prepare``.
+
+ Uses the warmup schedule in :class:`EMAModel`: the every-100-steps
+ form ``decay = (1 + n) / (10 + n)`` spread over single steps by its
+ 100th root, so the decay starts near 0.98 (not 0.09 โ€” that figure
+ describes the un-rooted form) and creeps toward the ``ema_decay`` cap,
+ reaching 0.9999 at roughly 90k optimizer steps.
+ """
+ self.accelerator = accelerator
+ if not self.use_ema:
+ return
+ self.ema_model = EMAModel(
+ parameters=self._unwrapped_params(),
+ decay=self.ema_decay,
+ use_ema_warmup=True,
+ )
+ self.ema_model.to(accelerator.device, dtype=torch.float32)
+ logger.info(f"EMA initialized with decay={self.ema_decay}, warmup=True")
+
+ # ------------------------------------------------------------------
+ # Properties & mode switching
+ # ------------------------------------------------------------------
+
+ @property
+ def device(self) -> torch.device:
+ return next(self.model.parameters()).device
+
+ def train(self, mode: bool = True):
+ """Delegates to the wrapped ``model`` (the trainer itself has no
+ trainable parameters)."""
+ self.model.train(mode)
+ return self
+
+ def eval(self):
+ return self.train(False)
+
+ # ------------------------------------------------------------------
+ # Loss computation
+ # ------------------------------------------------------------------
+
+ def compute_loss(
+ self, batch
+ ) -> Tuple[torch.Tensor, Dict[str, float]]:
+ """Compute diffusion/flow training loss.
+
+ Returns:
+ (loss, loss_dict) โ€” scalar for backprop and per-component floats.
+ """
+ motion, cond = batch
+ cond = self._to_device(cond)
+ model_kwargs = dict(cond=cond)
+
+ if self.config.training.diff_model == "flow":
+ loss_dict = self.diffusion.training_losses(
+ self.model, motion, model_kwargs
+ )
+ else: # "diffusion"
+ t = torch.randint(
+ 0, self.diffusion.num_timesteps,
+ (motion.size(0),), device=motion.device,
+ )
+ loss_dict = self.diffusion.training_losses(
+ self.model, motion, t, model_kwargs
+ )
+
+ loss = loss_dict["loss"].mean()
+ loss_dict = {k: v.mean().item() for k, v in loss_dict.items()}
+ return loss, loss_dict
+
+ # ------------------------------------------------------------------
+ # Visualization
+ # ------------------------------------------------------------------
+
+ @torch.no_grad()
+ def visualize_samples(
+ self,
+ save_dir: str,
+ prefix: str,
+ num_samples: int = 3,
+ cfg_scale: float = 1.0,
+ ) -> None:
+ """Generate and save sample motions. Uses EMA weights when available.
+
+ Temporarily swaps in EMA parameters for generation, then restores
+ the original weights so training can continue unaffected.
+ """
+ use_ema = self.use_ema and self.ema_model is not None
+ # Use the unwrapped model for visualization to avoid DDP
+ # communication that would cause NCCL timeouts on other ranks.
+ # Bound before the try/EMA-swap so the finally block can always
+ # restore train mode regardless of where a later error fires.
+ unwrapped_model = self.accelerator.unwrap_model(self.model)
+
+ if use_ema:
+ logger.info("Using EMA model for sample visualization.")
+ self.ema_model.store(self._unwrapped_params())
+ self.ema_model.copy_to(self._unwrapped_params())
+
+ try:
+ unwrapped_model.eval()
+ os.makedirs(save_dir, exist_ok=True)
+
+ # Build conditioning from both train and eval pools so each viz
+ # batch shows in-distribution and held-out behaviour side-by-side.
+ # Routing per dataset (handled inside create_sample_condition):
+ # * 'object_type' (truebones, objaverse) โ†’ num_samples train
+ # types + num_samples eval types, one random clip each.
+ # * 'clip' (mixamo) โ†’ num_samples random train clips + same
+ # for eval, all from the single skeleton (caption varies).
+ motion_dataset = self.data.dataset.motion_dataset
+ n_eval_types = len(motion_dataset.eval_object_motions_map)
+ logger.info(
+ f"Visualizing {num_samples} train + {num_samples} eval samples "
+ f"per dataset ({n_eval_types} eval object types loaded)"
+ )
+ sample_motion, cond = create_sample_condition(
+ config=self.config, data=self.data,
+ num_samples=num_samples,
+ )
+
+ # -- Sample from the generative model --
+ logger.info("Generating samples for visualization...")
+ cond = self._to_device(cond)
+ motion_shape = (
+ sample_motion.size(0),
+ self.config.dataset.max_joints,
+ self.config.dataset.feature_len,
+ self.config.dataset.max_motion_length,
+ )
+
+ samples = generate_samples(
+ model=unwrapped_model,
+ cond=cond,
+ motion_shape=motion_shape,
+ diff_model=self.config.training.diff_model,
+ diffusion=self.diffusion,
+ gen_diffusion=getattr(self, 'gen_diffusion', None),
+ device=self.device,
+ cfg_scale=cfg_scale,
+ )
+
+ # -- Save visualizations --
+ visualize_and_save_motions(
+ config=self.config, cond=cond,
+ samples=samples, save_dir=save_dir, prefix=prefix,
+ )
+ finally:
+ unwrapped_model.train()
+ if use_ema:
+ self.ema_model.restore(self._unwrapped_params())
+ logger.info("Sample visualization completed.")
+
+ # ------------------------------------------------------------------
+ # Internal helpers
+ # ------------------------------------------------------------------
+
+ def _unwrapped_params(self):
+ """Return parameters from the unwrapped (non-DDP) model."""
+ return self.accelerator.unwrap_model(self.model).parameters()
+
+ def _to_device(self, cond: dict) -> dict:
+ """Move all tensor values in a condition dict to ``self.device``."""
+ return {
+ k: v.to(self.device) if torch.is_tensor(v) else v
+ for k, v in cond.items()
+ }
diff --git a/unimate/utils/__init__.py b/unimate/utils/__init__.py
new file mode 100644
index 0000000..899db65
--- /dev/null
+++ b/unimate/utils/__init__.py
@@ -0,0 +1 @@
+"""Motion representation, skeleton topology, rotation, logging, and visualization utilities."""
diff --git a/unimate/utils/geo_utils.py b/unimate/utils/geo_utils.py
new file mode 100644
index 0000000..f927172
--- /dev/null
+++ b/unimate/utils/geo_utils.py
@@ -0,0 +1,22 @@
+"""Geodesic distance between rotation matrices."""
+
+import torch as th
+
+
+def geodesic_distance(R_pred, R_gt):
+ """Compute geodesic distance (angle in radians) between rotation matrices.
+
+ Args:
+ R_pred: Predicted rotation matrices (..., 3, 3).
+ R_gt: Ground truth rotation matrices (..., 3, 3).
+
+ Returns:
+ Geodesic angle in radians (..., 1).
+ """
+ R_rel = th.matmul(R_pred.transpose(-1, -2), R_gt)
+ trace = th.diagonal(R_rel, dim1=-2, dim2=-1).sum(-1)
+
+ epsilon = 1e-6
+ theta = th.arccos(th.clamp((trace - 1) / 2, -1 + epsilon, 1 - epsilon))
+
+ return theta[..., None]
diff --git a/unimate/utils/logger.py b/unimate/utils/logger.py
new file mode 100644
index 0000000..8968b7a
--- /dev/null
+++ b/unimate/utils/logger.py
@@ -0,0 +1,158 @@
+"""Rank-aware logging with Rich console output and optional file logging.
+
+All log methods are decorated with ``@zero_rank`` so that only the main
+process (rank 0) emits messages in distributed training.
+
+Usage::
+
+ from unimate.utils.logger import get_logger
+ logger = get_logger(file_name=__file__)
+ logger.info("Training started")
+"""
+
+import inspect
+import logging
+import os
+from typing import Optional
+
+import torch.distributed as dist
+from rich.logging import RichHandler
+
+
+# -------------------------------------------------------------------
+# Distributed helper
+# -------------------------------------------------------------------
+
+def zero_rank(func):
+ """Decorator that silences the wrapped method on non-zero ranks."""
+ def wrapper(*args, **kwargs):
+ if not dist.is_initialized() or dist.get_rank() == 0:
+ return func(*args, **kwargs)
+ return wrapper
+
+
+# -------------------------------------------------------------------
+# Logger
+# -------------------------------------------------------------------
+
+class Logger:
+ """Thin wrapper around :mod:`logging` with Rich formatting and rank gating.
+
+ Args:
+ file_name: Name used for the underlying ``logging.Logger`` and the
+ log file (when *log_dir* is provided).
+ log_dir: If set, a ``FileHandler`` is added that writes to
+ ``<log_dir>/<file_name>.log``.
+ level: ``"info"`` or ``"debug"`` (case-insensitive).
+ """
+
+ def __init__(self, file_name: str = "log", log_dir: str = None,
+ level: str = "info"):
+ self.logger = logging.getLogger(file_name)
+ self.logger.propagate = False
+
+ level = self._resolve_level(level)
+ self.level = level
+ self.logger.setLevel(level)
+
+ # Clear stale handlers (e.g. after re-instantiation)
+ for handler in self.logger.handlers[:]:
+ self.logger.removeHandler(handler)
+
+ # Console handler (Rich)
+ console_handler = RichHandler(rich_tracebacks=True, show_path=False)
+ console_handler.setLevel(level)
+ console_handler.setFormatter(
+ self._CallerFileFormatter("%(message)s (%(filename)s)")
+ )
+ self.logger.addHandler(console_handler)
+
+ # File handler (optional)
+ if log_dir:
+ log_file = os.path.join(log_dir, f"{file_name}.log")
+ file_handler = logging.FileHandler(log_file)
+ file_handler.setLevel(level)
+ file_handler.setFormatter(
+ self._CallerFileFormatter(
+ "%(asctime)s - %(levelname)s - %(message)s (%(filename)s)"
+ )
+ )
+ self.logger.addHandler(file_handler)
+
+ # ---------------------------------------------------------------
+ # Log methods (only rank 0 in distributed training)
+ # ---------------------------------------------------------------
+
+ @zero_rank
+ def debug(self, message):
+ self.logger.debug(message)
+
+ @zero_rank
+ def info(self, message):
+ self.logger.info(message)
+
+ @zero_rank
+ def warning(self, message):
+ self.logger.warning(message)
+
+ @zero_rank
+ def error(self, message):
+ self.logger.error(message)
+
+ @zero_rank
+ def critical(self, message):
+ self.logger.critical(message)
+
+ # ---------------------------------------------------------------
+ # Internal helpers
+ # ---------------------------------------------------------------
+
+ @staticmethod
+ def _resolve_level(level: str) -> int:
+ """Convert a level string to a ``logging`` constant."""
+ level = level.upper()
+ if level == "INFO":
+ return logging.INFO
+ if level == "DEBUG":
+ return logging.DEBUG
+ raise ValueError(f"Invalid log level: {level}")
+
+ class _CallerFileFormatter(logging.Formatter):
+ """Formatter that resolves ``%(filename)s`` to the *actual* caller,
+ skipping internal logging / Rich frames."""
+
+ def format(self, record):
+ frame = inspect.currentframe()
+ while frame:
+ co = frame.f_code.co_filename
+ if (co != __file__
+ and "logging" not in co
+ and "rich" not in co):
+ record.filename = os.path.basename(co)
+ break
+ frame = frame.f_back
+ if frame is None:
+ record.filename = "unknown"
+ return super().format(record)
+
+
+# -------------------------------------------------------------------
+# Factory
+# -------------------------------------------------------------------
+
+def get_logger(file_name: Optional[str] = None,
+ debug: Optional[str] = "", **kwargs) -> Logger:
+ """Create a :class:`Logger` instance.
+
+ The log level is set to ``DEBUG`` when the ``DEBUG`` env var matches
+ any value in *debug*; otherwise defaults to ``INFO``.
+
+ Args:
+ file_name: Passed through to :class:`Logger`.
+ debug: A string (or list of strings) compared against ``$DEBUG``.
+ **kwargs: Forwarded to :class:`Logger` (e.g. ``log_dir``).
+ """
+ if isinstance(debug, str):
+ debug = [debug]
+ level = "DEBUG" if os.environ.get("DEBUG") in debug else "INFO"
+ return Logger(file_name=file_name, level=level, **kwargs)
diff --git a/unimate/utils/motion_utils.py b/unimate/utils/motion_utils.py
new file mode 100644
index 0000000..bd8d937
--- /dev/null
+++ b/unimate/utils/motion_utils.py
@@ -0,0 +1,389 @@
+"""Construction and recovery of the UniMate (12-dim) motion representation.
+
+Per joint: ``RIFKE_pos(3) | rotation_6d(6) | local_velocity(3)``. Rotations
+are T-pose-relative (see :func:`compute_rots_from_tpos`) and HML-reordered
+(see :func:`compute_cont6d_params`). The root slot uses a special encoding:
+position is ``[0, Y_height, 0]``, the 6D channels store the facing-direction
+quaternion, and velocity is ``[XZ_vel_x, Y_vel, XZ_vel_z]`` (the XZ
+trajectory is recovered via cumulative integration).
+"""
+
+import numpy as np
+
+from Quaternions import Quaternions
+
+from unimate.utils.rotation_conversions import rotation_6d_to_matrix_np
+
+
+# ===========================================================================
+# UniMate 12-dim
+# ===========================================================================
+#
+# Layout: ``[RIFKE_pos(3) | rot6d(6) | local_velocity(3)]`` per joint.
+# Root is special (see ``compute_cont6d_params`` / ``compute_rifke``):
+# pos = ``[0, Y_height, 0]``, rot6d = facing quat,
+# vel = ``[XZ_vel_x, Y_vel, XZ_vel_z]``.
+#
+# Sections below:
+# 1. Forward feature construction
+# 2. Clip alignment
+# 3. HML โ†” BVH and Animation FK helpers (shared by recovery / augmentation)
+# 4. Recovery from motion features
+# ---------------------------------------------------------------------------
+# 1. Forward feature construction
+# ---------------------------------------------------------------------------
+
+def compute_rots_from_tpos(
+ tpos_quats: Quaternions,
+ anim_quats: Quaternions,
+ parents: np.ndarray,
+) -> Quaternions:
+ """Re-express animation rotations relative to a canonical T-pose.
+
+ For every joint, the transformed rotation represents the delta from the
+ T-pose orientation, conjugated into the parent's cumulative T-pose frame.
+ This makes rotations skeleton-agnostic (invariant to rest-pose choice).
+
+ Exported clip NPZs store raw BVH local rotations (see
+ ``data_process/utils/motion_features.py::save_clip``); the dataset loader
+ applies this rebase before feature extraction so the model always sees
+ T-pose-relative rotations.
+
+ Args:
+ tpos_quats: T-pose rotations (F, J) as a Quaternions array.
+ anim_quats: Animation rotations (F, J) as a Quaternions array.
+ parents: Parent indices (J,).
+
+ Returns:
+ New (F, J) Quaternions expressed relative to *tpos_quats*.
+ """
+ new_rots = anim_quats.copy()
+ # Root: cancel the T-pose root orientation from the animation root.
+ new_rots[:, 0] = new_rots[:, 0] * -tpos_quats[:, 0]
+
+ # Non-root joints: propagate cumulative T-pose rotations down the chain
+ # and re-express each joint rotation in the parent's cumulative frame.
+ cum_rots = tpos_quats.copy()
+ for j, p in enumerate(parents[1:], start=1):
+ cum_rots[:, j] = cum_rots[:, p] * tpos_quats[:, j]
+ new_rots[:, j] = (
+ cum_rots[:, p] * anim_quats[:, j] * -tpos_quats[:, j] * -cum_rots[:, p]
+ )
+
+ return new_rots
+
+
+def compute_cont6d_params(global_positions, local_rotations, parents,
+ root_facing_quat):
+ """Extract continuous 6D rotation parameters with HML joint reordering.
+
+ BVH convention stores parent-to-child rotation at the parent joint.
+ HML reordering shifts each child's rotation to the child index, so
+ joint j stores the rotation that was at its parent. The root stores
+ the facing-direction quaternion in 6D form instead.
+
+ Also computes root linear velocity (in facing frame) and root angular
+ velocity as quaternion differences.
+
+ Args:
+ global_positions: Global joint positions (T, J, 3).
+ local_rotations: Parent-relative joint rotations (T, J) as Quaternions.
+ parents: Parent joint indices (J,).
+ root_facing_quat: Per-frame root facing quaternion (T,) as Quaternions.
+
+ Returns:
+ Tuple of (cont_6d_reordered (T, J, 6), r_velocity (T-1, 4),
+ velocity (T-1, 3)).
+ """
+ cont_6d_params = local_rotations.copy().rotation_matrix(cont6d=True) # (T, J, 6)
+
+ # Reorder: each joint stores its own rotation (parent -> self)
+ cont_6d_params_reordered = np.zeros_like(cont_6d_params)
+ for j, p in enumerate(parents[1:], 1):
+ cont_6d_params_reordered[:, j] = cont_6d_params[:, p]
+ cont_6d_params_reordered[:, 0] = root_facing_quat.copy().rotation_matrix(cont6d=True)
+
+ # Root linear velocity (T-1, 3)
+ velocity = (global_positions[1:, 0] - global_positions[:-1, 0]).copy()
+ velocity = root_facing_quat[1:] * velocity # rotate into root-facing frame
+
+ # Root angular velocity (T-1, 4)
+ r_velocity = root_facing_quat[1:] * -root_facing_quat[:-1]
+
+ return cont_6d_params_reordered, r_velocity, velocity
+
+
+def compute_rifke(global_positions, root_facing_quat):
+ """Compute Root-Invariant Forward Kinematics (RIFKE) positions.
+
+ Subtracts root XZ from all joints (making root XZ always zero), then
+ rotates into the root-facing frame. Y (height) is kept as absolute value.
+
+ Args:
+ global_positions: Global joint positions (T, J, 3).
+ root_facing_quat: Per-frame root facing quaternion (T,) as Quaternions.
+
+ Returns:
+ RIFKE positions (T, J, 3).
+ """
+ positions = global_positions.copy()
+ positions[..., 0] -= positions[:, 0:1, 0]
+ positions[..., 2] -= positions[:, 0:1, 2]
+ positions = np.repeat(root_facing_quat[:, None], positions.shape[1], axis=1) * positions
+ return positions
+
+
+def compute_local_velocity(global_positions, root_facing_quat):
+ """Compute per-joint local velocity in the root-facing frame.
+
+ For each frame, the global position difference is rotated into the
+ root coordinate system of the *destination* frame.
+
+ Args:
+ global_positions: Global joint positions (T, J, 3).
+ root_facing_quat: Per-frame root facing quaternion (T,) as Quaternions.
+
+ Returns:
+ Local velocity (T-1, J, 3).
+ """
+ velocity = global_positions[1:] - global_positions[:-1]
+ velocity = np.repeat(root_facing_quat[1:, None], velocity.shape[1], axis=1) * velocity
+ return velocity
+
+
+def compute_unimate_motion_feats(
+ global_positions: np.ndarray,
+ local_rotations: Quaternions,
+ parents: np.ndarray,
+ root_facing_quat: Quaternions,
+):
+ """Extract 12-dim UniMate motion features.
+
+ Per joint: RIFKE_pos(3) | rotation_6d(6) | local_velocity(3).
+
+ Args:
+ global_positions: Global joint positions (T, J, 3).
+ local_rotations: Parent-relative joint rotations (T, J) as Quaternions.
+ parents: Parent joint indices (J,).
+ root_facing_quat: Per-frame root facing quaternion (T,) as Quaternions.
+
+ Returns:
+ Motion features (F-1, J, 12).
+ """
+ cont_6d_params, _, _ = compute_cont6d_params(
+ global_positions, local_rotations, parents, root_facing_quat)
+
+ positions = compute_rifke(global_positions, root_facing_quat) # (T, J, 3)
+ local_vel = compute_local_velocity(global_positions, root_facing_quat) # (T-1, J, 3)
+
+ return np.concatenate([positions[:-1], cont_6d_params[:-1], local_vel], axis=-1) # (T-1, J, 12)
+
+
+# ---------------------------------------------------------------------------
+# 2. Clip alignment
+# ---------------------------------------------------------------------------
+
+def realign_unimate_clip(clip_feats, parents):
+ """Re-align a clip so the root facing at frame 0 is identity (faces Z+).
+
+ The root facing quaternion (joint 0, channels 3:9) is the rotation that
+ maps the current facing direction to Z+, not the facing direction itself.
+ To make frame 0 identity, we right-multiply by the inverse of the
+ first-frame facing quat: ``q_t * q_0^{-1}``.
+
+ Direct children of the root store the root's local rotation (HML
+ reordering). These need the facing rotation applied: ``q_0 * q_child``.
+
+ RIFKE positions and velocities are per-frame root-relative and invariant
+ to global Y rotation, so only the 6D rotation channels need adjustment.
+
+ Args:
+ clip_feats: Clip motion features (T, J, 12).
+ parents: Parent index list (J,).
+
+ Returns:
+ Re-aligned clip features (T, J, 12).
+ """
+ clip = clip_feats.copy()
+
+ # Decode first-frame root facing quaternion
+ q0 = Quaternions.from_transforms(
+ rotation_6d_to_matrix_np(clip[0, 0, 3:9][None]))[0]
+
+ # Root facing (joint 0): make relative to first frame
+ root_6d = clip[:, 0, 3:9]
+ q_root = Quaternions.from_transforms(rotation_6d_to_matrix_np(root_6d))
+ clip[:, 0, 3:9] = (q_root * -q0).rotation_matrix(cont6d=True)
+
+ # Direct children of root: apply facing rotation to root's local rotation
+ for j, p in enumerate(parents):
+ if p == 0:
+ child_6d = clip[:, j, 3:9]
+ q_child = Quaternions.from_transforms(rotation_6d_to_matrix_np(child_6d))
+ clip[:, j, 3:9] = (q0 * q_child).rotation_matrix(cont6d=True)
+
+ return clip
+
+
+# ---------------------------------------------------------------------------
+# 3. HML โ†” BVH and Animation FK helpers
+# ---------------------------------------------------------------------------
+
+def hml_rotations_to_bvh_quaternions(motion_rot6d_hml, parents):
+ """Invert the HML joint re-ordering back to BVH-ordered rotations.
+
+ HML convention (see :func:`compute_cont6d_params`):
+ ``hml[j] = bvh[parents[j]]`` for ``j >= 1``. Slot 0 holds the root
+ facing quaternion โ€” it's ignored here, since the root's global rotation
+ is recovered from any child-of-root slot (which stores ``bvh[0]``).
+
+ Args:
+ motion_rot6d_hml: 6D rotations in HML order (T, J, 6).
+ parents: Parent indices (J,).
+
+ Returns:
+ BVH-ordered rotations as ``Quaternions`` (T, J).
+ """
+ T, J, _ = motion_rot6d_hml.shape
+ bvh_rot_mat = np.tile(np.eye(3), (T, J, 1, 1)) # identity defaults
+ hml_mat = rotation_6d_to_matrix_np(motion_rot6d_hml)
+ for j, p in enumerate(parents[1:], 1):
+ bvh_rot_mat[:, p] = hml_mat[:, j]
+ return Quaternions.from_transforms(bvh_rot_mat)
+
+
+def fk_global_positions(rotations_bvh, parents, offsets, root_positions):
+ """Run FK via the Animation library with BVH-ordered rotations.
+
+ Mirrors the FK call used during feature extraction (``positions_global``
+ in ``data_process/utils/motion_features.py``), so positions produced here
+ match the training data exactly.
+
+ Args:
+ rotations_bvh: Quaternions (T, J) in BVH order.
+ parents: (J,) parent indices.
+ offsets: (J, 3) rest-pose bone offsets.
+ root_positions: (T, 3) per-frame root world positions. Pass zeros to
+ obtain positions with the root pinned at the origin.
+
+ Returns:
+ Global joint positions (T, J, 3).
+ """
+ from Animation import Animation, positions_global
+ T = rotations_bvh.shape[0]
+ anim_positions = offsets[None].repeat(T, axis=0) # (T, J, 3)
+ anim_positions[:, 0] = root_positions
+ anim = Animation(
+ rotations=rotations_bvh,
+ positions=anim_positions,
+ offsets=offsets,
+ parents=parents,
+ orients=Quaternions.id(0),
+ )
+ return positions_global(anim)
+
+
+# ---------------------------------------------------------------------------
+# 4. Recovery from motion features
+# ---------------------------------------------------------------------------
+
+def recover_unimate_root_quat_and_pos(data):
+ """Recover root quaternion and global root position from 12-dim root features.
+
+ Root rotation is decoded from the 6D channels [3:9].
+ XZ trajectory is recovered by cumulatively integrating velocity channels
+ [9] and [11] (rotated back to world frame). Y is read directly from
+ the absolute height channel [1].
+
+ Args:
+ data: Root joint features, shape (..., T, 12).
+
+ Returns:
+ (r_rot_quat (..., T), r_pos (..., T, 3)).
+ """
+ r_rot_quat = Quaternions.from_transforms(rotation_6d_to_matrix_np(data[:, 3:9]))
+
+ r_pos = np.zeros(data.shape[:-1] + (3,)) # (T, 3)
+ r_pos[..., 1:, [0, 2]] = data[..., :-1, [9, 11]] # XZ velocity
+ r_pos = -r_rot_quat * r_pos # Rotate back to world frame
+ r_pos = np.cumsum(r_pos, axis=-2)
+ r_pos[..., 1] = data[..., 1]
+
+ return r_rot_quat, r_pos
+
+
+def recover_unimate_joint_pos_from_ric(data):
+ """Recover global joint positions from 12-dim features using RIFKE positions.
+
+ Inverts compute_rifke: un-rotates joint positions from the facing frame back to
+ world frame, then adds back the root XZ trajectory.
+
+ Args:
+ data: 12-dim features, shape (..., J, 12).
+
+ Returns:
+ Global positions, shape (..., J, 3).
+ """
+ r_rot_quat, r_pos = recover_unimate_root_quat_and_pos(data[..., 0, :])
+
+ positions = data[..., 1:, :3]
+ positions = np.repeat(-r_rot_quat[..., None, :], positions.shape[-2], axis=-2) * positions
+
+ positions[..., 0] += r_pos[..., 0:1]
+ positions[..., 2] += r_pos[..., 2:3]
+
+ positions = np.concatenate([r_pos[..., np.newaxis, :], positions], axis=-2)
+ return positions
+
+
+def recover_unimate_joint_pos_from_rot(data, parents, offsets):
+ """Recover global positions via FK from 12-dim rotation channels.
+
+ Reverses HML joint reordering, integrates the root trajectory from the
+ velocity channels, and runs FK via the Animation library.
+
+ Args:
+ data: 12-dim features (T, J, 12).
+ parents: Parent indices (J,).
+ offsets: Rest-pose bone offsets (J, 3).
+
+ Returns:
+ Global joint positions (T, J, 3).
+ """
+ _, r_pos = recover_unimate_root_quat_and_pos(data[:, 0])
+ bvh_rots = hml_rotations_to_bvh_quaternions(data[:, :, 3:9], parents)
+ return fk_global_positions(bvh_rots, parents, offsets, r_pos)
+
+
+def recover_unimate_anim_from_rot(data, parents, offsets):
+ """Recover an Animation object from 12-dim rotation channels.
+
+ Similar to ``recover_unimate_joint_pos_from_rot`` but returns the decoded
+ ``Animation`` (BVH-ordered local rotations, integrated root trajectory,
+ facing quaternions as orients) instead of running FK to positions โ€” used
+ to re-apply generated motion to rigged characters.
+
+ Args:
+ data: 12-dim features (T, J, 12).
+ parents: Parent indices (J,).
+ offsets: Rest-pose bone offsets (J, 3).
+
+ Returns:
+ The recovered ``Animation`` object.
+ """
+ nframes, njoints = data.shape[:2]
+ r_rot_quat, r_pos = recover_unimate_root_quat_and_pos(data[:, 0])
+ bvh_rots = hml_rotations_to_bvh_quaternions(data[:, :, 3:9], parents)
+
+ anim_positions = offsets[None].repeat(nframes, axis=0) # (T, J, 3)
+ anim_positions[:, 0] = r_pos
+
+ from Animation import Animation
+ anim = Animation(
+ rotations=bvh_rots,
+ positions=anim_positions,
+ offsets=offsets,
+ parents=parents,
+ orients=r_rot_quat,
+ )
+ return anim
diff --git a/unimate/utils/rotation_conversions.py b/unimate/utils/rotation_conversions.py
new file mode 100644
index 0000000..5eeff7f
--- /dev/null
+++ b/unimate/utils/rotation_conversions.py
@@ -0,0 +1,53 @@
+"""6D rotation representation โ†’ rotation matrix conversions.
+
+The 6D representation is from Zhou et al., "On the Continuity of Rotation
+Representations in Neural Networks", CVPR 2019
+(http://arxiv.org/abs/1812.07035): the first two rows of the rotation matrix,
+orthonormalized via Gram-Schmidt on decode.
+
+Convention: rotation matrices act on column vectors via post-multiplication,
+i.e. ``transformed_point = R @ point``.
+"""
+
+import numpy as np
+import torch
+
+
+def rotation_6d_to_matrix_safe(cont6d: torch.Tensor) -> torch.Tensor:
+ """Convert 6D rotation to matrix with NaN protection and epsilon offset.
+
+ Args:
+ cont6d: 6D rotation representation (*, 6).
+
+ Returns:
+ Rotation matrices (*, 3, 3).
+ """
+ assert cont6d.shape[-1] == 6, "The last dimension must be 6"
+ epsilon = 1e-8
+ cont6d = torch.nan_to_num(cont6d) + epsilon
+ x_raw = cont6d[..., 0:3]
+ y_raw = cont6d[..., 3:6]
+ x = x_raw / torch.linalg.norm(x_raw, dim=-1, keepdims=True)
+ z = torch.cross(x, y_raw, dim=-1)
+ z = z / torch.linalg.norm(z, dim=-1, keepdims=True)
+ y = torch.cross(z, x, dim=-1)
+ return torch.cat([x[..., None], y[..., None], z[..., None]], dim=-1)
+
+
+def rotation_6d_to_matrix_np(cont6d: np.ndarray) -> np.ndarray:
+ """Convert 6D rotation to matrix (numpy version).
+
+ Args:
+ cont6d: 6D rotation representation (*, 6).
+
+ Returns:
+ Rotation matrices (*, 3, 3).
+ """
+ assert cont6d.shape[-1] == 6, "The last dimension must be 6"
+ x_raw = cont6d[..., 0:3]
+ y_raw = cont6d[..., 3:6]
+ x = x_raw / np.linalg.norm(x_raw, axis=-1, keepdims=True)
+ z = np.cross(x, y_raw, axis=-1)
+ z = z / np.linalg.norm(z, axis=-1, keepdims=True)
+ y = np.cross(z, x, axis=-1)
+ return np.concatenate([x[..., None], y[..., None], z[..., None]], axis=-1)
diff --git a/unimate/utils/text_emb_cache.py b/unimate/utils/text_emb_cache.py
new file mode 100644
index 0000000..be348f9
--- /dev/null
+++ b/unimate/utils/text_emb_cache.py
@@ -0,0 +1,290 @@
+"""On-disk cache of text-encoder features.
+
+The dataset pre-encodes every unique caption and joint name at construction
+time, which means loading a text encoder onto the GPU and running it on every
+run โ€” seconds of startup and several GB of VRAM for a model that is thrown away
+immediately afterwards. Caching those features next to the features removes
+both: with a complete cache the encoder is never instantiated at all.
+
+**Per-token, not pooled.** Each text is stored as its ``(T_i, D)`` sequence of
+non-padding token features, because ``text_cond='cross_attn'`` needs the
+sequence โ€” a pooled vector would leave its cross-attention attending a single
+token, i.e. a more expensive adaLN. The pooled vector ``adaLN`` wants is the
+mean over those same rows, so it is derived on load rather than stored: one
+source of truth, and it cannot drift from the tokens.
+
+A caption key carries an embedding and a mask: ``emb`` is padded to the file's
+longest sequence and ``mask`` marks its real tokens. ``load_cache`` returns
+each key trimmed by its own mask, so the padding lives in the file (where zlib
+compresses it away โ€” a padded file is ~1% larger on disk) and never in RAM,
+which is where it would actually cost: truebones captions are 42% full, so a
+resident padded array would be 107 MB against 45 MB, and objaverse's 1.2 GB
+against 431 MB.
+
+Two files per feature directory, flat beside ``captions.json`` โ€” captions and
+joint names are separate sources with very different shapes (a caption is ~13
+tokens, a joint name ~2), and only one of them changes when captions are
+re-annotated::
+
+ dataset/features/<ds>/caption_emb_cache.npz one entry per CLIP KEY, i.e.
+ the keys of captions.json
+ keys : (N,) unicode the clip key to look up by
+ emb : (N, T_max, D) f32 per-token features, right-padded
+ mask : (N, T_max) bool True on this key's real tokens
+
+ dataset/features/<ds>/joint_emb_cache.npz one entry per UNIQUE joint name
+ keys : (N,) unicode the joint name
+ emb : (N, D) f32 the pooled vector, no mask
+
+ both:
+ meta : () object {'encoder_type', 'encoder_version',
+ 'emb_dim', 'format', 'pooled'}
+
+Joint names are stored pooled because that is all the model ever sees of them:
+``joint_names_emb`` is one vector per joint. Captions keep their sequence
+because ``text_cond='cross_attn'`` attends it; the pooled vector ``adaLN`` uses
+is the mean over those rows, derived by the data loader.
+
+The encoder is no longer part of the filename, so ``meta`` is the only thing
+standing between a t5 cache and a clip run: ``load_cache`` refuses a file whose
+recorded encoder is not the one being asked for, alongside the format-version
+and dimension checks.
+
+Written by ``unimate/tools/precompute_text_emb.py``; read by the mixture
+dataset. A missing or partial cache is never fatal โ€” the dataset encodes
+whatever the cache does not cover.
+"""
+
+import os
+from os.path import join as pjoin
+from typing import Dict, List, Optional
+
+import numpy as np
+
+from unimate.utils.logger import get_logger
+
+logger = get_logger(file_name=__file__)
+
+# Bumped when the on-disk layout changes. v1 stored one pooled vector per text,
+# v2 a ragged token sequence, v3 an (emb, mask) pair per key, v4 pools the
+# joint names. An older file is ignored rather than misread.
+CACHE_FORMAT = 4
+
+
+# The two text sources: the file each is cached in, and whether it is stored
+# pooled (one vector) or as a token sequence with a mask.
+KINDS = {'caption': ('caption_emb_cache.npz', False), # captions.json
+ 'joint': ('joint_emb_cache.npz', True)} # cond.npy joint names
+
+
+def cache_path(root_dir: str, kind: str) -> str:
+ """Path of one feature directory's cache for *kind* ('text' | 'joint').
+
+ Flat, beside ``captions.json`` and ``cond.npy`` โ€” the files it is derived
+ from โ€” rather than in a subdirectory of its own.
+ """
+ if kind not in KINDS:
+ raise ValueError(f'unknown cache kind {kind!r}; expected {sorted(KINDS)}')
+ return pjoin(root_dir, KINDS[kind][0])
+
+
+def sequences_from_hidden(hidden, attention_mask) -> List[np.ndarray]:
+ """Split an encoder's ``(B, T, D)`` output into per-text ``(T_i, D)`` rows.
+
+ Padding is dropped by the mask. An all-masked row โ€” which is how
+ ``T5Conditioner.tokenize`` marks an empty string โ€” yields a single ZERO
+ row, so its pooled vector is the zero vector the ``pool=True`` encoder
+ returns for empty text. Keeping the first real token instead would hand
+ back the ``</s>`` state and quietly change what "unconditional" means.
+ """
+ hidden = np.asarray(hidden, dtype=np.float32)
+ lengths = np.asarray(attention_mask).sum(axis=-1).astype(int)
+ out = []
+ for i, n in enumerate(lengths):
+ out.append(hidden[i, :n] if n > 0
+ else np.zeros((1, hidden.shape[-1]), dtype=np.float32))
+ return out
+
+
+def pooled_from_hidden(hidden, attention_mask) -> np.ndarray:
+ """The ``pool=True`` vector of an encoder's ``(B, T, D)`` output.
+
+ This is byte-for-byte ``T5Conditioner.forward``'s pooling arithmetic โ€”
+ the masked sum over all T positions divided by the token count โ€” run on
+ the same device and dtype as the hidden states. Re-deriving it later from
+ the trimmed rows (a plain mean over T_i) is mathematically the same but
+ sums in a different order, so it lands a few ulps away; adaLN reads this
+ stored vector instead, and gets exactly what the pooled encoder returned.
+ """
+ mask = attention_mask.to(hidden.dtype)
+ token_count = mask.sum(dim=-1, keepdim=True).clamp(min=1) # (B, 1)
+ pooled = (hidden * mask.unsqueeze(-1)).sum(dim=-2) / token_count
+ return pooled.detach().cpu().numpy().astype(np.float32)
+
+
+def pool(tokens: np.ndarray) -> np.ndarray:
+ """Pooled ``(D,)`` vector of a ``(T, D)`` token sequence.
+
+ Mathematically the encoder's ``pool=True`` output โ€” padding is already
+ excluded from the stored rows โ€” but summed in a different order, so it can
+ differ in the last bits. Only for sequences whose stored pooled vector is
+ unavailable; prefer :func:`pooled_from_hidden` at write time.
+ """
+ if tokens.ndim != 2 or tokens.shape[0] == 0:
+ raise ValueError(f'expected a non-empty (T, D) sequence, got {tokens.shape}')
+ return tokens.mean(axis=0)
+
+
+def save_cache(path: str, tokens_by_key: Dict[str, np.ndarray], kind: str,
+ encoder_type: str, encoder_version: Optional[str],
+ pooled_by_key: Optional[Dict[str, np.ndarray]] = None) -> int:
+ """Write ``{key: (T_i, D) tokens}`` to *path*. Returns the entry count.
+
+ A pooled *kind* ('joint') stores one vector per key as ``(N, D)`` and no
+ mask, since that is all the model ever reads. A sequence kind ('caption')
+ right-pads to the longest sequence, pairs it with a mask, and also stores
+ the pooled vector so the adaLN path reads the encoder's own number rather
+ than re-deriving it.
+
+ ``pooled_by_key`` should come from :func:`pooled_from_hidden`; without it
+ the pooled vectors fall back to :func:`pool` over the sequences.
+ """
+ if not tokens_by_key:
+ raise ValueError('refusing to write an empty text-embedding cache')
+ if kind not in KINDS:
+ raise ValueError(f'unknown cache kind {kind!r}; expected {sorted(KINDS)}')
+ pooled = KINDS[kind][1]
+
+ keys = sorted(tokens_by_key)
+ seqs = [np.asarray(tokens_by_key[k], dtype=np.float32) for k in keys]
+ dims = {x.shape[1] for x in seqs}
+ if len(dims) != 1:
+ raise ValueError(f'inconsistent embedding dims in the cache: {sorted(dims)}')
+ dim = dims.pop()
+
+ def _pooled(k, x):
+ if pooled_by_key is not None and k in pooled_by_key:
+ return np.asarray(pooled_by_key[k], dtype=np.float32)
+ return pool(x)
+
+ arrays = {'keys': np.asarray(keys, dtype=object)}
+ if pooled:
+ arrays['emb'] = np.stack([_pooled(k, x)
+ for k, x in zip(keys, seqs)]) # (N, D)
+ else:
+ t_max = max(len(x) for x in seqs)
+ emb = np.zeros((len(keys), t_max, dim), dtype=np.float32)
+ mask = np.zeros((len(keys), t_max), dtype=bool)
+ for i, x in enumerate(seqs):
+ emb[i, :len(x)] = x
+ mask[i, :len(x)] = True
+ arrays['emb'] = emb
+ arrays['mask'] = mask
+ arrays['pooled'] = np.stack([_pooled(k, x)
+ for k, x in zip(keys, seqs)]) # (N, D)
+
+ arrays['meta'] = np.asarray({'encoder_type': encoder_type,
+ 'encoder_version': encoder_version,
+ 'emb_dim': int(dim),
+ 'format': CACHE_FORMAT,
+ 'pooled': pooled}, dtype=object)
+
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ # Write-then-rename: an interrupted run must not leave a truncated cache
+ # that later loads as a silently incomplete one. A file object keeps
+ # np.savez from appending '.npz' to the temp name, which would leave the
+ # rename pointing at a file that never existed.
+ tmp = path + '.tmp'
+ with open(tmp, 'wb') as f:
+ np.savez_compressed(f, **arrays)
+ os.replace(tmp, path)
+ return len(keys)
+
+
+def load_cache(root_dir: str, kind: str, encoder_type: str,
+ encoder_version: Optional[str],
+ expected_dim: Optional[int] = None) -> Dict[str, np.ndarray]:
+ """Load one feature directory's *kind* cache.
+
+ ``{key: (D,)}`` for a pooled kind ('joint'); for a sequence kind
+ ('caption') ``{key: ((T_i, D) tokens, (D,) pooled)}`` โ€” the tokens trimmed
+ by their mask, the pooled vector as the encoder produced it.
+
+ ``{}`` when absent or unusable. Never raises on a bad file: a corrupt,
+ outdated, wrong-encoder or dimension-mismatched cache is logged and
+ ignored, so the caller falls back to encoding.
+ """
+ path = cache_path(root_dir, kind)
+ if not os.path.isfile(path):
+ return {}
+ try:
+ data = np.load(path, allow_pickle=True)
+ meta = data['meta'].item() if 'meta' in data else {}
+ if meta.get('format') != CACHE_FORMAT:
+ logger.warning(
+ f'Ignoring text-embedding cache {path}: format '
+ f'{meta.get("format")}, this build reads {CACHE_FORMAT} โ€” '
+ f'regenerate it with unimate/tools/precompute_text_emb.py')
+ return {}
+ got = (meta.get('encoder_type'), meta.get('encoder_version'))
+ if got != (encoder_type, encoder_version):
+ logger.warning(
+ f'Ignoring text-embedding cache {path}: built with '
+ f'{got[0]}/{got[1]}, this run uses {encoder_type}/'
+ f'{encoder_version} โ€” regenerate it with '
+ f'unimate/tools/precompute_text_emb.py')
+ return {}
+ if bool(meta.get('pooled')) != KINDS[kind][1]:
+ logger.warning(f'Ignoring text-embedding cache {path}: pooled='
+ f'{meta.get("pooled")} but {kind!r} expects '
+ f'pooled={KINDS[kind][1]}')
+ return {}
+ keys = [str(k) for k in data['keys']]
+ emb = np.asarray(data['emb'], dtype=np.float32)
+ mask = None if KINDS[kind][1] else np.asarray(data['mask'], dtype=bool)
+ stored_pooled = (np.asarray(data['pooled'], dtype=np.float32)
+ if 'pooled' in data.files else None)
+ except Exception as e: # noqa: BLE001 โ€” a bad cache is a cache miss
+ logger.warning(f'Ignoring unreadable text-embedding cache {path}: {e}')
+ return {}
+
+ if len(keys) != len(emb) or (mask is not None and emb.shape[:2] != mask.shape):
+ logger.warning(f'Ignoring text-embedding cache {path}: {len(keys)} keys '
+ f'against emb {emb.shape}')
+ return {}
+ if expected_dim is not None and emb.shape[-1] != expected_dim:
+ logger.warning(
+ f'Ignoring text-embedding cache {path}: {emb.shape[-1]}-d '
+ f'features but the model expects {expected_dim}-d โ€” '
+ f'regenerate it with unimate/tools/precompute_text_emb.py')
+ return {}
+ if mask is None:
+ logger.info(f'Loaded {len(keys)} pooled text embeddings from {path}')
+ return {k: emb[i] for i, k in enumerate(keys)}
+ if stored_pooled is None or len(stored_pooled) != len(keys):
+ logger.warning(f'Ignoring text-embedding cache {path}: no stored pooled '
+ f'vectors โ€” regenerate it with '
+ f'unimate/tools/precompute_text_emb.py')
+ return {}
+ # Boolean indexing copies, so the padded (N, T_max, D) block is released
+ # once these per-key sequences are built โ€” the padding stays on disk.
+ logger.info(f'Loaded {len(keys)} cached text sequences '
+ f'({int(mask.sum())} tokens) from {path}')
+ return {k: (emb[i][mask[i]], stored_pooled[i]) for i, k in enumerate(keys)}
+
+
+def load_caches(root_dirs: List[str], kind: str, encoder_type: str,
+ encoder_version: Optional[str],
+ expected_dim: Optional[int] = None) -> Dict[str, np.ndarray]:
+ """Merge the *kind* caches of several feature directories.
+
+ Joint names are shared vocabulary and encode identically everywhere;
+ clip keys are unique per dataset. Either way an overlapping entry is
+ interchangeable and the last one simply wins.
+ """
+ merged: Dict[str, np.ndarray] = {}
+ for root in root_dirs:
+ if root:
+ merged.update(load_cache(root, kind, encoder_type, encoder_version,
+ expected_dim))
+ return merged
diff --git a/unimate/utils/topology_utils.py b/unimate/utils/topology_utils.py
new file mode 100644
index 0000000..d74801e
--- /dev/null
+++ b/unimate/utils/topology_utils.py
@@ -0,0 +1,321 @@
+"""Skeleton topology utilities.
+
+All public functions accept a parent index array (J,) as list or numpy array
+where ``parents[j]`` is the parent of joint *j* (root has parent -1 or itself).
+
+Sections:
+ 1. Internal helpers
+ 2. Graph representations โ€” edge index, joint depths
+ 3. Graph positional encodings โ€” Laplacian eigenvectors
+ 4. Pairwise relations โ€” edge types, topology distances
+"""
+
+from collections import deque
+
+import numpy as np
+import torch
+from torch_geometric.utils import get_laplacian, to_scipy_sparse_matrix
+
+
+# ---------------------------------------------------------------------------
+# 1. Internal helpers
+# ---------------------------------------------------------------------------
+
+def _parse_parents(parents):
+ """Normalize *parents* to a 1-D int64 numpy array."""
+ return np.asarray(parents, dtype=np.int64).ravel()
+
+
+def _children_map(parents):
+ """Build a list-of-lists mapping each joint to its children.
+
+ Args:
+ parents: List of parent indices (J,).
+
+ Returns:
+ List of lists, where ``children[j]`` contains the children of joint *j*.
+ """
+ n = len(parents)
+ children = [[] for _ in range(n)]
+ for c, p in enumerate(parents):
+ if p is None or p == -1:
+ continue
+ if not (0 <= p < n):
+ raise ValueError(f"Invalid parent index parents[{c}]={p}")
+ children[p].append(c)
+ return children
+
+
+def _adjacency_list(parents):
+ """Build an undirected adjacency list from *parents*.
+
+ Args:
+ parents: List of parent indices (J,).
+
+ Returns:
+ List of lists, where ``adj[j]`` contains the neighbors of joint *j*.
+ """
+ n = len(parents)
+ adj = [[] for _ in range(n)]
+ for c, p in enumerate(parents):
+ if p is None or p == -1:
+ continue
+ adj[c].append(p)
+ adj[p].append(c)
+ return adj
+
+
+
+# ---------------------------------------------------------------------------
+# 2. Graph representations
+# ---------------------------------------------------------------------------
+
+def compute_edge_indexs(parents):
+ """Build a PyG-style edge index array from a skeleton parent array.
+
+ Undirected: includes both parent->child and child->parent edges.
+ Self-loops are excluded.
+
+ Args:
+ parents: Parent indices (J,).
+
+ Returns:
+ ``np.ndarray`` of shape ``[2, 2*(J-1)]`` with dtype int64.
+ """
+ parents = _parse_parents(parents)
+ children = np.arange(len(parents))
+ valid = (children != parents) & (parents >= 0)
+ p = parents[valid]
+ c = children[valid]
+ return np.stack([np.concatenate([p, c]), np.concatenate([c, p])], axis=0)
+
+
+def compute_joint_depths(parents):
+ """Compute the depth of each joint in the kinematic tree.
+
+ Handles arbitrary joint ordering (parent index may be > child index)
+ by iterating until all depths are resolved.
+
+ Args:
+ parents: Parent indices (J,).
+
+ Returns:
+ ``np.ndarray`` of shape ``(J,)`` with dtype int64 (root=0).
+ """
+ parents = list(parents)
+ n = len(parents)
+ depths = np.full(n, -1, dtype=np.int64)
+
+ for j in range(n):
+ if parents[j] == -1 or parents[j] == j:
+ depths[j] = 0
+
+ changed = True
+ while changed:
+ changed = False
+ for j in range(n):
+ if depths[j] >= 0:
+ continue
+ p = parents[j]
+ if 0 <= p < n and depths[p] >= 0:
+ depths[j] = depths[p] + 1
+ changed = True
+
+ return depths
+
+
+# ---------------------------------------------------------------------------
+# 3. Graph positional encodings
+# ---------------------------------------------------------------------------
+
+def _build_laplacian(parents, norm='none'):
+ """Build the graph Laplacian via ``torch_geometric.utils.get_laplacian``.
+
+ Uses PyG's implementation which supports all standard normalization
+ variants, matching the pipeline in GRIT / GraphGPS.
+
+ Args:
+ parents: Already-parsed (J,) int64 array.
+ norm: Laplacian normalization passed to ``get_laplacian``.
+
+ - ``'none'``: combinatorial ``L = D - A``
+ - ``'sym'``: symmetric normalized ``L_sym = I - D^{-1/2} A D^{-1/2}``
+ - ``'rw'``: random walk normalized ``L_rw = I - D^{-1} A``
+
+ Returns:
+ ``np.ndarray`` of shape ``(J, J)`` with dtype float64.
+ """
+ n = len(parents)
+ edge_index = torch.from_numpy(compute_edge_indexs(parents)) # [2, 2*(J-1)]
+ pyg_norm = None if norm == 'none' else norm
+ lap_index, lap_weight = get_laplacian(edge_index, normalization=pyg_norm,
+ num_nodes=n)
+ L = to_scipy_sparse_matrix(lap_index, lap_weight, num_nodes=n)
+ return L.toarray()
+
+
+def _normalize_eigvecs(eigvecs, eigvals, norm='L2', eps=1e-12):
+ """Normalize eigenvectors using various strategies.
+
+ Args:
+ eigvecs: ``(J, K)`` eigenvectors.
+ eigvals: ``(K,)`` eigenvalues.
+ norm: Normalization type โ€” ``'L1'``, ``'L2'``, ``'abs-max'``,
+ ``'wavelength'``, ``'sign'`` (sign canonicalization only).
+
+ Returns:
+ ``(J, K)`` normalized eigenvectors.
+ """
+ eigvecs = eigvecs.copy()
+
+ if norm == 'sign':
+ for k in range(eigvecs.shape[1]):
+ max_idx = np.argmax(np.abs(eigvecs[:, k]))
+ if eigvecs[max_idx, k] < 0:
+ eigvecs[:, k] *= -1
+ return eigvecs
+
+ for k in range(eigvecs.shape[1]):
+ col = eigvecs[:, k]
+ if norm == 'L1':
+ denom = np.abs(col).sum()
+ elif norm == 'L2':
+ denom = np.sqrt((col ** 2).sum())
+ elif norm == 'abs-max':
+ denom = np.abs(col).max()
+ elif norm == 'wavelength':
+ denom = np.abs(col).max()
+ lam = np.sqrt(max(eigvals[k], eps))
+ denom = denom * lam * 2.0 / np.pi
+ else:
+ raise ValueError(f"Unsupported eigvec norm: '{norm}'. "
+ f"Choose from 'sign', 'L1', 'L2', 'abs-max', 'wavelength'.")
+ if denom > eps:
+ eigvecs[:, k] = col / denom
+
+ return eigvecs
+
+
+def compute_laplacian_eigenvectors(parents, max_freqs=8,
+ laplacian_norm='sym', eigvec_norm='L2'):
+ """Compute the smallest eigenvectors of the graph Laplacian.
+
+ Follows the same decomposition pipeline as GRIT / GraphGPS:
+ build the Laplacian, run eigendecomposition, clamp eigenvalues for
+ numerical stability, and normalize eigenvectors.
+
+ Args:
+ parents: Parent indices (J,).
+ max_freqs: Maximum number of frequencies to return. Clamped to
+ J-1 if the skeleton has fewer joints.
+ laplacian_norm: Laplacian type โ€” ``'none'`` (combinatorial
+ ``L = D - A``), ``'sym'`` (symmetric normalized), or
+ ``'rw'`` (random walk normalized).
+ eigvec_norm: Eigenvector normalization โ€” ``'sign'`` (canonical
+ sign only, default), ``'L1'``, ``'L2'``, ``'abs-max'``, or
+ ``'wavelength'``.
+
+ Returns:
+ Tuple of:
+
+ - ``eigvecs``: ``(J, max_freqs)`` float32 โ€” spectral coordinates.
+ When the skeleton has fewer than ``max_freqs + 1`` joints, only
+ ``J - 1`` real eigenvectors exist and the trailing columns are
+ zero-padded so downstream spectral encoders see a fixed width.
+ - ``eigvals``: ``(max_freqs,)`` float32 โ€” corresponding eigenvalues
+ (ascending, starting from the Fiedler value), zero-padded to match.
+ """
+ parents = _parse_parents(parents)
+ n = len(parents)
+ k = min(n - 1, max_freqs)
+
+ laplacian = _build_laplacian(parents, norm=laplacian_norm.lower())
+ eigvals_all, eigvecs_all = np.linalg.eigh(laplacian)
+
+ # Keep the smallest non-trivial eigenvectors (skip trivial eigenvalue ~ 0)
+ eigvals = eigvals_all[1:1 + k]
+ eigvecs = np.real(eigvecs_all[:, 1:1 + k])
+
+ # Clamp eigenvalues >= 0 for numerical stability
+ eigvals = np.maximum(eigvals, 0.0)
+
+ # Normalize eigenvectors
+ eigvecs = _normalize_eigvecs(eigvecs, eigvals, norm=eigvec_norm)
+
+ # Right-pad the frequency axis to max_freqs so every skeleton yields the
+ # same width regardless of joint count. Padding columns are zero, which
+ # is a no-op through WIRE (v=0 โ†’ angle=0) and a sample-global constant
+ # offset through SignNet (cancels in RoPE attention dot products).
+ if k < max_freqs:
+ eigvecs = np.pad(eigvecs, ((0, 0), (0, max_freqs - k)))
+ eigvals = np.pad(eigvals, (0, max_freqs - k))
+
+ return eigvecs.astype(np.float32), eigvals.astype(np.float32)
+
+
+# ---------------------------------------------------------------------------
+# 4. Pairwise relations and topology distances
+# ---------------------------------------------------------------------------
+
+EDGE_TYPES = {
+ 'self': 0, 'parent': 1, 'child': 2, 'sibling': 3,
+ 'no_relation': 4, 'end_effector': 5, 'ts_token_conn': 6,
+}
+
+
+def compute_edge_relations_and_distances(parents, max_path_len=5):
+ """Compute pairwise edge relation types and topology distances.
+
+ Edge relation types:
+ 0=self, 1=parent, 2=child, 3=sibling, 4=no_relation,
+ 5=end_effector, 6=ts_token_conn
+
+ Args:
+ parents: Parent indices (J,).
+ max_path_len: Maximum topology distance (longer paths are clamped).
+
+ Returns:
+ Tuple of ``(edge_rel, topo_rel)``, each ``(J, J)`` int16.
+ """
+ parents = list(parents)
+ n = len(parents)
+
+ children = _children_map(parents)
+
+ # --- Edge relations ---
+ edge_rel = np.full((n, n), EDGE_TYPES['no_relation'], dtype=np.int16)
+ for i in range(n):
+ pi = parents[i]
+ for j in range(n):
+ pj = parents[j]
+ if i == j:
+ edge_rel[i, j] = EDGE_TYPES['self']
+ elif pj == i:
+ edge_rel[i, j] = EDGE_TYPES['child']
+ elif j == pi and pi != -1:
+ edge_rel[i, j] = EDGE_TYPES['parent']
+ elif pi != -1 and pj == pi:
+ edge_rel[i, j] = EDGE_TYPES['sibling']
+
+ if len(children[i]) == 0:
+ edge_rel[i, i] = EDGE_TYPES['end_effector']
+
+ # --- Topology distances via BFS ---
+ adj = _adjacency_list(parents)
+
+ topo_rel = np.full((n, n), max_path_len, dtype=np.int16)
+ for s in range(n):
+ dist = np.full(n, 32767, dtype=np.int16)
+ dist[s] = 0
+ q = deque([s])
+ while q:
+ u = q.popleft()
+ if dist[u] >= max_path_len:
+ continue
+ for v in adj[u]:
+ if dist[v] > dist[u] + 1:
+ dist[v] = dist[u] + 1
+ q.append(v)
+ topo_rel[s] = np.minimum(dist, max_path_len)
+
+ return edge_rel, topo_rel
diff --git a/unimate/utils/visualization.py b/unimate/utils/visualization.py
new file mode 100644
index 0000000..5af10d1
--- /dev/null
+++ b/unimate/utils/visualization.py
@@ -0,0 +1,200 @@
+"""Visualization utilities for generated motion samples."""
+
+import os
+
+import numpy as np
+import torch
+from typing import Dict, List, Optional
+from PIL import Image
+
+from unimate.configs.schema import MainConfig
+from unimate.utils.motion_utils import (
+ recover_unimate_joint_pos_from_ric,
+ recover_unimate_joint_pos_from_rot,
+)
+# Skeleton rendering lives in the (public, self-contained) data_process
+# package; unimate/ may depend on data_process but never the other way around.
+from data_process.utils.plotting import (
+ save_skeleton_motion as plot_motion,
+ save_skeleton_motion_spectral as plot_motion_spectral,
+ render_skeleton_tpose,
+ render_skeleton_tpos_spectral,
+)
+from unimate.utils.logger import get_logger
+
+logger = get_logger(file_name=__file__)
+
+FPS = 30
+
+
+def visualize_and_save_motions(
+ config: MainConfig,
+ cond: Dict[str, torch.Tensor],
+ samples: torch.Tensor,
+ save_dir: str,
+ prefix: str,
+ case_ids: Optional[List[str]] = None,
+ only_save_motion: bool = False,
+ save_ric: bool = True,
+ valid_lengths: Optional[torch.Tensor] = None,
+):
+ """Visualize and save generated motion samples as MP4 videos and T-pose images.
+
+ Args:
+ config: Main training/inference config.
+ cond: Conditioning dict from the dataloader (tensors).
+ samples: Generated motion samples (B, J, D, T).
+ save_dir: Output directory for saved files.
+ prefix: Filename prefix for saved files.
+ case_ids: Optional per-sample identifiers (e.g. test-case keys). When
+ given, output files use them as the per-sample suffix and the
+ ``[train]/[eval]`` split tag is suppressed in titles/filenames.
+ only_save_motion: If True, only the denormalized motion-feature
+ ``.npy`` is written under ``<save_dir>/motions/``; the FK / RIC
+ mp4 renders, the T-pose PNG, and the position recoveries that
+ feed them are all skipped.
+ save_ric: If False, skip the RIC-recovered ``_ric.mp4`` render (FK
+ and T-pose are still saved). Inference defaults to False.
+ valid_lengths: optional ``(B,)`` tensor of per-sample valid frame
+ counts. When provided, the saved motion (and downstream FK / RIC
+ renders) is trimmed to the per-sample valid length instead of
+ keeping the padded ``T = max_motion_length`` window โ€” useful for
+ saving GT clips whose true length is shorter than the padded
+ ODE window.
+ """
+ motions_dir = os.path.join(save_dir, 'motions')
+ os.makedirs(motions_dir, exist_ok=True)
+ if not only_save_motion:
+ animations_dir = os.path.join(save_dir, 'animations')
+ os.makedirs(animations_dir, exist_ok=True)
+
+ for object_idx, sample_motion in enumerate(samples):
+ object_type = cond["object_type"][object_idx]
+ n_joints = cond["n_joints"][object_idx].item()
+
+ motion = sample_motion[:n_joints].cpu().permute(2, 0, 1).numpy().copy() # (F, J, D)
+ if valid_lengths is not None:
+ valid_T = int(valid_lengths[object_idx].item())
+ motion = motion[:valid_T]
+ tpos_first_frame = cond["tpos_first_frame"][object_idx][:n_joints][None, ...].cpu().numpy().copy()
+
+ mean = cond["mean"][object_idx][:n_joints][None, ...].cpu().numpy().copy()
+ std = cond["std"][object_idx][:n_joints][None, ...].cpu().numpy().copy()
+ motion = motion * std + mean
+ tpos_first_frame = tpos_first_frame * std + mean
+
+ parents = cond["parents"][object_idx]
+ offsets = cond["offsets"][object_idx][:n_joints].cpu().numpy().copy()
+
+ # None falls back to the red/blue joint coloring in plotting.py.
+ spectral_feats = None
+ if "spectral_feats" in cond and cond["spectral_feats"] is not None:
+ spectral_feats = (
+ cond["spectral_feats"][object_idx][:n_joints].cpu().numpy().copy()
+ )
+
+ recover_gl_pos = None
+ recover_gl_pos_fk = None
+ if not only_save_motion:
+ if save_ric:
+ recover_gl_pos = recover_unimate_joint_pos_from_ric(motion)
+ recover_gl_pos_fk = recover_unimate_joint_pos_from_rot(motion, parents, offsets)
+
+ case_id = case_ids[object_idx] if case_ids is not None else None
+
+ # case_ids encode user-supplied test setups; train/eval origin
+ # is meaningless there, so suppress it in titles + filenames.
+ if case_id is not None:
+ split_tag = None
+ else:
+ split_tags = cond.get("split_tag")
+ split_tag = split_tags[object_idx] if split_tags is not None else None
+
+ title = case_id if case_id else object_type
+ if split_tag:
+ title += f" [{split_tag}]"
+
+ if config.model.cond_mode == 'text':
+ caption = cond.get("caption", [None] * len(samples))
+ caption_text = caption[object_idx] if caption[object_idx] else None
+ if caption_text:
+ title += f"\n{caption_text}"
+
+ # .npy filenames follow the training-data convention
+ # ``{object_type}-{motion}[-{clip}]`` so downstream tools (e.g. the
+ # mesh-animation stage in ``data_process/``) can recover the
+ # object_type by splitting on the first '-'. All separators are '-'
+ # (never '_') to stay aligned with that template.
+ # ``prefix`` encodes the training iteration and ``object_idx`` is
+ # unique within a batch, so ``{lead}-{prefix}-{object_idx}`` is
+ # unique per (object_type, iteration, sample).
+ split_suffix = f'-{split_tag}' if split_tag else ''
+ if case_id is not None:
+ npy_lead = case_id
+ base_name = f'{case_id}-{prefix}-sample{object_idx}'
+ else:
+ npy_lead = f'{object_type}{split_suffix}'
+ base_name = f'{prefix}-{object_type}{split_suffix}-{object_idx}'
+
+ motion_npy_name = f'{npy_lead}-{prefix}-{object_idx}'
+
+ motion_npy_path = os.path.join(motions_dir, f'{motion_npy_name}.npy')
+ np.save(motion_npy_path, motion)
+ logger.info(f"Saved motion features at [{motion_npy_path}]")
+
+ if only_save_motion:
+ continue
+
+ tag_str = f", {case_id}" if case_id else (f", {split_tag}" if split_tag else "")
+
+ if save_ric:
+ save_path = os.path.join(animations_dir, f'{base_name}_ric.mp4')
+ if spectral_feats is not None:
+ plot_motion_spectral(
+ save_path=save_path, parents=parents, positions=recover_gl_pos,
+ spectral_feats=spectral_feats, fps=FPS, title=title,
+ figsize=(6.4, 6.4), dpi=100
+ )
+ else:
+ plot_motion(
+ save_path=save_path, parents=parents,
+ positions=recover_gl_pos, fps=FPS, title=title,
+ figsize=(6.4, 6.4), dpi=100
+ )
+ logger.info(f"Saved sample for object [{object_type}, {object_idx}{tag_str}] at [{save_path}]")
+
+ fk_save_path = os.path.join(animations_dir, f'{base_name}_fk.mp4')
+ if spectral_feats is not None:
+ plot_motion_spectral(
+ save_path=fk_save_path, parents=parents, positions=recover_gl_pos_fk,
+ spectral_feats=spectral_feats, fps=FPS, title=title,
+ figsize=(6.4, 6.4), dpi=100
+ )
+ else:
+ plot_motion(
+ save_path=fk_save_path, parents=parents,
+ positions=recover_gl_pos_fk, fps=FPS, title=title,
+ figsize=(6.4, 6.4), dpi=100
+ )
+ logger.info(f"Saved FK results for object [{object_type}, {object_idx}{tag_str}] at [{fk_save_path}]")
+
+ # T-pose is a per-object_type property โ€” render it once per type
+ # (skip when the stable-named file already exists from a prior call).
+ tpos_save_path = os.path.join(animations_dir, f'{object_type}_tpos.png')
+ if os.path.exists(tpos_save_path):
+ continue
+ # tpos is (1, J, 12) after feature-dim padding; positions live in [:3].
+ recover_tpos_gl_pos = tpos_first_frame[0, :, :3]
+ if spectral_feats is not None:
+ vis_tpos = render_skeleton_tpos_spectral(
+ parents=parents, positions=recover_tpos_gl_pos,
+ spectral_feats=spectral_feats, title=object_type,
+ figsize=(6.4, 6.4), dpi=100
+ )
+ else:
+ vis_tpos = render_skeleton_tpose(
+ parents=parents, positions=recover_tpos_gl_pos, title=object_type,
+ figsize=(6.4, 6.4), dpi=100
+ )
+ Image.fromarray(vis_tpos).save(tpos_save_path)
+ logger.info(f"Saved tpose visualization at [{tpos_save_path}]")